Skip to content

armgit / Ix

Public Imported from GitHub
0

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

35.1 KB
Raw Blame
// Copyright 2026 Ix Infrastructure Inc.

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 { createClient } from "../../client/factory.js";
import { absoluteFromSourceUri, isReadablePath, readableRoots, resolveWorkspaceRoot } from "../config.js";
import { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.js";
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
import { anchorSpan, bareName } from "../edge-sites.js";
import { WALK_ENTRY_BUDGET, WALK_IGNORE_DIRS, basenameMatcher } from "../symbol-read-check.js";
import { relativePath, printJson } from "../format.js";
import { llmError, llmLine, llmShortId, printLlmLines } from "../llm.js";
import { parsePickOption } from "../options.js";
import { disambiguationHint } from "../next-step.js";
import { reportResolutionNotices, reportUnresolvedTarget } from "../ui.js";

export interface ReadResult {
  targetType: "file" | "file-range" | "filename-match" | "symbol";
  path: string;
  lineStart: number;
  lineEnd: number;
  content: string;
  symbol?: string;
  kind?: string;
  stale?: boolean;
  warning?: string;
  /** Set when the default line cap stopped the read short of the file. */
  truncated?: boolean;
  /**
   * How many lines the read's whole target has, when the read was capped: the
   * file's line count for a file, and the span's line count (`spanEnd` minus
   * its first line, plus one) for a symbol or a paged range. It is a count,
   * never a line number; `spanEnd` is where a symbol or paged range ends.
   */
  totalLines?: number;
  /**
   * The last line of the symbol or paged range being paged, when the read was
   * capped. Absent on plain file reads, where `totalLines` is already the last
   * line.
   */
  spanEnd?: number;
  /**
   * The next page, ready to run. `path:401-800` for a file. For a symbol or a
   * paged range it is `path:<first>-<last>@<from>`: the same span, read from
   * `<from>` and capped again, so following it repeatedly reaches `spanEnd`.
   */
  next?: string;
}

interface AmbiguityResult {
  targetType: "ambiguous-file" | "ambiguous-symbol";
  candidates: Array<{ name: string; kind?: string; path?: string; id?: string; rank?: number; container?: string }>;
  diagnostics?: Array<{ code: string; message: string }>;
}

function checkStale(filePath: string): boolean {
  try { return isFileStale(filePath); } catch { return false; }
}

/**
 * Refuse a file outside every readable workspace root, and say so.
 *
 * `ix read` resolves its target four ways, and three of them can end at an
 * arbitrary absolute path: the caller passes one directly, or the graph hands
 * back a `source_uri` that is already absolute. Nothing downstream re-checked
 * it, so `ix read /etc/shadow` read `/etc/shadow` — no workspace involved, no
 * backend involved. That matters most through `ix mcp`, where the caller is an
 * agent and the target is a string it chose.
 *
 * Returns true when the read may proceed. On refusal it reports a structured
 * machine error, or prints the reason and allowed roots for text output.
 */
function guardReadable(absPath: string, explicitRoot: string | undefined, what: string, format: string): boolean {
  if (isReadablePath(absPath, explicitRoot)) return true;
  const message = `Refusing to read ${what} outside the workspace: ${absPath}`;
  if (format === "json") {
    printJson({ error: "path_outside_workspace", message });
  } else if (format === "llm") {
    console.log(llmError("path_outside_workspace", message));
  } else {
    stderr(chalk.red(message));
    for (const root of readableRoots(explicitRoot)) stderr(chalk.dim(`  allowed root: ${root}`));
    stderr(chalk.dim("  Use --root to read from a different workspace, or ix init to register one."));
  }
  process.exitCode = 1;
  return false;
}

function reportInvalidLineRange(target: string, format: string, paged = false): void {
  const message = paged
    ? `Invalid line range in "${target}". Line numbers must start at 1, the end must not precede the start, and a page start (@n) must fall inside the range.`
    : `Invalid line range in "${target}". Line numbers must start at 1 and the end must not precede the start.`;
  if (format === "json") {
    printJson({ error: "invalid_line_range", message });
  } else if (format === "llm") {
    console.log(llmError("invalid_line_range", message));
  } else {
    stderr(chalk.red(message));
  }
  process.exitCode = 1;
}

/**
 * How much of a file a caller gets without asking for more.
 *
 * `ix read <file>` had no bound at all, and a file is the one target whose size
 * the caller cannot see before asking: recorded reads ran 20,000 to 53,000
 * tokens, and one benchmark run read the same file in eleven slices because the
 * first read arrived from the wrong anchor and cost too much to repeat.
 *
 * 400 lines is roughly 4-6k tokens of TypeScript — enough to hold a whole
 * small module, and small enough that a wrong guess is cheap to abandon. A
 * range the caller typed is never capped: they said what they wanted.
 */
const READ_LINE_CAP = 400;

function readFileRange(
  filePath: string,
  start?: number,
  end?: number,
  cap?: number,
): { content: string; lineStart: number; lineEnd: number; truncated?: boolean; totalLines?: number } {
  const raw = fs.readFileSync(filePath, "utf-8");
  const lines = raw.split("\n");
  const lineStart = start ?? 1;
  const requestedEnd = end ?? lines.length;
  const capped = cap !== undefined && end === undefined && requestedEnd - lineStart + 1 > cap
    ? lineStart + cap - 1
    : requestedEnd;
  const content = lines.slice(lineStart - 1, capped).join("\n");
  if (capped === requestedEnd) return { content, lineStart, lineEnd: capped };
  return { content, lineStart, lineEnd: capped, truncated: true, totalLines: lines.length };
}

/**
 * The path a `next=` cursor names its file by: relative to the workspace root,
 * because that is what `ix read` resolves a relative target against.
 *
 * It used to be relative to the cwd (`relativePath`). From a subdirectory of
 * the workspace that cursor did not round-trip: `big.ts` printed from `src/`
 * resolved to `<root>/big.ts`, which is a miss, a basename match, or a
 * different file with the same name. A symbol's file is often outside the
 * cwd's subtree, so symbol cursors hit this far more than file cursors did.
 * Run from the root, the cursor is the same as before.
 *
 * Both sides are compared through `realpath` as a fallback, since a root
 * reached through a symlink (macOS `/var` -> `/private/var`, a `~/code` link)
 * fails a plain prefix match. Falls back to the absolute path rather than to
 * `..`: a file outside the root is named the one way every cwd agrees on.
 */
function cursorPath(filePath: string, root: string): string {
  const inside = (from: string, to: string): string | undefined => {
    const rel = path.relative(from, to);
    return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel.split(path.sep).join("/") : undefined;
  };
  const direct = inside(path.resolve(root), path.resolve(filePath));
  if (direct) return direct;
  try {
    const real = inside(fs.realpathSync(root), fs.realpathSync(filePath));
    if (real) return real;
  } catch {
    // An unreadable root or a file deleted under us: the absolute path stands.
  }
  return filePath;
}

/** `src/a.ts:401-800`, or nothing when the cap landed on the last line. */
function nextPage(filePath: string, root: string, lineEnd: number, lastLine: number): string | undefined {
  if (lineEnd >= lastLine) return undefined;
  const from = lineEnd + 1;
  const to = Math.min(lastLine, lineEnd + READ_LINE_CAP);
  return `${cursorPath(filePath, root)}:${from}-${to}`;
}

/**
 * A paged span's next page: `src/a.ts:10-1327@410`. A plain `path:a-b` is a
 * range the caller typed and is never capped, so a symbol's cursor in that
 * form ended the paging after one hop; this form is capped again and carries
 * the span with it, so every page has a cursor until the span's last line.
 */
function nextSpanPage(filePath: string, root: string, spanStart: number, lineEnd: number, lastLine: number): string | undefined {
  if (lineEnd >= lastLine) return undefined;
  return `${cursorPath(filePath, root)}:${spanStart}-${lastLine}@${lineEnd + 1}`;
}

/** Fold a capped read's cursor into the result the renderers see. */
function withCursor(
  result: ReadResult,
  capped: { truncated?: boolean; totalLines?: number; lastLine?: number; spanStart?: number },
  root: string,
): ReadResult {
  if (!capped.truncated || capped.totalLines === undefined) return result;
  if (capped.lastLine !== undefined && capped.spanStart !== undefined) {
    return {
      ...result,
      truncated: true,
      totalLines: capped.totalLines,
      spanEnd: capped.lastLine,
      next: nextSpanPage(result.path, root, capped.spanStart, result.lineEnd, capped.lastLine),
    };
  }
  return {
    ...result,
    truncated: true,
    totalLines: capped.totalLines,
    next: nextPage(result.path, root, result.lineEnd, capped.lastLine ?? capped.totalLines),
  };
}

/**
 * Cut a span at `cap` lines from `from` (its start, unless a paged cursor
 * resumes it further in). `lastLine` is where the span ends, so a `next=`
 * cursor never pages past it; `totalLines` is the whole span's line count,
 * the same on every page. With no cap, or a remainder that fits, nothing is
 * cut.
 *
 * The end is clamped to EOF first: a stale graph span that could not be
 * re-anchored can claim lines the file no longer has, and an unclamped end
 * would report `truncated` with a cursor that pages past the last line.
 */
export function capSpan(
  lines: string[], start: number, rawEnd: number, cap?: number, from: number = start,
): { content: string; lineStart: number; lineEnd: number; truncated?: boolean; totalLines?: number; lastLine?: number; spanStart?: number } {
  const end = Math.max(start, Math.min(rawEnd, lines.length));
  const first = Math.min(Math.max(from, start), end);
  if (cap !== undefined && end - first + 1 > cap) {
    const shownEnd = first + cap - 1;
    return {
      content: lines.slice(first - 1, shownEnd).join("\n"),
      lineStart: first,
      lineEnd: shownEnd,
      truncated: true,
      totalLines: end - start + 1,
      lastLine: end,
      spanStart: start,
    };
  }
  return { content: lines.slice(first - 1, end).join("\n"), lineStart: first, lineEnd: end };
}

/**
 * Read a file target: the whole file (capped), a typed `path:a-b` range
 * (never capped), or a paged `path:a-b@from` cursor (capped, inside a-b).
 */
function readFileTarget(
  filePath: string, start: number | undefined, end: number | undefined, pageFrom: number | undefined, cap: number | undefined,
): ReturnType<typeof capSpan> {
  if (pageFrom !== undefined && start !== undefined && end !== undefined) {
    const lines = fs.readFileSync(filePath, "utf-8").split("\n");
    return capSpan(lines, start, end, cap, pageFrom);
  }
  return readFileRange(filePath, start, end, cap);
}

/**
 * `ix read --format llm`.
 *
 * The one command whose payload is not records: an agent asked for source.
 * Everything around it goes — `text` pads a 4-column gutter and wraps it in
 * an ANSI dim escape — but the line numbers themselves stay, as a bare
 * `<n>\t` prefix in the shape `cat -n` taught every agent to read. Without
 * them the reader had `line_start` and a count, and to cite or edit line 312
 * it had to count lines by hand or read the file again with a tool that
 * numbers them; 23 of 31 benchmark reads were followed by exactly that.
 *
 * The `content lines=<n> numbered=true` record makes the block
 * self-delimiting, so a consumer knows exactly how many following lines are
 * payload and never has to guess whether a line of source is another record,
 * and says that each one carries a number to strip before the source.
 */
/**
 * The lines to show for a symbol. The graph's span is from the last ingest; in
 * a file edited since, it no longer covers the symbol -- `resolveMapRoot` read
 * as 36-46 while it sat at 38-48, and the read cut off its last two lines. A
 * stale file's span is re-anchored to where the name is declared on disk now
 * (`anchorSpan`, the same step edge sites use) and shifted with it. A fresh
 * file's span is used as recorded: there, the nearest declaration can be a
 * line below a recorded decorator, and moving to it would drop that line.
 */
export function symbolRange(
  lines: string[], name: string, lineStart: number, lineEnd: number | undefined, stale: boolean,
): { lineStart: number; lineEnd: number; movedFrom?: number } {
  const end = lineEnd ?? lines.length;
  if (!stale) return { lineStart, lineEnd: end };
  const span = anchorSpan(lines, bareName(name), lineStart, end);
  if (!span.anchored || span.start === lineStart) return { lineStart, lineEnd: end };
  return { lineStart: span.start, lineEnd: Math.min(span.end, lines.length), movedFrom: lineStart };
}

export function renderReadLlm(result: ReadResult): string[] {
  const contentLines = result.content.split("\n");
  return [
    llmLine("file", [
      ["path", relativePath(result.path) ?? result.path],
      ["line_start", String(result.lineStart)],
      ["line_end", String(result.lineEnd)],
      ["target", result.targetType],
      ["symbol", result.symbol],
      ["kind", result.kind],
      ["stale", result.stale ? "true" : null],
      // The three fields that make a capped read recoverable in one call.
      ["truncated", result.truncated ? "true" : null],
      ["total_lines", result.totalLines !== undefined ? String(result.totalLines) : null],
      ["span_end", result.spanEnd !== undefined ? String(result.spanEnd) : null],
      ["next", result.next],
    ]),
    llmLine("content", [["lines", String(contentLines.length)], ["numbered", "true"]]),
    ...contentLines.map((line, i) => `${result.lineStart + i}\t${line}`),
  ];
}

/** `ix read --format llm` when the target resolves to more than one thing. */
export function renderReadAmbiguityLlm(result: AmbiguityResult, target: string): string[] {
  const isFile = result.targetType === "ambiguous-file";
  const lines = [
    llmLine("ambiguous", [
      ["kind", isFile ? "file" : "symbol"],
      ["target", target],
      ["count", String(result.candidates.length)],
    ]),
  ];
  result.candidates.forEach((c, i) => {
    lines.push(llmLine("candidate", [
      ["n", String(i + 1)],
      ["name", c.name],
      ["kind", c.kind],
      ["path", c.path ? relativePath(c.path) ?? c.path : undefined],
      ["id", llmShortId(c.id)],
      ["container", c.container],
    ]));
  });
  lines.push(llmLine("hint", [[
    "text",
    isFile
      ? "Provide a more specific path to disambiguate."
      : disambiguationHint("Use --pick <n>, --kind, or --path to disambiguate."),
  ]]));
  for (const d of result.diagnostics ?? []) {
    lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
  }
  return lines;
}

// Exported for the tests: the `content lines=<n>` invariant is a property of
// render *composed with* print, not of either alone. Asserting on
// renderReadLlm's return value passes just as happily when printLlmLines drops
// the blank lines out from under the count.
export function outputResult(result: ReadResult, format: string): void {
  if (format === "llm") {
    printLlmLines(renderReadLlm(result));
  } else if (format === "json") {
    const out = { ...result, path: relativePath(result.path) ?? result.path };
    printJson(out);
  } else {
    if (result.stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix map to update.\n"));
    if (result.targetType === "symbol" || result.targetType === "filename-match") {
      stderr(chalk.dim(`  ${result.path}:${result.lineStart}-${result.lineEnd}\n`));
    }
    const lines = result.content.split("\n");
    for (let i = 0; i < lines.length; i++) {
      console.log(`${chalk.dim(String(result.lineStart + i).padStart(4))} ${lines[i]}`);
    }
    if (result.truncated) {
      stderr(chalk.dim(
        `\n  ${result.lineEnd - result.lineStart + 1} of ${result.totalLines} lines`
        + (result.next ? ` — next: ix read ${result.next}` : "")
        + (result.targetType === "symbol"
          ? ", or --all for the whole symbol"
          : result.spanEnd !== undefined
            // A cursor page starts at its @from, and so does --all on it.
            ? ", or --all for the rest of the range"
            : ", or --all for the whole file"),
      ));
    }
  }
}

function outputAmbiguity(result: AmbiguityResult, target: string, format: string): void {
  if (format === "llm") {
    printLlmLines(renderReadAmbiguityLlm(result, target));
  } else if (format === "json") {
    printJson(result);
  } else {
    const label = result.targetType === "ambiguous-file" ? "file" : "symbol";
    stderr(`Ambiguous ${label} "${target}":`);
    for (let i = 0; i < result.candidates.length; i++) {
      const c = result.candidates[i];
      const kindStr = c.kind ? chalk.cyan(c.kind.padEnd(10)) : "";
      const pathStr = c.path ? chalk.dim(` ${c.path}`) : "";
      const idStr = c.id ? chalk.dim(` ${c.id.slice(0, 8)}`) : "";
      const containerStr = c.container ? `  ${c.container}` : "";
      stderr(`  ${i + 1}. ${kindStr}${idStr}  ${c.name}${containerStr}${pathStr}`);
    }
    if (result.targetType === "ambiguous-file") {
      stderr(chalk.dim("\nProvide a more specific path to disambiguate."));
    } else {
      stderr(chalk.dim("\nUse --pick <n>, --kind, or --path to disambiguate."));
    }
  }
}

export function registerReadCommand(program: Command): void {
  program
    .command("read <target>")
    .description("Read raw file content, line ranges, or symbol source code")
    .option("--format <fmt>", "Output format (text|json|llm)", "text")
    .option("--kind <kind>", "Filter symbol by kind")
    .option("--path <path>", "Restrict to symbols from files matching this path substring")
    .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
    .option("--root <dir>", "Workspace root directory")
    .option("--all", `Read the whole file or symbol, past the ${READ_LINE_CAP}-line default cap`)
    .addHelpText("after", `\nResolution order:
  1. Exact file path          ix read src/main.ts
  2. File path with line range ix read src/main.ts:10-50
     (a capped read's next= cursor, path:10-1327@410, pages within 10-1327)
  3. Unique filename match     ix read Node.scala
  4. Unique symbol match       ix read IngestionService
  5. Ambiguity candidates      (prompted to disambiguate)

Examples:
  ix read src/cli/commands/read.ts
  ix read Node.scala
  ix read Node.scala:30-50
  ix read IngestionService
  ix read ingestFile --kind method
  ix read verify_token --path auth`)
    .action(async (target: string, opts: { format: string; kind?: string; path?: string; pick?: number; root?: string; all?: boolean }) => {
      // A range the caller typed is theirs; a whole file is capped unless they
      // say otherwise.
      const cap = opts.all ? undefined : READ_LINE_CAP;
      const root = resolveWorkspaceRoot(opts.root);
      const client = createClient();

      // --- Step 1: Parse line range if present ---
      // `path:a-b` is a range the caller typed. `path:a-b@from` is a paged
      // cursor (what a capped symbol read hands back as next=): lines a-b,
      // read from `from` and capped like a whole file.
      const lineRangeMatch = target.match(/^(.+?):(\d+)-(\d+)(?:@(\d+))?$/);
      const rawTarget = lineRangeMatch ? lineRangeMatch[1] : target;
      const rangeStart = lineRangeMatch ? parseInt(lineRangeMatch[2], 10) : undefined;
      const rangeEnd = lineRangeMatch ? parseInt(lineRangeMatch[3], 10) : undefined;
      const pageFrom = lineRangeMatch?.[4] !== undefined ? parseInt(lineRangeMatch[4], 10) : undefined;
      if (rangeStart !== undefined && rangeEnd !== undefined && (rangeStart < 1 || rangeEnd < rangeStart)) {
        reportInvalidLineRange(target, opts.format, pageFrom !== undefined);
        return;
      }
      if (pageFrom !== undefined && rangeStart !== undefined && rangeEnd !== undefined
        && (pageFrom < rangeStart || pageFrom > rangeEnd)) {
        reportInvalidLineRange(target, opts.format, true);
        return;
      }

      // --- Step 2: Try exact file path ---
      const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(root, rawTarget);
      // A path-shaped target is checked before it is stat'ed: refusing only
      // the paths that exist told a caller which files exist outside the
      // workspace. A bare name resolves inside the root and passes.
      if (/[\\/]/.test(rawTarget) && !guardReadable(resolvedPath, opts.root, "file", opts.format)) return;
      if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {
        if (!guardReadable(resolvedPath, opts.root, "file", opts.format)) return;
        const stale = checkStale(resolvedPath);
        const capped = readFileTarget(resolvedPath, rangeStart, rangeEnd, pageFrom, cap);
        const result: ReadResult = withCursor({
          targetType: lineRangeMatch ? "file-range" : "file",
          path: resolvedPath,
          lineStart: capped.lineStart,
          lineEnd: capped.lineEnd,
          content: capped.content,
        }, capped, root);
        if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }
        outputResult(result, opts.format);
        return;
      }

      // --- Step 3: Try unique filename match (always, not just file-like targets) ---
      // read should prefer resolving to a real file before trying symbol match.
      // e.g. "ix read Node" should find Node.scala before trying symbol resolution.
      //
      // C-3 also asked for the reverse on an extension-less target — symbol
      // before filename, because `ix read config` means the symbol far more
      // often than the file. It is NOT done here: the only way to know a
      // symbol exists is to ask, and `read-local-first.test.ts` guarantees
      // zero round trips for exactly this case, after a measured 60-80s
      // incident. The line cap below removes the cost that motivated the flip
      // (a whole file is now 400 lines with a cursor, not 20-53k tokens), so
      // the remaining question is precision, and it is worth one explicit
      // decision rather than a quiet change here.
      {
        const filenameMatches = await tryFilenameMatch(client, rawTarget, root);
        if (filenameMatches.length === 1) {
          const matchPath = filenameMatches[0].path;
          if (matchPath && fs.existsSync(matchPath)) {
            // The path came back from the graph rather than the caller, so this
            // guard is what stops a backend from naming a file off the disk.
            if (!guardReadable(matchPath, opts.root, "graph file match", opts.format)) return;
            const stale = checkStale(matchPath);
            const capped = readFileTarget(matchPath, rangeStart, rangeEnd, pageFrom, cap);
            const result: ReadResult = withCursor({
              targetType: "filename-match",
              path: matchPath,
              lineStart: capped.lineStart,
              lineEnd: capped.lineEnd,
              content: capped.content,
            }, capped, root);
            if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }
            outputResult(result, opts.format);
            return;
          }
        }
        if (filenameMatches.length > 1) {
          outputAmbiguity({
            targetType: "ambiguous-file",
            candidates: filenameMatches.map((m, i) => ({ name: m.name, path: m.path, rank: i + 1 })),
            diagnostics: [{ code: "ambiguous_resolution", message: "Provide a more specific path to disambiguate." }],
          }, target, opts.format);
          return;
        }
        // No filename match — fall through to symbol resolution
      }

      // --- Step 4: Try unique symbol match ---
      const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick, format: opts.format });
      if (symbolResult.type === "resolved") {
        const { node, sourceUri } = symbolResult;
        // sourceUri coming from the graph is workspace-relative under the
        // client-agnostic backend. Resolve it against the active workspace
        // root before any fs call.
        const absSourceUri = sourceUri ? absoluteFromSourceUri(sourceUri, opts.root) : null;
        const stale = absSourceUri ? checkStale(absSourceUri) : false;

        // If the source file exists, extract the symbol's lines
        if (absSourceUri && fs.existsSync(absSourceUri)) {
          // absoluteFromSourceUri passes an already-absolute source_uri through
          // untouched, so a graph row can still point anywhere on the disk.
          if (!guardReadable(absSourceUri, opts.root, "symbol source", opts.format)) return;
          const fileContent = fs.readFileSync(absSourceUri, "utf-8");
          const allLines = fileContent.split("\n");
          const range = symbolRange(
            allLines, node.name,
            node.attrs?.lineStart ?? node.attrs?.line_start ?? 1,
            node.attrs?.lineEnd ?? node.attrs?.line_end,
            stale,
          );
          const span = capSpan(allLines, range.lineStart, range.lineEnd, cap);
          const result: ReadResult = withCursor({
            targetType: "symbol",
            path: absSourceUri,
            lineStart: span.lineStart,
            lineEnd: span.lineEnd,
            content: span.content,
            symbol: node.name,
            kind: node.kind,
          }, span, root);
          if (stale) {
            result.stale = true;
            result.warning = range.movedFrom
              ? `The file has changed since the last ingest; ${node.name} was found at ${range.lineStart} on disk, not ${range.movedFrom} as the graph recorded. Lines added inside it since are not shown.`
              : "Results may be stale; file has changed since last ingest.";
          }
          outputResult(result, opts.format);
          return;
        }

        // No source file — try attrs.content
        const attrContent = node.attrs?.content;
        if (attrContent) {
          const lines = String(attrContent).split("\n");
          // Deliberately uncapped: there is no file on disk to page, so a cap
          // would drop lines 401+ with no cursor and no way to recover them
          // (the MCP tool has no --all).
          const result: ReadResult = {
            targetType: "symbol",
            path: absSourceUri ?? sourceUri ?? "(no source file)",
            lineStart: 1,
            lineEnd: lines.length,
            content: String(attrContent),
            symbol: node.name,
            kind: node.kind,
          };
          if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }
          outputResult(result, opts.format);
          return;
        }

        stderr(`Source file not found for symbol: ${node.name} (${absSourceUri ?? sourceUri ?? "no provenance"})`);
        return;
      }

      if (symbolResult.type === "ambiguous") {
        outputAmbiguity({
          targetType: "ambiguous-symbol",
          candidates: symbolResult.candidates.map((c, i) => ({ ...c, rank: i + 1 })),
          diagnostics: [{ code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") }],
        }, target, opts.format);
        return;
      }

      reportUnresolvedTarget(target, opts.format);
    });
}

