Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat: lazy bootstrap in ix map; ix config command; clean up UX surface
kagebinary3fa9b6020c00
diff --git a/.claude/hooks/post-edit-ingest.sh b/.claude/hooks/post-edit-ingest.shnew file mode 100755index 00000000..f2683acb--- /dev/null+++ b/.claude/hooks/post-edit-ingest.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+# Optionally auto-ingest files after edits.+# Currently a stub — enable by adding: ix ingest "$CLAUDE_TOOL_INPUT_FILE_PATH" 2>/dev/null || true+exit 0diff --git a/.claude/hooks/pre-tool-ix-check.sh b/.claude/hooks/pre-tool-ix-check.shnew file mode 100755index 00000000..63777d97--- /dev/null+++ b/.claude/hooks/pre-tool-ix-check.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+# Optionally intercept Grep/Glob calls to suggest ix commands instead.+# Currently a stub — non-blocking.+exit 0diff --git a/.claude/hooks/session-start.sh b/.claude/hooks/session-start.shnew file mode 100755index 00000000..c1a9d042--- /dev/null+++ b/.claude/hooks/session-start.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+# Run at session start to orient Claude to the current project state.+# Exit 0 always — non-blocking.+exit 0diff --git a/.claude/hooks/stop-decision-reminder.sh b/.claude/hooks/stop-decision-reminder.shnew file mode 100755index 00000000..574d9da7--- /dev/null+++ b/.claude/hooks/stop-decision-reminder.sh@@ -0,0 +1,4 @@+#!/usr/bin/env bash+# Remind Claude to record significant design decisions after each session.+# Exit 0 always — non-blocking reminder only.+exit 0diff --git a/.claude/settings.json b/.claude/settings.jsonindex a47511e9..d5f8a0a8 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -4,7 +4,7 @@"command": "npx","args": ["tsx",- "/Users/rileythompson/startprojes/startup/IX-Memory/ix-cli/src/mcp/server.ts"+ "/home/ianhock/ix/IX-Memory/ix-cli/src/mcp/server.ts"],"env": {"IX_ENDPOINT": "http://localhost:8090"diff --git a/ix-cli/src/cli/__tests__/init.test.ts b/ix-cli/src/cli/__tests__/init.test.tsdeleted file mode 100644index 1697be4d..00000000--- a/ix-cli/src/cli/__tests__/init.test.ts+++ /dev/null@@ -1,56 +0,0 @@-import { describe, it, expect, vi, beforeAll } from "vitest";--// Mock dependencies that init.ts imports so we can load it without side effects-vi.mock("../../client/api.js", () => ({- IxClient: vi.fn().mockImplementation(() => ({- health: vi.fn().mockResolvedValue(true),- })),-}));--vi.mock("../config.js", () => ({- getEndpoint: vi.fn().mockReturnValue("http://localhost:8090"),-}));--let CLAUDE_MD: string;--beforeAll(async () => {- const mod = await import("../commands/init.js");- CLAUDE_MD = mod.IX_CLAUDE_MD_BLOCK;-});--describe("CLAUDE_MD template", () => {- it("contains mandatory rules and CLI command routing", () => {- expect(CLAUDE_MD).toContain("ix decide");- expect(CLAUDE_MD).toContain("ix conflicts");- expect(CLAUDE_MD).toContain("NEVER guess");- expect(CLAUDE_MD).toContain("ix ingest");- expect(CLAUDE_MD).toContain("ix truth");- expect(CLAUDE_MD).toContain("ix search");- expect(CLAUDE_MD).toContain("ix explain");- expect(CLAUDE_MD).toContain("ix callers");- });-- it("routes through CLI exclusively", () => {- expect(CLAUDE_MD).toContain("ix` CLI exclusively");- expect(CLAUDE_MD).not.toContain("MCP");- });-- it("contains a Do NOT Use section", () => {- expect(CLAUDE_MD).toContain("## Do NOT Use");- });-- it("contains a Confidence Scores section", () => {- expect(CLAUDE_MD).toContain("## Confidence Scores");- });-- it("is under 80 lines to keep it concise", () => {- const lines = CLAUDE_MD.split("\n");- expect(lines.length).toBeLessThan(80);- });-- it("has numbered rules 1-6 in the MANDATORY RULES section", () => {- for (let i = 1; i <= 6; i++) {- expect(CLAUDE_MD).toContain(`${i}.`);- }- });-});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsnew file mode 100644index 00000000..39e32723--- /dev/null+++ b/ix-cli/src/cli/bootstrap.ts@@ -0,0 +1,85 @@+import { mkdirSync, existsSync } from "node:fs";+import { join, basename, resolve } from "node:path";+import { homedir } from "node:os";+import { randomUUID } from "node:crypto";+import chalk from "chalk";+import { IxClient } from "../client/api.js";+import { getEndpoint, loadConfig, saveConfig, type WorkspaceConfig } from "./config.js";++export interface BootstrapResult {+ createdConfig: boolean;+ registeredWorkspace: boolean;+ workspaceName: string;+}++/**+ * Ensure ~/.ix/config.yaml exists. Creates it silently if missing.+ * Returns true if it was just created.+ */+export function ensureLocalConfig(): boolean {+ const configDir = join(homedir(), ".ix");+ const configPath = join(configDir, "config.yaml");+ if (existsSync(configPath)) return false;+ mkdirSync(configDir, { recursive: true });+ const { writeFileSync } = require("node:fs");+ writeFileSync(configPath, `endpoint: ${getEndpoint()}\nformat: text\n`);+ return true;+}++/**+ * Ensure the current directory (or given path) is registered as a workspace.+ * Returns the workspace name. Does nothing if already registered.+ */+export function ensureWorkspaceRegistered(cwd = process.cwd()): { registered: boolean; name: string } {+ const rootPath = resolve(cwd);+ const name = basename(rootPath);+ const config = loadConfig();+ const existing = (config.workspaces ?? []).find(w => w.root_path === rootPath);+ if (existing) return { registered: false, name: existing.workspace_name };++ const workspaces = config.workspaces ?? [];+ const hasDefault = workspaces.some(w => w.default);+ const newWs: WorkspaceConfig = {+ workspace_id: randomUUID().slice(0, 8),+ workspace_name: name,+ root_path: rootPath,+ default: !hasDefault,+ };+ config.workspaces = [...workspaces, newWs];+ saveConfig(config);+ return { registered: true, name };+}++/**+ * Ensure the backend is reachable. Throws with a friendly message if not.+ */+export async function ensureBackendAvailable(): Promise<void> {+ const endpoint = getEndpoint();+ const client = new IxClient(endpoint);+ try {+ await client.health();+ } catch {+ throw new Error(+ `Ix backend not reachable at ${endpoint}\n` ++ ` Run: ix docker start`+ );+ }+}++/**+ * Full lazy bootstrap. Call at the top of map/watch actions.+ * Prints user-friendly output only on first run (when something was created).+ */+export async function bootstrap(cwd = process.cwd()): Promise<void> {+ const createdConfig = ensureLocalConfig();+ const { registered, name } = ensureWorkspaceRegistered(cwd);++ if (createdConfig || registered) {+ console.log(chalk.bold("Ix\n"));+ if (createdConfig) console.log(chalk.dim(`Created default config.`));+ if (registered) console.log(chalk.dim(`Registered workspace "${name}".`));+ console.log();+ }++ await ensureBackendAvailable();+}diff --git a/ix-cli/src/cli/commands/config.ts b/ix-cli/src/cli/commands/config.tsnew file mode 100644index 00000000..87529cee--- /dev/null+++ b/ix-cli/src/cli/commands/config.ts@@ -0,0 +1,75 @@+import type { Command } from "commander";+import chalk from "chalk";+import { loadConfig, saveConfig } from "../config.js";++/** Resolve a dotted key path into a config object and return [obj, lastKey]. */+function resolvePath(obj: any, key: string): [any, string] {+ const parts = key.split(".");+ let cur = obj;+ for (const part of parts.slice(0, -1)) {+ if (cur[part] === undefined) cur[part] = {};+ cur = cur[part];+ }+ return [cur, parts[parts.length - 1]];+}++export function registerConfigCommand(program: Command): void {+ const config = program+ .command("config")+ .description("Show or update Ix configuration");++ config+ .command("show")+ .description("Show current configuration")+ .action(() => {+ const cfg = loadConfig();+ console.log(chalk.bold("Ix Configuration\n"));+ console.log(` endpoint ${chalk.cyan(cfg.endpoint)}`);+ console.log(` format ${chalk.cyan(cfg.format)}`);+ if (cfg.workspaces?.length) {+ console.log(` workspaces`);+ for (const ws of cfg.workspaces) {+ const marker = ws.default ? chalk.green(" (default)") : "";+ console.log(` ${chalk.bold(ws.workspace_name)}${marker} ${chalk.dim(ws.root_path)}`);+ }+ }+ // Print any extra keys (user.name, team.name, etc.)+ const known = new Set(["endpoint", "format", "workspaces"]);+ for (const [k, v] of Object.entries(cfg)) {+ if (known.has(k)) continue;+ if (typeof v === "object" && v !== null) {+ for (const [k2, v2] of Object.entries(v as object)) {+ console.log(` ${k}.${k2} ${chalk.cyan(String(v2))}`);+ }+ } else {+ console.log(` ${k} ${chalk.cyan(String(v))}`);+ }+ }+ });++ config+ .command("get <key>")+ .description("Get a config value (e.g. endpoint, user.name)")+ .action((key: string) => {+ const cfg = loadConfig() as any;+ const [obj, lastKey] = resolvePath(cfg, key);+ const val = obj[lastKey];+ if (val === undefined) {+ console.error(chalk.red(`Key not found: ${key}`));+ process.exitCode = 1;+ return;+ }+ console.log(val);+ });++ config+ .command("set <key> <value>")+ .description("Set a config value (e.g. ix config set user.name 'Alice')")+ .action((key: string, value: string) => {+ const cfg = loadConfig() as any;+ const [obj, lastKey] = resolvePath(cfg, key);+ obj[lastKey] = value;+ saveConfig(cfg);+ console.log(chalk.green("✓") + ` ${key} = ${chalk.cyan(value)}`);+ });+}diff --git a/ix-cli/src/cli/commands/init.ts b/ix-cli/src/cli/commands/init.tsindex f865423c..82c74cbb 100644--- a/ix-cli/src/cli/commands/init.ts+++ b/ix-cli/src/cli/commands/init.ts@@ -1,168 +1,22 @@-import { mkdir, writeFile, readFile } from "node:fs/promises";-import { existsSync } from "node:fs";-import { join, basename, resolve } from "node:path";-import { homedir } from "node:os";-import { randomUUID } from "node:crypto";import type { Command } from "commander";-import { IxClient } from "../../client/api.js";-import { getEndpoint, loadConfig, saveConfig, type WorkspaceConfig } from "../config.js";--export const IX_MARKER_START = "<!-- IX-MEMORY START -->";-export const IX_MARKER_END = "<!-- IX-MEMORY END -->";--export const IX_CLAUDE_MD_BLOCK = `${IX_MARKER_START}-# Ix Memory System--This project uses Ix Memory — persistent, time-aware context for LLM assistants.--## Interface--Use the \`ix\` CLI exclusively. All commands support \`--format json\` for machine-readable output.--## MANDATORY RULES-1. BEFORE answering codebase questions → use targeted \`ix\` CLI commands (see routing below). Do NOT answer from training data alone.-2. AFTER every design or architecture decision → run \`ix decide <title> --rationale <text>\`.-3. When you notice contradictory information → run \`ix conflicts\` and present results to the user.-4. NEVER guess about codebase facts — if Ix has structured data, use it.-5. IMMEDIATELY after modifying code → run \`ix ingest <path>\` on changed files.-6. When the user states a goal → run \`ix truth add "<statement>"\`.--## Ix CLI Command Routing--Use bounded, composable CLI commands — never broad queries.--### Finding & Understanding Code-- \`ix search <term>\` — find entities by name (\`--kind class --limit 10\`)-- \`ix explain <symbol>\` — structure, container, history, calls-- \`ix read <target>\` — read source (\`file.py:10-50\` or symbol name)-- \`ix entity <id>\` — full entity details by ID-- \`ix text <term>\` — fast text search (\`--language python --limit 20\`)-- \`ix locate <symbol>\` — find symbol via graph + text--### Navigating Relationships-- \`ix callers <symbol>\` — what calls a function (cross-file)-- \`ix callees <symbol>\` — what a function calls-- \`ix contains <symbol>\` — members of a class/module-- \`ix imports <symbol>\` — what an entity imports-- \`ix imported-by <symbol>\` — what imports an entity-- \`ix depends <symbol>\` — dependency impact analysis--### History & Decisions-- \`ix decisions\` — list design decisions (\`--topic ingestion\`)-- \`ix history <entityId>\` — entity provenance chain-- \`ix diff <from> <to>\` — changes between revisions-- \`ix conflicts\` — detect contradictions--### Planning & Goals-- \`ix goal create <statement>\` — create a project goal-- \`ix goal list\` — list all goals-- \`ix plan create <title> --goal <id>\` — create a plan linked to a goal-- \`ix plan task <title> --plan <id>\` — add a task to a plan-- \`ix plan next <plan-id>\` — get the next actionable task-- \`ix task update <id> --status done\` — update task status-- \`ix decide <title> --rationale <text> --affects <entities>\` — record a linked decision--### Best practices-- Use \`--kind\` and \`--limit\` to constrain results-- Use \`--format json\` when chaining command results-- Use \`--path\` or \`--language\` to restrict text searches-- Use exact entity IDs from previous JSON results-- Decompose large questions into multiple targeted calls--## Do NOT Use-- \`ix query\` — deprecated, oversized low-signal responses-- Broad repo-wide inventory queries--## Confidence Scores-Ix returns confidence scores with results. When data has low confidence:-- Mention the uncertainty to the user-- Suggest re-ingesting the relevant files-- Never present low-confidence data as established fact-${IX_MARKER_END}`;+import chalk from "chalk";+import { bootstrap } from "../bootstrap.js";+/** @deprecated Use `ix map .` — bootstrap is now automatic. */export function registerInitCommand(program: Command): void {- program+ const cmd = program.command("init")- .description("Initialize Ix in the current project")- .option("--force", "Overwrite existing CLAUDE.md")- .action(async (opts: { force?: boolean }) => {- console.log("Initializing Ix Memory...\n");-- // 1. Check backend health- const client = new IxClient(getEndpoint());+ .description("(deprecated) Initialize Ix — use ix map . instead")+ .action(async () => {try {- await client.health();- console.log(" [ok] Backend is running at " + getEndpoint());- } catch {- console.error(" [!!] Backend not reachable at " + getEndpoint());- console.error(" Run ./stack.sh first, or set IX_ENDPOINT.");- process.exit(1);+ await bootstrap();+ console.log(chalk.green("✓") + " Ix is ready. Run " + chalk.bold("ix map .") + " to get started.");+ } catch (err: any) {+ console.error(chalk.red("Error:"), err.message);+ process.exitCode = 1;}-- // 2. Create ~/.ix/config.yaml- const configDir = join(homedir(), ".ix");- await mkdir(configDir, { recursive: true });- await writeFile(- join(configDir, "config.yaml"),- `endpoint: ${getEndpoint()}\nformat: text\n`- );- console.log(" [ok] Created ~/.ix/config.yaml");-- // 2b. Register workspace- const rootPath = resolve(process.cwd());- const workspaceName = basename(rootPath);-- const config = loadConfig();- const existingWorkspaces = config.workspaces ?? [];- const alreadyRegistered = existingWorkspaces.find(w => w.root_path === rootPath);-- if (alreadyRegistered) {- console.log(` [ok] Workspace already registered: ${alreadyRegistered.workspace_name} (${alreadyRegistered.workspace_id})`);- } else {- const hasDefault = existingWorkspaces.some(w => w.default);- const newWs: WorkspaceConfig = {- workspace_id: randomUUID().slice(0, 8),- workspace_name: workspaceName,- root_path: rootPath,- default: !hasDefault,- };-- if (hasDefault) {- const defaultWs = existingWorkspaces.find(w => w.default)!;- console.log(`\n A default workspace already exists:`);- console.log(` ${defaultWs.workspace_name} at ${defaultWs.root_path}`);- console.log(` New workspace: ${workspaceName} at ${rootPath}`);- console.log(` (Set as non-default. Use 'ix init --set-default' to change.)\n`);- }-- config.workspaces = [...existingWorkspaces, newWs];- saveConfig(config);- console.log(` [ok] Registered workspace: ${workspaceName} (${newWs.workspace_id})`);- }-- // 3. Add IX block to CLAUDE.md (using markers for clean add/remove)- if (existsSync("CLAUDE.md")) {- const existing = await readFile("CLAUDE.md", "utf-8");- if (existing.includes(IX_MARKER_START)) {- if (opts.force) {- // Replace existing IX block- const re = new RegExp(`${IX_MARKER_START}[\\s\\S]*?${IX_MARKER_END}`, "g");- await writeFile("CLAUDE.md", existing.replace(re, IX_CLAUDE_MD_BLOCK));- console.log(" [ok] Updated Ix rules in CLAUDE.md");- } else {- console.log(" [ok] CLAUDE.md already contains Ix rules (use --force to replace)");- }- } else {- // Append IX block to existing CLAUDE.md- await writeFile("CLAUDE.md", existing.trimEnd() + "\n\n" + IX_CLAUDE_MD_BLOCK + "\n");- console.log(" [ok] Appended Ix rules to CLAUDE.md");- }- } else {- await writeFile("CLAUDE.md", IX_CLAUDE_MD_BLOCK + "\n");- console.log(" [ok] Created CLAUDE.md with Ix rules");- }-- console.log("\nIx Memory initialized.");- console.log("Next: run 'ix ingest ./src --recursive' to ingest your codebase.");});++ // Hide from default help — no longer the recommended entrypoint+ (cmd as any).hidden = true;}diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex 94893094..30f6d5ff 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -2,6 +2,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";+import { bootstrap } from "../bootstrap.js";interface MapRegion {id: string;@@ -32,8 +33,8 @@ interface MapResult {export function registerMapCommand(program: Command): void {program- .command("map")- .description("Infer multi-scale architectural hierarchy from code structure")+ .command("map [path]")+ .description("Map the architectural hierarchy of a codebase").option("--format <fmt>", "Output format (text|json)", "text").option("--level <n>", "Show only regions at this level (1=finest, higher=coarser)").option("--min-confidence <n>", "Only show regions above this confidence threshold (0-1)", "0")@@ -50,12 +51,22 @@ Levels:3 = system (top-level architectural regions)Examples:- ix map+ ix map .ix map --format jsonix map --level 2ix map --min-confidence 0.5`)- .action(async (opts: { format: string; level?: string; minConfidence: string }) => {+ .action(async (pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string }) => {+ const cwd = pathArg ? require("node:path").resolve(pathArg) : process.cwd();++ try {+ await bootstrap(cwd);+ } catch (err: any) {+ console.error(chalk.red("Error:"), err.message);+ process.exitCode = 1;+ return;+ }+const client = new IxClient(getEndpoint());if (opts.format !== "json") {diff --git a/ix-cli/src/cli/commands/watch.ts b/ix-cli/src/cli/commands/watch.tsindex 4d62635c..562189ed 100644--- a/ix-cli/src/cli/commands/watch.ts+++ b/ix-cli/src/cli/commands/watch.ts@@ -5,6 +5,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";+import { bootstrap } from "../bootstrap.js";import { loadWatchIngestionModules } from "./ingestion-loader.js";import { readFileContent } from "./watch-utils.js";const SUPPORTED_EXTENSIONS = new Set([@@ -40,6 +41,13 @@ export function registerWatchCommand(program: Command): void {.option("--path <path>", "Restrict watching to a subdirectory").option("--root <dir>", "Workspace root directory").action(async (opts: { path?: string; root?: string }) => {+ try {+ await bootstrap();+ } catch (err: any) {+ console.error(chalk.red("Error:"), err.message);+ process.exit(1);+ }+const root = resolveWorkspaceRoot(opts.root);const watchPath = opts.path? path.resolve(root, opts.path)@@ -52,14 +60,6 @@ export function registerWatchCommand(program: Command): void {const client = new IxClient(getEndpoint());- // Verify backend is reachable- try {- await client.health();- } catch {- console.error(`Ix backend not reachable at ${getEndpoint()}`);- process.exit(1);- }-const relative = path.relative(root, watchPath) || ".";console.log(chalk.cyan(`[watch] Watching ${relative}`));console.log(chalk.dim(`[watch] Debounce: ${DEBOUNCE_MS}ms`));diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.tsindex 01364c72..3aa42c56 100644--- a/ix-cli/src/cli/help-text.ts+++ b/ix-cli/src/cli/help-text.ts@@ -1,27 +1,30 @@const OSS_HELP = `ix — Code Memory CLI-Core:- init Initialize Ix in a project directory+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 termlocate <symbol> Resolve symbol to definition with contextexplain <symbol> Explain an entity with historyimpact <target> Blast-radius / dependency analysisoverview <target> One-shot structural summary- watch Watch files and auto-ingest on change--Utilities:read <target> Read file content or symbol source code++Explore:inventory List entities by kindrank Hotspot discovery by metrichistory <entityId> Show entity provenance chaindiff <from> <to> Show diff between revisionsSystem:- ingest [path] Ingest source files or GitHub datastatus Show backend healthstats Show graph statisticsdoctor Check system healthdocker <action> Manage the IX backend containers+ reset Wipe all graph data for a clean re-ingest`;const FOOTER = `Use "ix help advanced" for low-level graph commands.diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.tsindex b67b53d9..2b8688f7 100644--- a/ix-cli/src/cli/register/oss.ts+++ b/ix-cli/src/cli/register/oss.ts@@ -27,6 +27,7 @@ import { registerDockerCommand } from "../commands/docker.js";import { registerWorkflowsHelpCommand } from "../commands/workflows.js";import { registerMapCommand } from "../commands/map.js";import { registerResetCommand } from "../commands/reset.js";+import { registerConfigCommand } from "../commands/config.js";const PRO_COMMANDS: { name: string; desc: string }[] = [{ name: "briefing", desc: "Session-resume briefing" },@@ -49,6 +50,8 @@ const PRO_COMMANDS: { name: string; desc: string }[] = [const ADVANCED_COMMANDS = ["contains", "callers", "callees", "imports", "imported-by","depends", "entity", "text", "conflicts", "query",+ // init is deprecated; ingest is now an implementation detail+ "init", "ingest",];export function registerOssCommands(program: Command): void {@@ -80,6 +83,7 @@ export function registerOssCommands(program: Command): void {registerWorkflowsHelpCommand(program);registerMapCommand(program);registerResetCommand(program);+ registerConfigCommand(program);// Hide advanced commands from default helpconst advancedSet = new Set(ADVANCED_COMMANDS);