Skip to content

armgit / Ix

Public Imported from GitHub
0

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

wip: multi-lang parse improvements and CLI updates

Joseph Mikhail402301a456c3
diff --git a/core-ingestion/dist/index.js b/core-ingestion/dist/index.js
index d3e96d77..40ba655e 100644
--- a/core-ingestion/dist/index.js
+++ b/core-ingestion/dist/index.js
@@ -1,5 +1,6 @@
import * as nodePath from 'node:path';
import * as crypto from 'node:crypto';
+import { createRequire } from 'node:module';
// @ts-ignore — tree-sitter has no bundled types
import Parser from 'tree-sitter';
// @ts-ignore
@@ -26,6 +27,17 @@ import Ruby from 'tree-sitter-ruby';
import PHP from 'tree-sitter-php';
// @ts-ignore
import Scala from 'tree-sitter-scala';
+const _require = createRequire(import.meta.url);
+function tryLoadGrammar(pkg) {
+ try {
+ return _require(pkg);
+ }
+ catch {
+ return null;
+ }
+}
+const Kotlin = tryLoadGrammar('tree-sitter-kotlin');
+const Swift = tryLoadGrammar('tree-sitter-swift');
import { SupportedLanguages, languageFromPath } from './languages.js';
import { LANGUAGE_QUERIES } from './queries.js';
import { classifyFileRole } from './role-classifier.js';
@@ -45,6 +57,8 @@ const GRAMMAR_MAP = {
[SupportedLanguages.Ruby]: Ruby,
[SupportedLanguages.PHP]: PHP.php_only,
[SupportedLanguages.Scala]: Scala,
+ ...(Kotlin ? { [SupportedLanguages.Kotlin]: Kotlin } : {}),
+ ...(Swift ? { [SupportedLanguages.Swift]: Swift } : {}),
};
// Capture key prefix → NodeKind string
const DEFINITION_KIND_MAP = {
@@ -157,7 +171,7 @@ export function parseFile(filePath, source) {
try {
const parser = getParser();
parser.setLanguage(grammar);
- const tree = parser.parse(source);
+ const tree = parser.parse(source, undefined, { bufferSize: source.length + 1 });
const cacheKey = isTsx ? 'tsx' : language;
const query = getCachedQuery(cacheKey, grammar, queries);
const matches = query.matches(tree.rootNode);
diff --git a/core-ingestion/dist/queries.d.ts b/core-ingestion/dist/queries.d.ts
index 6642ee57..36c000ea 100644
--- a/core-ingestion/dist/queries.d.ts
+++ b/core-ingestion/dist/queries.d.ts
@@ -1,6 +1,6 @@
import { SupportedLanguages } from './languages.js';
export declare const TYPESCRIPT_QUERIES = "\n(class_declaration\n name: (type_identifier) @name) @definition.class\n\n(interface_declaration\n name: (type_identifier) @name) @definition.interface\n\n(function_declaration\n name: (identifier) @name) @definition.function\n\n(method_definition\n name: (property_identifier) @name) @definition.method\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function)))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression)))) @definition.function\n\n(import_statement\n source: (string) @import.source) @import\n\n; Re-export statements: export { X } from './y'\n(export_statement\n source: (string) @import.source) @import\n\n; Dynamic import with string literal: import('./foo') or await import('./foo')\n(call_expression\n function: (import)\n arguments: (arguments (string) @import.source)) @import\n\n(call_expression\n function: (identifier) @call.name) @call\n\n(call_expression\n function: (member_expression\n property: (property_identifier) @call.name)) @call\n\n; Constructor calls: new Foo()\n(new_expression\n constructor: (identifier) @call.name) @call\n\n; Heritage queries - class extends\n(class_declaration\n name: (type_identifier) @heritage.class\n (class_heritage\n (extends_clause\n value: (identifier) @heritage.extends))) @heritage\n\n; Heritage queries - class implements interface\n(class_declaration\n name: (type_identifier) @heritage.class\n (class_heritage\n (implements_clause\n (type_identifier) @heritage.implements))) @heritage.impl\n\n; Heritage queries - interface extends interface\n(interface_declaration\n name: (type_identifier) @heritage.class\n (extends_type_clause\n (type_identifier) @heritage.extends)) @heritage\n\n; Type references \u2014 captures types used in annotations/parameters/return types\n(type_annotation (type_identifier) @reference.type)\n";
-export declare const JAVASCRIPT_QUERIES = "\n(class_declaration\n name: (identifier) @name) @definition.class\n\n(function_declaration\n name: (identifier) @name) @definition.function\n\n(method_definition\n name: (property_identifier) @name) @definition.method\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function)))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression)))) @definition.function\n\n(import_statement\n source: (string) @import.source) @import\n\n; Re-export statements: export { X } from './y'\n(export_statement\n source: (string) @import.source) @import\n\n; Dynamic import with string literal: import('./foo') or await import('./foo')\n(call_expression\n function: (import)\n arguments: (arguments (string) @import.source)) @import\n\n(call_expression\n function: (identifier) @call.name) @call\n\n(call_expression\n function: (member_expression\n property: (property_identifier) @call.name)) @call\n\n; Constructor calls: new Foo()\n(new_expression\n constructor: (identifier) @call.name) @call\n\n; Heritage queries - class extends (JavaScript uses different AST than TypeScript)\n; In tree-sitter-javascript, class_heritage directly contains the parent identifier\n(class_declaration\n name: (identifier) @heritage.class\n (class_heritage\n (identifier) @heritage.extends)) @heritage\n";
+export declare const JAVASCRIPT_QUERIES = "\n(class_declaration\n name: (identifier) @name) @definition.class\n\n(function_declaration\n name: (identifier) @name) @definition.function\n\n(method_definition\n name: (property_identifier) @name) @definition.method\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n(lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n; var foo = function() {} (CommonJS var declarations)\n(variable_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression))) @definition.function\n\n; var foo = () => {} (CommonJS var arrow functions)\n(variable_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function))) @definition.function\n\n; obj.method = function name() {} (prototype/mixin method assignments)\n(expression_statement\n (assignment_expression\n left: (member_expression\n property: (property_identifier) @name)\n right: (function_expression))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (arrow_function)))) @definition.function\n\n(export_statement\n declaration: (lexical_declaration\n (variable_declarator\n name: (identifier) @name\n value: (function_expression)))) @definition.function\n\n(import_statement\n source: (string) @import.source) @import\n\n; Re-export statements: export { X } from './y'\n(export_statement\n source: (string) @import.source) @import\n\n; Dynamic import with string literal: import('./foo') or await import('./foo')\n(call_expression\n function: (import)\n arguments: (arguments (string) @import.source)) @import\n\n; CommonJS require() \u2192 IMPORTS\n(call_expression\n function: (identifier) @_req\n arguments: (arguments (string) @import.source)\n (#eq? @_req \"require\")) @import\n\n(call_expression\n function: (identifier) @call.name) @call\n\n(call_expression\n function: (member_expression\n property: (property_identifier) @call.name)) @call\n\n; Constructor calls: new Foo()\n(new_expression\n constructor: (identifier) @call.name) @call\n\n; Heritage queries - class extends (JavaScript uses different AST than TypeScript)\n; In tree-sitter-javascript, class_heritage directly contains the parent identifier\n(class_declaration\n name: (identifier) @heritage.class\n (class_heritage\n (identifier) @heritage.extends)) @heritage\n";
export declare const PYTHON_QUERIES = "\n(class_definition\n name: (identifier) @name) @definition.class\n\n(function_definition\n name: (identifier) @name) @definition.function\n\n(import_statement\n name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (dotted_name) @import.source) @import\n\n(import_from_statement\n module_name: (relative_import) @import.source) @import\n\n; from . import utils / from .models import User \u2014 also capture the imported symbol names\n(import_from_statement\n module_name: (relative_import)\n name: (dotted_name (identifier) @import.name)) @import.names\n\n(call\n function: (identifier) @call.name) @call\n\n(call\n function: (attribute\n attribute: (identifier) @call.name)) @call\n\n; Heritage queries - Python class inheritance\n(class_definition\n name: (identifier) @heritage.class\n superclasses: (argument_list\n (identifier) @heritage.extends)) @heritage\n\n; Type references \u2014 captures types used in type annotations / hints\n(typed_parameter type: (type (identifier) @reference.type))\n(typed_default_parameter type: (type (identifier) @reference.type))\n";
export declare const JAVA_QUERIES = "\n; Classes, Interfaces, Enums, Annotations\n(class_declaration name: (identifier) @name) @definition.class\n(interface_declaration name: (identifier) @name) @definition.interface\n(enum_declaration name: (identifier) @name) @definition.enum\n(annotation_type_declaration name: (identifier) @name) @definition.annotation\n\n; Methods & Constructors\n(method_declaration name: (identifier) @name) @definition.method\n(constructor_declaration name: (identifier) @name) @definition.constructor\n\n; Imports - capture any import declaration child as source\n(import_declaration (_) @import.source) @import\n\n; Calls\n(method_invocation name: (identifier) @call.name) @call\n(method_invocation object: (_) name: (identifier) @call.name) @call\n\n; Constructor calls: new Foo()\n(object_creation_expression type: (type_identifier) @call.name) @call\n\n; Heritage - extends class\n(class_declaration name: (identifier) @heritage.class\n (superclass (type_identifier) @heritage.extends)) @heritage\n\n; Heritage - implements interfaces\n(class_declaration name: (identifier) @heritage.class\n (super_interfaces (type_list (type_identifier) @heritage.implements))) @heritage.impl\n\n; Type references \u2014 captures types used in field/param/return-type positions\n(field_declaration type: (type_identifier) @reference.type)\n(formal_parameter type: (type_identifier) @reference.type)\n(local_variable_declaration type: (type_identifier) @reference.type)\n(method_declaration type: (type_identifier) @reference.type)\n";
export declare const C_QUERIES = "\n; Functions (direct declarator)\n(function_definition declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n(declaration declarator: (function_declarator declarator: (identifier) @name)) @definition.function\n\n; Functions returning pointers (pointer_declarator wraps function_declarator)\n(function_definition declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n(declaration declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name))) @definition.function\n\n; Functions returning double pointers (nested pointer_declarator)\n(function_definition declarator: (pointer_declarator declarator: (pointer_declarator declarator: (function_declarator declarator: (identifier) @name)))) @definition.function\n\n; Structs, Unions, Enums, Typedefs\n(struct_specifier name: (type_identifier) @name) @definition.struct\n(union_specifier name: (type_identifier) @name) @definition.union\n(enum_specifier name: (type_identifier) @name) @definition.enum\n(type_definition declarator: (type_identifier) @name) @definition.typedef\n\n; Macros\n(preproc_function_def name: (identifier) @name) @definition.macro\n(preproc_def name: (identifier) @name) @definition.macro\n\n; Includes\n(preproc_include path: (_) @import.source) @import\n\n; Calls\n(call_expression function: (identifier) @call.name) @call\n(call_expression function: (field_expression field: (field_identifier) @call.name)) @call\n\n; Type references \u2014 captures types used in declaration/parameter positions\n(declaration type: (type_identifier) @reference.type)\n(parameter_declaration type: (type_identifier) @reference.type)\n";
diff --git a/core-ingestion/dist/queries.js b/core-ingestion/dist/queries.js
index 16490aa5..7abf429c 100644
--- a/core-ingestion/dist/queries.js
+++ b/core-ingestion/dist/queries.js
@@ -109,6 +109,25 @@ export const JAVASCRIPT_QUERIES = `
name: (identifier) @name
value: (function_expression))) @definition.function
+; var foo = function() {} (CommonJS var declarations)
+(variable_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+; var foo = () => {} (CommonJS var arrow functions)
+(variable_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+; obj.method = function name() {} (prototype/mixin method assignments)
+(expression_statement
+ (assignment_expression
+ left: (member_expression
+ property: (property_identifier) @name)
+ right: (function_expression))) @definition.function
+
(export_statement
declaration: (lexical_declaration
(variable_declarator
@@ -133,6 +152,12 @@ export const JAVASCRIPT_QUERIES = `
function: (import)
arguments: (arguments (string) @import.source)) @import
+; CommonJS require() → IMPORTS
+(call_expression
+ function: (identifier) @_req
+ arguments: (arguments (string) @import.source)
+ (#eq? @_req "require")) @import
+
(call_expression
function: (identifier) @call.name) @call
diff --git a/core-ingestion/package-lock.json b/core-ingestion/package-lock.json
index 33917a71..0754e6e4 100644
--- a/core-ingestion/package-lock.json
+++ b/core-ingestion/package-lock.json
@@ -15,11 +15,13 @@
"tree-sitter-go": "^0.21.0",
"tree-sitter-java": "^0.21.0",
"tree-sitter-javascript": "^0.21.0",
+ "tree-sitter-kotlin": "^0.3.8",
"tree-sitter-php": "^0.23.12",
"tree-sitter-python": "^0.21.0",
"tree-sitter-ruby": "^0.23.1",
"tree-sitter-rust": "^0.21.0",
"tree-sitter-scala": "^0.24.0",
+ "tree-sitter-swift": "^0.6.0",
"tree-sitter-typescript": "^0.21.0"
},
"devDependencies": {
@@ -418,6 +420,7 @@
"integrity": "sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"undici-types": "~6.21.0"
}
@@ -655,6 +658,12 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
"node_modules/lightningcss": {
"version": "1.32.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz",
@@ -996,6 +1005,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -1164,6 +1174,7 @@
"integrity": "sha512-7dxoA6kYvtgWw80265MyqJlkRl4yawIjO7S5MigytjELkX43fV2WsAXzsNfO7sBpPPCF5Gp0+XzHk0DwLCq3xQ==",
"hasInstallScript": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"node-addon-api": "^8.0.0",
"node-gyp-build": "^4.8.0"
@@ -1207,6 +1218,19 @@
}
}
},
+ "node_modules/tree-sitter-cli": {
+ "version": "0.23.2",
+ "resolved": "https://registry.npmjs.org/tree-sitter-cli/-/tree-sitter-cli-0.23.2.tgz",
+ "integrity": "sha512-kPPXprOqREX+C/FgUp2Qpt9jd0vSwn+hOgjzVv/7hapdoWpa+VeWId53rf4oNNd29ikheF12BYtGD/W90feMbA==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "tree-sitter": "cli.js"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/tree-sitter-cpp": {
"version": "0.22.3",
"resolved": "https://registry.npmjs.org/tree-sitter-cpp/-/tree-sitter-cpp-0.22.3.tgz",
@@ -1283,6 +1307,31 @@
}
}
},
+ "node_modules/tree-sitter-kotlin": {
+ "version": "0.3.8",
+ "resolved": "https://registry.npmjs.org/tree-sitter-kotlin/-/tree-sitter-kotlin-0.3.8.tgz",
+ "integrity": "sha512-A4obq6bjzmYrA+F0JLLoheFPcofFkctNaZSpnDd+GPn1SfVZLY4/GG4C0cYVBTOShuPBGGAOPLM1JWLZQV4m1g==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^7.1.0",
+ "node-gyp-build": "^4.8.0"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.21.0"
+ },
+ "peerDependenciesMeta": {
+ "tree_sitter": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/tree-sitter-kotlin/node_modules/node-addon-api": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
+ "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
+ "license": "MIT"
+ },
"node_modules/tree-sitter-php": {
"version": "0.23.12",
"resolved": "https://registry.npmjs.org/tree-sitter-php/-/tree-sitter-php-0.23.12.tgz",
@@ -1390,6 +1439,27 @@
}
}
},
+ "node_modules/tree-sitter-swift": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/tree-sitter-swift/-/tree-sitter-swift-0.6.0.tgz",
+ "integrity": "sha512-9vOJZes4/UFjBr4COHtp6ZHVuZYwfChSQbpneXQog04dAstfx5px3ybVX2cN+ylvLqsvVpmXLpidxxgF2rDQ7A==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "dependencies": {
+ "node-addon-api": "^8.0.0",
+ "node-gyp-build": "^4.8.0",
+ "tree-sitter-cli": "^0.23",
+ "which": "2.0.2"
+ },
+ "peerDependencies": {
+ "tree-sitter": "^0.21.1"
+ },
+ "peerDependenciesMeta": {
+ "tree_sitter": {
+ "optional": true
+ }
+ }
+ },
"node_modules/tree-sitter-typescript": {
"version": "0.21.2",
"resolved": "https://registry.npmjs.org/tree-sitter-typescript/-/tree-sitter-typescript-0.21.2.tgz",
@@ -1444,6 +1514,7 @@
"integrity": "sha512-fPGaRNj9Zytaf8LEiBhY7Z6ijnFKdzU/+mL8EFBaKr7Vw1/FWcTBAMW0wLPJAGMPX38ZPVCVgLceWiEqeoqL2Q==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@oxc-project/runtime": "0.115.0",
"lightningcss": "^1.32.0",
@@ -1599,6 +1670,21 @@
}
}
},
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
diff --git a/core-ingestion/package.json b/core-ingestion/package.json
index a692e64f..b2a1404b 100644
--- a/core-ingestion/package.json
+++ b/core-ingestion/package.json
@@ -24,11 +24,13 @@
"tree-sitter-go": "^0.21.0",
"tree-sitter-java": "^0.21.0",
"tree-sitter-javascript": "^0.21.0",
+ "tree-sitter-kotlin": "^0.3.8",
"tree-sitter-php": "^0.23.12",
"tree-sitter-python": "^0.21.0",
"tree-sitter-ruby": "^0.23.1",
"tree-sitter-rust": "^0.21.0",
"tree-sitter-scala": "^0.24.0",
+ "tree-sitter-swift": "^0.6.0",
"tree-sitter-typescript": "^0.21.0"
},
"devDependencies": {
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 93d090b4..d05c7492 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -1,5 +1,6 @@
import * as nodePath from 'node:path';
import * as crypto from 'node:crypto';
+import { createRequire } from 'node:module';
// @ts-ignore — tree-sitter has no bundled types
import Parser from 'tree-sitter';
// @ts-ignore
@@ -26,6 +27,12 @@ import Ruby from 'tree-sitter-ruby';
import PHP from 'tree-sitter-php';
// @ts-ignore
import Scala from 'tree-sitter-scala';
+const _require = createRequire(import.meta.url);
+function tryLoadGrammar(pkg: string): any {
+ try { return _require(pkg); } catch { return null; }
+}
+const Kotlin = tryLoadGrammar('tree-sitter-kotlin');
+const Swift = tryLoadGrammar('tree-sitter-swift');
import { SupportedLanguages, languageFromPath } from './languages.js';
import { LANGUAGE_QUERIES } from './queries.js';
@@ -95,6 +102,8 @@ const GRAMMAR_MAP: Partial<Record<SupportedLanguages, any>> = {
[SupportedLanguages.Ruby]: Ruby,
[SupportedLanguages.PHP]: PHP.php_only,
[SupportedLanguages.Scala]: Scala,
+ ...(Kotlin ? { [SupportedLanguages.Kotlin]: Kotlin } : {}),
+ ...(Swift ? { [SupportedLanguages.Swift]: Swift } : {}),
};
// Capture key prefix → NodeKind string
@@ -217,7 +226,7 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
try {
const parser = getParser();
parser.setLanguage(grammar);
- const tree = parser.parse(source);
+ const tree = parser.parse(source, undefined, { bufferSize: source.length + 1 });
const cacheKey = isTsx ? 'tsx' as const : language;
const query = getCachedQuery(cacheKey, grammar, queries);
const matches = query.matches(tree.rootNode);
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index 1ae0446a..26acae33 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -112,6 +112,25 @@ export const JAVASCRIPT_QUERIES = `
name: (identifier) @name
value: (function_expression))) @definition.function
+; var foo = function() {} (CommonJS var declarations)
+(variable_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (function_expression))) @definition.function
+
+; var foo = () => {} (CommonJS var arrow functions)
+(variable_declaration
+ (variable_declarator
+ name: (identifier) @name
+ value: (arrow_function))) @definition.function
+
+; obj.method = function name() {} (prototype/mixin method assignments)
+(expression_statement
+ (assignment_expression
+ left: (member_expression
+ property: (property_identifier) @name)
+ right: (function_expression))) @definition.function
+
(export_statement
declaration: (lexical_declaration
(variable_declarator
@@ -136,6 +155,12 @@ export const JAVASCRIPT_QUERIES = `
function: (import)
arguments: (arguments (string) @import.source)) @import
+; CommonJS require() → IMPORTS
+(call_expression
+ function: (identifier) @_req
+ arguments: (arguments (string) @import.source)
+ (#eq? @_req "require")) @import
+
(call_expression
function: (identifier) @call.name) @call
diff --git a/ix-cli/src/cli/__tests__/help-coverage.test.ts b/ix-cli/src/cli/__tests__/help-coverage.test.ts
index 2c4d053c..ac03a44a 100644
--- a/ix-cli/src/cli/__tests__/help-coverage.test.ts
+++ b/ix-cli/src/cli/__tests__/help-coverage.test.ts
@@ -6,6 +6,10 @@ import { buildHelpText } from "../help-text.js";
* This prevents regression where new commands become invisible.
*/
+function stripAnsi(s: string): string {
+ return s.replace(/\u001b\[[0-9;]*m/g, "");
+}
+
const ossHelp = buildHelpText();
const REQUIRED_COMMANDS = [
@@ -30,8 +34,8 @@ describe("help coverage", () => {
});
it("OSS help uses new branding", () => {
- expect(ossHelp).toContain("ix — Code Memory CLI");
- expect(ossHelp).not.toContain("Persistent Memory for LLM Systems");
+ expect(stripAnsi(ossHelp)).toContain("ix — Code Memory CLI");
+ expect(stripAnsi(ossHelp)).not.toContain("Persistent Memory for LLM Systems");
});
it("OSS help does not show a Pro section", () => {
diff --git a/ix-cli/src/cli/__tests__/ui.test.ts b/ix-cli/src/cli/__tests__/ui.test.ts
new file mode 100644
index 00000000..7d9dbde8
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/ui.test.ts
@@ -0,0 +1,134 @@
+import { describe, it, expect } from "vitest";
+import {
+ renderBreadcrumb,
+ renderKeyValue,
+ renderSection,
+ renderNote,
+ renderWarning,
+ renderSuccess,
+ renderError,
+ renderResolvedHeader,
+ colorizeKind,
+ colorizeEntity,
+} from "../ui.js";
+
+function stripAnsi(s: string): string {
+ return s.replace(/\u001b\[[0-9;]*m/g, "");
+}
+
+function captureLog(fn: () => void): string {
+ const lines: string[] = [];
+ const orig = console.log;
+ console.log = (...args: unknown[]) => lines.push(args.map(String).join(" "));
+ try { fn(); } finally { console.log = orig; }
+ return lines.join("\n");
+}
+
+describe("renderBreadcrumb", () => {
+ it("joins node names with separator", () => {
+ const result = renderBreadcrumb([{ name: "Alpha" }, { name: "Beta" }, { name: "Gamma" }]);
+ expect(stripAnsi(result)).toBe("Alpha → Beta → Gamma");
+ });
+
+ it("uses custom separator when provided", () => {
+ const result = renderBreadcrumb([{ name: "A" }, { name: "B" }], " / ");
+ expect(stripAnsi(result)).toContain("A");
+ expect(stripAnsi(result)).toContain("B");
+ });
+
+ it("handles single node", () => {
+ const result = renderBreadcrumb([{ name: "Solo" }]);
+ expect(stripAnsi(result)).toBe("Solo");
+ });
+});
+
+describe("renderKeyValue", () => {
+ it("includes colon-suffixed label and value", () => {
+ const output = captureLog(() => renderKeyValue("File", "/src/index.ts"));
+ const stripped = stripAnsi(output);
+ expect(stripped).toContain("File:");
+ expect(stripped).toContain("/src/index.ts");
+ });
+
+ it("pads label to 18 characters", () => {
+ const output = captureLog(() => renderKeyValue("A", "val"));
+ const stripped = stripAnsi(output);
+ // "A:" padded to 18 means 16 trailing spaces before value
+ expect(stripped).toMatch(/A:\s+val/);
+ });
+});
+
+describe("renderSection", () => {
+ it("output starts with newline", () => {
+ const output = captureLog(() => renderSection("Overview"));
+ expect(output.startsWith("\n")).toBe(true);
+ });
+
+ it("contains the title", () => {
+ const output = captureLog(() => renderSection("My Section"));
+ expect(stripAnsi(output)).toContain("My Section");
+ });
+});
+
+describe("renderNote", () => {
+ it("contains Note and the text", () => {
+ const output = captureLog(() => renderNote("check this"));
+ const stripped = stripAnsi(output);
+ expect(stripped).toContain("Note");
+ expect(stripped).toContain("check this");
+ });
+});
+
+describe("renderWarning", () => {
+ it("contains Warning and the text", () => {
+ const output = captureLog(() => renderWarning("something stale"));
+ const stripped = stripAnsi(output);
+ expect(stripped).toContain("Warning");
+ expect(stripped).toContain("something stale");
+ });
+});
+
+describe("renderSuccess", () => {
+ it("contains the text", () => {
+ const output = captureLog(() => renderSuccess("All good"));
+ expect(stripAnsi(output)).toContain("All good");
+ });
+});
+
+describe("renderError", () => {
+ it("contains Error and the text", () => {
+ const output = captureLog(() => renderError("something failed"));
+ const stripped = stripAnsi(output);
+ expect(stripped).toContain("Error");
+ expect(stripped).toContain("something failed");
+ });
+});
+
+describe("renderResolvedHeader", () => {
+ it("contains Resolved:, the kind, and the name", () => {
+ const output = captureLog(() => renderResolvedHeader("class", "IxClient"));
+ const stripped = stripAnsi(output);
+ expect(stripped).toContain("Resolved:");
+ expect(stripped).toContain("class");
+ expect(stripped).toContain("IxClient");
+ });
+});
+
+describe("colorizeKind", () => {
+ it("stripped result is the kind padded to 10 chars", () => {
+ const result = colorizeKind("function");
+ expect(stripAnsi(result)).toBe("function ");
+ });
+
+ it("handles empty string", () => {
+ const result = colorizeKind("");
+ expect(stripAnsi(result)).toBe(" ");
+ });
+});
+
+describe("colorizeEntity", () => {
+ it("stripped result is the name", () => {
+ const result = colorizeEntity("MyClass");
+ expect(stripAnsi(result)).toBe("MyClass");
+ });
+});
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index b0d44cb4..f5ec148a 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -1,5 +1,6 @@
import type { Command } from "commander";
import chalk from "chalk";
+import { renderSection, renderSuccess, renderError } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
@@ -79,7 +80,8 @@ export function registerDoctorCommand(program: Command): void {
return;
}
- console.log(chalk.bold("\nIx Doctor\n"));
+ renderSection("Ix Doctor");
+ console.log();
for (const r of results) {
const icon = r.ok ? chalk.green("✓") : chalk.red("✗");
const detail = chalk.dim(` — ${r.detail}`);
@@ -89,9 +91,9 @@ export function registerDoctorCommand(program: Command): void {
const allOk = results.every((r) => r.ok);
console.log();
if (allOk) {
- console.log(chalk.green("All checks passed."));
+ renderSuccess("All checks passed.");
} else {
- console.log(chalk.red("Some checks failed. Run with --format json for details."));
+ renderError("Some checks failed. Run with --format json for details.");
}
console.log();
});
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index 8504e118..f2663338 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -9,7 +9,7 @@ import { inferRole } from "../explain/role-inference.js";
import { inferImportance } from "../explain/importance.js";
import { renderExplanation } from "../explain/render.js";
import { stderr } from "../stderr.js";
-import chalk from "chalk";
+import { renderSection, renderWarning, renderNote } from "../ui.js";
export function registerExplainCommand(program: Command): void {
program
@@ -52,29 +52,28 @@ export function registerExplainCommand(program: Command): void {
console.log(JSON.stringify(output, null, 2));
} else {
if (facts.stale) {
- stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));
+ renderWarning("Source has changed since last ingest. Run ix ingest to update.");
}
- console.log(chalk.bold.underline("\nExplanation"));
+ renderSection("Explanation");
console.log(` ${rendered.explanation}`);
- console.log(chalk.bold.underline("\nContext"));
+ renderSection("Context");
for (const line of rendered.context.split("\n")) {
console.log(` ${line}`);
}
if (rendered.usedBy) {
- console.log(chalk.bold.underline("\nUsed by"));
+ renderSection("Used by");
console.log(` ${rendered.usedBy}`);
}
- console.log(chalk.bold.underline("\nWhy it matters"));
+ renderSection("Why it matters");
console.log(` ${rendered.whyItMatters}`);
if (rendered.notes.length > 0) {
- console.log(chalk.bold.underline("\nNote"));
for (const note of rendered.notes) {
- console.log(` ${chalk.dim(note)}`);
+ renderNote(note);
}
}
console.log();
@@ -214,7 +213,7 @@ async function rawExplain(
}
console.log(JSON.stringify(output, null, 2));
} else {
- if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));
+ if (stale) renderWarning("Source has changed since last ingest. Run ix ingest to update.");
formatExplain(result, "text");
}
}
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index 52193724..46ecb707 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -1,5 +1,6 @@
import type { Command } from "commander";
import chalk from "chalk";
+import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, colorizeKind } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
@@ -62,22 +63,23 @@ function renderRiskHeader(
risk: RiskSemantics,
systemPath: SystemPath,
): void {
- console.log(chalk.bold(`Target: ${target.kind} ${target.name}\n`));
+ renderResolvedHeader(target.kind, target.name);
+ console.log();
if (systemPath.length > 1 && hasMapData(systemPath)) {
- console.log(` System path: ${chalk.dim(formatSystemPath(systemPath))}`);
+ renderKeyValue("System path", formatSystemPath(systemPath));
}
// Risk summary — the lead section
const color = riskColor(risk.riskLevel);
- console.log(chalk.bold("\nRisk summary"));
+ renderSection("Risk summary");
console.log(` ${color(risk.riskSummary)}`);
// At-risk behavior
if (risk.behaviorAtRisk.length > 0) {
- console.log(chalk.bold("\nAt-risk behavior"));
+ renderSection("At-risk behavior");
for (const b of risk.behaviorAtRisk) {
- console.log(` ${chalk.white("•")} ${b}`);
+ console.log(` • ${b}`);
}
}
}
@@ -87,7 +89,7 @@ function renderPropagationBuckets(
flowPropagation?: { flowName: string; count: number },
): void {
if (propagationBuckets.length === 0 && !flowPropagation) return;
- console.log(chalk.bold("\nPropagation"));
+ renderSection("Propagation");
// Flow propagation line first
if (flowPropagation) {
@@ -131,17 +133,17 @@ function renderMostAffected(
}
if (items.length > 0) {
- console.log(chalk.bold("\nMost affected"));
+ renderSection("Most affected");
for (const item of items.slice(0, 3)) {
- console.log(` ${chalk.white("•")} ${item}`);
+ console.log(` • ${item}`);
}
}
}
function renderNextStep(risk: RiskSemantics): void {
if (risk.nextStep) {
- console.log(chalk.bold("\nNext"));
- console.log(` ${chalk.dim(risk.nextStep)}`);
+ renderSection("Next");
+ renderNote(risk.nextStep);
}
}
@@ -150,9 +152,9 @@ function renderSupportingContext(
): void {
const entries = Object.entries(counts).filter(([, v]) => v > 0);
if (entries.length === 0) return;
- console.log(chalk.bold("\nSupporting context"));
+ renderSection("Supporting context");
for (const [label, value] of entries) {
- console.log(` ${chalk.dim(label.padEnd(24))} ${value}`);
+ renderKeyValue(label.replace(/:$/, ""), String(value));
}
}
@@ -162,14 +164,14 @@ function renderDecisionsTasksBugs(
bugs: Array<{ name: string; status: string; severity: string }>,
): void {
if (decisions.length > 0) {
- console.log(chalk.bold("\nDecisions:"));
+ renderSection("Decisions");
for (const d of decisions) {
console.log(` ${chalk.yellow(d.name)}`);
}
}
if (tasks.length > 0) {
- console.log(chalk.bold("\nTasks:"));
+ renderSection("Tasks");
for (const t of tasks) {
const icon = t.status === "done" ? "✓" : "○";
console.log(` ${icon} [${t.status}] ${t.name}`);
@@ -177,7 +179,7 @@ function renderDecisionsTasksBugs(
}
if (bugs.length > 0) {
- console.log(chalk.bold("\nBugs:"));
+ renderSection("Bugs");
for (const b of bugs) {
const icon = b.status === "closed" || b.status === "resolved" ? "✓" : "○";
console.log(` ${icon} [${b.status}] ${chalk.red(b.severity)} ${b.name}`);
@@ -359,7 +361,7 @@ async function containerImpact(
renderDecisionsTasksBugs(decisions, tasks, bugs);
if (diagnostics.length > 0) {
- console.log(chalk.dim(`\nDiagnostics: ${diagnostics.join("; ")}`));
+ renderNote(`Diagnostics: ${diagnostics.join("; ")}`);
}
}
}
@@ -494,11 +496,11 @@ async function leafImpact(
// 6. Callees (as supporting detail)
if (calleesResult.nodes.length > 0) {
- console.log(chalk.bold("\nCalls:"));
+ renderSection("Calls");
for (const n of calleesResult.nodes) {
const node = n as any;
const name = node.name || node.attrs?.name || "(unnamed)";
- console.log(` ${chalk.dim((node.kind || "").padEnd(10))} ${name}`);
+ console.log(` ${colorizeKind(node.kind || "")} ${name}`);
}
}
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 0b53ed2e..e4d1ea2a 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -34,6 +34,8 @@ const SUPPORTED_EXTENSIONS = new Set([
const IGNORE_DIRS = new Set([
'node_modules', '.git', 'dist', 'build', 'target', '.next',
'.cache', '__pycache__', '.ix', '.claude', '.gitnexus',
+ 'test', 'tests', '__tests__', 'spec', 'specs', 'e2e',
+ 'examples', 'fixtures', '__mocks__', '__fixtures__',
]);
const MAX_FILE_BYTES = 1024 * 1024; // 1 MB
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 36b71e54..0842a8f4 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -1,6 +1,5 @@
import * as path from "node:path";
import type { Command } from "commander";
-import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import {
@@ -11,6 +10,7 @@ import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
import { getSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
+import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb } from "../ui.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
const FILE_KINDS = new Set(["file"]);
@@ -204,10 +204,11 @@ function toRepoRelative(filePath: string): string {
// ── Humanized system path breadcrumb ────────────────────────────────────────
function humanizeBreadcrumb(nodes: Array<{ name: string; kind: string }>): string {
- return nodes.map((n) => {
+ const humanized = nodes.map((n) => {
if (REGION_KINDS.has(n.kind)) return humanizeLabel(n.name).replace(/ layer$/, "");
return n.name;
- }).join(" → ");
+ });
+ return renderBreadcrumb(humanized.map((name) => ({ name })));
}
// ── Output ──────────────────────────────────────────────────────────────────
@@ -218,7 +219,7 @@ function outputLocate(output: LocateOutput, symbol: string, format: string): voi
return;
}
- if (output.stale) stderr(chalk.yellow("⚠ Some results may be stale. Run ix ingest to update.\n"));
+ if (output.stale) renderWarning("Some results may be stale. Run ix ingest to update.");
if (!output.resolvedTarget) {
stderr(`No graph entity found for "${symbol}".`);
@@ -231,26 +232,26 @@ function outputLocate(output: LocateOutput, symbol: string, format: string): voi
// Location section
const hasLocation = t.path || output.lineRange || output.container;
if (hasLocation) {
- console.log(chalk.bold("\nLocation"));
+ renderSection("Location");
if (t.path) {
- console.log(` ${chalk.dim("File:".padEnd(16))}${t.path}`);
+ renderKeyValue("File", t.path);
}
if (output.lineRange) {
- console.log(` ${chalk.dim("Lines:".padEnd(16))}${output.lineRange.start}-${output.lineRange.end}`);
+ renderKeyValue("Lines", `${output.lineRange.start}-${output.lineRange.end}`);
}
if (output.container) {
- console.log(` ${chalk.dim("Contained in:".padEnd(16))}${output.container.name}`);
+ renderKeyValue("Contained in", output.container.name);
}
}
// System path section
if (output.systemPath && output.systemPath.length > 1 && output.hasMapData) {
- console.log(chalk.bold("\nSystem path"));
+ renderSection("System path");
console.log(` ${humanizeBreadcrumb(output.systemPath)}`);
}
// Diagnostics
for (const d of output.diagnostics) {
- stderr(chalk.dim(` ${d}`));
+ renderNote(d);
}
}
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index f364df9e..b090240e 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -1,11 +1,11 @@
import * as nodePath from "node:path";
import type { Command } from "commander";
-import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { getSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
+import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
const STRUCTURAL_CONTAINER_KINDS = new Set(["class", "object", "trait", "interface"]);
@@ -83,10 +83,11 @@ function toRepoRelative(filePath: string): string {
}
function humanizeBreadcrumb(nodes: Array<{ name: string; kind: string }>): string {
- return nodes.map((n) => {
+ const humanized = nodes.map((n) => {
if (REGION_KINDS.has(n.kind)) return humanizeLabel(n.name).replace(/ layer$/, "");
return n.name;
- }).join(" → ");
+ });
+ return renderBreadcrumb(humanized.map((name) => ({ name })));
}
/** Label for the "Key ..." section based on target kind. */
@@ -201,15 +202,15 @@ async function overviewContainer(
renderOverviewHeader(target, displayPath, null, systemPathMapped, hasMap);
if (Object.keys(childrenByKind).length > 0) {
- console.log(chalk.bold("\nContains"));
+ renderSection("Contains");
const sorted = Object.entries(childrenByKind).sort((a, b) => b[1] - a[1]);
for (const [kind, count] of sorted) {
- console.log(` ${chalk.dim((kindLabel(kind) + ":").padEnd(22))}${count}`);
+ renderKeyValue(kindLabel(kind), String(count));
}
}
if (keyItems.length > 0) {
- console.log(chalk.bold(`\n${keyItemsLabel(target.kind)}`));
+ renderSection(keyItemsLabel(target.kind));
for (const item of keyItems) {
console.log(` ${item.name}`);
}
@@ -331,16 +332,16 @@ async function overviewLeaf(
// Nearby structure
if (siblingsByKind && Object.keys(siblingsByKind).length > 0) {
- console.log(chalk.bold("\nNearby structure"));
+ renderSection("Nearby structure");
const sorted = Object.entries(siblingsByKind).sort((a, b) => b[1] - a[1]);
for (const [kind, count] of sorted) {
- console.log(` ${chalk.dim((siblingKindLabel(kind) + ":").padEnd(24))}${count}`);
+ renderKeyValue(siblingKindLabel(kind), String(count));
}
}
// Key siblings
if (keySiblings && keySiblings.length > 0) {
- console.log(chalk.bold("\nKey siblings"));
+ renderSection("Key siblings");
for (const s of keySiblings) {
console.log(` ${s.name}`);
}
@@ -358,24 +359,24 @@ function renderOverviewHeader(
systemPath: Array<{ name: string; kind: string }>,
hasMap: boolean,
): void {
- console.log(chalk.bold("\nOverview"));
- console.log(` ${chalk.dim("Kind:".padEnd(16))}${target.kind}`);
+ renderSection("Overview");
+ renderKeyValue("Kind", target.kind);
if (displayPath) {
- console.log(` ${chalk.dim("File:".padEnd(16))}${displayPath}`);
+ renderKeyValue("File", displayPath);
}
if (containedIn) {
const containerLabel = STRUCTURAL_CONTAINER_KINDS.has(containedIn.kind)
? `${containedIn.kind} ${containedIn.name}`
: containedIn.name;
- console.log(` ${chalk.dim("Contained in:".padEnd(16))}${containerLabel}`);
+ renderKeyValue("Contained in", containerLabel);
}
if (systemPath.length > 1 && hasMap) {
- console.log(` ${chalk.dim("System path:".padEnd(16))}${humanizeBreadcrumb(systemPath)}`);
+ renderKeyValue("System path", humanizeBreadcrumb(systemPath));
}
}
function renderDiagnostics(diagnostics: string[]): void {
for (const d of diagnostics) {
- console.log(chalk.dim(`\n ${d}`));
+ renderNote(d);
}
}
diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.ts
index ddd5fd9d..5fd9490c 100644
--- a/ix-cli/src/cli/commands/status.ts
+++ b/ix-cli/src/cli/commands/status.ts
@@ -1,5 +1,5 @@
import type { Command } from "commander";
-import chalk from "chalk";
+import { renderSection, renderKeyValue, renderWarning, renderNote, renderSuccess } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { detectStaleFiles } from "../stale.js";
@@ -34,25 +34,26 @@ export function registerStatusCommand(program: Command): void {
};
console.log(JSON.stringify(result, null, 2));
} else {
- console.log(`Ix Memory: ${health.status}`);
- console.log(`Endpoint: ${getEndpoint()}`);
+ renderSection("Status");
+ renderKeyValue("Ix Memory", health.status);
+ renderKeyValue("Endpoint", getEndpoint());
if (staleInfo) {
- console.log(`Revision: ${staleInfo.currentRev}`);
+ renderKeyValue("Revision", String(staleInfo.currentRev));
if (staleInfo.lastIngestAt) {
const ago = timeSince(staleInfo.lastIngestAt);
- console.log(`Last ingest: ${ago}`);
+ renderKeyValue("Last ingest", ago);
}
if (staleInfo.staleFiles > 0) {
- console.log(chalk.yellow(`\n⚠ ${staleInfo.staleFiles} file(s) changed since last ingest:`));
+ renderWarning(`${staleInfo.staleFiles} file(s) changed since last ingest:`);
for (const f of staleInfo.sampleChangedFiles) {
- console.log(` ${chalk.dim(f)}`);
+ console.log(` ${f}`);
}
if (staleInfo.staleFiles > staleInfo.sampleChangedFiles.length) {
- console.log(chalk.dim(` ... and ${staleInfo.staleFiles - staleInfo.sampleChangedFiles.length} more`));
+ renderNote(`... and ${staleInfo.staleFiles - staleInfo.sampleChangedFiles.length} more`);
}
- console.log(chalk.dim("\nRun ix ingest to update."));
+ renderNote("Run ix ingest to update.");
} else {
- console.log(chalk.green("\nGraph is up to date."));
+ renderSuccess("Graph is up to date.");
}
}
}
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index 18a18001..0a79d258 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -5,6 +5,7 @@ import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, isRawId } from "../resolve.js";
import { stderr } from "../stderr.js";
import { buildDependencyTree } from "./depends.js";
+import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";
// ── Types ────────────────────────────────────────────────────────────
@@ -176,7 +177,7 @@ function renderTraceTree(children: Array<{ name: string; kind?: string; children
const kindStr = child.cycle
? chalk.dim((child.kind ?? "").padEnd(10))
- : chalk.cyan((child.kind ?? "").padEnd(10));
+ : colorizeKind(child.kind ?? "");
const nameStr = child.cycle
? chalk.dim(child.name) + chalk.yellow(" ↺")
: child.name;
@@ -192,10 +193,6 @@ function renderTraceTree(children: Array<{ name: string; kind?: string; children
}
-function printKV(key: string, value: string, indent = " "): void {
- console.log(`${indent}${chalk.dim(key + ":")} ${value}`);
-}
-
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
@@ -310,21 +307,21 @@ export function registerTraceCommand(program: Command): void {
}
// ── Text output ────────────────────────────────────────
- console.log(chalk.bold("Resolved path"));
- console.log(chalk.bold("\nTrace"));
- printKV("From", fromTarget.name);
- printKV("To ", toTarget.name);
- printKV("Kind", cap(relKind));
+ renderResolvedHeader(fromTarget.kind, fromTarget.name);
+ renderSection("Trace");
+ renderKeyValue("From", fromTarget.name);
+ renderKeyValue("To", toTarget.name);
+ renderKeyValue("Kind", cap(relKind));
if (pathNodes.length === 0) {
console.log(`\nNo route found from ${chalk.bold(fromTarget.name)} to ${chalk.bold(toTarget.name)}.`);
return;
}
- console.log(chalk.bold("\nRoute"));
+ renderSection("Route");
for (let i = 0; i < pathNodes.length; i++) {
const n = pathNodes[i];
- const kindStr = chalk.cyan((n.kind ?? "").padEnd(10));
+ const kindStr = colorizeKind(n.kind ?? "");
if (i === 0) {
console.log(` ${kindStr} ${n.name}`);
} else {
@@ -332,8 +329,8 @@ export function registerTraceCommand(program: Command): void {
}
}
- console.log(chalk.bold("\nSummary"));
- printKV("Path length", String(pathNodes.length));
+ renderSection("Summary");
+ renderKeyValue("Path length", String(pathNodes.length));
return;
}
@@ -392,13 +389,13 @@ export function registerTraceCommand(program: Command): void {
}
// ── Text ──────────────────────────────────────────────
- console.log(`${chalk.bold("Resolved:")} ${target.kind} ${chalk.bold(target.name)}`);
- console.log(chalk.bold("\nTrace"));
- printKV("Direction", "Both");
- printKV("Kind ", cap(relKind));
+ renderResolvedHeader(target.kind, target.name);
+ renderSection("Trace");
+ renderKeyValue("Direction", "Both");
+ renderKeyValue("Kind", cap(relKind));
// Upstream section (in edges — who depends on this)
- console.log(chalk.bold("\nUpstream"));
+ renderSection("Upstream");
console.log(` ${target.name}`);
if (upResult.tree.length === 0) {
console.log(chalk.dim(" (none)"));
@@ -409,7 +406,7 @@ export function registerTraceCommand(program: Command): void {
}
// Downstream section (out edges — what this depends on)
- console.log(chalk.bold("\nDownstream"));
+ renderSection("Downstream");
console.log(` ${target.name}`);
if (downResult.tree.length === 0) {
console.log(chalk.dim(" (none)"));
@@ -421,9 +418,9 @@ export function registerTraceCommand(program: Command): void {
const totalNodes = upResult.nodesVisited + downResult.nodesVisited;
const maxD = Math.max(upResult.maxDepthReached, downResult.maxDepthReached);
- console.log(chalk.bold("\nSummary"));
- printKV("Nodes visited", String(totalNodes));
- printKV("Max depth ", String(maxD));
+ renderSection("Summary");
+ renderKeyValue("Nodes visited", String(totalNodes));
+ renderKeyValue("Max depth", String(maxD));
return;
}
@@ -482,10 +479,10 @@ export function registerTraceCommand(program: Command): void {
}
// ── Text ────────────────────────────────────────────────────
- console.log(`${chalk.bold("Resolved:")} ${target.kind} ${chalk.bold(target.name)}`);
- console.log(chalk.bold("\nTrace"));
- printKV("Direction", cap(direction));
- printKV("Kind ", cap(relKind));
+ renderResolvedHeader(target.kind, target.name);
+ renderSection("Trace");
+ renderKeyValue("Direction", cap(direction));
+ renderKeyValue("Kind", cap(relKind));
if (tree.length === 0) {
const relDir = doUpstream ? "upstream" : "downstream";
@@ -493,16 +490,16 @@ export function registerTraceCommand(program: Command): void {
return;
}
- console.log(chalk.bold("\nPath"));
+ renderSection("Path");
console.log(` ${target.name}`);
for (const line of renderTraceTree(tree, [])) {
console.log(` ${line}`);
}
- console.log(chalk.bold("\nSummary"));
- printKV("Nodes visited", String(nodesVisited));
- printKV("Max depth ", String(maxDepthReached));
+ renderSection("Summary");
+ renderKeyValue("Nodes visited", String(nodesVisited));
+ renderKeyValue("Max depth", String(maxDepthReached));
},
);
}
diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.ts
index ddebdafd..52c7fd81 100644
--- a/ix-cli/src/cli/help-text.ts
+++ b/ix-cli/src/cli/help-text.ts
@@ -1,33 +1,37 @@
-const OSS_HELP = `ix — Code Memory CLI
-
-Start:
- map [path] Map the architectural hierarchy of a codebase
- watch Watch files and auto-ingest on change
- config Show or update configuration
-
-Understand:
- search <term> Search the knowledge graph by term
- locate <symbol> Resolve symbol to definition with context
- explain <symbol> Explain an entity with history
- impact <target> Blast-radius / dependency analysis
- overview <target> One-shot structural summary
- read <target> Read file content or symbol source code
-
-Explore:
- trace <symbol> Follow how a symbol connects upstream and downstream
- inventory List entities by kind
- rank Hotspot discovery by metric
- history <entityId> Show entity provenance chain
- diff <from> <to> Show diff between revisions
-
-System:
- status Show backend health
- stats Show graph statistics
- doctor Check system health
- docker <action> Manage the IX backend containers
- reset Wipe all graph data for a clean re-ingest
- upgrade Upgrade ix CLI and backend to the latest version
-`;
+import chalk from "chalk";
+
+const OSS_HELP = [
+ `${chalk.cyan("ix")} — Code Memory CLI`,
+ ``,
+ chalk.bold(`Start:`),
+ ` map [path] Map the architectural hierarchy of a codebase`,
+ ` watch Watch files and auto-ingest on change`,
+ ` config Show or update configuration`,
+ ``,
+ chalk.bold(`Understand:`),
+ ` search <term> Search the knowledge graph by term`,
+ ` locate <symbol> Resolve symbol to definition with context`,
+ ` explain <symbol> Explain an entity with history`,
+ ` impact <target> Blast-radius / dependency analysis`,
+ ` overview <target> One-shot structural summary`,
+ ` read <target> Read file content or symbol source code`,
+ ``,
+ chalk.bold(`Explore:`),
+ ` trace <symbol> Follow how a symbol connects upstream and downstream`,
+ ` inventory List entities by kind`,
+ ` rank Hotspot discovery by metric`,
+ ` history <entityId> Show entity provenance chain`,
+ ` diff <from> <to> Show diff between revisions`,
+ ``,
+ chalk.bold(`System:`),
+ ` status Show backend health`,
+ ` stats Show graph statistics`,
+ ` doctor Check system health`,
+ ` docker <action> Manage the IX backend containers`,
+ ` reset Wipe all graph data for a clean re-ingest`,
+ ` upgrade Upgrade ix CLI and backend to the latest version`,
+ ``,
+].join("\n");
const FOOTER = `Use "ix help advanced" for low-level graph commands.
Use "ix <command> --help" for details on any command.
diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.ts
new file mode 100644
index 00000000..582cff87
--- /dev/null
+++ b/ix-cli/src/cli/ui.ts
@@ -0,0 +1,88 @@
+/**
+ * ui.ts — Ix CLI brand presentation layer.
+ *
+ * Centralizes color, formatting, and layout for all CLI commands.
+ * Do not add command logic here. Do not extend format.ts.
+ */
+
+import chalk from "chalk";
+
+// ── Brand palette ─────────────────────────────────────────────────────────────
+//
+// Primary / kind accent chalk.cyan
+// Entity names / values chalk.bold
+// Section titles chalk.bold
+// Success chalk.green
+// Warning / note chalk.yellow / chalk.dim
+// Error chalk.red
+// Muted labels chalk.dim
+
+// ── Section / structure ───────────────────────────────────────────────────────
+
+/** Print a bold section title preceded by a blank line. */
+export function renderSection(title: string): void {
+ console.log(chalk.bold(`\n${title}`));
+}
+
+/**
+ * Print a dim label + value row.
+ * Label is colon-suffixed and padded to 18 characters.
+ */
+export function renderKeyValue(label: string, value: string, indent = " "): void {
+ console.log(`${indent}${chalk.dim((label + ":").padEnd(18))}${value}`);
+}
+
+// ── Entity emphasis ───────────────────────────────────────────────────────────
+
+/** Render an entity kind: cyan, padded to 10 characters. */
+export function colorizeKind(kind: string): string {
+ return chalk.cyan((kind ?? "").padEnd(10));
+}
+
+/** Render a resolved entity name: bold. */
+export function colorizeEntity(name: string): string {
+ return chalk.bold(name);
+}
+
+// ── Hierarchy / breadcrumb ────────────────────────────────────────────────────
+
+/**
+ * Render a breadcrumb path as a string.
+ * Node names are joined with a dim separator.
+ * Pass pre-humanized node names when applicable.
+ */
+export function renderBreadcrumb(
+ nodes: Array<{ name: string; kind?: string }>,
+ separator = " → ",
+): string {
+ return nodes.map((n) => n.name).join(chalk.dim(separator));
+}
+
+// ── Alerts ────────────────────────────────────────────────────────────────────
+
+/** Advisory hint, stale data, or informational note. */
+export function renderNote(text: string): void {
+ console.log(` ${chalk.dim("Note")} ${chalk.dim(text)}`);
+}
+
+/** Partial or degraded result. */
+export function renderWarning(text: string): void {
+ console.log(` ${chalk.yellow("Warning")} ${chalk.yellow(text)}`);
+}
+
+/** Success confirmation. */
+export function renderSuccess(text: string): void {
+ console.log(` ${chalk.green(text)}`);
+}
+
+/** Command failure or unresolved target. */
+export function renderError(text: string): void {
+ console.log(` ${chalk.red("Error")} ${chalk.red(text)}`);
+}
+
+// ── Resolved header ───────────────────────────────────────────────────────────
+
+/** Print the "Resolved: kind name" header shown at the top of most command text output. */
+export function renderResolvedHeader(kind: string, name: string): void {
+ console.log(`${chalk.bold("Resolved:")} ${chalk.cyan(kind)} ${chalk.bold(name)}`);
+}