/**
 * Search the graph for file nodes whose name matches the target filename.
 * Tries multiple search strategies to find files even when the bare name
 * is ambiguous or crowded out by other results.
 */
async function tryFilenameMatch(
  client: IxClient,
  target: string,
  root: string
): Promise<Array<{ name: string; path: string }>> {
  const basename = path.basename(target);
  const hasExtension = path.extname(basename) !== "";

  // Strategy 0: the workspace itself. `read` can only display a file that
  // exists locally — every graph result below is re-checked with `existsSync`
  // and dropped when it is missing — so disk is the authority here, not a cache
  // of the backend. It answers in milliseconds against seconds, and reaching it
  // before `ensureReadScope` also skips that call's scope lookup, which is its
  // own ~1.5 s on a large graph.
  const local = findLocalBasenameMatches(root, basename);
  if (local.paths.length > 0) {
    return local.paths.map(p => ({ name: path.basename(p), path: p }));
  }

  // An extension-less target with no local file of that basename is not a
  // filename in this workspace, and the graph cannot say otherwise: `ix map`'s
  // IGNORE_DIRS is a strict superset of the walk's, so every file the graph
  // holds for this workspace is a file the walk visited. Asking the backend
  // anyway costs ~8 s of `kind: file` search that returns empty every time.
  // Targets that DO carry an extension still go to the graph, which is what
  // answers `ix read Node.scala` for a file that is ingested but not checked out.
  if (!hasExtension && local.exhaustive) return [];

  // Scope to the active workspace / co-ingest system / Path-2 stitched system.
  await ensureReadScope(client);
  const scope = activeReadScope();

  // Strategy 1: Search with the exact target (may include extension)
  let nodes = await client.search(basename, { limit: 20, kind: "file", ...scope });

  // Strategy 2: If bare name (no extension), also search with common extensions
  // to avoid being crowded out by unrelated results — a bare `upgrade` search
  // is a substring match, and on a large graph the file actually called
  // `upgrade.ts` does not survive the backend's LIMIT.
  //
  // Gated on `local.exhaustive`, and that gate is the whole point. These nine
  // searches are fired concurrently, and nine concurrent unindexed scans do not
  // cost what one costs: measured on a 1.16M-node graph they take ~54 s EACH
  // rather than ~10 s, because they contend for the same collection. For a
  // symbol like `registerUpgradeCommand` all nine return empty, and `ix read`
  // spent 60-80 s before reaching the symbol lookup that answers it.
  //
  // When the walk above completed, "no local file has this basename" is proven,
  // and a graph hit could not be displayed anyway. Only when the walk ran out
  // of budget is the question still open, and then the fallback still runs.
  if (!hasExtension && !filterMatches(nodes, basename).length) {
    const extensions = [".scala", ".ts", ".tsx", ".py", ".rs", ".go", ".java", ".js", ".md"];
    const perExt = await Promise.all(
      extensions.map(ext =>
        client.search(basename + ext, { limit: 5, kind: "file", ...scope })
          .then(r => (filterMatches(r, basename).length ? r : []))
          .catch(() => [] as any[])),
    );
    const merged = perExt.flat();
    if (merged.length) nodes = [...merged, ...nodes];
  }

  const matches = filterMatches(nodes, basename);

  // Deduplicate by path
  const seen = new Set<string>();
  return matches.filter(m => {
    if (seen.has(m.path)) return false;
    seen.add(m.path);
    return true;
  });
}

