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: developer workflow freshness — watch, staleness, path resolution
Tanner Kocheraf815ce4ba0a
diff --git a/ix-cli/src/cli/commands/decide.ts b/ix-cli/src/cli/commands/decide.tsindex f613b99a..8dcae163 100644--- a/ix-cli/src/cli/commands/decide.ts+++ b/ix-cli/src/cli/commands/decide.ts@@ -74,7 +74,7 @@ export function buildDecisionPatch(source: {uri: `ix://decision/${encodeURIComponent(title)}`,extractor: "ix-cli:decide",- sourceType: "Decision",+ sourceType: "decision",},baseRev: 0,ops,diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex f249d00d..78f5ff6e 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -3,15 +3,19 @@ import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { formatExplain, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";import { resolveEntity, isRawId } from "../resolve.js";+import { isFileStale } from "../stale.js";+import { stderr } from "../stderr.js";+import chalk from "chalk";export function registerExplainCommand(program: Command): void {program.command("explain <symbol>").description("Explain an entity — shows structure, container, and history").option("--kind <kind>", "Filter target entity by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring").option("--format <fmt>", "Output format (text|json)", "text")- .addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain verify_token --kind function --format json")- .action(async (symbol: string, opts: { kind?: string; format: string }) => {+ .addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json")+ .action(async (symbol: string, opts: { kind?: string; path?: string; format: string }) => {const client = new IxClient(getEndpoint());const target = await resolveEntity(client, symbol, ["class", "function", "method", "trait", "object", "interface", "module", "file"], opts);if (!target) return;@@ -42,6 +46,13 @@ export function registerExplainCommand(program: Command): void {const node = details.node as any;+ // Check staleness+ let stale = false;+ const sourceUri = node.provenance?.source_uri ?? node.provenance?.sourceUri;+ if (sourceUri) {+ try { stale = await isFileStale(client, sourceUri); } catch {}+ }+// Extract snippet fields from attrsconst signature = node.attrs?.signature || node.attrs?.summary;const docstring = node.attrs?.docstring || node.attrs?.description;@@ -93,11 +104,18 @@ export function registerExplainCommand(program: Command): void {}}- const result: ExplainResult = {+ if (stale) {+ diagnostics.push({+ code: "stale_source",+ message: "Results may be stale; file has changed since last ingest.",+ });+ }++ const result: ExplainResult & { stale?: boolean; warning?: string } = {kind: node.kind,name: node.name || node.attrs?.name || target.name,id: target.id,- file: node.provenance?.source_uri ?? node.provenance?.sourceUri,+ file: sourceUri,container: container ? { kind: container.kind, name: container.name || container.attrs?.name || "(unknown)" } : undefined,introducedRev: node.createdRev ?? node.created_rev,calledBy: callEdges.filter((e: any) => e.dst === target.id).length,@@ -110,6 +128,27 @@ export function registerExplainCommand(program: Command): void {diagnostics: diagnostics.length > 0 ? diagnostics : undefined,};- formatExplain(result, opts.format);+ if (stale) {+ (result as any).stale = true;+ (result as any).warning = "Results may be stale; file has changed since last ingest.";+ }++ if (opts.format === "json") {+ // Include resolvedTarget and stale fields in JSON+ const output: any = {+ resolvedTarget: { id: target.id, kind: target.kind, name: target.name },+ resolutionMode: target.resolutionMode,+ resultSource: "graph",+ result,+ };+ if (stale) {+ output.stale = true;+ output.warning = "Results may be stale; file has changed since last ingest.";+ }+ 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"));+ formatExplain(result, "text");+ }});}diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex a21b7529..ceb4ee0e 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -6,6 +6,8 @@ import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";import { formatLocateResults, type LocateResult } from "../format.js";import type { ResultSource } from "../format.js";+import { isFileStale } from "../stale.js";+import { stderr } from "../stderr.js";const execFileAsync = promisify(execFile);@@ -14,23 +16,31 @@ export function registerLocateCommand(program: Command): void {.command("locate <symbol>").description("Find a symbol in code and resolve to graph entities").option("--limit <n>", "Max text hits to check", "10")+ .option("--path <path>", "Prefer results from files matching this path substring").option("--format <fmt>", "Output format (text|json)", "text").option("--root <dir>", "Workspace root directory")- .action(async (symbol: string, opts: { limit: string; format: string; root?: string }) => {+ .action(async (symbol: string, opts: { limit: string; path?: string; format: string; root?: string }) => {const client = new IxClient(getEndpoint());const limit = parseInt(opts.limit, 10);+ const pathFilter = opts.path;// Step 1: Search the graph for matching entities- const graphNodes = await client.search(symbol, { limit: 5 });+ const graphNodes = await client.search(symbol, { limit: 10 });// Step 2: Run ripgrep for text hitslet textHits: Array<{ path: string; line: number }> = [];try {- const { stdout } = await execFileAsync("rg", [+ const rgArgs = ["--json", "--max-count", String(limit),"--no-heading", "--word-regexp",- symbol, resolveWorkspaceRoot(opts.root),- ], { maxBuffer: 10 * 1024 * 1024 });+ ];+ // If path filter provided, restrict ripgrep to that subtree+ const searchRoot = pathFilter+ ? resolveWorkspaceRoot(opts.root) + "/" + pathFilter+ : resolveWorkspaceRoot(opts.root);+ rgArgs.push(symbol, searchRoot);++ const { stdout } = await execFileAsync("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024 });for (const line of stdout.split("\n")) {if (!line.trim()) continue;@@ -52,7 +62,7 @@ export function registerLocateCommand(program: Command): void {textHits = textHits.slice(0, 10);// Step 3: Build results — graph entities first, then unmatched text hits- const results: LocateResult[] = [];+ let results: LocateResult[] = [];for (const node of graphNodes) {const n = node as any;results.push({@@ -64,6 +74,13 @@ export function registerLocateCommand(program: Command): void {});}+ // Apply path filter to graph results — put matching results first+ if (pathFilter) {+ const matching = results.filter(r => r.file?.includes(pathFilter));+ const nonMatching = results.filter(r => !r.file?.includes(pathFilter));+ results = [...matching, ...nonMatching];+ }+// Add text-only hits that didn't match any graph entityconst graphFiles = new Set(results.map(r => r.file).filter(Boolean));const seenPaths = new Set<string>();@@ -90,9 +107,22 @@ export function registerLocateCommand(program: Command): void {? "graph": "text";+ // Check staleness for the top result+ let stale = false;+ const topFile = results[0]?.file;+ if (topFile) {+ try { stale = await isFileStale(client, topFile); } catch {}+ }+if (opts.format === "json") {- console.log(JSON.stringify({ results, resultSource }, null, 2));+ const output: any = { results, resultSource };+ if (stale) {+ output.stale = true;+ output.warning = "Results may be stale; files have changed since last ingest.";+ }+ console.log(JSON.stringify(output, null, 2));} else {+ if (stale) stderr(chalk.yellow("⚠ Some results may be stale. Run ix ingest to update.\n"));if (results.length === 0) {console.log("No matches found.");} else {diff --git a/ix-cli/src/cli/commands/plan.ts b/ix-cli/src/cli/commands/plan.tsindex 80ffd121..707d2dad 100644--- a/ix-cli/src/cli/commands/plan.ts+++ b/ix-cli/src/cli/commands/plan.ts@@ -200,7 +200,7 @@ export function registerPlanCommand(program: Command): void {// Expand PLAN_HAS_TASK to get all tasksconst { nodes: taskNodes, edges: taskEdges } = await client.expand(planId, {- direction: "outgoing",+ direction: "out",predicates: ["PLAN_HAS_TASK"],});@@ -214,7 +214,7 @@ export function registerPlanCommand(program: Command): void {// Expand DEPENDS_ON for this taskconst { edges: depEdges } = await client.expand(node.id, {- direction: "outgoing",+ direction: "out",predicates: ["DEPENDS_ON"],});const dependsOn = depEdges.map((e: any) => e.dst as string);@@ -287,7 +287,7 @@ export function registerPlanCommand(program: Command): void {const client = new IxClient(getEndpoint());const { nodes: taskNodes } = await client.expand(planId, {- direction: "outgoing",+ direction: "out",predicates: ["PLAN_HAS_TASK"],});@@ -299,7 +299,7 @@ export function registerPlanCommand(program: Command): void {const status = getTaskStatus(entityDetail);const { edges: depEdges } = await client.expand(node.id, {- direction: "outgoing",+ direction: "out",predicates: ["DEPENDS_ON"],});const dependsOn = depEdges.map((e: any) => e.dst as string);diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex a4b1a0c0..97f44975 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -6,6 +6,7 @@ import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";import { resolveEntity } from "../resolve.js";import { stderr } from "../stderr.js";+import { isFileStale } from "../stale.js";export function registerReadCommand(program: Command): void {program@@ -13,8 +14,9 @@ export function registerReadCommand(program: Command): void {.description("Read source code — by file path, path:lines, or symbol name").option("--format <fmt>", "Output format (text|json)", "text").option("--kind <kind>", "Filter symbol by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring").option("--root <dir>", "Workspace root directory")- .action(async (target: string, opts: { format: string; kind?: string; root?: string }) => {+ .action(async (target: string, opts: { format: string; kind?: string; path?: string; root?: string }) => {// Check if target has a line range (path:start-end)const lineRangeMatch = target.match(/^(.+?):(\d+)-(\d+)$/);const rawPath = lineRangeMatch ? lineRangeMatch[1] : target;@@ -25,21 +27,41 @@ export function registerReadCommand(program: Command): void {if (fs.existsSync(filePath)) {const content = fs.readFileSync(filePath, "utf-8");const lines = content.split("\n");++ // Check staleness for direct file reads+ let stale = false;+ try {+ const client = new IxClient(getEndpoint());+ stale = await isFileStale(client, filePath);+ } catch { /* ignore — don't block read on staleness check */ }+if (lineRangeMatch) {const start = parseInt(lineRangeMatch[2], 10) - 1;const end = parseInt(lineRangeMatch[3], 10);const slice = lines.slice(start, end);if (opts.format === "json") {- console.log(JSON.stringify({ file: filePath, lines: [start + 1, end], content: slice.join("\n") }, null, 2));+ const result: any = { file: filePath, lines: [start + 1, end], content: slice.join("\n") };+ if (stale) {+ result.stale = true;+ result.warning = "Results may be stale; file has changed since last ingest.";+ }+ console.log(JSON.stringify(result, null, 2));} else {+ if (stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix ingest to update.\n"));for (let i = 0; i < slice.length; i++) {console.log(`${chalk.dim(String(start + i + 1).padStart(4))} ${slice[i]}`);}}} else {if (opts.format === "json") {- console.log(JSON.stringify({ file: filePath, lines: [1, lines.length], content }, null, 2));+ const result: any = { file: filePath, lines: [1, lines.length], content };+ if (stale) {+ result.stale = true;+ result.warning = "Results may be stale; file has changed since last ingest.";+ }+ console.log(JSON.stringify(result, null, 2));} else {+ if (stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix ingest to update.\n"));for (let i = 0; i < lines.length; i++) {console.log(`${chalk.dim(String(i + 1).padStart(4))} ${lines[i]}`);}@@ -61,12 +83,25 @@ export function registerReadCommand(program: Command): void {const details = await client.entity(resolved.id);const node = details.node as any;const sourceUri = node.provenance?.source_uri ?? node.provenance?.sourceUri;++ // Check staleness for resolved symbols+ let stale = false;+ if (sourceUri) {+ try { stale = await isFileStale(client, sourceUri); } catch {}+ }+if (!sourceUri || !fs.existsSync(sourceUri)) {const content = node.attrs?.content;if (content) {if (opts.format === "json") {- console.log(JSON.stringify({ symbol: resolved.name, content }, null, 2));+ const result: any = { symbol: resolved.name, content };+ if (stale) {+ result.stale = true;+ result.warning = "Results may be stale; file has changed since last ingest.";+ }+ console.log(JSON.stringify(result, null, 2));} else {+ if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));console.log(content);}return;@@ -81,13 +116,19 @@ export function registerReadCommand(program: Command): void {const lineEnd = node.attrs?.lineEnd ?? node.attrs?.line_end ?? allLines.length;if (opts.format === "json") {- console.log(JSON.stringify({+ const result: any = {symbol: resolved.name,file: sourceUri,lines: [lineStart, lineEnd],content: allLines.slice(lineStart - 1, lineEnd).join("\n"),- }, null, 2));+ };+ if (stale) {+ result.stale = true;+ result.warning = "Results may be stale; file has changed since last ingest.";+ }+ console.log(JSON.stringify(result, null, 2));} else {+ if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));console.log(chalk.dim(` ${sourceUri}:${lineStart}-${lineEnd}`));console.log();for (let i = lineStart - 1; i < lineEnd && i < allLines.length; i++) {diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.tsindex deaeffeb..ddd5fd9d 100644--- a/ix-cli/src/cli/commands/status.ts+++ b/ix-cli/src/cli/commands/status.ts@@ -1,21 +1,60 @@import type { Command } from "commander";+import chalk from "chalk";import { IxClient } from "../../client/api.js";-import { getEndpoint } from "../config.js";+import { getEndpoint, resolveWorkspaceRoot } from "../config.js";+import { detectStaleFiles } from "../stale.js";export function registerStatusCommand(program: Command): void {program.command("status").description("Show Ix backend health and status").option("--format <fmt>", "Output format (text|json)", "text")- .action(async (opts: { format: string }) => {+ .option("--root <dir>", "Workspace root directory")+ .action(async (opts: { format: string; root?: string }) => {const client = new IxClient(getEndpoint());try {const health = await client.health();+ const root = resolveWorkspaceRoot(opts.root);++ // Detect stale files+ let staleInfo;+ try {+ staleInfo = await detectStaleFiles(client, root);+ } catch {+ staleInfo = null;+ }+if (opts.format === "json") {- console.log(JSON.stringify(health, null, 2));+ const result: any = {+ backend: health.status,+ currentRev: staleInfo?.currentRev ?? null,+ lastIngestAt: staleInfo?.lastIngestAt ?? null,+ staleFiles: staleInfo?.staleFiles ?? 0,+ sampleChangedFiles: staleInfo?.sampleChangedFiles ?? [],+ };+ console.log(JSON.stringify(result, null, 2));} else {console.log(`Ix Memory: ${health.status}`);console.log(`Endpoint: ${getEndpoint()}`);+ if (staleInfo) {+ console.log(`Revision: ${staleInfo.currentRev}`);+ if (staleInfo.lastIngestAt) {+ const ago = timeSince(staleInfo.lastIngestAt);+ console.log(`Last ingest: ${ago}`);+ }+ if (staleInfo.staleFiles > 0) {+ console.log(chalk.yellow(`\n⚠ ${staleInfo.staleFiles} file(s) changed since last ingest:`));+ for (const f of staleInfo.sampleChangedFiles) {+ console.log(` ${chalk.dim(f)}`);+ }+ if (staleInfo.staleFiles > staleInfo.sampleChangedFiles.length) {+ console.log(chalk.dim(` ... and ${staleInfo.staleFiles - staleInfo.sampleChangedFiles.length} more`));+ }+ console.log(chalk.dim("\nRun ix ingest to update."));+ } else {+ console.log(chalk.green("\nGraph is up to date."));+ }+ }}} catch (err) {console.error(`Ix backend not reachable at ${getEndpoint()}`);@@ -23,3 +62,15 @@ export function registerStatusCommand(program: Command): void {}});}++function timeSince(isoString: string): string {+ const diff = Date.now() - new Date(isoString).getTime();+ const seconds = Math.floor(diff / 1000);+ if (seconds < 60) return `${seconds}s ago`;+ const minutes = Math.floor(seconds / 60);+ if (minutes < 60) return `${minutes}m ago`;+ const hours = Math.floor(minutes / 60);+ if (hours < 24) return `${hours}h ago`;+ const days = Math.floor(hours / 24);+ return `${days}d ago`;+}diff --git a/ix-cli/src/cli/commands/watch.ts b/ix-cli/src/cli/commands/watch.tsnew file mode 100644index 00000000..32a2576a--- /dev/null+++ b/ix-cli/src/cli/commands/watch.ts@@ -0,0 +1,214 @@+import * as fs from "node:fs";+import * as path from "node:path";+import type { Command } from "commander";+import chalk from "chalk";+import { IxClient } from "../../client/api.js";+import { getEndpoint, resolveWorkspaceRoot } from "../config.js";++const SUPPORTED_EXTENSIONS = new Set([+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",+ ".scala", ".sc", ".java",+ ".py", ".rb", ".go", ".rs",+ ".md", ".mdx",+ ".json", ".yaml", ".yml", ".toml",+ ".sql", ".graphql", ".gql",+]);++const SUPPORTED_NAMES = new Set([+ ".gitignore", ".gitattributes", ".editorconfig", ".env",+ ".eslintrc", ".prettierrc", ".babelrc",+ "Makefile", "Dockerfile", "Procfile", "Gemfile", "Rakefile",+ "BUILD", "WORKSPACE",+]);++const IGNORE_DIRS = new Set([+ "node_modules", ".git", "dist", "build", "target", ".next",+ ".cache", "__pycache__", ".ix", ".claude",+]);++const DEBOUNCE_MS = 1500;++export function registerWatchCommand(program: Command): void {+ program+ .command("watch")+ .description("Watch files and auto-ingest on changes")+ .option("--path <path>", "Restrict watching to a subdirectory")+ .option("--root <dir>", "Workspace root directory")+ .action(async (opts: { path?: string; root?: string }) => {+ const root = resolveWorkspaceRoot(opts.root);+ const watchPath = opts.path+ ? path.resolve(root, opts.path)+ : root;++ if (!fs.existsSync(watchPath)) {+ console.error(`Path does not exist: ${watchPath}`);+ process.exit(1);+ }++ 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`));+ console.log(chalk.dim("[watch] Press Ctrl+C to stop.\n"));++ // Track pending changes with debounce+ const pending = new Map<string, NodeJS.Timeout>();++ function shouldWatch(filePath: string): boolean {+ const ext = path.extname(filePath).toLowerCase();+ const basename = path.basename(filePath);+ if (!SUPPORTED_EXTENSIONS.has(ext) && !SUPPORTED_NAMES.has(basename)) return false;+ // Check no segment is an ignored dir+ const segments = path.relative(root, filePath).split(path.sep);+ return !segments.some(s => IGNORE_DIRS.has(s));+ }++ async function ingestFile(filePath: string): Promise<void> {+ const rel = path.relative(root, filePath);+ try {+ const result = await client.ingest(filePath, false);+ if (result.patchesApplied > 0) {+ console.log(`${chalk.cyan("[watch]")} ingested: ${chalk.bold(rel)} → rev ${result.latestRev}`);+ } else {+ console.log(`${chalk.dim("[watch]")} unchanged: ${rel}`);+ }+ } catch (err: any) {+ console.error(`${chalk.red("[watch]")} error ingesting ${rel}: ${err.message}`);+ }+ }++ // Use fs.watch recursively+ try {+ const watcher = fs.watch(watchPath, { recursive: true }, (_event, filename) => {+ if (!filename) return;+ const fullPath = path.resolve(watchPath, filename);+ if (!shouldWatch(fullPath)) return;++ // Check file still exists (might be a delete event)+ if (!fs.existsSync(fullPath)) return;++ const rel = path.relative(root, fullPath);++ // Cancel any existing debounce for this file+ const existing = pending.get(fullPath);+ if (existing) clearTimeout(existing);++ // Set new debounce+ pending.set(fullPath, setTimeout(async () => {+ pending.delete(fullPath);++ // Double-check file still exists and is stable+ if (!fs.existsSync(fullPath)) return;++ console.log(`${chalk.dim("[watch]")} changed: ${rel}`);+ await ingestFile(fullPath);+ }, DEBOUNCE_MS));+ });++ // Keep process alive+ process.on("SIGINT", () => {+ watcher.close();+ // Clear pending timers+ for (const timer of pending.values()) clearTimeout(timer);+ console.log(chalk.dim("\n[watch] Stopped."));+ process.exit(0);+ });+ } catch (err: any) {+ // Fallback to polling if fs.watch with recursive isn't supported+ if (err.code === "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") {+ console.log(chalk.dim("[watch] Falling back to polling mode (2s interval)..."));+ await pollMode(watchPath, root, client);+ } else {+ throw err;+ }+ }+ });+}++/**+ * Fallback polling mode for platforms where recursive fs.watch isn't available.+ */+async function pollMode(+ watchPath: string,+ root: string,+ client: IxClient+): Promise<void> {+ const mtimes = new Map<string, number>();++ function collectFiles(dir: string): string[] {+ const results: string[] = [];+ const stack = [dir];+ while (stack.length > 0) {+ const current = stack.pop()!;+ let entries: fs.Dirent[];+ try { entries = fs.readdirSync(current, { withFileTypes: true }); }+ catch { continue; }+ for (const entry of entries) {+ if (IGNORE_DIRS.has(entry.name)) continue;+ if (entry.name.startsWith(".") && entry.isDirectory()) continue;+ const fullPath = path.join(current, entry.name);+ if (entry.isDirectory()) {+ stack.push(fullPath);+ } else if (entry.isFile()) {+ const ext = path.extname(entry.name).toLowerCase();+ if (SUPPORTED_EXTENSIONS.has(ext) || SUPPORTED_NAMES.has(entry.name)) {+ results.push(fullPath);+ }+ }+ }+ }+ return results;+ }++ // Initial scan+ for (const f of collectFiles(watchPath)) {+ try { mtimes.set(f, fs.statSync(f).mtimeMs); } catch {}+ }++ const poll = async () => {+ const currentFiles = collectFiles(watchPath);+ const changed: string[] = [];++ for (const f of currentFiles) {+ try {+ const mtime = fs.statSync(f).mtimeMs;+ const prev = mtimes.get(f);+ if (prev === undefined || mtime > prev) {+ changed.push(f);+ mtimes.set(f, mtime);+ }+ } catch {}+ }++ for (const f of changed) {+ const rel = path.relative(root, f);+ console.log(`${chalk.dim("[watch]")} changed: ${rel}`);+ try {+ const result = await client.ingest(f, false);+ if (result.patchesApplied > 0) {+ console.log(`${chalk.cyan("[watch]")} ingested: ${chalk.bold(rel)} → rev ${result.latestRev}`);+ } else {+ console.log(`${chalk.dim("[watch]")} unchanged: ${rel}`);+ }+ } catch (err: any) {+ console.error(`${chalk.red("[watch]")} error: ${err.message}`);+ }+ }+ };++ setInterval(poll, 2000);++ process.on("SIGINT", () => {+ console.log(chalk.dim("\n[watch] Stopped."));+ process.exit(0);+ });+}diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.tsindex dd6853e9..7b838329 100644--- a/ix-cli/src/cli/format.ts+++ b/ix-cli/src/cli/format.ts@@ -416,7 +416,9 @@ export type DiagnosticCode =| "dangling_reference_filtered"| "ambiguous_resolution"| "no_edges"- | "text_fallback_used";+ | "text_fallback_used"+ | "stale_source"+ | "unfiltered_search";export interface Diagnostic {code: DiagnosticCode;diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.tsindex 990799d0..a99320cf 100644--- a/ix-cli/src/cli/main.ts+++ b/ix-cli/src/cli/main.ts@@ -29,6 +29,7 @@ import { registerRankCommand } from "./commands/rank.js";import { registerOverviewCommand } from "./commands/overview.js";import { registerGoalCommand } from "./commands/goal.js";import { registerPlanCommand, registerTaskCommand } from "./commands/plan.js";+import { registerWatchCommand } from "./commands/watch.js";const program = new Command();program@@ -66,5 +67,6 @@ registerOverviewCommand(program);registerGoalCommand(program);registerPlanCommand(program);registerTaskCommand(program);+registerWatchCommand(program);program.parse();diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex bae4e69d..18f9e4fc 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -8,25 +8,54 @@ export interface ResolvedEntity {id: string;kind: string;name: string;+ path?: string;resolutionMode: ResolutionMode;}+export interface AmbiguousResult {+ resolutionMode: "ambiguous";+ candidates: Array<{ id: string; name: string; kind: string; path?: string }>;+}++export type ResolveResult =+ | { resolved: true; entity: ResolvedEntity }+ | { resolved: false; ambiguous: true; result: AmbiguousResult }+ | { resolved: false; ambiguous: false };+/**- * Resolve a symbol to a single entity, preferring specific kinds.+ * Resolve a symbol to a single entity, preferring specific kinds and path filters.* Returns null and prints guidance if no match or ambiguous.*/export async function resolveEntity(client: IxClient,symbol: string,preferredKinds: string[],- opts?: { kind?: string }+ opts?: { kind?: string; path?: string }): Promise<ResolvedEntity | null> {+ const result = await resolveEntityFull(client, symbol, preferredKinds, opts);+ if (result.resolved) return result.entity;+ if (result.ambiguous) {+ printAmbiguous(symbol, result.result, opts);+ }+ return null;+}++/**+ * Full resolution returning structured result for JSON consumers.+ */+export async function resolveEntityFull(+ client: IxClient,+ symbol: string,+ preferredKinds: string[],+ opts?: { kind?: string; path?: string }+): Promise<ResolveResult> {const kindFilter = opts?.kind;+ const pathFilter = opts?.path;const nodes = await client.search(symbol, { limit: 20, kind: kindFilter });if (nodes.length === 0) {stderr(`No entity found matching "${symbol}".`);- return null;+ return { resolved: false, ambiguous: false };}// Exact name matches only@@ -35,42 +64,93 @@ export async function resolveEntity(return name.toLowerCase() === symbol.toLowerCase();});- const candidates = exact.length > 0 ? exact : nodes;+ let candidates = exact.length > 0 ? exact : nodes;++ // Apply path filter if provided — prefer entities whose file path contains the filter+ if (pathFilter) {+ const pathMatches = candidates.filter((n: any) => {+ const uri = n.provenance?.sourceUri ?? n.provenance?.source_uri ?? n.path ?? "";+ return uri.includes(pathFilter);+ });+ if (pathMatches.length > 0) {+ candidates = pathMatches;+ }+ }// If user specified --kind, take the first matchif (kindFilter) {const node = candidates[0] as any;- return { id: node.id, kind: node.kind, name: node.name || node.attrs?.name || symbol, resolutionMode: "exact" };+ return { resolved: true, entity: nodeToResolved(node, symbol, "exact") };}// Try preferred kinds in orderfor (const pk of preferredKinds) {- const match = candidates.find((n: any) => n.kind === pk);- if (match) {- return { id: (match as any).id, kind: (match as any).kind, name: (match as any).name || (match as any).attrs?.name || symbol, resolutionMode: "preferred-kind" };+ const matches = candidates.filter((n: any) => n.kind === pk);+ if (matches.length === 1) {+ return { resolved: true, entity: nodeToResolved(matches[0], symbol, "preferred-kind") };+ }+ if (matches.length > 1) {+ // Multiple matches of the same preferred kind — check if path disambiguates+ if (pathFilter) {+ // Path already filtered above, so if we still have multiple, it's genuinely ambiguous+ return { resolved: false, ambiguous: true, result: buildAmbiguous(matches) };+ }+ // Without path filter, check if all are the same entity (dedup by id)+ const uniqueIds = new Set(matches.map((n: any) => n.id));+ if (uniqueIds.size === 1) {+ return { resolved: true, entity: nodeToResolved(matches[0], symbol, "exact") };+ }+ return { resolved: false, ambiguous: true, result: buildAmbiguous(matches) };}}// If only one candidate, use itif (candidates.length === 1) {const node = candidates[0] as any;- return { id: node.id, kind: node.kind, name: node.name || node.attrs?.name || symbol, resolutionMode: "exact" };+ return { resolved: true, entity: nodeToResolved(node, symbol, "exact") };}- // Multiple candidates, no preferred kind match — show ambiguity- stderr(`Multiple matches for "${symbol}":`);+ // Multiple candidates, no preferred kind match — ambiguous+ return { resolved: false, ambiguous: true, result: buildAmbiguous(candidates) };+}++function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): ResolvedEntity {+ return {+ id: node.id,+ kind: node.kind,+ name: node.name || node.attrs?.name || symbol,+ path: node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path,+ resolutionMode: mode,+ };+}++function buildAmbiguous(nodes: any[]): AmbiguousResult {const seen = new Set<string>();- for (const n of candidates.slice(0, 5)) {+ const candidates: AmbiguousResult["candidates"] = [];+ for (const n of nodes.slice(0, 5)) {const node = n as any;- const key = `${node.kind}:${node.id}`;- if (seen.has(key)) continue;- seen.add(key);- const shortId = node.id.slice(0, 8);- const name = node.name || node.attrs?.name || "(unnamed)";- stderr(` ${chalk.cyan((node.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);+ if (seen.has(node.id)) continue;+ seen.add(node.id);+ candidates.push({+ id: node.id,+ name: node.name || node.attrs?.name || "(unnamed)",+ kind: node.kind ?? "",+ path: node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path,+ });}- stderr(chalk.dim(`\nUse --kind <kind> to disambiguate.`));- return null;+ return { resolutionMode: "ambiguous", candidates };+}++function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {+ stderr(`Ambiguous symbol "${symbol}":`);+ for (const c of result.candidates) {+ const shortPath = c.path ? ` in ${c.path}` : "";+ stderr(` ${chalk.cyan((c.kind ?? "").padEnd(10))} ${chalk.dim(c.id.slice(0, 8))} ${c.name}${chalk.dim(shortPath)}`);+ }+ const hints: string[] = [];+ if (!opts?.kind) hints.push("--kind");+ if (!opts?.path) hints.push("--path");+ stderr(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate.`));}/**diff --git a/ix-cli/src/cli/stale.ts b/ix-cli/src/cli/stale.tsnew file mode 100644index 00000000..a79a0239--- /dev/null+++ b/ix-cli/src/cli/stale.ts@@ -0,0 +1,134 @@+import * as fs from "node:fs";+import * as path from "node:path";+import { IxClient } from "../client/api.js";++export interface StaleInfo {+ lastIngestAt: string | null;+ currentRev: number;+ staleFiles: number;+ sampleChangedFiles: string[];+}++const SUPPORTED_EXTENSIONS = new Set([+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",+ ".scala", ".sc", ".java",+ ".py", ".rb", ".go", ".rs",+ ".md", ".mdx",+ ".json", ".yaml", ".yml", ".toml",+ ".sql", ".graphql", ".gql",+]);++const SUPPORTED_NAMES = new Set([+ ".gitignore", ".gitattributes", ".editorconfig", ".env",+ ".eslintrc", ".prettierrc", ".babelrc",+ "Makefile", "Dockerfile", "Procfile", "Gemfile", "Rakefile",+ "BUILD", "WORKSPACE",+]);++const IGNORE_DIRS = new Set([+ "node_modules", ".git", "dist", "build", "target", ".next",+ ".cache", "__pycache__", ".ix", ".claude",+]);++/**+ * Walk a directory and collect file paths with supported extensions.+ * Bounded to prevent runaway on huge repos.+ */+function collectFiles(dir: string, limit: number = 5000): string[] {+ const results: string[] = [];+ const stack = [dir];++ while (stack.length > 0 && results.length < limit) {+ const current = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(current, { withFileTypes: true });+ } catch {+ continue;+ }+ for (const entry of entries) {+ if (results.length >= limit) break;+ if (entry.name.startsWith(".") && entry.isDirectory()) continue;+ if (IGNORE_DIRS.has(entry.name)) continue;++ const fullPath = path.join(current, entry.name);+ if (entry.isDirectory()) {+ stack.push(fullPath);+ } else if (entry.isFile()) {+ const ext = path.extname(entry.name).toLowerCase();+ if (SUPPORTED_EXTENSIONS.has(ext) || SUPPORTED_NAMES.has(entry.name)) {+ results.push(fullPath);+ }+ }+ }+ }+ return results;+}++/**+ * Detect files that have been modified since the last ingest.+ * Uses mtime comparison against the latest patch timestamp.+ */+export async function detectStaleFiles(+ client: IxClient,+ root: string,+ maxSamples: number = 5+): Promise<StaleInfo> {+ // Get latest patch to determine last ingest time+ const patches = await client.listPatches({ limit: 1 });+ const stats = await client.stats();++ const lastPatch = patches[0];+ const lastIngestAt = lastPatch?.timestamp ?? null;+ const currentRev = lastPatch?.rev ?? 0;++ if (!lastIngestAt) {+ return { lastIngestAt: null, currentRev: 0, staleFiles: 0, sampleChangedFiles: [] };+ }++ const lastIngestTime = new Date(lastIngestAt).getTime();+ const files = collectFiles(root);+ const changedFiles: string[] = [];++ for (const filePath of files) {+ try {+ const stat = fs.statSync(filePath);+ if (stat.mtimeMs > lastIngestTime) {+ // Make path relative to root for display+ const relative = path.relative(root, filePath);+ changedFiles.push(relative);+ }+ } catch {+ // skip inaccessible files+ }+ }++ return {+ lastIngestAt,+ currentRev,+ staleFiles: changedFiles.length,+ sampleChangedFiles: changedFiles.slice(0, maxSamples),+ };+}++/**+ * Check if a specific file path is stale (modified since last ingest).+ */+export async function isFileStale(+ client: IxClient,+ filePath: string+): Promise<boolean> {+ if (!fs.existsSync(filePath)) return false;++ const patches = await client.listPatches({ limit: 1 });+ const lastPatch = patches[0];+ if (!lastPatch?.timestamp) return false;++ const lastIngestTime = new Date(lastPatch.timestamp).getTime();+ try {+ const stat = fs.statSync(filePath);+ return stat.mtimeMs > lastIngestTime;+ } catch {+ return false;+ }+}diff --git a/ix-cli/src/index.ts b/ix-cli/src/index.tsindex 2912342e..4655dc18 100644--- a/ix-cli/src/index.ts+++ b/ix-cli/src/index.ts@@ -1,2 +1,3 @@export { IxClient } from "./client/api.js";export type { StructuredContext, ScoredClaim, CommitResult } from "./client/types.js";+///Test\ No newline at end of filediff --git a/memory-layer/src/main/scala/ix/memory/model/Provenance.scala b/memory-layer/src/main/scala/ix/memory/model/Provenance.scalaindex 5934ff30..60079cf5 100644--- a/memory-layer/src/main/scala/ix/memory/model/Provenance.scala+++ b/memory-layer/src/main/scala/ix/memory/model/Provenance.scala@@ -16,6 +16,8 @@ object SourceType {case object Comment extends SourceTypecase object Inferred extends SourceTypecase object Human extends SourceType+ case object Cli extends SourceType+ case object Decision extends SourceType/** Base authority weight for confidence scoring. */def baseAuthority(st: SourceType): Double = st match {@@ -28,6 +30,8 @@ object SourceType {case Comment => 0.50case Inferred => 0.40case Human => 0.80+ case Cli => 0.75+ case Decision => 0.80}private val nameMap: Map[String, SourceType] = Map(@@ -39,7 +43,9 @@ object SourceType {"commit" -> Commit,"comment" -> Comment,"inferred" -> Inferred,- "human" -> Human+ "human" -> Human,+ "cli" -> Cli,+ "decision" -> Decision)implicit val encoder: Encoder[SourceType] = Encoder[String].contramap {@@ -52,6 +58,8 @@ object SourceType {case Comment => "comment"case Inferred => "inferred"case Human => "human"+ case Cli => "cli"+ case Decision => "decision"}implicit val decoder: Decoder[SourceType] = Decoder[String].emap { s =>