interface LocalMatches {
  paths: string[];
  /** False when the budget ran out, i.e. "no match" is not a proven answer. */
  exhaustive: boolean;
}

/**
 * Find files in the workspace whose basename matches `target`, on disk.
 *
 * `read` can only ever *display* a file that exists locally — the graph branch
 * below re-checks `existsSync` on whatever path the backend hands back and
 * falls through when it is missing. So the filesystem is not a shortcut here,
 * it is the authority, and it answers in milliseconds where the graph takes
 * seconds.
 *
 * Returns `exhaustive: false` if the entry budget ran out. A negative answer is
 * only trustworthy when the whole workspace was walked, and the caller uses
 * that distinction to decide whether it may skip the backend fallback.
 */
function findLocalBasenameMatches(root: string, target: string, limit = 25): LocalMatches {
  const matches = basenameMatcher(target);
  const paths: string[] = [];
  const stack = [root];
  let budget = WALK_ENTRY_BUDGET;

  while (stack.length > 0 && paths.length < limit) {
    const current = stack.pop()!;
    let entries: fs.Dirent[];
    try {
      entries = fs.readdirSync(current, { withFileTypes: true });
    } catch {
      continue; // unreadable directory is not an error for a lookup
    }
    for (const entry of entries) {
      if (--budget <= 0) return { paths, exhaustive: false };
      if (entry.isDirectory()) {
        if (entry.name.startsWith(".") || WALK_IGNORE_DIRS.has(entry.name)) continue;
        stack.push(path.join(current, entry.name));
        continue;
      }
      if (!entry.isFile()) continue; // symlinks are not followed
      if (matches(entry.name)) {
        paths.push(path.join(current, entry.name));
        if (paths.length >= limit) return { paths, exhaustive: true };
      }
    }
  }
  return { paths, exhaustive: stack.length === 0 };
}

/** Filter nodes to those whose filename actually matches the target basename. */
function filterMatches(
  nodes: any[],
  basename: string
): Array<{ name: string; path: string }> {
  const basenameNoExt = basename.replace(/\.[^.]+$/, "");
  const results: Array<{ name: string; path: string }> = [];

  for (const n of nodes) {
    const name: string = n.name || "";
    const nameNoExt = name.replace(/\.[^.]+$/, "");
    const uri: string = n.provenance?.sourceUri ?? n.provenance?.source_uri ?? "";

    if (
      name === basename ||                 // exact: Node.scala === Node.scala
      nameNoExt === basename ||            // bare name: Node === Node (from Node.scala)
      nameNoExt === basenameNoExt ||       // both stripped: Node === Node
      name.endsWith(`/${basename}`) ||
      uri.endsWith(`/${basename}`) || uri.endsWith(`/${basename}`)
    ) {
      results.push({ name: name || basename, path: uri });
    }
  }

  return results;
}

type SymbolResult =
  | { type: "resolved"; node: any; sourceUri: string | null }
  | { type: "ambiguous"; candidates: Array<{ name: string; kind?: string; path?: string; id?: string; container?: string }> }
  | { type: "not-found" };

/**
 * Search the graph for a symbol using the shared scored resolver.
 * read prefers file/structural entities (class, object, file) before methods/functions.
 *
 * Calls resolveEntityFull once to avoid duplicate ambiguity output.
 */
async function trySymbolMatch(
  client: IxClient,
  symbol: string,
  opts: { kind?: string; path?: string; pick?: number; format?: string }
): Promise<SymbolResult> {
  const preferredKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method", "constant"];
  const full = await resolveEntityFull(client, symbol, preferredKinds, opts);

  if (full.resolved) {
    if (full.notices?.length) reportResolutionNotices(full.notices, opts.format, opts);
    const details = await client.entity(full.entity.id);
    const fullNode = details.node as any;
    const sourceUri = fullNode.provenance?.source_uri ?? fullNode.provenance?.sourceUri ?? null;
    return { type: "resolved", node: fullNode, sourceUri };
  }

  if (full.ambiguous) {
    return {
      type: "ambiguous",
      candidates: full.result.candidates.map(c => ({
        name: c.name, kind: c.kind, path: c.path, id: c.id,
        ...(c.container ? { container: c.container } : {}),
      })),
    };
  }

  return { type: "not-found" };
}