/**
 * Local Backend (Multi-Repo)
 *
 * Provides tool implementations using local .gitnexus/ indexes.
 * Supports multiple indexed repositories via a global registry.
 * LadybugDB connections are opened lazily per repo on first query.
 */

import fs from 'fs/promises';
import path from 'path';
import { createHash } from 'crypto';
import {
  initLbug,
  executeQuery,
  executeParameterized,
  closeLbug,
  isLbugReady,
} from '../../core/lbug/pool-adapter.js';
import { isValidQueryParams } from '../../core/lbug/query-params.js';
import { isWalCorruptionError, WAL_RECOVERY_SUGGESTION } from '../../core/lbug/lbug-config.js';
// Embedding imports are lazy (dynamic import) to avoid loading onnxruntime-node
// at MCP server startup — crashes on unsupported Node ABI versions (#89)
// git utilities available if needed
// import { isGitRepo, getCurrentCommit, getGitRoot } from '../../storage/git.js';
import {
  parseDiffHunks,
  getCanonicalRepoRoot,
  getGitRoot,
  type FileDiff,
} from '../../storage/git.js';
import { realpathSync } from 'fs';
import {
  listRegisteredRepos,
  cleanupOldKuzuFiles,
  canonicalizePath,
  RegistryAmbiguousTargetError,
  type RegistryEntry,
} from '../../storage/repo-manager.js';
import { GroupService, type GroupToolPort } from '../../core/group/service.js';
import { resolveAtGroupMemberRepoPath } from '../../core/group/resolve-at-member.js';
import { collectBestChunks } from '../../core/embeddings/types.js';
import {
  rankExactEmbeddingRows,
  type ExactEmbeddingRow,
} from '../../core/embeddings/exact-search.js';
import { EMBEDDING_TABLE_NAME, EMBEDDING_INDEX_NAME } from '../../core/lbug/schema.js';
import {
  getExactScanLimit,
  isVectorExtensionSupportedByPlatform,
} from '../../core/platform/capabilities.js';
import { PhaseTimer } from '../../core/search/phase-timer.js';
import { checkStalenessAsync, checkCwdMatch } from '../../core/git-staleness.js';
import { logger } from '../../core/logger.js';
// AI context generation is CLI-only (gitnexus analyze)
// import { generateAIContextFiles } from '../../cli/ai-context.js';

/**
 * Quick test-file detection for filtering impact results.
 * Matches common test file patterns across all supported languages.
 */
export function isTestFilePath(filePath: string): boolean {
  const p = filePath.toLowerCase().replace(/\\/g, '/');
  return (
    p.includes('.test.') ||
    p.includes('.spec.') ||
    p.includes('__tests__/') ||
    p.includes('__mocks__/') ||
    p.includes('/test/') ||
    p.includes('/tests/') ||
    p.includes('/testing/') ||
    p.includes('/fixtures/') ||
    p.endsWith('_test.go') ||
    p.endsWith('_test.py') ||
    p.endsWith('_spec.rb') ||
    p.endsWith('_test.rb') ||
    p.includes('/spec/') ||
    p.includes('/test_') ||
    p.includes('/conftest.')
  );
}

/** Valid LadybugDB node labels for safe Cypher query construction */
export const VALID_NODE_LABELS = new Set([
  'File',
  'Folder',
  'Function',
  'Class',
  'Interface',
  'Method',
  'CodeElement',
  'Community',
  'Process',
  'Struct',
  'Enum',
  'Macro',
  'Typedef',
  'Union',
  'Namespace',
  'Trait',
  'Impl',
  'TypeAlias',
  'Const',
  'Static',
  'Property',
  'Record',
  'Delegate',
  'Annotation',
  'Constructor',
  'Template',
  'Module',
  'Route',
  'Tool',
]);

/** Valid relation types for impact analysis filtering */
export const VALID_RELATION_TYPES = new Set([
  'CALLS',
  'IMPORTS',
  'EXTENDS',
  'IMPLEMENTS',
  'HAS_METHOD',
  'HAS_PROPERTY',
  'METHOD_OVERRIDES',
  'OVERRIDES', // Legacy alias — dual-read for pre-rename indexes
  'METHOD_IMPLEMENTS',
  'ACCESSES',
  'HANDLES_ROUTE',
  'FETCHES',
  'HANDLES_TOOL',
  'ENTRY_POINT_OF',
  'WRAPS',
]);

/**
 * Per-relation-type confidence floor for impact analysis.
 *
 * When the graph stores a relation with a confidence value, that stored
 * value is used as-is (it reflects resolution-tier accuracy from analysis
 * time).  This map provides the floor for each edge type when no stored
 * confidence is available, and is also used for display / tooltip hints.
 *
 * Rationale:
 *   CALLS / IMPORTS  – direct, strongly-typed references → 0.9
 *   EXTENDS          – class hierarchy, statically verifiable → 0.85
 *   IMPLEMENTS       – interface contract, statically verifiable → 0.85
 *   METHOD_OVERRIDES  – method override, statically verifiable → 0.85
 *   METHOD_IMPLEMENTS – interface method implementation, statically verifiable → 0.85
 *   HAS_METHOD       – structural containment → 0.95
 *   HAS_PROPERTY     – structural containment → 0.95
 *   ACCESSES         – field read/write, may be indirect → 0.8
 *   CONTAINS         – folder/file containment → 0.95
 *   (unknown type)   – conservative fallback → 0.5
 */
export const IMPACT_RELATION_CONFIDENCE: Readonly<Record<string, number>> = {
  CALLS: 0.9,
  IMPORTS: 0.9,
  EXTENDS: 0.85,
  IMPLEMENTS: 0.85,
  METHOD_OVERRIDES: 0.85,
  METHOD_IMPLEMENTS: 0.85,
  HAS_METHOD: 0.95,
  HAS_PROPERTY: 0.95,
  ACCESSES: 0.8,
  CONTAINS: 0.95,
};

/**
 * Return the confidence floor for a given relation type.
 * Falls back to 0.5 for unknown types so they are not silently elevated.
 */
const confidenceForRelType = (relType: string | undefined): number =>
  IMPACT_RELATION_CONFIDENCE[relType ?? ''] ?? 0.5;

/** Structured error logging for query failures — replaces empty catch blocks */
function logQueryError(context: string, err: unknown): void {
  const msg = err instanceof Error ? err.message : String(err);
  logger.error({ context, err: msg }, 'GitNexus query failed');
}

const isReadOnlyDbError = (err: unknown): boolean => {
  // Walk the `cause` chain (bounded) so a wrapped read-only error (e.g. the
  // pool adapter's `{ cause }` wrapper) is still detected here — this is the
  // copy the MCP cypher handler uses to surface its curated read-only message
  // (#2068 follow-up). Mirrors lbug-adapter's isReadOnlyDbError.
  let cur: unknown = err;
  for (let depth = 0; depth < 5 && cur != null; depth++) {
    const msg = cur instanceof Error ? cur.message : String(cur);
    if (/read-only database/i.test(msg)) return true;
    cur = cur instanceof Error ? (cur as { cause?: unknown }).cause : undefined;
  }
  return false;
};

/**
 * Per-query latency telemetry for production aggregation (#553).
 *
 * Logged at `debug` level — timing is observability/telemetry, not an
 * error. Operators wanting per-query timing set `GITNEXUS_LOG_LEVEL=debug`
 * (or equivalent). Emitting at `error` level (the original migration
 * artifact) caused alerting rules to fire on every successful query and
 * inflated stderr noise for every MCP/CLI invocation.
 *
 * Emitted via the project logger which routes to stderr — never stdout —
 * because the MCP stdio transport uses stdout exclusively for JSON-RPC
 * responses (#324) and the CLI e2e test `tool output goes to stdout via
 * fd 1` asserts stdout parses cleanly as JSON.
 */
function logQueryTiming(query: string, phases: Record<string, number>): void {
  const totalMs = phases.wall ?? Object.values(phases).reduce((a, b) => a + b, 0);
  const truncated = query.length > 80 ? `${query.slice(0, 80)}…` : query;
  logger.debug({ query: truncated, totalMs, phases }, 'GitNexus query timing');
}

export interface CodebaseContext {
  projectName: string;
  stats: {
    fileCount: number;
    functionCount: number;
    communityCount: number;
    processCount: number;
  };
}

interface RepoHandle {
  id: string; // unique key = repo name (basename)
  name: string;
  repoPath: string;
  storagePath: string;
  lbugPath: string;
  indexedAt: string;
  lastCommit: string;
  remoteUrl?: string;
  stats?: RegistryEntry['stats'];
}

/** Resolve symlinks for path comparison; falls back to path.resolve on error.
 * Uses `realpathSync.native` (not the pure-JS `realpathSync`) so that Windows
 * 8.3 short names (e.g. RUNNER~1 → runneradmin) are expanded to long form,
 * matching the output of `git rev-parse --show-toplevel`. */
function tryRealpath(p: string): string {
  try {
    return realpathSync.native(p);
  } catch {
    return path.resolve(p);
  }
}

/**
 * Resolve the git diff cwd for detect_changes, auto-detecting linked worktrees.
 *
 * When `launchCwd` is a linked worktree of the same canonical repository as
 * `repoPath` (i.e. `getGitRoot(launchCwd)` differs from `repoPath` but both
 * share the same `getCanonicalRepoRoot`), returns the worktree's git root so
 * that `git diff` sees the correct working directory and index.
 *
 * Returns `repoPath` unchanged in all other cases (non-worktree, git
 * unavailable, unrelated repo).
 *
 * Extracted as a module-level export so tests can pass any `launchCwd` instead
 * of relying on `process.cwd()`, which is fixed to the server launch directory
 * and cannot be changed mid-process.
 */
export function resolveWorktreeCwd(repoPath: string, launchCwd: string): string {
  try {
    // Verify repoPath is a git root before comparing against its canonical
    // root. If getGitRoot returns a different path, repoPath is an arbitrary
    // subdirectory — skip both the linked-worktree guard and auto-detection
    // and fall through to the repoPath fallback.
    const repoGitRoot = getGitRoot(repoPath);
    const repoCanonical =
      repoGitRoot && tryRealpath(repoGitRoot) === tryRealpath(repoPath)
        ? getCanonicalRepoRoot(repoPath)
        : null;

    // Early exit: if repoPath is a linked worktree (differs from its canonical
    // main-checkout root), return it unchanged. Do NOT override it with the
    // server's launch directory — that would silently replace the explicitly-
    // resolved worktree index with the main checkout.
    //
    // getCanonicalRepoRoot returns the main-checkout path for both the checkout
    // and all linked worktrees:
    //   repoPath === canonical → main checkout (auto-detect may fire below)
    //   repoPath !== canonical → linked worktree (return as-is)
    if (repoCanonical && tryRealpath(repoPath) !== tryRealpath(repoCanonical)) {
      return repoPath;
    }

    const launchGitRoot = getGitRoot(launchCwd);
    if (launchGitRoot) {
      // Normalise via realpathSync before comparing so macOS /var → /private/var
      // symlinks (and Windows 8.3 short names) don't create false mismatches.
      const realLaunch = tryRealpath(launchGitRoot);
      const realRepo = tryRealpath(repoPath);
      if (realLaunch !== realRepo) {
        const launchCanonical = getCanonicalRepoRoot(launchCwd);
        // Use tryRealpath on both canonical values for cross-platform safety.
        if (
          launchCanonical &&
          repoCanonical &&
          tryRealpath(launchCanonical) === tryRealpath(repoCanonical)
        ) {
          return launchGitRoot;
        }
      }
    }
  } catch {
    // Best-effort; fall through to repoPath.
  }
  return repoPath;
}

/**
 * Length of the path-derived suffix appended to a colliding repo id.
 * Exported so tests can pin the suffix shape without re-deriving the
 * literal; see `assignRepoId()` and the hashed-id resolution tier (#1658).
 *
 * Note: base64url is an *encoding*, not a hash — it preserves byte order, so
 * two paths that share a long common prefix (sibling clones under one parent)
 * collapse to the same sliced suffix. `assignRepoId()` keeps the legacy
 * base64url suffix only for the first colliding duplicate (id compatibility)
 * and falls back to a content hash of the resolved path on a real collision
 * (#2054).
 */
export const REPO_ID_HASH_LENGTH = 6;

interface ImpactParams {
  target: string;
  target_uid?: string;
  file_path?: string;
  kind?: string;
  direction: 'upstream' | 'downstream';
  maxDepth?: number;
  relationTypes?: string[];
  includeTests?: boolean;
  minConfidence?: number;
  limit?: number;
  offset?: number;
  summaryOnly?: boolean;
}

export class LocalBackend {
  private repos: Map<string, RepoHandle> = new Map();
  private contextCache: Map<string, CodebaseContext> = new Map();
  private initializedRepos: Set<string> = new Set();
  private reinitPromises: Map<string, Promise<void>> = new Map();
  private lastStalenessCheck: Map<string, number> = new Map();
  private groupToolSvc: GroupService | null = null;
  /**
   * One-shot stderr warnings for sibling-clone drift, keyed by
   * `${repoId}|${cwdGitRoot}`. Without this guard every tool call
   * from inside a sibling clone would print the same warning,
   * making MCP stderr unreadable.
   */
  private warnedSiblingDrift: Set<string> = new Set();

  /**
   * One-shot stderr warning for the VECTOR-extension fallback. Without this
   * guard the diagnostic would fire on every `semanticSearch()` call on
   * platforms where the extension is unsupported (e.g. Windows), making MCP
   * stderr noisy per DoD §2.8.
   */
  private warnedVectorUnsupported = false;

  /**
   * Cross-repo group tools (CLI). Shares logic with MCP `group_*` handlers.
   */
  getGroupService(): GroupService {
    if (!this.groupToolSvc) {
      const port: GroupToolPort = {
        resolveRepo: (p) => this.resolveRepo(p),
        impact: (r, p) => this.impact(r as RepoHandle, p),
        query: (r, p) => this.query(r as RepoHandle, p),
        impactByUid: (id, uid, d, o) => this.impactByUid(id, uid, d, o),
        context: (r, p) => this.context(r as RepoHandle, p),
      };
      this.groupToolSvc = new GroupService(port);
    }
    return this.groupToolSvc;
  }

  /** Close all pooled LadybugDB connections (CLI one-shot; optional for long-lived MCP). */
  async dispose(): Promise<void> {
    await closeLbug();
  }

  // ─── Initialization ──────────────────────────────────────────────

  /**
   * Initialize from the global registry.
   * Returns true if at least one repo is available.
   */
  async init(): Promise<boolean> {
    await this.refreshRepos();
    return this.repos.size > 0;
  }

  /**
   * Re-read the global registry and update the in-memory repo map.
   * New repos are added, existing repos are updated, removed repos are pruned.
   * LadybugDB connections for removed repos are NOT closed (they idle-timeout naturally).
   */
  private async refreshRepos(): Promise<void> {
    const entries = await listRegisteredRepos({ validate: true });

    // Build the next map from scratch and swap it in atomically. Mutating the
    // live map in place let stale entries influence fresh id assignment: a
    // bare-name id, once handed to the first registry entry, stuck to it across
    // refreshes and reorders, and colliding path suffixes silently overwrote
    // each other so sibling clones disappeared from `list_repos` (#2054).
    const nextRepos = new Map<string, RepoHandle>();
    const nextContext = new Map<string, CodebaseContext>();
    const assigned = new Map<string, string>(); // id -> resolved repo path

    // Assign ids over a path-sorted view so a registered clone always gets the
    // same id regardless of the registry's on-disk order: the bare name and
    // each path-derived suffix become a pure function of the resolved-path set,
    // not of iteration order, so a memorized id can't drift to a different
    // clone after a registry reorder (#2067 follow-up).
    const ordered = [...entries].sort((a, b) => {
      const ra = path.resolve(a.path);
      const rb = path.resolve(b.path);
      return ra < rb ? -1 : ra > rb ? 1 : 0;
    });

    for (const entry of ordered) {
      // path.resolve (not canonicalizePath) matches the pre-#2054 collision
      // check and keeps refreshRepos free of mockable deps on the hot init
      // path. registerRepo writes path.resolve'd paths (not realpath), and
      // resolveRepoFromCache canonicalizes both sides when matching by path, so
      // keying id assignment on path.resolve here is consistent and correct.
      const resolved = path.resolve(entry.path);
      const id = this.assignRepoId(entry.name, entry.path, resolved, assigned);

      const storagePath = entry.storagePath;
      const lbugPath = path.join(storagePath, 'lbug');

      // Clean up any leftover KuzuDB files from before the LadybugDB migration.
      // If kuzu exists but lbug doesn't, warn so the user knows to re-analyze.
      const kuzu = await cleanupOldKuzuFiles(storagePath);
      if (kuzu.found && kuzu.needsReindex) {
        logger.error(
          `GitNexus: "${entry.name}" has a stale KuzuDB index. Run: gitnexus analyze ${entry.path}`,
        );
      }

      const handle: RepoHandle = {
        id,
        name: entry.name,
        repoPath: entry.path,
        storagePath,
        lbugPath,
        indexedAt: entry.indexedAt,
        lastCommit: entry.lastCommit,
        remoteUrl: entry.remoteUrl,
        stats: entry.stats,
      };

      nextRepos.set(id, handle);

      // Build lightweight context (no LadybugDB needed)
      const s = entry.stats || {};
      nextContext.set(id, {
        projectName: entry.name,
        stats: {
          fileCount: s.files || 0,
          functionCount: s.nodes || 0,
          communityCount: s.communities || 0,
          processCount: s.processes || 0,
        },
      });
    }

    // Prune per-clone pool state for databases that are no longer registered.
    // The LadybugDB pool and the init/staleness/reinit maps are keyed by the
    // immutable lbugPath (see ensureInitialized), so a repo id that merely
    // moves to a different clone needs NO eviction — distinct clones have
    // distinct lbugPaths and can never share a pool entry, which is what closes
    // the resolve→query wrong-clone window for good (#2067). Only a path that
    // dropped out of the registry must release its pooled connection + state.
    const liveLbugPaths = new Set([...nextRepos.values()].map((h) => h.lbugPath));
    for (const prev of this.repos.values()) {
      if (liveLbugPaths.has(prev.lbugPath)) continue;
      this.initializedRepos.delete(prev.lbugPath);
      this.lastStalenessCheck.delete(prev.lbugPath);
      this.reinitPromises.delete(prev.lbugPath);
      closeLbug(prev.lbugPath).catch(() => {});
    }

    this.repos = nextRepos;
    this.contextCache = nextContext;
  }

  /**
   * Assign a collision-free in-memory id for a registered repo.
   *
   * - Unique name → the bare lowercased name.
   * - Duplicate name → a path-derived suffix. The *first* colliding clone keeps
   *   the legacy `base64url(path)` suffix so ids generated before #2054 still
   *   resolve (the #1658 hashed-id tier). base64url is an encoding, not a hash:
   *   it preserves byte order, so sibling clones under one parent (e.g.
   *   `.../REPO_2` and `.../REPO_3`) yield identical leading characters and thus
   *   the same sliced suffix. Any further collision therefore falls back to a
   *   content hash of the *resolved* path (order-insensitive), extended
   *   deterministically until unique.
   *
   * `assigned` maps every id handed out in this refresh to its resolved path,
   * so a candidate is "free" when it is unused or already owned by this exact
   * path. This method records its own assignment into `assigned` before
   * returning, so the map-update is the function's invariant, not a caller
   * obligation. A returned id never overwrites a different path's handle (#2054).
   */
  private assignRepoId(
    name: string,
    repoPath: string,
    resolved: string,
    assigned: Map<string, string>,
  ): string {
    const base = name.toLowerCase();
    const free = (id: string): boolean => {
      const owner = assigned.get(id);
      return owner === undefined || owner === resolved;
    };
    // Record the assignment so subsequent entries in the same refresh see this
    // id as taken (the function owns its own invariant).
    const claim = (id: string): string => {
      assigned.set(id, resolved);
      return id;
    };

    if (free(base)) return claim(base);

    // Legacy suffix from the *raw* path — kept byte-for-byte so the first
    // colliding duplicate keeps the id it had before #2054 (#1658 tier).
    const legacy = `${base}-${Buffer.from(repoPath)
      .toString('base64url')
      .slice(0, REPO_ID_HASH_LENGTH)
      .toLowerCase()}`;
    if (free(legacy)) return claim(legacy);

    // Real collision — hash the resolved path. Lowercase hex survives the
    // `paramLower` lookup in resolveRepoFromCache.
    const digest = createHash('sha256').update(resolved).digest('hex');
    for (let len = REPO_ID_HASH_LENGTH; len <= digest.length; len++) {
      const candidate = `${base}-${digest.slice(0, len)}`;
      if (free(candidate)) return claim(candidate);
    }

    // Two distinct resolved paths sharing a full SHA-256 digest is a hash
    // break, not a runtime condition — fail loudly rather than silently
    // overwrite a different repo's handle (#2054 invariant).
    throw new Error(
      `GitNexus internal: unable to assign a unique repo id for "${name}" at ${repoPath}`,
    );
  }

  // ─── Repo Resolution ─────────────────────────────────────────────

  /**
   * Resolve which repo to use.
   * - If repoParam is given, match by name or path
   * - If only 1 repo, use it
   * - If 0 or multiple without param, throw with helpful message
   *
   * On a miss, re-reads the registry once in case a new repo was indexed
   * while the MCP server was running.
   */
  async resolveRepo(repoParam?: string): Promise<RepoHandle> {
    let refreshedAfterAmbiguity = false;
    let result: RepoHandle | null;
    try {
      result = this.resolveRepoFromCache(repoParam);
    } catch (err) {
      if (!(err instanceof RegistryAmbiguousTargetError)) throw err;
      // Stale in-memory duplicate siblings can linger after unregister; refresh
      // once before re-throwing so a resolved registry can disambiguate (#1658).
      await this.refreshRepos();
      refreshedAfterAmbiguity = true;
      result = this.resolveRepoFromCache(repoParam);
    }

    if (result) {
      // Issue: silent graph drift across sibling clones.
      // If the caller's cwd lives in a *different* on-disk clone of
      // the same repo (matched by `remoteUrl`), warn once per
      // (repo, cwd) pair on stderr. We do not fail or refuse to
      // serve — the index is still the best answer we have — but
      // the operator/agent has to know the answer may be stale.
      this.maybeWarnSiblingDrift(result).catch(() => {
        /* best-effort; never throw from resolveRepo */
      });
      return result;
    }

    // Miss — refresh registry and try once more (skip if already refreshed above)
    if (!refreshedAfterAmbiguity) {
      await this.refreshRepos();
    }
    const retried = this.resolveRepoFromCache(repoParam);
    if (retried) {
      this.maybeWarnSiblingDrift(retried).catch(() => {});
      return retried;
    }

    // Still no match — throw with helpful message
    if (this.repos.size === 0) {
      throw new Error('No indexed repositories. Run: gitnexus analyze');
    }

    // Build a disambiguated "Available: …" list (#829). When two handles
    // share a name, annotate each colliding label with its path so the
    // caller can actually pick the right one. Single-name entries render
    // identically to pre-#829 output.
    const nameCounts = new Map<string, number>();
    for (const h of this.repos.values()) {
      const key = h.name.toLowerCase();
      nameCounts.set(key, (nameCounts.get(key) ?? 0) + 1);
    }
    const labels = [...this.repos.values()].map((h) =>
      (nameCounts.get(h.name.toLowerCase()) ?? 0) > 1 ? `${h.name} (${h.repoPath})` : h.name,
    );

    if (repoParam) {
      throw new Error(`Repository "${repoParam}" not found. Available: ${labels.join(', ')}`);
    }
    throw new Error(
      `Multiple repositories indexed. Specify which one with the "repo" parameter. Available: ${labels.join(', ')}`,
    );
  }

  /**
   * Try to resolve a repo from the in-memory cache. Returns null on miss.
   * Throws {@link RegistryAmbiguousTargetError} when `repoParam` matches
   * multiple handles by name and cwd cannot disambiguate (#1658).
   */
  private resolveRepoFromCache(repoParam?: string): RepoHandle | null {
    if (this.repos.size === 0) return null;

    if (repoParam) {
      const paramLower = repoParam.toLowerCase();
      const looksLikePath =
        path.isAbsolute(repoParam) || repoParam.includes(path.sep) || repoParam.includes('/');

      const resolvePathMatch = (): RepoHandle | undefined => {
        const canonicalTarget = canonicalizePath(repoParam);
        return [...this.repos.values()].find((handle) => {
          const stored = canonicalizePath(handle.repoPath);
          return process.platform === 'win32'
            ? stored.toLowerCase() === canonicalTarget.toLowerCase()
            : stored === canonicalTarget;
        });
      };

      // Path-like params first (absolute or contains separators) — aligns with
      // resolveRegistryEntry (#829). Bare aliases such as ".tmp-repro-mini" must
      // not be resolved via path.resolve(cwd) before duplicate-name handling.
      if (looksLikePath) {
        const pathMatch = resolvePathMatch();
        if (pathMatch) return pathMatch;
      }

      // Exact name before id — the first duplicate sibling keeps id === name
      // (e.g. id "shared"), so a name lookup must not be captured by the id tier.
      const nameMatches = [...this.repos.values()].filter(
        (handle) => handle.name.toLowerCase() === paramLower,
      );
      if (nameMatches.length === 1) return nameMatches[0];
      if (nameMatches.length > 1) {
        const cwdPick = this.pickRepoHandleForCwd(nameMatches);
        if (cwdPick) return cwdPick;
        throw new RegistryAmbiguousTargetError(
          repoParam,
          nameMatches.map((h) => this.handleToRegistryEntry(h)),
        );
      }

      // Stable hashed id (e.g. "shared-abc123") from repoId() collision suffix
      if (this.repos.has(paramLower)) return this.repos.get(paramLower)!;

      // Bare name resolved as a cwd-relative path (e.g. "myrepo" against process.cwd()),
      // after name/id tiers. Path-like strings with separators were handled at the top.
      if (!looksLikePath) {
        const pathMatch = resolvePathMatch();
        if (pathMatch) return pathMatch;
      }

      // Partial name — only when unambiguous
      const partialMatches = [...this.repos.values()].filter((handle) =>
        handle.name.toLowerCase().includes(paramLower),
      );
      if (partialMatches.length === 1) return partialMatches[0];

      return null;
    }

    if (this.repos.size === 1) {
      return this.repos.values().next().value!;
    }

    return null; // Multiple repos, no param — ambiguous
  }

  /**
   * Prefer the indexed repo whose path matches the git root of process.cwd().
   *
   * In MCP stdio server mode, `process.cwd()` is the server's launch directory,
   * not the agent client's cwd. If the server was started from an unrelated
   * directory, `getGitRoot` returns null and duplicate-name resolution throws
   * {@link RegistryAmbiguousTargetError} — callers should pass an absolute path.
   */
  private pickRepoHandleForCwd(candidates: RepoHandle[]): RepoHandle | null {
    const cwdRoot = getGitRoot(process.cwd());
    if (!cwdRoot) return null;
    const canonicalCwd = canonicalizePath(cwdRoot);
    const cwdMatches = candidates.filter((handle) => {
      const stored = canonicalizePath(handle.repoPath);
      return process.platform === 'win32'
        ? stored.toLowerCase() === canonicalCwd.toLowerCase()
        : stored === canonicalCwd;
    });
    return cwdMatches.length === 1 ? cwdMatches[0] : null;
  }

  private handleToRegistryEntry(handle: RepoHandle): RegistryEntry {
    return {
      name: handle.name,
      path: handle.repoPath,
      storagePath: handle.storagePath,
      indexedAt: handle.indexedAt,
      lastCommit: handle.lastCommit,
      stats: handle.stats,
      remoteUrl: handle.remoteUrl,
    };
  }

  // ─── Lazy LadybugDB Init ────────────────────────────────────────────

  /**
   * Ensure the LadybugDB pool is open for the *resolved* repo.
   *
   * Takes the `RepoHandle` the caller resolved — NOT a bare id — and keys the
   * pool (and the init/staleness/reinit maps) by the immutable `lbugPath`. Two
   * things matter for multi-clone correctness: (1) the handle is the one the
   * caller resolved, so a concurrent `refreshRepos` can't substitute a different
   * clone; (2) the pool key is the database path, so distinct clones never share
   * a pool entry even when their name-derived id transiently collides (#2067).
   */
  private async ensureInitialized(repo: RepoHandle): Promise<void> {
    const poolKey = repo.lbugPath;
    // If a reinit is already in progress for this repo, wait for it
    const pending = this.reinitPromises.get(poolKey);
    if (pending) return pending;

    // Check if the index was rebuilt since we opened the connection (#297).
    // Throttle staleness checks to at most once per 5 seconds per repo to
    // avoid an fs.readFile round-trip on every tool invocation.
    if (this.initializedRepos.has(poolKey) && isLbugReady(poolKey)) {
      const now = Date.now();
      const lastCheck = this.lastStalenessCheck.get(poolKey) ?? 0;
      if (now - lastCheck < 5000) return; // Checked recently — skip

      this.lastStalenessCheck.set(poolKey, now);
      try {
        const metaPath = path.join(repo.storagePath, 'meta.json');
        const metaRaw = await fs.readFile(metaPath, 'utf-8');
        const meta = JSON.parse(metaRaw);
        if (meta.indexedAt && meta.indexedAt !== repo.indexedAt) {
          // Index was rebuilt — close stale connection and re-init.
          // Wrap in reinitPromises to prevent TOCTOU race where concurrent
          // callers both detect staleness and double-close the pool.
          const reinit = (async () => {
            try {
              await closeLbug(poolKey);
              this.initializedRepos.delete(poolKey);
              repo.indexedAt = meta.indexedAt;
              await initLbug(poolKey, repo.lbugPath);
              this.initializedRepos.add(poolKey);
            } finally {
              this.reinitPromises.delete(poolKey);
            }
          })();
          this.reinitPromises.set(poolKey, reinit);
          return reinit;
        } else {
          return; // Pool is current
        }
      } catch {
        return; // Can't read meta — assume pool is fine
      }
    }

    try {
      await initLbug(poolKey, repo.lbugPath);
      this.initializedRepos.add(poolKey);
    } catch (err: any) {
      // If lock error, mark as not initialized so next call retries
      this.initializedRepos.delete(poolKey);
      throw err;
    }
  }

  // ─── Public Getters ──────────────────────────────────────────────

  /**
   * Get context for a specific repo (or the single repo if only one).
   */
  getContext(repoId?: string): CodebaseContext | null {
    if (repoId && this.contextCache.has(repoId)) {
      return this.contextCache.get(repoId)!;
    }
    if (this.repos.size === 1) {
      return this.contextCache.values().next().value ?? null;
    }
    return null;
  }

  /**
   * List all registered repos with their metadata.
   * Re-reads the global registry so newly indexed repos are discovered
   * without restarting the MCP server.
   *
   * Each entry includes:
   *   - `staleness`: if the indexed clone's own HEAD has moved past
   *     the recorded `lastCommit` (option D in the issue's fix list).
   *   - `siblings`: other registered entries sharing the same
   *     `remoteUrl` (option B's payoff: callers can see at a glance
   *     that another clone of the same logical repo is registered).
   *   - `remoteUrl`: the canonical origin URL recorded at index time.
   */
  async listRepos(): Promise<
    Array<{
      name: string;
      path: string;
      indexedAt: string;
      lastCommit: string;
      remoteUrl?: string;
      stats?: any;
      staleness?: { commitsBehind: number; hint?: string };
      siblings?: Array<{ name: string; path: string; lastCommit: string }>;
    }>
  > {
    await this.refreshRepos();
    const handles = [...this.repos.values()];

    // Pre-group registered handles by `remoteUrl` so the sibling
    // lookup is O(1) per handle. We reuse the in-memory `this.repos`
    // (already populated by `refreshRepos`) instead of doing a fresh
    // `readRegistry()` per entry — that would be N file reads for N
    // registered repos.
    const isWin = process.platform === 'win32';
    const norm = (p: string) => (isWin ? path.resolve(p).toLowerCase() : path.resolve(p));
    const byRemote = new Map<string, RepoHandle[]>();
    for (const h of handles) {
      if (!h.remoteUrl) continue;
      const list = byRemote.get(h.remoteUrl) ?? [];
      list.push(h);
      byRemote.set(h.remoteUrl, list);
    }

    // Check staleness for all repos in parallel instead of sequentially.
    // Each check spawns an async `git rev-list` — with 200 repos the sync
    // variant took ~50 s; parallel async brings it under a second (#1363).
    const stalenessResults = await Promise.all(
      handles.map((h) => checkStalenessAsync(h.repoPath, h.lastCommit)),
    );

    return handles.map((h, i) => {
      const stale = stalenessResults[i];
      const selfNorm = norm(h.repoPath);
      const siblings = h.remoteUrl
        ? (byRemote.get(h.remoteUrl) ?? []).filter((e) => norm(e.repoPath) !== selfNorm)
        : [];
      return {
        name: h.name,
        path: h.repoPath,
        indexedAt: h.indexedAt,
        lastCommit: h.lastCommit,
        remoteUrl: h.remoteUrl,
        stats: h.stats,
        staleness: stale.isStale
          ? { commitsBehind: stale.commitsBehind, hint: stale.hint }
          : undefined,
        siblings:
          siblings.length > 0
            ? siblings.map((s) => ({
                name: s.name,
                path: s.repoPath,
                lastCommit: s.lastCommit,
              }))
            : undefined,
      };
    });
  }

  /**
   * Best-effort sibling-clone drift warning.
   *
   * When the resolved index has a `remoteUrl` recorded and the caller's
   * `process.cwd()` is inside a *different* clone of the same repo, emit
   * one stderr line per (repo, cwd) pair so the operator knows the
   * graph may be stale relative to what's actually on disk under their
   * cwd. Silent on path matches and on repos without a remote URL.
   *
   * Limitation: in MCP stdio server mode `process.cwd()` is the
   * server's CWD at start time, *not* the agent client's CWD. The
   * warning therefore only fires when the MCP server itself was
   * launched from inside a sibling clone (typical for `npx gitnexus
   * serve` from a polecat workspace). Surfacing the client's CWD
   * would require a per-tool-call `cwd` parameter — out of scope for
   * the current MCP contract.
   *
   * Pure side-effect (stderr); never affects the returned handle.
   * After the first computation for a given (repo, cwd) pair the
   * result is cached so subsequent `resolveRepo()` calls don't
   * re-shell-out to git.
   */
  private async maybeWarnSiblingDrift(handle: RepoHandle): Promise<void> {
    if (!handle.remoteUrl) return;
    let cwd: string;
    try {
      cwd = process.cwd();
    } catch {
      return;
    }
    // Early-exit cache: keyed on (repo, cwd) BEFORE any git shellout.
    // After the first call for a given cwd, this short-circuits the
    // up-to-four `execSync`/`execFileSync` calls inside `checkCwdMatch`
    // — important for MCP-server mode where `process.cwd()` is constant
    // and `resolveRepo` runs on every tool call.
    const cacheKey = `${handle.id}|${cwd}`;
    if (this.warnedSiblingDrift.has(cacheKey)) return;

    const match = await checkCwdMatch(cwd);
    if (
      match.match !== 'sibling-by-remote' ||
      !match.entry ||
      !match.cwdGitRoot ||
      match.entry.path !== handle.repoPath ||
      !match.hint
    ) {
      // Cache "nothing to warn about" outcomes too — `checkCwdMatch`
      // is deterministic for a fixed (registry, cwd) pair, so re-running
      // it yields nothing new.
      this.warnedSiblingDrift.add(cacheKey);
      return;
    }

    this.warnedSiblingDrift.add(cacheKey);
    logger.error(`GitNexus: ${match.hint}`);
  }

  // ─── Tool Dispatch ───────────────────────────────────────────────

  async callTool(method: string, params: any): Promise<any> {
    if (method === 'list_repos') {
      return this.listRepos();
    }

    if (method.startsWith('group_')) {
      return this.handleGroupTool(method, params || {});
    }

    const p = params && typeof params === 'object' ? (params as Record<string, unknown>) : {};
    if (
      (method === 'impact' || method === 'query' || method === 'context') &&
      typeof p.repo === 'string' &&
      p.repo.startsWith('@')
    ) {
      return this.callToolAtGroupRepo(method, p);
    }

    // Resolve repo from optional param (re-reads registry on miss)
    const repo = await this.resolveRepo((params as { repo?: string } | undefined)?.repo);

    switch (method) {
      case 'query':
        return this.query(repo, params);
      case 'cypher': {
        const raw = await this.cypher(repo, params);
        return this.formatCypherAsMarkdown(raw);
      }
      case 'context':
        return this.context(repo, params);
      case 'impact':
        return this.impact(repo, params);
      case 'detect_changes':
        return this.detectChanges(repo, params);
      case 'rename':
        return this.rename(repo, params);
      // Legacy aliases for backwards compatibility
      case 'search':
        return this.query(repo, params);
      case 'explore':
        return this.context(repo, { name: params?.name, ...params });
      case 'overview':
        return this.overview(repo, params);
      case 'route_map':
        return this.routeMap(repo, params);
      case 'shape_check':
        return this.shapeCheck(repo, params);
      case 'tool_map':
        return this.toolMap(repo, params);
      case 'api_impact':
        return this.apiImpact(repo, params);
      default:
        throw new Error(`Unknown tool: ${method}`);
    }
  }

  // ─── Tool Implementations ────────────────────────────────────────

  /**
   * Query tool — process-grouped search.
   *
   * 1. Hybrid search (BM25 + semantic) to find matching symbols
   * 2. Trace each match to its process(es) via STEP_IN_PROCESS
   * 3. Group by process, rank by aggregate relevance + internal cluster cohesion
   * 4. Return: { processes, process_symbols, definitions }
   */
  private async query(
    repo: RepoHandle,
    params: {
      query: string;
      task_context?: string;
      goal?: string;
      limit?: number;
      max_symbols?: number;
      include_content?: boolean;
    },
  ): Promise<any> {
    if (!params.query?.trim()) {
      return { error: 'query parameter is required and cannot be empty.' };
    }

    await this.ensureInitialized(repo);

    const processLimit = params.limit || 5;
    const maxSymbolsPerProcess = params.max_symbols || 10;
    const includeContent = params.include_content ?? false;
    const searchQuery = params.query.trim();

    // Per-phase timing instrumentation (#553). Records wall time for each
    // observable sub-step of the search pipeline so production latency can
    // be aggregated offline for Pareto analysis and bottleneck detection.
    // Overhead is <0.1 ms per phase; the timer is passive and never alters
    // query behaviour.
    const timer = new PhaseTimer();
    const wallStart = performance.now();

    // Step 1: Run hybrid search to get matching symbols. BM25 and vector
    // search run concurrently via Promise.all — use `timer.time()` for
    // each so both get independent wall-time records without fighting
    // over a single `current` phase slot.
    const searchLimit = processLimit * maxSymbolsPerProcess; // fetch enough raw results
    const [bm25SearchResult, semanticResults] = await Promise.all([
      timer.time('bm25', this.bm25Search(repo, searchQuery, searchLimit)),
      timer.time('vector', this.semanticSearch(repo, searchQuery, searchLimit)),
    ]);

    // Guard against undefined results (#1489) — when FTS is entirely
    // unavailable the search helper may return an unexpected shape.
    const bm25Results = bm25SearchResult?.results ?? [];
    const ftsUsed = bm25SearchResult?.ftsUsed ?? false;

    // Merge via reciprocal rank fusion
    timer.start('merge');
    const scoreMap = new Map<string, { score: number; data: any }>();

    for (let i = 0; i < bm25Results.length; i++) {
      const result = bm25Results[i];
      const key = result.nodeId || result.filePath;
      const rrfScore = 1 / (60 + i);
      const existing = scoreMap.get(key);
      if (existing) {
        existing.score += rrfScore;
      } else {
        scoreMap.set(key, { score: rrfScore, data: result });
      }
    }

    const safeSemanticResults = semanticResults ?? [];
    for (let i = 0; i < safeSemanticResults.length; i++) {
      const result = safeSemanticResults[i];
      const key = result.nodeId || result.filePath;
      const rrfScore = 1 / (60 + i);
      const existing = scoreMap.get(key);
      if (existing) {
        existing.score += rrfScore;
      } else {
        scoreMap.set(key, { score: rrfScore, data: result });
      }
    }

    const merged = Array.from(scoreMap.entries())
      .sort((a, b) => b[1].score - a[1].score)
      .slice(0, searchLimit);
    timer.stop(); // merge

    // Step 2: For each match with a nodeId, trace to process(es)
    timer.start('symbol_lookup');
    const processMap = new Map<
      string,
      {
        id: string;
        label: string;
        heuristicLabel: string;
        processType: string;
        stepCount: number;
        totalScore: number;
        cohesionBoost: number;
        symbols: any[];
      }
    >();
    const definitions: any[] = []; // standalone symbols not in any process

    for (const [_, item] of merged) {
      const sym = item.data;
      if (!sym.nodeId) {
        // File-level results go to definitions
        definitions.push({
          name: sym.name,
          type: sym.type || 'File',
          filePath: sym.filePath,
        });
        continue;
      }

      // Find processes this symbol participates in
      let processRows: any[] = [];
      try {
        processRows = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (n {id: $nodeId})-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
          RETURN p.id AS pid, p.label AS label, p.heuristicLabel AS heuristicLabel, p.processType AS processType, p.stepCount AS stepCount, r.step AS step
        `,
          { nodeId: sym.nodeId },
        );
      } catch (e) {
        logQueryError('query:process-lookup', e);
      }

      // Get cluster membership + cohesion (cohesion used as internal ranking signal)
      let cohesion = 0;
      let module: string | undefined;
      try {
        const cohesionRows = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (n {id: $nodeId})-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
          RETURN c.cohesion AS cohesion, c.heuristicLabel AS module
          LIMIT 1
        `,
          { nodeId: sym.nodeId },
        );
        if (cohesionRows.length > 0) {
          cohesion = (cohesionRows[0].cohesion ?? cohesionRows[0][0]) || 0;
          module = cohesionRows[0].module ?? cohesionRows[0][1];
        }
      } catch (e) {
        logQueryError('query:cluster-info', e);
      }

      // Optionally fetch content
      let content: string | undefined;
      if (includeContent) {
        try {
          const contentRows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (n {id: $nodeId})
            RETURN n.content AS content
          `,
            { nodeId: sym.nodeId },
          );
          if (contentRows.length > 0) {
            content = contentRows[0].content ?? contentRows[0][0];
          }
        } catch (e) {
          logQueryError('query:content-fetch', e);
        }
      }

      const symbolEntry = {
        id: sym.nodeId,
        name: sym.name,
        type: sym.type,
        filePath: sym.filePath,
        startLine: sym.startLine,
        endLine: sym.endLine,
        ...(module ? { module } : {}),
        ...(includeContent && content ? { content } : {}),
      };

      if (processRows.length === 0) {
        // Symbol not in any process — goes to definitions
        definitions.push(symbolEntry);
      } else {
        // Add to each process it belongs to
        for (const row of processRows) {
          const pid = row.pid ?? row[0];
          const label = row.label ?? row[1];
          const hLabel = row.heuristicLabel ?? row[2];
          const pType = row.processType ?? row[3];
          const stepCount = row.stepCount ?? row[4];
          const step = row.step ?? row[5];

          if (!processMap.has(pid)) {
            processMap.set(pid, {
              id: pid,
              label,
              heuristicLabel: hLabel,
              processType: pType,
              stepCount,
              totalScore: 0,
              cohesionBoost: 0,
              symbols: [],
            });
          }

          const proc = processMap.get(pid)!;
          proc.totalScore += item.score;
          proc.cohesionBoost = Math.max(proc.cohesionBoost, cohesion);
          proc.symbols.push({
            ...symbolEntry,
            process_id: pid,
            step_index: step,
          });
        }
      }
    }

    timer.stop(); // symbol_lookup

    // Step 3: Rank processes by aggregate score + internal cohesion boost
    timer.start('ranking');
    const rankedProcesses = Array.from(processMap.values())
      .map((p) => ({
        ...p,
        priority: p.totalScore + p.cohesionBoost * 0.1, // cohesion as subtle ranking signal
      }))
      .sort((a, b) => b.priority - a.priority)
      .slice(0, processLimit);
    timer.stop(); // ranking

    // Step 4: Build response
    timer.start('formatting');
    const processes = rankedProcesses.map((p) => ({
      id: p.id,
      summary: p.heuristicLabel || p.label,
      priority: Math.round(p.priority * 1000) / 1000,
      symbol_count: p.symbols.length,
      process_type: p.processType,
      step_count: p.stepCount,
    }));

    const processSymbols = rankedProcesses.flatMap((p) =>
      p.symbols.slice(0, maxSymbolsPerProcess).map((s) => ({
        ...s,
        // remove internal fields
      })),
    );

    // Deduplicate process_symbols by id
    const seen = new Set<string>();
    const dedupedSymbols = processSymbols.filter((s) => {
      if (seen.has(s.id)) return false;
      seen.add(s.id);
      return true;
    });
    timer.stop(); // formatting

    // End-to-end wall time — deliberately a separate mark so callers can
    // compare sum(phases) vs wall to see how much Promise.all concurrency
    // saved. Must come before summary() so it's included.
    timer.mark('wall', performance.now() - wallStart);
    const timing = timer.summary();
    logQueryTiming(searchQuery, timing);

    return {
      processes,
      process_symbols: dedupedSymbols,
      definitions: definitions.slice(0, 20), // cap standalone definitions
      timing,
      ...(!ftsUsed && {
        warning:
          'FTS indexes missing — keyword search degraded. Run: gitnexus analyze --repair-fts (or gitnexus analyze --force) to rebuild indexes.',
      }),
    };
  }

  /**
   * BM25 keyword search helper - uses LadybugDB FTS for always-fresh results
   */
  private async bm25Search(
    repo: RepoHandle,
    query: string,
    limit: number,
  ): Promise<{ results: any[]; ftsUsed: boolean }> {
    let searchFTSFromLbug;
    try {
      ({ searchFTSFromLbug } = await import('../../core/search/bm25-index.js'));
    } catch (err: any) {
      // Module import can fail in sandboxed MCP contexts (#1489)
      logger.warn(
        { err: err?.message },
        'GitNexus: bm25-index.js import failed — falling back to semantic-only',
      );
      return { results: [], ftsUsed: false };
    }
    let ftsResponse;
    try {
      ftsResponse = await searchFTSFromLbug(query, limit, repo.lbugPath);
    } catch (err: any) {
      logger.error(
        { err: err.message },
        'GitNexus: BM25/FTS search failed (FTS indexes may not exist) -',
      );
      return { results: [], ftsUsed: false };
    }

    // Guard against unexpected response shape (#1489) — ftsResponse.results
    // could be undefined when the FTS extension is unavailable in the MCP process.
    const bm25Results = ftsResponse?.results ?? [];
    const ftsUsed = ftsResponse?.ftsAvailable ?? false;

    const results: any[] = [];

    for (const bm25Result of bm25Results) {
      const fullPath = bm25Result.filePath;
      try {
        // Prefer direct nodeId lookup (exact FTS-matched nodes) over filePath fallback.
        // Without this, LIMIT 3 on filePath returns arbitrary symbols rather than
        // the nodes that actually scored highest in the BM25 index.
        const nodeIds = bm25Result.nodeIds?.length ? bm25Result.nodeIds : null;
        const symbols = nodeIds
          ? await executeParameterized(
              repo.lbugPath,
              `
              MATCH (n)
              WHERE n.id IN $nodeIds
              RETURN n.id AS id, n.name AS name, labels(n)[0] AS type, n.filePath AS filePath, n.startLine AS startLine, n.endLine AS endLine
            `,
              { nodeIds },
            )
          : await executeParameterized(
              repo.lbugPath,
              `
              MATCH (n)
              WHERE n.filePath = $filePath
              RETURN n.id AS id, n.name AS name, labels(n)[0] AS type, n.filePath AS filePath, n.startLine AS startLine, n.endLine AS endLine
              LIMIT 3
            `,
              { filePath: fullPath },
            );

        if (symbols.length > 0) {
          for (const sym of symbols) {
            results.push({
              nodeId: sym.id || sym[0],
              name: sym.name || sym[1],
              type: sym.type || sym[2],
              filePath: sym.filePath || sym[3],
              startLine: sym.startLine || sym[4],
              endLine: sym.endLine || sym[5],
              bm25Score: bm25Result.score,
            });
          }
        } else {
          const fileName = fullPath.split('/').pop() || fullPath;
          results.push({
            name: fileName,
            type: 'File',
            filePath: bm25Result.filePath,
            bm25Score: bm25Result.score,
          });
        }
      } catch {
        const fileName = fullPath.split('/').pop() || fullPath;
        results.push({
          name: fileName,
          type: 'File',
          filePath: bm25Result.filePath,
          bm25Score: bm25Result.score,
        });
      }
    }

    return { results, ftsUsed };
  }

  /**
   * Semantic vector search helper
   */
  private async semanticSearch(repo: RepoHandle, query: string, limit: number): Promise<any[]> {
    try {
      // Check if embedding table exists before loading the model (avoids heavy model init when embeddings are off)
      const tableCheck = await executeQuery(
        repo.lbugPath,
        `MATCH (e:${EMBEDDING_TABLE_NAME}) RETURN COUNT(*) AS cnt LIMIT 1`,
      );
      if (!tableCheck.length || (tableCheck[0].cnt ?? tableCheck[0][0]) === 0) return [];

      const { embedQuery, getEmbeddingDims } = await import('../core/embedder.js');
      const queryVec = await embedQuery(query);
      const dims = getEmbeddingDims();
      const queryVecStr = `[${queryVec.join(',')}]`;

      let bestChunks = new Map<
        string,
        { distance: number; chunkIndex: number; startLine: number; endLine: number }
      >();
      if (isVectorExtensionSupportedByPlatform()) {
        try {
          bestChunks = await collectBestChunks(limit, async (fetchLimit) => {
            const vectorQuery = `
            CALL QUERY_VECTOR_INDEX('${EMBEDDING_TABLE_NAME}', '${EMBEDDING_INDEX_NAME}',
              CAST(${queryVecStr} AS FLOAT[${dims}]), ${fetchLimit})
            YIELD node AS emb, distance
            WITH emb, distance
            WHERE distance < 0.6
            RETURN emb.nodeId AS nodeId, emb.chunkIndex AS chunkIndex,
                   emb.startLine AS startLine, emb.endLine AS endLine, distance
            ORDER BY distance
          `;

            const embResults = await executeQuery(repo.lbugPath, vectorQuery);
            return embResults.map((row) => ({
              nodeId: row.nodeId ?? row[0],
              chunkIndex: row.chunkIndex ?? row[1] ?? 0,
              startLine: row.startLine ?? row[2] ?? 0,
              endLine: row.endLine ?? row[3] ?? 0,
              distance: row.distance ?? row[4],
            }));
          });
        } catch {
          bestChunks = new Map();
        }
      } else if (!this.warnedVectorUnsupported) {
        // Rare diagnostic: surface why we fell back to the exact scan path so
        // operators can see at a glance that VECTOR is disabled by platform
        // policy. Emitted once per `LocalBackend` instance lifetime to avoid
        // noisy stderr on hot semantic-search paths (DoD §2.8).
        this.warnedVectorUnsupported = true;
        logger.warn(
          'GitNexus [query:vector]: VECTOR extension not supported on this platform; using exact scan fallback',
        );
      }

      if (bestChunks.size === 0) {
        const embeddingCount = Number(tableCheck[0].cnt ?? tableCheck[0][0] ?? 0);
        const exactLimit = getExactScanLimit();
        if (embeddingCount > exactLimit) return [];

        const rows = await executeQuery(
          repo.lbugPath,
          `
          MATCH (e:${EMBEDDING_TABLE_NAME})
          RETURN e.nodeId AS nodeId, e.chunkIndex AS chunkIndex,
                 e.startLine AS startLine, e.endLine AS endLine, e.embedding AS embedding
        `,
        );
        const exactRows: ExactEmbeddingRow[] = rows.map((row) => ({
          nodeId: row.nodeId ?? row[0],
          chunkIndex: row.chunkIndex ?? row[1] ?? 0,
          startLine: row.startLine ?? row[2] ?? 0,
          endLine: row.endLine ?? row[3] ?? 0,
          embedding: row.embedding ?? row[4] ?? [],
        }));
        bestChunks = new Map(
          rankExactEmbeddingRows(exactRows, queryVec, limit, 0.6).map((row) => [
            row.nodeId,
            {
              distance: row.distance,
              chunkIndex: row.chunkIndex,
              startLine: row.startLine,
              endLine: row.endLine,
            },
          ]),
        );
      }

      if (bestChunks.size === 0) return [];

      const results: any[] = [];

      for (const [nodeId, chunk] of Array.from(bestChunks.entries()).slice(0, limit)) {
        const labelEndIdx = nodeId.indexOf(':');
        const label = labelEndIdx > 0 ? nodeId.substring(0, labelEndIdx) : 'Unknown';

        // Validate label against known node types to prevent Cypher injection
        if (!VALID_NODE_LABELS.has(label)) continue;

        try {
          const nodeQuery =
            label === 'File'
              ? `MATCH (n:File {id: $nodeId}) RETURN n.name AS name, n.filePath AS filePath`
              : `MATCH (n:\`${label}\` {id: $nodeId}) RETURN n.name AS name, n.filePath AS filePath`;

          const nodeRows = await executeParameterized(repo.lbugPath, nodeQuery, { nodeId });
          if (nodeRows.length > 0) {
            const nodeRow = nodeRows[0];
            results.push({
              nodeId,
              name: nodeRow.name ?? nodeRow[0] ?? '',
              type: label,
              filePath: nodeRow.filePath ?? nodeRow[1] ?? '',
              distance: chunk.distance,
              startLine: chunk.startLine,
              endLine: chunk.endLine,
            });
          }
        } catch {}
      }

      return results;
    } catch {
      // Expected when embeddings are disabled — silently fall back to BM25-only
      return [];
    }
  }

  async executeCypher(
    repoName: string,
    query: string,
    params: Record<string, unknown> = {},
  ): Promise<any> {
    const repo = await this.resolveRepo(repoName);
    return this.cypher(repo, { query, params });
  }

  private async cypher(
    repo: RepoHandle,
    request: { query: string; params?: Record<string, unknown> },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    if (!isLbugReady(repo.lbugPath)) {
      return { error: 'LadybugDB not ready. Index may be corrupted.' };
    }
    if (request.params !== undefined && !isValidQueryParams(request.params)) {
      return {
        error: '"params" must be a plain object with scalar values (string/number/boolean/null).',
      };
    }

    try {
      const result = await executeParameterized(repo.lbugPath, request.query, request.params ?? {});
      return result;
    } catch (err: any) {
      const msg = err.message || 'Query failed';
      if (isReadOnlyDbError(err)) {
        return {
          error:
            'Write operations (CREATE, DELETE, SET, MERGE, REMOVE, DROP, ALTER, COPY, DETACH) are not allowed. The knowledge graph is read-only.',
        };
      }
      if (isWalCorruptionError(err)) {
        return {
          error: msg,
          recoverySuggestion: WAL_RECOVERY_SUGGESTION,
        };
      }
      return { error: msg };
    }
  }

  /**
   * Format raw Cypher result rows as a markdown table for LLM readability.
   * Falls back to raw result if rows aren't tabular objects.
   */
  private formatCypherAsMarkdown(result: any): any {
    if (!Array.isArray(result) || result.length === 0) return result;

    const firstRow = result[0];
    if (typeof firstRow !== 'object' || firstRow === null) return result;

    const keys = Object.keys(firstRow);
    if (keys.length === 0) return result;

    const header = '| ' + keys.join(' | ') + ' |';
    const separator = '| ' + keys.map(() => '---').join(' | ') + ' |';
    const dataRows = result.map(
      (row: any) =>
        '| ' +
        keys
          .map((k) => {
            const v = row[k];
            if (v === null || v === undefined) return '';
            if (typeof v === 'object') return JSON.stringify(v);
            return String(v);
          })
          .join(' | ') +
        ' |',
    );

    return {
      markdown: [header, separator, ...dataRows].join('\n'),
      row_count: result.length,
    };
  }

  /**
   * Aggregate same-named clusters: group by heuristicLabel, sum symbols,
   * weighted-average cohesion, filter out tiny clusters (<5 symbols).
   * Raw communities stay intact in LadybugDB for Cypher queries.
   */
  private aggregateClusters(clusters: any[]): any[] {
    const groups = new Map<
      string,
      { ids: string[]; totalSymbols: number; weightedCohesion: number; largest: any }
    >();

    for (const c of clusters) {
      const label = c.heuristicLabel || c.label || 'Unknown';
      const symbols = c.symbolCount || 0;
      const cohesion = c.cohesion || 0;
      const existing = groups.get(label);

      if (!existing) {
        groups.set(label, {
          ids: [c.id],
          totalSymbols: symbols,
          weightedCohesion: cohesion * symbols,
          largest: c,
        });
      } else {
        existing.ids.push(c.id);
        existing.totalSymbols += symbols;
        existing.weightedCohesion += cohesion * symbols;
        if (symbols > (existing.largest.symbolCount || 0)) {
          existing.largest = c;
        }
      }
    }

    return Array.from(groups.entries())
      .map(([label, g]) => ({
        id: g.largest.id,
        label,
        heuristicLabel: label,
        symbolCount: g.totalSymbols,
        cohesion: g.totalSymbols > 0 ? g.weightedCohesion / g.totalSymbols : 0,
        subCommunities: g.ids.length,
      }))
      .filter((c) => c.symbolCount >= 5)
      .sort((a, b) => b.symbolCount - a.symbolCount);
  }

  private async overview(
    repo: RepoHandle,
    params: { showClusters?: boolean; showProcesses?: boolean; limit?: number },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    const limit = params.limit || 20;
    const result: any = {
      repo: repo.name,
      repoPath: repo.repoPath,
      stats: repo.stats,
      indexedAt: repo.indexedAt,
      lastCommit: repo.lastCommit,
    };

    if (params.showClusters !== false) {
      try {
        // Fetch more raw communities than the display limit so aggregation has enough data
        const rawLimit = Math.max(limit * 5, 200);
        const clusters = await executeQuery(
          repo.lbugPath,
          `
          MATCH (c:Community)
          RETURN c.id AS id, c.label AS label, c.heuristicLabel AS heuristicLabel, c.cohesion AS cohesion, c.symbolCount AS symbolCount
          ORDER BY c.symbolCount DESC
          LIMIT ${rawLimit}
        `,
        );
        const rawClusters = clusters.map((c: any) => ({
          id: c.id || c[0],
          label: c.label || c[1],
          heuristicLabel: c.heuristicLabel || c[2],
          cohesion: c.cohesion || c[3],
          symbolCount: c.symbolCount || c[4],
        }));
        result.clusters = this.aggregateClusters(rawClusters).slice(0, limit);
      } catch {
        result.clusters = [];
      }
    }

    if (params.showProcesses !== false) {
      try {
        const processes = await executeQuery(
          repo.lbugPath,
          `
          MATCH (p:Process)
          RETURN p.id AS id, p.label AS label, p.heuristicLabel AS heuristicLabel, p.processType AS processType, p.stepCount AS stepCount
          ORDER BY p.stepCount DESC
          LIMIT ${limit}
        `,
        );
        result.processes = processes.map((p: any) => ({
          id: p.id || p[0],
          label: p.label || p[1],
          heuristicLabel: p.heuristicLabel || p[2],
          processType: p.processType || p[3],
          stepCount: p.stepCount || p[4],
        }));
      } catch {
        result.processes = [];
      }
    }

    return result;
  }

  /**
   * Patch the `type` field on candidates whose `labels(n)[0]` projection
   * came back empty — a known LadybugDB behaviour for several node types.
   *
   * Uses one scoped UNION query across the five priority labels rather
   * than per-candidate round-trips, so cost is a single DB call regardless
   * of how many candidates need enrichment. No-op when every candidate
   * already has a non-empty type.
   *
   * Failures are swallowed: label enrichment is an optimisation for
   * downstream scoring and #480 Class/Interface BFS seeding; if it fails
   * the symbol still resolves, just without the kind-priority bonus.
   */
  private async enrichCandidateLabels(
    repo: RepoHandle,
    candidates: Array<{ id: string; type: string }>,
  ): Promise<void> {
    const ids = candidates.filter((c) => c.type === '' && c.id).map((c) => c.id);
    if (ids.length === 0) return;
    try {
      const rows = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (n:\`Class\`) WHERE n.id IN $ids RETURN n.id AS id, 'Class' AS label
        UNION ALL
        MATCH (n:\`Interface\`) WHERE n.id IN $ids RETURN n.id AS id, 'Interface' AS label
        UNION ALL
        MATCH (n:\`Function\`) WHERE n.id IN $ids RETURN n.id AS id, 'Function' AS label
        UNION ALL
        MATCH (n:\`Method\`) WHERE n.id IN $ids RETURN n.id AS id, 'Method' AS label
        UNION ALL
        MATCH (n:\`Constructor\`) WHERE n.id IN $ids RETURN n.id AS id, 'Constructor' AS label
        `,
        { ids },
      );
      const labelById = new Map<string, string>();
      for (const r of rows as any[]) {
        const id = (r.id ?? r[0]) as string;
        const label = (r.label ?? r[1]) as string;
        if (id && label && !labelById.has(id)) labelById.set(id, label);
      }
      for (const c of candidates) {
        if (c.type === '' && labelById.has(c.id)) c.type = labelById.get(c.id) as string;
      }
    } catch {
      /* best-effort — downstream resolvers still work without the label */
    }
  }

  /**
   * Score a symbol candidate for disambiguation ranking.
   *
   * Deterministic, no DB round-trip:
   *   - base 0.50
   *   - +0.40 when file_path hint matches (substring, case-insensitive)
   *   - +0.20 when kind hint exactly matches the candidate's kind
   *   - when no kind hint, a small priority bonus (Class > Interface >
   *     Function > Method > Constructor) to preserve the intuition that
   *     class-level names are usually what the user wanted.
   *
   * Capped at 1.0. Intentionally simple and inspectable — a future v2 can
   * plug in BM25/embedding signals here without changing the surrounding
   * resolver shape.
   */
  private scoreCandidate(
    c: { kind: string; filePath: string },
    hints: { file_path?: string; kind?: string },
  ): number {
    let s = 0.5;
    if (hints.file_path && c.filePath && typeof c.filePath === 'string') {
      if (c.filePath.toLowerCase().includes(hints.file_path.toLowerCase())) {
        s += 0.4;
      }
    }
    if (hints.kind && c.kind === hints.kind) {
      s += 0.2;
    }
    if (!hints.kind) {
      const priority: Record<string, number> = {
        Class: 5,
        Interface: 4,
        Function: 3,
        Method: 2,
        Constructor: 1,
      };
      s += (priority[c.kind] ?? 0) * 0.02;
    }
    return Math.min(1.0, s);
  }

  /**
   * Shared symbol resolver used by `context` and `impact`.
   *
   * Returns one of:
   *   - `{ kind: 'ok', symbol, resolvedLabel }` — single confident match
   *     (either direct UID, only one candidate after filtering, Class/
   *     Constructor collapse, or a top-scoring candidate with a clear gap
   *     to the runner-up).
   *   - `{ kind: 'ambiguous', candidates }` — multiple viable matches,
   *     sorted by score desc. Each candidate carries a relevance score.
   *   - `{ kind: 'not_found' }` — no matches at all.
   *
   * Preserves the #480 Class/Constructor preference: when the only
   * ambiguity is between a Class and its own Constructor (same name,
   * same filePath), the Class wins silently.
   */
  private async resolveSymbolCandidates(
    repo: RepoHandle,
    query: { uid?: string; name?: string; include_content?: boolean },
    hints: { file_path?: string; kind?: string },
  ): Promise<
    | {
        kind: 'ok';
        symbol: {
          id: string;
          name: string;
          type: string;
          filePath: string;
          startLine: number;
          endLine: number;
          content?: string;
        };
        resolvedLabel: string;
      }
    | {
        kind: 'ambiguous';
        candidates: Array<{
          id: string;
          name: string;
          type: string;
          filePath: string;
          startLine: number;
          endLine: number;
          score: number;
        }>;
      }
    | { kind: 'not_found' }
  > {
    const { uid, name, include_content } = query;
    const selectClause = `n.id AS id, n.name AS name, labels(n)[0] AS type, n.filePath AS filePath, n.startLine AS startLine, n.endLine AS endLine${include_content ? ', n.content AS content' : ''}`;

    // Direct UID — zero-ambiguity path.
    if (uid) {
      const rows = await executeParameterized(
        repo.lbugPath,
        `MATCH (n {id: $uid}) RETURN ${selectClause} LIMIT 1`,
        { uid },
      );
      if (rows.length === 0) return { kind: 'not_found' };
      const r = rows[0] as any;
      const symbol = {
        id: (r.id ?? r[0]) as string,
        name: (r.name ?? r[1]) as string,
        type: (r.type ?? r[2] ?? '') as string,
        filePath: (r.filePath ?? r[3]) as string,
        startLine: (r.startLine ?? r[4]) as number,
        endLine: (r.endLine ?? r[5]) as number,
        ...(include_content ? { content: (r.content ?? r[6]) as string | undefined } : {}),
      };
      // Same LadybugDB label-enrichment as the name-based path: a UID
      // pointing at a Class must still surface `type: 'Class'` so impact's
      // Class/Interface BFS seed fires. No-op when type is already set.
      await this.enrichCandidateLabels(repo, [symbol]);
      return { kind: 'ok', symbol, resolvedLabel: symbol.type };
    }

    if (!name) return { kind: 'not_found' };

    const isQualified = name.includes('/') || name.includes(':');
    let whereClause: string;
    const queryParams: Record<string, any> = { symName: name };
    if (hints.file_path) {
      whereClause = `WHERE n.name = $symName AND n.filePath CONTAINS $filePath`;
      queryParams.filePath = hints.file_path;
    } else if (isQualified) {
      whereClause = `WHERE n.id = $symName OR n.name = $symName`;
    } else {
      whereClause = `WHERE n.name = $symName`;
    }

    // LIMIT 20 (was 10) — scoring is the point now, so give the ranker
    // headroom instead of arbitrary truncation.
    const rows = await executeParameterized(
      repo.lbugPath,
      `MATCH (n) ${whereClause} RETURN ${selectClause} LIMIT 20`,
      queryParams,
    );

    if (rows.length === 0) return { kind: 'not_found' };

    // Normalise row shape across object / tuple returns from LadybugDB.
    const normalized = rows.map((r: any) => ({
      id: (r.id ?? r[0]) as string,
      name: (r.name ?? r[1]) as string,
      type: (r.type ?? r[2] ?? '') as string,
      filePath: (r.filePath ?? r[3]) as string,
      startLine: (r.startLine ?? r[4]) as number,
      endLine: (r.endLine ?? r[5]) as number,
      ...(include_content ? { content: (r.content ?? r[6]) as string | undefined } : {}),
    }));

    // Enrich labels for any candidates where `labels(n)[0]` came back empty.
    // LadybugDB returns an empty string for that projection on certain node
    // types (notably Class), which left downstream consumers (impact's
    // Class/Interface BFS seed, the kind-priority scoring bonus) unable to
    // distinguish a Class target from "unknown kind". One scoped UNION
    // across the five priority labels patches the type in-place without
    // per-candidate round-trips.
    await this.enrichCandidateLabels(repo, normalized);

    // Preserve #480 Class/Constructor collapse: if we have exactly one
    // Class (or Interface) candidate and one Constructor sharing name +
    // filePath, fold into the Class. This used to require a follow-up
    // label query because LadybugDB sometimes returns an empty labels()[0]
    // for Class nodes — enrichment above handles the empty-type case, but
    // the `type === 'Constructor'` gate still correctly triggers when a
    // Class and its Constructor share the name.
    if (!hints.kind && normalized.length > 1) {
      const ambiguousType = normalized.some((s) => s.type === '' || s.type === 'Constructor');
      if (ambiguousType) {
        const candidateIds = normalized.map((s) => s.id).filter(Boolean);
        for (const label of ['Class', 'Interface']) {
          const labelRows = await executeParameterized(
            repo.lbugPath,
            `MATCH (n:\`${label}\`) WHERE n.id IN $candidateIds RETURN n.id AS id LIMIT 1`,
            { candidateIds },
          ).catch(() => []);
          if (labelRows.length > 0) {
            const preferredId = (labelRows[0] as any).id ?? (labelRows[0] as any)[0];
            const preferred = normalized.find((s) => s.id === preferredId);
            if (preferred) {
              return {
                kind: 'ok',
                symbol: preferred,
                resolvedLabel: label,
              };
            }
          }
        }
      }
    }

    if (normalized.length === 1) {
      return {
        kind: 'ok',
        symbol: normalized[0],
        resolvedLabel: '',
      };
    }

    // Score, sort desc, stable tiebreak on shorter filePath then lex uid.
    const scored = normalized.map((s) => ({
      ...s,
      score: this.scoreCandidate({ kind: s.type, filePath: s.filePath || '' }, hints),
    }));
    scored.sort((a, b) => {
      if (b.score !== a.score) return b.score - a.score;
      const fpA = (a.filePath || '').length;
      const fpB = (b.filePath || '').length;
      if (fpA !== fpB) return fpA - fpB;
      return String(a.id).localeCompare(String(b.id));
    });

    // Confident single-result: top score ≥ 0.95 AND beats runner-up by a
    // clear margin. This lets a very strong file_path/kind hint resolve
    // cleanly instead of forcing the caller through a disambiguation
    // round-trip.
    //
    // The gap threshold uses `> 0.09` rather than `>= 0.10` on purpose:
    // IEEE754 addition of the scoring terms (0.50 + 0.40 + 0.20 - 0.90
    // yields 0.09999999999999998, not exactly 0.10) would otherwise break
    // the comparison for legitimate "top is 1.00, runner is 0.90" cases.
    // The intent is a clearly-dominant winner; 0.09 is a large enough
    // margin to mean that unambiguously.
    //
    // The `scored.length >= 2` guard is defensive. The `normalized.length === 1`
    // early return above already handles the single-candidate path, so in
    // practice `scored` always has at least two elements by the time we get
    // here — keeping the guard means changes to the upstream early-return
    // logic cannot accidentally index out of bounds at `scored[1]`.
    if (scored.length >= 2 && scored[0].score >= 0.95 && scored[0].score - scored[1].score > 0.09) {
      return { kind: 'ok', symbol: scored[0], resolvedLabel: scored[0].type };
    }

    return { kind: 'ambiguous', candidates: scored };
  }

  /**
   * Context tool — 360-degree symbol view with categorized refs.
   * Disambiguation (ranked) when multiple symbols share a name.
   * UID-based direct lookup. No cluster in output.
   */
  private async context(
    repo: RepoHandle,
    params: {
      name?: string;
      uid?: string;
      file_path?: string;
      kind?: string;
      include_content?: boolean;
    },
  ): Promise<any> {
    try {
      return await this._contextImpl(repo, params);
    } catch (err: any) {
      const msg = (err instanceof Error ? err.message : String(err)) || 'Context query failed';
      if (isWalCorruptionError(err)) {
        return {
          error: msg,
          recoverySuggestion: WAL_RECOVERY_SUGGESTION,
        };
      }
      throw err;
    }
  }

  private async _contextImpl(
    repo: RepoHandle,
    params: {
      name?: string;
      uid?: string;
      file_path?: string;
      kind?: string;
      include_content?: boolean;
    },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    const { name, uid, file_path, kind, include_content } = params;

    if (!name && !uid) {
      return { error: 'Either "name" or "uid" parameter is required.' };
    }

    const outcome = await this.resolveSymbolCandidates(
      repo,
      { uid, name, include_content },
      { file_path, kind },
    );

    if (outcome.kind === 'not_found') {
      return { error: `Symbol '${name || uid}' not found` };
    }

    if (outcome.kind === 'ambiguous') {
      return {
        status: 'ambiguous',
        message: `Found ${outcome.candidates.length} symbols matching '${name}'. Use uid, file_path, or kind to disambiguate.`,
        candidates: outcome.candidates.map((c) => ({
          uid: c.id,
          name: c.name,
          kind: c.type,
          filePath: c.filePath,
          line: c.startLine,
          score: Number(c.score.toFixed(2)),
        })),
      };
    }

    // Step 3: Build full context
    const sym = outcome.symbol;
    const resolvedLabel = outcome.resolvedLabel;
    const symId = sym.id;

    // Categorized incoming refs
    const incomingRows = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (caller)-[r:CodeRelation]->(n {id: $symId})
      WHERE r.type IN ['CALLS', 'IMPORTS', 'EXTENDS', 'IMPLEMENTS', 'USES', 'HAS_METHOD', 'HAS_PROPERTY', 'METHOD_OVERRIDES', 'OVERRIDES', 'METHOD_IMPLEMENTS', 'ACCESSES']
      RETURN r.type AS relType, caller.id AS uid, caller.name AS name, caller.filePath AS filePath, labels(caller)[0] AS kind
      LIMIT 30
    `,
      { symId },
    );
    let typedPropertyRows: any[] = [];

    // Fix #480: Class/Interface nodes have no direct CALLS/IMPORTS edges —
    // those point to Constructor and File nodes respectively. Fetch those
    // extra incoming refs and merge them in so context() shows real callers.
    //
    // Determine if this is a Class/Interface node. If resolvedLabel was set
    // during disambiguation (Step 2), use it directly — no extra round-trip.
    // Otherwise fall back to a single label check only when the type field is
    // empty (LadybugDB labels(n)[0] limitation).
    const symRawType = sym.type || sym[2] || '';
    let isClassLike = resolvedLabel === 'Class' || resolvedLabel === 'Interface';
    if (!isClassLike && symRawType === '') {
      try {
        // Single UNION query instead of two serial round-trips.
        const typeCheck = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (n:Class) WHERE n.id = $symId RETURN 'Class' AS label LIMIT 1
          UNION ALL
          MATCH (n:Interface) WHERE n.id = $symId RETURN 'Interface' AS label LIMIT 1
        `,
          { symId },
        );
        isClassLike = typeCheck.length > 0;
      } catch {
        /* not a Class/Interface node */
      }
    } else if (!isClassLike) {
      isClassLike = symRawType === 'Class' || symRawType === 'Interface';
    }

    if (isClassLike) {
      try {
        // Run incoming-ref queries in parallel — they are independent.
        const [ctorIncoming, fileIncoming, typedPropertyIncoming, typedProperties] =
          await Promise.all([
            executeParameterized(
              repo.lbugPath,
              `
            MATCH (n)-[hm:CodeRelation]->(ctor:Constructor)
            WHERE n.id = $symId AND hm.type = 'HAS_METHOD'
            MATCH (caller)-[r:CodeRelation]->(ctor)
            WHERE r.type IN ['CALLS', 'IMPORTS', 'EXTENDS', 'IMPLEMENTS', 'USES', 'ACCESSES']
            RETURN r.type AS relType, caller.id AS uid, caller.name AS name, caller.filePath AS filePath, labels(caller)[0] AS kind
            LIMIT 30
          `,
              { symId },
            ),
            executeParameterized(
              repo.lbugPath,
              `
            MATCH (f:File)-[rel:CodeRelation]->(n)
            WHERE n.id = $symId AND rel.type = 'DEFINES'
            MATCH (caller)-[r:CodeRelation]->(f)
            WHERE r.type IN ['CALLS', 'IMPORTS']
            RETURN r.type AS relType, caller.id AS uid, caller.name AS name, caller.filePath AS filePath, labels(caller)[0] AS kind
            LIMIT 30
          `,
              { symId },
            ),
            executeParameterized(
              repo.lbugPath,
              `
            MATCH (p:\`Property\`)
            WHERE p.declaredType = $name
               OR p.declaredType STARTS WITH $genericPrefix
               OR p.declaredType CONTAINS $genericArg
            MATCH (caller)-[r:CodeRelation]->(p)
            WHERE r.type IN ['CALLS', 'IMPORTS', 'EXTENDS', 'IMPLEMENTS', 'USES', 'ACCESSES']
            RETURN r.type AS relType, caller.id AS uid, caller.name AS name, caller.filePath AS filePath, labels(caller)[0] AS kind
            LIMIT 30
          `,
              {
                name: sym.name,
                genericPrefix: `${sym.name}<`,
                genericArg: `<${sym.name}>`,
              },
            ),
            executeParameterized(
              repo.lbugPath,
              `
            MATCH (p:\`Property\`)
            WHERE p.declaredType = $name
               OR p.declaredType STARTS WITH $genericPrefix
               OR p.declaredType CONTAINS $genericArg
            RETURN p.id AS uid, p.name AS name, p.filePath AS filePath, labels(p)[0] AS kind,
                   p.declaredType AS declaredType
            LIMIT 30
          `,
              {
                name: sym.name,
                genericPrefix: `${sym.name}<`,
                genericArg: `<${sym.name}>`,
              },
            ),
          ]);
        typedPropertyRows = typedProperties;

        // Deduplicate by (relType, uid) — a caller can have multiple relation
        // types to the same target (e.g. both IMPORTS and CALLS), and each
        // must be preserved so every category appears in the output.
        const seenKeys = new Set(
          incomingRows.map((r: any) => `${r.relType || r[0]}:${r.uid || r[1]}`),
        );
        for (const r of [...ctorIncoming, ...fileIncoming, ...typedPropertyIncoming]) {
          const key = `${r.relType || r[0]}:${r.uid || r[1]}`;
          if (!seenKeys.has(key)) {
            seenKeys.add(key);
            incomingRows.push(r);
          }
        }
      } catch (e) {
        logQueryError('context:class-incoming-expansion', e);
      }
    }

    // Categorized outgoing refs
    const outgoingRows = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (n {id: $symId})-[r:CodeRelation]->(target)
      WHERE r.type IN ['CALLS', 'IMPORTS', 'EXTENDS', 'IMPLEMENTS', 'USES', 'HAS_METHOD', 'HAS_PROPERTY', 'METHOD_OVERRIDES', 'OVERRIDES', 'METHOD_IMPLEMENTS', 'ACCESSES']
      RETURN r.type AS relType, target.id AS uid, target.name AS name, target.filePath AS filePath, labels(target)[0] AS kind
      LIMIT 30
    `,
      { symId },
    );

    // Process participation
    let processRows: any[] = [];
    try {
      processRows = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (n {id: $symId})-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
        RETURN p.id AS pid, p.heuristicLabel AS label, r.step AS step, p.stepCount AS stepCount
      `,
        { symId },
      );
    } catch (e) {
      logQueryError('context:process-participation', e);
    }

    // Helper to categorize refs
    const categorize = (rows: any[]) => {
      const cats: Record<string, any[]> = {};
      for (const row of rows) {
        const relType = (row.relType || row[0] || '').toLowerCase();
        const entry = {
          uid: row.uid || row[1],
          name: row.name || row[2],
          filePath: row.filePath || row[3],
          kind: row.kind || row[4],
        };
        if (!cats[relType]) cats[relType] = [];
        cats[relType].push(entry);
      }
      return cats;
    };

    // Method/Function/Constructor enrichment: fetch method-specific properties
    const symKind = isClassLike ? resolvedLabel || 'Class' : sym.type || sym[2];
    const isMethodLike =
      symKind === 'Method' || symKind === 'Function' || symKind === 'Constructor';
    let methodMetadata: Record<string, unknown> | undefined;
    if (isMethodLike) {
      try {
        const metaRows = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (n {id: $symId})
          RETURN n.visibility AS visibility, n.isStatic AS isStatic, n.isAbstract AS isAbstract,
                 n.isFinal AS isFinal, n.isVirtual AS isVirtual, n.isOverride AS isOverride,
                 n.isAsync AS isAsync, n.isPartial AS isPartial, n.returnType AS returnType,
                 n.parameterCount AS parameterCount, n.isVariadic AS isVariadic,
                 n.requiredParameterCount AS requiredParameterCount,
                 n.parameterTypes AS parameterTypes, n.annotations AS annotations
          LIMIT 1
        `,
          { symId },
        );
        if (metaRows.length > 0) {
          const row = metaRows[0];
          const meta: Record<string, unknown> = {};
          // Only include defined properties to distinguish "not applicable" from "not enriched"
          for (const key of Object.keys(row)) {
            const val = row[key];
            if (val !== null && val !== undefined) meta[key] = val;
          }
          if (Object.keys(meta).length > 0) methodMetadata = meta;
        }
      } catch {
        /* method metadata unavailable — omit silently */
      }
    }

    return {
      status: 'found',
      symbol: {
        uid: sym.id || sym[0],
        name: sym.name || sym[1],
        kind: symKind,
        filePath: sym.filePath || sym[3],
        startLine: sym.startLine || sym[4],
        endLine: sym.endLine || sym[5],
        ...(include_content && (sym.content || sym[6]) ? { content: sym.content || sym[6] } : {}),
        ...(methodMetadata ? { methodMetadata } : {}),
      },
      incoming: categorize(incomingRows),
      outgoing: categorize(outgoingRows),
      ...(typedPropertyRows.length > 0
        ? {
            typed_properties: typedPropertyRows.map((r: any) => ({
              uid: r.uid || r[0],
              name: r.name || r[1],
              filePath: r.filePath || r[2],
              kind: r.kind || r[3],
              declaredType: r.declaredType || r[4],
            })),
          }
        : {}),
      processes: processRows.map((r: any) => ({
        id: r.pid || r[0],
        name: r.label || r[1],
        step_index: r.step || r[2],
        step_count: r.stepCount || r[3],
      })),
    };
  }

  /**
   * Legacy explore — kept for backwards compatibility with resources.ts.
   * Routes cluster/process types to direct graph queries.
   */
  private async explore(
    repo: RepoHandle,
    params: { name: string; type: 'symbol' | 'cluster' | 'process' },
  ): Promise<any> {
    await this.ensureInitialized(repo);
    const { name, type } = params;

    if (type === 'symbol') {
      return this.context(repo, { name });
    }

    if (type === 'cluster') {
      const clusters = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (c:Community)
        WHERE c.label = $clusterName OR c.heuristicLabel = $clusterName
        RETURN c.id AS id, c.label AS label, c.heuristicLabel AS heuristicLabel, c.cohesion AS cohesion, c.symbolCount AS symbolCount
      `,
        { clusterName: name },
      );
      if (clusters.length === 0) return { error: `Cluster '${name}' not found` };

      const rawClusters = clusters.map((c: any) => ({
        id: c.id || c[0],
        label: c.label || c[1],
        heuristicLabel: c.heuristicLabel || c[2],
        cohesion: c.cohesion || c[3],
        symbolCount: c.symbolCount || c[4],
      }));

      let totalSymbols = 0,
        weightedCohesion = 0;
      for (const c of rawClusters) {
        const s = c.symbolCount || 0;
        totalSymbols += s;
        weightedCohesion += (c.cohesion || 0) * s;
      }

      const members = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
        WHERE c.label = $clusterName OR c.heuristicLabel = $clusterName
        RETURN DISTINCT n.name AS name, labels(n)[0] AS type, n.filePath AS filePath
        LIMIT 30
      `,
        { clusterName: name },
      );

      return {
        cluster: {
          id: rawClusters[0].id,
          label: rawClusters[0].heuristicLabel || rawClusters[0].label,
          heuristicLabel: rawClusters[0].heuristicLabel || rawClusters[0].label,
          cohesion: totalSymbols > 0 ? weightedCohesion / totalSymbols : 0,
          symbolCount: totalSymbols,
          subCommunities: rawClusters.length,
        },
        members: members.map((m: any) => ({
          name: m.name || m[0],
          type: m.type || m[1],
          filePath: m.filePath || m[2],
        })),
      };
    }

    if (type === 'process') {
      const processes = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (p:Process)
        WHERE p.label = $processName OR p.heuristicLabel = $processName
        RETURN p.id AS id, p.label AS label, p.heuristicLabel AS heuristicLabel, p.processType AS processType, p.stepCount AS stepCount
        LIMIT 1
      `,
        { processName: name },
      );
      if (processes.length === 0) return { error: `Process '${name}' not found` };

      const proc = processes[0];
      const procId = proc.id || proc[0];
      const steps = await executeParameterized(
        repo.lbugPath,
        `
        MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p {id: $procId})
        RETURN n.name AS name, labels(n)[0] AS type, n.filePath AS filePath, r.step AS step
        ORDER BY r.step
      `,
        { procId },
      );

      return {
        process: {
          id: procId,
          label: proc.label || proc[1],
          heuristicLabel: proc.heuristicLabel || proc[2],
          processType: proc.processType || proc[3],
          stepCount: proc.stepCount || proc[4],
        },
        steps: steps.map((s: any) => ({
          step: s.step || s[3],
          name: s.name || s[0],
          type: s.type || s[1],
          filePath: s.filePath || s[2],
        })),
      };
    }

    return { error: 'Invalid type. Use: symbol, cluster, or process' };
  }

  /**
   * Detect changes — git-diff based impact analysis.
   * Maps changed lines to indexed symbols, then finds affected processes.
   */
  private async detectChanges(
    repo: RepoHandle,
    params: {
      scope?: string;
      base_ref?: string;
      worktree?: string;
    },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    const scope = params.scope || 'unstaged';
    const { execFileSync } = await import('child_process');

    // Build git diff args based on scope (using execFileSync to avoid shell injection)
    let diffArgs: string[];
    switch (scope) {
      case 'staged':
        diffArgs = ['diff', '--staged', '-U0'];
        break;
      case 'all':
        diffArgs = ['diff', 'HEAD', '-U0'];
        break;
      case 'compare':
        if (!params.base_ref) return { error: 'base_ref is required for "compare" scope' };
        diffArgs = ['diff', params.base_ref, '-U0'];
        break;
      case 'unstaged':
      default:
        diffArgs = ['diff', '-U0'];
        break;
    }

    let diffOutput: string;
    try {
      // Resolve the cwd for git diff.
      //
      // In a linked worktree (e.g. /repo/wt-feature/), the user's staged and
      // unstaged changes live in that worktree's separate working directory and
      // index. Running `git diff` from the canonical repo root sees a different
      // working tree and returns empty output.
      //
      // Resolution order (see resolveWorktreeCwd for details):
      //   1. params.worktree — explicit override, validated against the
      //      registered repo's canonical root.
      //   2. Auto-detect — if the server's launch cwd (process.cwd()) is a
      //      linked worktree of the same canonical repo, use its git root.
      //   3. repo.repoPath — fallback (original behaviour, handled inside
      //      resolveWorktreeCwd when no worktree is detected).
      //
      // Start with the auto-detected value; override with the validated
      // explicit param when provided. This avoids a dead initial assignment.
      let diffCwd = resolveWorktreeCwd(repo.repoPath, process.cwd());
      if (params.worktree) {
        if (!path.isAbsolute(params.worktree)) {
          return {
            error: `worktree must be an absolute path, got: "${params.worktree}"`,
          };
        }
        const providedResolved = path.resolve(params.worktree);
        const repoCanonical = getCanonicalRepoRoot(repo.repoPath);
        if (!repoCanonical) {
          return {
            error: `Could not determine canonical root for repo "${repo.repoPath}". Is git available?`,
          };
        }
        const worktreeCanonical = getCanonicalRepoRoot(providedResolved);
        if (!worktreeCanonical || tryRealpath(worktreeCanonical) !== tryRealpath(repoCanonical)) {
          return {
            error: `worktree "${params.worktree}" is not a worktree of repo "${repo.repoPath}". Ensure the path is inside the same git repository.`,
          };
        }
        diffCwd = providedResolved;
      }

      // maxBuffer raised from Node's 1MB default to 256MB to avoid ENOBUFS on
      // repos with large unstaged/untracked diffs (e.g. unignored build folders).
      // See issue: spawnSync git ENOBUFS in detect_changes(scope="unstaged").
      diffOutput = execFileSync('git', diffArgs, {
        cwd: diffCwd,
        encoding: 'utf-8',
        maxBuffer: 256 * 1024 * 1024,
        windowsHide: true,
      });
    } catch (err: any) {
      return { error: `Git diff failed: ${err.message}` };
    }

    const fileDiffs: FileDiff[] = parseDiffHunks(diffOutput);

    if (fileDiffs.length === 0) {
      return {
        summary: {
          changed_count: 0,
          affected_count: 0,
          risk_level: 'none',
          message: 'No changes detected.',
        },
        changed_symbols: [],
        affected_processes: [],
      };
    }

    // Map diff hunks to indexed symbols via range overlap
    const changedSymbols: any[] = [];
    for (const fileDiff of fileDiffs) {
      if (fileDiff.hunks.length === 0) continue;

      // Build range overlap conditions for all hunks in this file
      const overlapConditions = fileDiff.hunks
        .map((_, i) => `(n.startLine <= $hunkEnd${i} AND n.endLine >= $hunkStart${i})`)
        .join(' OR ');

      const queryParams: Record<string, any> = { filePath: fileDiff.filePath };
      fileDiff.hunks.forEach((hunk, i) => {
        queryParams[`hunkStart${i}`] = hunk.startLine;
        queryParams[`hunkEnd${i}`] = hunk.endLine;
      });

      const symbolQuery = `
        MATCH (n) WHERE n.filePath ENDS WITH $filePath
          AND n.startLine IS NOT NULL AND n.endLine IS NOT NULL
          AND (${overlapConditions})
        RETURN n.id AS id, n.name AS name, labels(n)[0] AS type,
               n.filePath AS filePath, n.startLine AS startLine, n.endLine AS endLine
      `;

      try {
        const rows = await executeParameterized(repo.lbugPath, symbolQuery, queryParams);
        for (const sym of rows) {
          changedSymbols.push({
            id: sym.id || sym[0],
            name: sym.name || sym[1],
            type: sym.type || sym[2],
            filePath: sym.filePath || sym[3],
            change_type: 'touched',
          });
        }
      } catch (e) {
        logQueryError('detect-changes:file-symbols', e);
      }
    }

    // Find affected processes -- single batched query instead of N+1
    const affectedProcesses = new Map<string, any>();
    if (changedSymbols.length > 0) {
      const symIds = changedSymbols.map((s) => s.id);
      const symNameById = new Map(changedSymbols.map((s) => [s.id, s.name]));
      try {
        const procs = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
          WHERE n.id IN $ids
          RETURN n.id AS nodeId, p.id AS pid, p.heuristicLabel AS label,
                 p.processType AS processType, p.stepCount AS stepCount, r.step AS step
        `,
          { ids: symIds },
        );
        for (const proc of procs) {
          const nodeId = proc.nodeId || proc[0];
          const pid = proc.pid || proc[1];
          if (!affectedProcesses.has(pid)) {
            affectedProcesses.set(pid, {
              id: pid,
              name: proc.label || proc[2],
              process_type: proc.processType || proc[3],
              step_count: proc.stepCount || proc[4],
              changed_steps: [],
            });
          }
          affectedProcesses.get(pid)!.changed_steps.push({
            symbol: symNameById.get(nodeId) ?? nodeId,
            step: proc.step || proc[5],
          });
        }
      } catch (e) {
        logQueryError('detect-changes:process-lookup', e);
      }
    }

    const processCount = affectedProcesses.size;
    const risk =
      processCount === 0
        ? 'low'
        : processCount <= 5
          ? 'medium'
          : processCount <= 15
            ? 'high'
            : 'critical';

    return {
      summary: {
        changed_count: changedSymbols.length,
        affected_count: processCount,
        changed_files: fileDiffs.length,
        risk_level: risk,
      },
      changed_symbols: changedSymbols,
      affected_processes: Array.from(affectedProcesses.values()),
    };
  }

  /**
   * Rename tool — multi-file coordinated rename using graph + text search.
   * Graph refs are tagged "graph" (high confidence).
   * Additional refs found via text search are tagged "text_search" (lower confidence).
   */
  private async rename(
    repo: RepoHandle,
    params: {
      symbol_name?: string;
      symbol_uid?: string;
      new_name: string;
      file_path?: string;
      dry_run?: boolean;
    },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    const { new_name, file_path } = params;
    const dry_run = params.dry_run ?? true;

    if (!params.symbol_name && !params.symbol_uid) {
      return { error: 'Either symbol_name or symbol_uid is required.' };
    }

    /** Guard: ensure a file path resolves within the repo root (prevents path traversal) */
    const assertSafePath = (filePath: string): string => {
      const full = path.resolve(repo.repoPath, filePath);
      if (!full.startsWith(repo.repoPath + path.sep) && full !== repo.repoPath) {
        throw new Error(`Path traversal blocked: ${filePath}`);
      }
      return full;
    };

    // Step 1: Find the target symbol (reuse context's lookup)
    const lookupResult = await this.context(repo, {
      name: params.symbol_name,
      uid: params.symbol_uid,
      file_path,
    });

    if (lookupResult.status === 'ambiguous') {
      return lookupResult; // pass disambiguation through
    }
    if (lookupResult.error) {
      return lookupResult;
    }

    const sym = lookupResult.symbol;
    const oldName = sym.name;

    if (oldName === new_name) {
      return { error: 'New name is the same as the current name.' };
    }

    // Step 2: Collect edits from graph (high confidence)
    const changes = new Map<string, { file_path: string; edits: any[] }>();

    const addEdit = (
      filePath: string,
      line: number,
      oldText: string,
      newText: string,
      confidence: string,
    ) => {
      if (!changes.has(filePath)) {
        changes.set(filePath, { file_path: filePath, edits: [] });
      }
      changes.get(filePath)!.edits.push({ line, old_text: oldText, new_text: newText, confidence });
    };

    // The definition itself
    if (sym.filePath && sym.startLine) {
      try {
        const content = await fs.readFile(assertSafePath(sym.filePath), 'utf-8');
        const lines = content.split('\n');
        const lineIdx = sym.startLine - 1;
        if (lineIdx >= 0 && lineIdx < lines.length && lines[lineIdx].includes(oldName)) {
          const defRegex = new RegExp(
            `\\b${oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`,
            'g',
          );
          addEdit(
            sym.filePath,
            sym.startLine,
            lines[lineIdx].trim(),
            lines[lineIdx].replace(defRegex, new_name).trim(),
            'graph',
          );
        }
      } catch (e) {
        logQueryError('rename:read-definition', e);
      }
    }

    // All incoming refs from graph (callers, importers, etc.)
    const allIncoming = [
      ...(lookupResult.incoming.calls || []),
      ...(lookupResult.incoming.imports || []),
      ...(lookupResult.incoming.extends || []),
      ...(lookupResult.incoming.implements || []),
    ];

    let graphEdits = changes.size > 0 ? 1 : 0; // count definition edit

    for (const ref of allIncoming) {
      if (!ref.filePath) continue;
      try {
        const content = await fs.readFile(assertSafePath(ref.filePath), 'utf-8');
        const lines = content.split('\n');
        for (let i = 0; i < lines.length; i++) {
          if (lines[i].includes(oldName)) {
            addEdit(
              ref.filePath,
              i + 1,
              lines[i].trim(),
              lines[i]
                .replace(
                  new RegExp(`\\b${oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g'),
                  new_name,
                )
                .trim(),
              'graph',
            );
            graphEdits++;
            break; // one edit per file from graph refs
          }
        }
      } catch (e) {
        logQueryError('rename:read-ref', e);
      }
    }

    // Step 3: Text search for refs the graph might have missed
    let astSearchEdits = 0;
    const graphFiles = new Set(
      [sym.filePath, ...allIncoming.map((r) => r.filePath)].filter(Boolean),
    );

    // Simple text search across the repo for the old name (in files not already covered by graph)
    try {
      const { execFileSync } = await import('child_process');
      const rgArgs = [
        '-l',
        '--type-add',
        'code:*.{ts,tsx,js,jsx,py,go,rs,java,c,h,cpp,cc,cxx,hpp,hxx,hh,cs,php,swift}',
        '-t',
        'code',
        `\\b${oldName}\\b`,
        '.',
      ];
      const output = execFileSync('rg', rgArgs, {
        cwd: repo.repoPath,
        encoding: 'utf-8',
        timeout: 5000,
        // Avoid ENOBUFS on large repos: rg -l can list many files.
        maxBuffer: 256 * 1024 * 1024,
        windowsHide: true,
      });
      const files = output
        .trim()
        .split('\n')
        .filter((f) => f.length > 0);

      for (const file of files) {
        const normalizedFile = file.replace(/\\/g, '/').replace(/^\.\//, '');
        if (graphFiles.has(normalizedFile)) continue; // already covered by graph

        try {
          const content = await fs.readFile(assertSafePath(normalizedFile), 'utf-8');
          const lines = content.split('\n');
          const regex = new RegExp(`\\b${oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g');
          for (let i = 0; i < lines.length; i++) {
            regex.lastIndex = 0;
            if (regex.test(lines[i])) {
              regex.lastIndex = 0;
              addEdit(
                normalizedFile,
                i + 1,
                lines[i].trim(),
                lines[i].replace(regex, new_name).trim(),
                'text_search',
              );
              astSearchEdits++;
            }
          }
        } catch (e) {
          logQueryError('rename:text-search-read', e);
        }
      }
    } catch (e) {
      logQueryError('rename:ripgrep', e);
    }

    // Step 4: Apply or preview
    const allChanges = Array.from(changes.values());
    const totalEdits = allChanges.reduce((sum, c) => sum + c.edits.length, 0);

    if (!dry_run) {
      // Apply edits to files
      for (const change of allChanges) {
        try {
          const fullPath = assertSafePath(change.file_path);
          let content = await fs.readFile(fullPath, 'utf-8');
          const regex = new RegExp(`\\b${oldName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, 'g');
          content = content.replace(regex, new_name);
          await fs.writeFile(fullPath, content, 'utf-8');
        } catch (e) {
          logQueryError('rename:apply-edit', e);
        }
      }
    }

    return {
      status: 'success',
      old_name: oldName,
      new_name,
      files_affected: allChanges.length,
      total_edits: totalEdits,
      graph_edits: graphEdits,
      text_search_edits: astSearchEdits,
      changes: allChanges,
      applied: !dry_run,
    };
  }

  private async impact(repo: RepoHandle, params: ImpactParams): Promise<any> {
    try {
      return await this._impactImpl(repo, params);
    } catch (err: any) {
      // Return structured error instead of crashing (#321)
      return {
        error: (err instanceof Error ? err.message : String(err)) || 'Impact analysis failed',
        target: { name: params.target },
        direction: params.direction,
        impactedCount: 0,
        risk: 'UNKNOWN',
        suggestion: 'The graph query failed — try gitnexus context <symbol> as a fallback',
        ...(isWalCorruptionError(err) ? { recoverySuggestion: WAL_RECOVERY_SUGGESTION } : {}),
      };
    }
  }

  private async _impactImpl(repo: RepoHandle, params: ImpactParams): Promise<any> {
    await this.ensureInitialized(repo);

    const { target, direction } = params;
    const maxDepth = params.maxDepth || 3;
    // Map legacy relation type names before filtering (backward compat for OVERRIDES → METHOD_OVERRIDES)
    const mappedRelTypes = params.relationTypes?.flatMap((t: string) =>
      t === 'OVERRIDES' ? ['OVERRIDES', 'METHOD_OVERRIDES'] : [t],
    );
    const hasExplicitRelationTypes = mappedRelTypes !== undefined && mappedRelTypes.length > 0;
    const rawRelTypes =
      mappedRelTypes && mappedRelTypes.length > 0
        ? mappedRelTypes.filter((t: string) => VALID_RELATION_TYPES.has(t))
        : [
            'CALLS',
            'IMPORTS',
            'EXTENDS',
            'IMPLEMENTS',
            'USES',
            'METHOD_OVERRIDES',
            'OVERRIDES',
            'METHOD_IMPLEMENTS',
          ];
    const relationTypes =
      rawRelTypes.length > 0
        ? rawRelTypes
        : [
            'CALLS',
            'IMPORTS',
            'EXTENDS',
            'IMPLEMENTS',
            'USES',
            'METHOD_OVERRIDES',
            'OVERRIDES',
            'METHOD_IMPLEMENTS',
          ];
    const includeTests = params.includeTests ?? false;
    const minConfidence = params.minConfidence ?? 0;

    // Resolve target via the shared symbol resolver. When the caller passes
    // target_uid we skip the name lookup entirely (zero-ambiguity). Otherwise
    // we rank candidates (#470) and either proceed with a confident single
    // match, or return a structured ambiguous response instead of silently
    // picking the wrong symbol.
    //
    // The resolver preserves the #480 Class/Constructor preference heuristic:
    // when a Class and its Constructor share name + filePath, the Class is
    // selected silently.
    const outcome = await this.resolveSymbolCandidates(
      repo,
      { uid: params.target_uid, name: target },
      { file_path: params.file_path, kind: params.kind },
    );

    if (outcome.kind === 'not_found') {
      const missing = params.target_uid ?? target;
      return {
        error: `Target '${missing}' not found`,
        target: { name: target },
        direction,
        impactedCount: 0,
        risk: 'UNKNOWN',
      };
    }

    if (outcome.kind === 'ambiguous') {
      return {
        status: 'ambiguous',
        message: `Found ${outcome.candidates.length} symbols matching '${target}'. Use target_uid, file_path, or kind to disambiguate.`,
        target: { name: target },
        direction,
        impactedCount: 0,
        risk: 'UNKNOWN',
        candidates: outcome.candidates.map((c) => ({
          uid: c.id,
          name: c.name,
          kind: c.type,
          filePath: c.filePath,
          line: c.startLine,
          score: Number(c.score.toFixed(2)),
        })),
      };
    }

    const sym = {
      id: outcome.symbol.id,
      name: outcome.symbol.name,
      filePath: outcome.symbol.filePath,
    };
    const symType = outcome.resolvedLabel || outcome.symbol.type || '';

    const effectiveRelationTypes =
      (symType === 'Class' || symType === 'Interface') &&
      !hasExplicitRelationTypes &&
      !relationTypes.includes('ACCESSES')
        ? [...relationTypes, 'ACCESSES']
        : relationTypes;

    return this._runImpactBFS(repo, sym, symType, direction, {
      maxDepth,
      relationTypes: effectiveRelationTypes,
      includeTests,
      minConfidence,
      limit: Number.isFinite(params.limit) ? params.limit : 100,
      offset: Number.isFinite(params.offset) ? params.offset : 0,
      summaryOnly: params.summaryOnly,
    });
  }

  /**
   * Shared BFS traversal for impact analysis (name-resolved or UID-resolved symbol).
   */
  private async _runImpactBFS(
    repo: RepoHandle,
    sym: any,
    symType: string,
    direction: 'upstream' | 'downstream',
    opts: {
      maxDepth: number;
      relationTypes: string[];
      includeTests: boolean;
      minConfidence: number;
      limit?: number;
      offset?: number;
      summaryOnly?: boolean;
      skipPerSymbolEnrichment?: boolean;
    },
  ): Promise<any> {
    const { maxDepth, relationTypes, includeTests, minConfidence } = opts;
    const skipPerSymbolEnrichment = opts.skipPerSymbolEnrichment ?? false;
    const hasExplicitLimit = typeof opts.limit === 'number' && Number.isFinite(opts.limit);
    const paginationLimit = hasExplicitLimit
      ? Math.max(1, Math.min(Math.trunc(opts.limit!), 10000))
      : Infinity;
    const rawOffset =
      typeof opts.offset === 'number' && Number.isFinite(opts.offset) ? opts.offset : 0;
    const paginationOffset = Math.max(0, Math.trunc(rawOffset));
    const summaryOnly = opts.summaryOnly ?? false;
    // Bind the BFS frontier query's filters as parameters (#1907 review F5):
    // node ids and relation types as bound lists, the confidence floor as a
    // bound number — no string interpolation reaches the query text. Preserve
    // the original "no confidence clause when minConfidence <= 0" behavior: an
    // unconditional `>= 0` would wrongly exclude NULL-confidence edges that the
    // unfiltered query includes.
    const safeMinConfidence = Number.isFinite(minConfidence) ? minConfidence : 0;
    const confidenceFilter = safeMinConfidence > 0 ? ' AND r.confidence >= $minConfidence' : '';

    const symId = sym.id || sym[0];

    const impacted: any[] = [];
    const visited = new Set<string>([symId]);
    let frontier = [symId];
    let traversalComplete = true;

    // Fix #480: For Java (and other JVM) Class/Interface nodes, CALLS edges
    // point to Constructor nodes and IMPORTS edges point to File nodes — not
    // the Class/Interface itself. Seed the frontier with the Constructor(s)
    // and owning File so the BFS traversal finds those edges naturally.
    // The owning File is kept only as an internal seed (frontier/visited) and
    // is NOT added to impacted — it is the definition container, not an
    // upstream dependent. The BFS will discover IMPORTS edges on it naturally.
    if (symType === 'Class' || symType === 'Interface') {
      try {
        // Run both seed queries in parallel — they are independent.
        const [ctorRows, fileRows] = await Promise.all([
          executeParameterized(
            repo.lbugPath,
            `
            MATCH (n)-[hm:CodeRelation]->(c:Constructor)
            WHERE n.id = $symId AND hm.type = 'HAS_METHOD'
            RETURN c.id AS id, c.name AS name, labels(c)[0] AS type, c.filePath AS filePath
          `,
            { symId },
          ),
          // Restrict to DEFINES edges only — other File->Class edge types (if
          // any) should not be treated as the owning file relationship.
          executeParameterized(
            repo.lbugPath,
            `
            MATCH (f:File)-[rel:CodeRelation]->(n)
            WHERE n.id = $symId AND rel.type = 'DEFINES'
            RETURN f.id AS id, f.name AS name, labels(f)[0] AS type, f.filePath AS filePath
          `,
            { symId },
          ),
        ]);

        for (const r of ctorRows) {
          const rid = r.id || r[0];
          if (rid && !visited.has(rid)) {
            visited.add(rid);
            frontier.push(rid);
          }
        }
        for (const r of fileRows) {
          const rid = r.id || r[0];
          if (rid && !visited.has(rid)) {
            visited.add(rid);
            frontier.push(rid);
          }
        }

        const typedPropertyRows = await executeParameterized(
          repo.lbugPath,
          `
          MATCH (p:\`Property\`)
          WHERE p.declaredType = $name
             OR p.declaredType STARTS WITH $genericPrefix
             OR p.declaredType CONTAINS $genericArg
          RETURN p.id AS id, p.name AS name, labels(p)[0] AS type, p.filePath AS filePath
        `,
          {
            name: sym.name,
            genericPrefix: `${sym.name}<`,
            genericArg: `<${sym.name}>`,
          },
        );

        for (const r of typedPropertyRows) {
          const rid = r.id || r[0];
          if (rid && !visited.has(rid)) {
            visited.add(rid);
            frontier.push(rid);
          }
        }
      } catch (e) {
        logQueryError('impact:class-node-expansion', e);
      }
    }

    for (let depth = 1; depth <= maxDepth && frontier.length > 0; depth++) {
      const nextFrontier: string[] = [];

      // Batch frontier nodes into a single Cypher query per depth level.
      // ids/types/confidence are bound parameters (see above) — no interpolation.
      const query =
        direction === 'upstream'
          ? `MATCH (caller)-[r:CodeRelation]->(n) WHERE n.id IN $frontierIds AND r.type IN $relTypes${confidenceFilter} RETURN n.id AS sourceId, caller.id AS id, caller.name AS name, labels(caller)[0] AS type, caller.filePath AS filePath, r.type AS relType, r.confidence AS confidence`
          : `MATCH (n)-[r:CodeRelation]->(callee) WHERE n.id IN $frontierIds AND r.type IN $relTypes${confidenceFilter} RETURN n.id AS sourceId, callee.id AS id, callee.name AS name, labels(callee)[0] AS type, callee.filePath AS filePath, r.type AS relType, r.confidence AS confidence`;

      try {
        const related = await executeParameterized(repo.lbugPath, query, {
          frontierIds: frontier,
          relTypes: relationTypes,
          ...(safeMinConfidence > 0 ? { minConfidence: safeMinConfidence } : {}),
        });

        for (const rel of related) {
          const relId = rel.id || rel[1];
          const filePath = rel.filePath || rel[4] || '';

          if (!includeTests && isTestFilePath(filePath)) continue;

          if (!visited.has(relId)) {
            visited.add(relId);
            nextFrontier.push(relId);
            const storedConfidence = rel.confidence ?? rel[6];
            const relationType = rel.relType || rel[5];
            // Prefer the stored confidence from the graph (set at analysis time);
            // fall back to the per-type floor for edges without a stored value.
            const effectiveConfidence =
              typeof storedConfidence === 'number' && storedConfidence > 0
                ? storedConfidence
                : confidenceForRelType(relationType);
            impacted.push({
              depth,
              id: relId,
              name: rel.name || rel[2],
              type: rel.type || rel[3],
              filePath,
              relationType,
              confidence: effectiveConfidence,
            });
          }
        }
      } catch (e) {
        logQueryError('impact:depth-traversal', e);
        // Break out of depth loop on query failure but return partial results
        // collected so far, rather than silently swallowing the error (#321)
        traversalComplete = false;
        break;
      }

      frontier = nextFrontier;
    }

    const grouped: Record<number, any[]> = {};
    for (const item of impacted) {
      if (!grouped[item.depth]) grouped[item.depth] = [];
      grouped[item.depth].push(item);
    }

    // ── Enrichment: affected processes, modules, risk ──────────────
    const directCount = (grouped[1] || []).length;
    let affectedProcesses: any[] = [];
    let affectedModules: any[] = [];
    // Per-symbol process membership: maps impacted symbol id -> list of processes
    // it participates in. Populated by a second chunked Cypher pass below when
    // any process is affected at all. Surfaced as `processes: [...]` on each
    // byDepth item so consumers can tell which caller belongs to which cron/
    // webhook/route without a follow-up query.
    const perSymbolProcesses = new Map<
      string,
      Array<{ id: string; label: string; processType: string; step: number }>
    >();

    // Chunking bounds for batched DB round-trips. Declared at function scope so
    // both the in-block enrichment passes and the post-pagination per-symbol
    // process enrichment can reference them.
    const CHUNK_SIZE = 100;
    // Max number of chunks to process to avoid unbounded DB round-trips.
    // Configurable via env IMPACT_MAX_CHUNKS, default 10 => max items = 1000
    const MAX_CHUNKS = parseInt(process.env.IMPACT_MAX_CHUNKS || '10', 10);

    if (impacted.length > 0) {
      // ── Process enrichment: batched chunking (bounded by MAX_CHUNKS) ─
      // Uses merged Cypher query (WITH + OPTIONAL MATCH) to fetch
      // process + entry point info in 1 round-trip per chunk. Converted to
      // parameterized queries to avoid manual string escaping and long query strings.
      const entryPointMap = new Map<
        string,
        {
          name: string;
          type: string;
          filePath: string;
          affected_process_count: number;
          total_hits: number;
          earliest_broken_step: number;
        }
      >();

      // Map process id -> entryPointId to allow fixing missing minStep values later
      const processToEntryPoint = new Map<string, string>();
      // Collect process ids where MIN(r.step) returned null so we can retry in batch
      const processesMissingMinStep = new Set<string>();

      let chunksProcessed = 0;
      for (
        let i = 0;
        i < impacted.length && chunksProcessed < MAX_CHUNKS;
        i += CHUNK_SIZE, chunksProcessed++
      ) {
        const chunk = impacted.slice(i, i + CHUNK_SIZE);
        const ids = chunk.map((item) => String(item.id ?? ''));

        try {
          // Use parameterized list to avoid building long query strings
          const rows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
            WHERE s.id IN $ids
            WITH p, COUNT(DISTINCT s.id) AS hits, MIN(r.step) AS minStep
            OPTIONAL MATCH (ep {id: p.entryPointId})
            RETURN p.id AS pId, p.heuristicLabel AS name, p.processType AS processType,
                   p.entryPointId AS entryPointId, hits, minStep, p.stepCount AS stepCount,
                   ep.name AS epName, labels(ep)[0] AS epType, ep.filePath AS epFilePath
          `,
            { ids },
          ).catch(() => []);

          for (const row of rows) {
            const pId = row.pId ?? row[0];
            const epId = row.entryPointId ?? row[3] ?? row.pId ?? row[0];
            // Track mapping from process -> entryPoint so we can backfill missing minStep
            if (pId) processToEntryPoint.set(String(pId), String(epId));

            // Normalize epName: prefer epName, fall back to other columns, and
            // ensure we don't keep an empty string (labels(...) can return "").
            const epNameRaw = row.epName ?? row[7] ?? row.name ?? row[1] ?? 'unknown';
            const epName =
              typeof epNameRaw === 'string' && epNameRaw.trim().length > 0
                ? epNameRaw.trim()
                : 'unknown';

            // Normalize epType: labels(ep)[0] can return an empty string in
            // some DBs (LadybugDB). Using nullish coalescing (??) preserves
            // empty strings, which results in empty `type` values being
            // propagated. Treat empty-string labels as missing and fall back
            // to the next candidate or a sensible default.
            const epTypeRaw = row.epType ?? row[8] ?? '';
            const epType =
              typeof epTypeRaw === 'string' && epTypeRaw.trim().length > 0
                ? epTypeRaw.trim()
                : 'Function';

            const epFilePath = row.epFilePath ?? row[9] ?? '';
            const hits = row.hits ?? row[4] ?? 0;
            const minStep = row.minStep ?? row[5];
            // If the DB returned null for minStep, note the process id so we
            // can run a follow-up query using a different aggregation strategy.
            if (minStep === null || minStep === undefined) {
              if (pId) processesMissingMinStep.add(String(pId));
            }
            if (!entryPointMap.has(epId)) {
              entryPointMap.set(epId, {
                name: epName,
                type: epType,
                filePath: epFilePath,
                affected_process_count: 0,
                total_hits: 0,
                earliest_broken_step: Infinity,
              });
            }
            const ep = entryPointMap.get(epId)!;
            ep.affected_process_count += 1;
            ep.total_hits += hits;
            ep.earliest_broken_step = Math.min(ep.earliest_broken_step, minStep ?? Infinity);
          }
        } catch (e) {
          logQueryError('impact:process-chunk', e);
        }
      }

      // If some processes returned null minStep, try a batched follow-up query
      // using the full impacted id set. This handles older indexes or DBs
      // where MIN(r.step) can come back null even when step properties exist.
      if (processesMissingMinStep.size > 0) {
        try {
          const pIds = Array.from(processesMissingMinStep);
          const allImpactedIds = impacted.map((it) => String(it.id ?? ''));
          const missingRows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
            WHERE p.id IN $pIds AND s.id IN $ids
            RETURN p.id AS pid, MIN(r.step) AS minStep
          `,
            { pIds, ids: allImpactedIds },
          ).catch(() => []);

          for (const mr of missingRows) {
            const pid = mr.pid ?? mr[0];
            const minStep = mr.minStep ?? mr[1];
            const epId = processToEntryPoint.get(String(pid));
            if (!epId) continue;
            const ep = entryPointMap.get(epId);
            if (!ep) continue;
            if (typeof minStep === 'number') {
              ep.earliest_broken_step = Math.min(ep.earliest_broken_step, minStep);
            }
          }
        } catch (e) {
          logQueryError('impact:process-chunk-backfill', e);
        }
      }

      // If we capped chunks, mark traversal incomplete so caller knows results are partial
      if (chunksProcessed * CHUNK_SIZE < impacted.length) {
        traversalComplete = false;
      }

      affectedProcesses = Array.from(entryPointMap.values())
        .map((ep) => ({
          ...ep,
          earliest_broken_step:
            ep.earliest_broken_step === Infinity ? null : ep.earliest_broken_step,
        }))
        .sort((a, b) => b.total_hits - a.total_hits);

      // Per-symbol process membership is populated post-pagination (see below)
      // so it covers exactly the symbols returned in byDepth, not a pre-capped
      // flat slice that could miss depth-2+ symbols when depth-1 is large.

      // ── Module enrichment: use same cap as process enrichment and parameterized queries
      const maxItems = Math.min(impacted.length, MAX_CHUNKS * CHUNK_SIZE);
      const cappedImpacted = impacted.slice(0, maxItems);
      const allIdsArr = cappedImpacted.map((i: any) => String(i.id ?? ''));
      const d1Items = (grouped[1] || []).slice(0, maxItems);
      const d1IdsArr = d1Items.map((i: any) => String(i.id ?? ''));

      // Chunked module enrichment: run the MEMBER_OF queries in chunks
      // to avoid large single queries or concurrent Kuzu calls that can
      // crash (SIGSEGV) on arm64 macOS; behavior preserves existing maxItems cap and returns equivalent aggregated results.
      const moduleHitsMap = new Map<string, number>();
      const directModuleSet = new Set<string>();

      // Helper to run a single module chunk and accumulate hits by name
      const runModuleChunk = async (idsChunk: string[]) => {
        if (!idsChunk || idsChunk.length === 0) return;
        try {
          const rows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
            WHERE s.id IN $ids
            RETURN c.heuristicLabel AS name, COUNT(DISTINCT s.id) AS hits
            ORDER BY hits DESC
            LIMIT 20
          `,
            { ids: idsChunk },
          ).catch(() => []);

          for (const r of rows) {
            const name = r.name ?? r[0] ?? null;
            const hits = (r.hits ?? r[1]) || 0;
            if (!name) continue;
            moduleHitsMap.set(name, (moduleHitsMap.get(name) || 0) + hits);
          }
        } catch (e) {
          logQueryError('impact:module-chunk', e);
        }
      };

      // Run module query chunks sequentially (safe on arm64 macOS)
      for (let i = 0; i < allIdsArr.length; i += CHUNK_SIZE) {
        const chunkIds = allIdsArr.slice(i, i + CHUNK_SIZE);
        await runModuleChunk(chunkIds);
      }

      // Run direct module query similarly (distinct heuristic labels for depth-1 items)
      const runDirectModuleChunk = async (idsChunk: string[]) => {
        if (!idsChunk || idsChunk.length === 0) return;
        try {
          const rows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (s)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
            WHERE s.id IN $ids
            RETURN DISTINCT c.heuristicLabel AS name
          `,
            { ids: idsChunk },
          ).catch(() => []);
          for (const r of rows) {
            const name = r.name ?? r[0] ?? null;
            if (name) directModuleSet.add(name);
          }
        } catch (e) {
          logQueryError('impact:direct-module-chunk', e);
        }
      };

      for (let i = 0; i < d1IdsArr.length; i += CHUNK_SIZE) {
        const chunkIds = d1IdsArr.slice(i, i + CHUNK_SIZE);
        await runDirectModuleChunk(chunkIds);
      }

      // Build final moduleRows array from aggregated hits map, sorted & limited
      const moduleRows = Array.from(moduleHitsMap.entries())
        .map(([name, hits]) => ({ name, hits }))
        .sort((a, b) => b.hits - a.hits)
        .slice(0, 20);

      const directModuleRows = Array.from(directModuleSet).map((name) => ({ name }));

      // Build affectedModules in the same shape as original implementation
      const directModuleNameSet = new Set(directModuleRows.map((r: any) => r.name || r[0]));
      affectedModules = moduleRows.map((r: any) => {
        const name = r.name ?? r[0];
        const hits = r.hits ?? r[1] ?? 0;
        return {
          name,
          hits,
          impact: directModuleNameSet.has(name) ? 'direct' : 'indirect',
        };
      });
    }

    // Risk scoring
    const processCount = affectedProcesses.length;
    const moduleCount = affectedModules.length;
    let risk = 'LOW';
    if (directCount >= 30 || processCount >= 5 || moduleCount >= 5 || impacted.length >= 200) {
      risk = 'CRITICAL';
    } else if (
      directCount >= 15 ||
      processCount >= 3 ||
      moduleCount >= 3 ||
      impacted.length >= 100
    ) {
      risk = 'HIGH';
    } else if (directCount >= 5 || impacted.length >= 30) {
      risk = 'MEDIUM';
    }

    // Build per-depth counts (always included, even in summaryOnly mode)
    const byDepthCounts: Record<number, number> = {};
    for (const [depth, items] of Object.entries(grouped)) {
      byDepthCounts[Number(depth)] = items.length;
    }

    const base = {
      target: {
        id: symId,
        name: sym.name || sym[1],
        type: symType,
        filePath: sym.filePath || sym[2],
      },
      direction,
      impactedCount: impacted.length,
      risk,
      ...(!traversalComplete && { partial: true }),
      summary: {
        direct: directCount,
        processes_affected: processCount,
        modules_affected: moduleCount,
      },
      byDepthCounts,
      affected_processes: affectedProcesses,
      affected_modules: affectedModules,
    };

    if (summaryOnly) {
      return base;
    }

    // Apply limit/offset pagination per depth level.
    const paginatedGrouped: Record<number, any[]> = {};
    let anyTruncated = false;
    for (const [depth, items] of Object.entries(grouped)) {
      const total = items.length;
      const sliced = items.slice(paginationOffset, paginationOffset + paginationLimit);
      paginatedGrouped[Number(depth)] = sliced;
      if (paginationOffset > 0 || paginationOffset + paginationLimit < total) {
        anyTruncated = true;
      }
    }

    // ── Per-symbol process membership enrichment (post-pagination) ───────
    // Runs after paginatedGrouped is built so we enrich only the IDs that
    // actually appear in the response. This eliminates the false-empty
    // processes:[] case where a depth-2+ symbol's flat position in `impacted`
    // exceeded MAX_CHUNKS*CHUNK_SIZE even though it is returned by byDepth.
    // Also uses DISTINCT + MIN(r.step) per (symbol, process) pair to avoid
    // duplicate entries when a symbol has multiple STEP_IN_PROCESS edges.
    // Skipped entirely when `skipPerSymbolEnrichment` is set (group cross-repo
    // fan-out, which consumes byDepth but not byDepth[].processes); the
    // attach-loop below still stamps an empty processes:[] for shape stability.
    let perSymbolEnrichmentCapped = false;
    if (affectedProcesses.length > 0 && !skipPerSymbolEnrichment) {
      // Collect unique IDs from the paginated result in one pass.
      const pageIds = new Set<string>();
      for (const items of Object.values(paginatedGrouped)) {
        for (const it of items) {
          const id = String(it.id ?? '');
          if (id) pageIds.add(id);
        }
      }
      // Bound the enrichment to the same ceiling as the aggregation pass
      // (MAX_CHUNKS * CHUNK_SIZE) so a large paginated page cannot trigger
      // unbounded DB round-trips (DoD 2.6). When capped, mark the result
      // partial so callers know some returned symbols may carry an empty
      // processes:[] that is a cap artifact, not a true absence.
      const maxPageIds = MAX_CHUNKS * CHUNK_SIZE;
      let pageIdArr = Array.from(pageIds);
      if (pageIdArr.length > maxPageIds) {
        pageIdArr = pageIdArr.slice(0, maxPageIds);
        perSymbolEnrichmentCapped = true;
      }
      for (let i = 0; i < pageIdArr.length; i += CHUNK_SIZE) {
        const chunkIds = pageIdArr.slice(i, i + CHUNK_SIZE);
        try {
          const rows = await executeParameterized(
            repo.lbugPath,
            `
            MATCH (s)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p:Process)
            WHERE s.id IN $ids
            RETURN s.id AS sid, p.id AS pid, p.heuristicLabel AS pName,
                   p.processType AS pType, MIN(r.step) AS step
          `,
            { ids: chunkIds },
          ).catch(() => []);
          for (const row of rows) {
            const sid = row.sid ?? row[0];
            if (!sid) continue;
            const procEntry = {
              id: String(row.pid ?? row[1] ?? ''),
              label: String(row.pName ?? row[2] ?? ''),
              processType: String(row.pType ?? row[3] ?? ''),
              step: Number(row.step ?? row[4] ?? -1),
            };
            const list = perSymbolProcesses.get(String(sid));
            if (list) list.push(procEntry);
            else perSymbolProcesses.set(String(sid), [procEntry]);
          }
        } catch (e) {
          logQueryError('impact:per-symbol-process-chunk', e);
        }
      }
    }

    // Attach processes field to each paginated item.
    for (const items of Object.values(paginatedGrouped)) {
      for (const it of items) {
        it.processes = perSymbolProcesses.get(String(it.id)) ?? [];
      }
    }

    return {
      ...base,
      // Surface partial if the per-symbol enrichment was capped, even when the
      // BFS traversal itself completed — some returned symbols may carry an
      // empty processes:[] that is a cap artifact rather than a true absence.
      ...(perSymbolEnrichmentCapped && { partial: true }),
      ...(anyTruncated && {
        pagination: {
          ...(Number.isFinite(paginationLimit) && { limit: paginationLimit }),
          offset: paginationOffset,
          truncated: true,
        },
      }),
      byDepth: paginatedGrouped,
    };
  }

  /**
   * UID-based impact for cross-repo fan-out. Same result shape as `impact`.
   * Returns null if the repo is unknown, the UID is missing, or analysis fails.
   */
  async impactByUid(
    repoId: string,
    uid: string,
    direction: string,
    opts: {
      maxDepth: number;
      relationTypes: string[];
      minConfidence: number;
      includeTests: boolean;
      signal?: AbortSignal;
    },
  ): Promise<any | null> {
    // Honor an already-aborted signal at the entry boundary as a fast
    // path. Cooperative cancellation inside _runImpactBFS is out of
    // scope — the caller's Promise.race against the same signal
    // resolves the await regardless of how long this body runs.
    if (opts.signal?.aborted) return null;
    let repo: RepoHandle | undefined;
    try {
      await this.refreshRepos();
      // Fetch the resolved handle BEFORE init and pass it through, so a
      // concurrent refresh can't remap the id to a different clone (#2067).
      repo = this.repos.get(repoId);
      if (repo) await this.ensureInitialized(repo);
    } catch {
      return null;
    }
    if (!repo) return null; // unknown repo → null (preserves contract)

    const dir: 'upstream' | 'downstream' = direction === 'downstream' ? 'downstream' : 'upstream';

    let rows: any[];
    try {
      rows = await executeParameterized(
        repo.lbugPath, // pool keyed by the resolved clone's path, not the id
        `MATCH (n) WHERE n.id = $uid
         RETURN n.id AS id, n.name AS name, n.filePath AS filePath, labels(n)[0] AS type
         LIMIT 1`,
        { uid },
      );
    } catch {
      return null;
    }
    if (!rows?.length) return null;

    const sym = rows[0];
    const labelRaw = sym.type ?? sym[3];
    const symType =
      typeof labelRaw === 'string' && labelRaw.trim().length > 0 ? labelRaw.trim() : '';

    // Map legacy relation type names (backward compat for OVERRIDES → METHOD_OVERRIDES)
    const mappedRelTypes = opts.relationTypes?.flatMap((t: string) =>
      t === 'OVERRIDES' ? ['OVERRIDES', 'METHOD_OVERRIDES'] : [t],
    );
    const rawRelTypes =
      mappedRelTypes && mappedRelTypes.length > 0
        ? mappedRelTypes.filter((t: string) => VALID_RELATION_TYPES.has(t))
        : [
            'CALLS',
            'IMPORTS',
            'EXTENDS',
            'IMPLEMENTS',
            'METHOD_OVERRIDES',
            'OVERRIDES',
            'METHOD_IMPLEMENTS',
          ];
    const relationTypes =
      rawRelTypes.length > 0
        ? rawRelTypes
        : [
            'CALLS',
            'IMPORTS',
            'EXTENDS',
            'IMPLEMENTS',
            'METHOD_OVERRIDES',
            'OVERRIDES',
            'METHOD_IMPLEMENTS',
          ];

    try {
      // skipPerSymbolEnrichment suppresses ONLY the per-symbol STEP_IN_PROCESS
      // enrichment pass while preserving byDepth. Group-mode cross-repo fan-out
      // may fan across many repos; the per-symbol pass adds up to MAX_CHUNKS
      // extra round-trips per repo, which is unacceptable at group scale. But
      // cross-impact fan-out DOES consume byDepth (cross-impact.ts reads
      // fan.byDepth to populate group by_depth), so summaryOnly would wrongly
      // drop it. Group callers do not consume byDepth[].processes, so skipping
      // only that enrichment is the correct, targeted suppression.
      return await this._runImpactBFS(repo, sym, symType, dir, {
        maxDepth: opts.maxDepth,
        relationTypes,
        includeTests: opts.includeTests,
        minConfidence: opts.minConfidence,
        skipPerSymbolEnrichment: true,
      });
    } catch {
      return null;
    }
  }

  private handleGroupTool(method: string, params: Record<string, unknown>): Promise<unknown> {
    switch (method) {
      case 'group_list':
        return this.groupList(params);
      case 'group_sync':
        return this.groupSync(params);
      default:
        throw new Error(
          `Unknown group tool: ${method}. Removed tools: use repo "@<groupName>" on impact, query, or context (optional "/<memberPath>"), or MCP resources.`,
        );
    }
  }

  /**
   * Dispatch impact/query/context when `repo` is `@groupName` or `@groupName/memberPath`
   * (group mode — not the global indexed-repo `repo` parameter).
   */
  private async callToolAtGroupRepo(
    method: string,
    params: Record<string, unknown>,
  ): Promise<unknown> {
    await this.refreshRepos();

    if (
      params.service !== undefined &&
      params.service !== null &&
      String(params.service).trim() === ''
    ) {
      return { error: 'service must not be an empty string' };
    }

    const raw = String(params.repo).slice(1);
    const slash = raw.indexOf('/');
    const groupName = (slash === -1 ? raw : raw.slice(0, slash)).trim();
    const memberRest = slash === -1 ? undefined : raw.slice(slash + 1).trim() || undefined;

    const resolved = await resolveAtGroupMemberRepoPath(groupName, memberRest);
    if (resolved.ok === false) return { error: resolved.error };

    const svc = this.getGroupService();
    if (method === 'impact') {
      const impactArgs: Record<string, unknown> = {
        name: groupName,
        repo: resolved.repoPath,
        target: params.target,
        direction: params.direction,
      };
      if (params.maxDepth !== undefined) impactArgs.maxDepth = params.maxDepth;
      if (params.crossDepth !== undefined) impactArgs.crossDepth = params.crossDepth;
      if (params.relationTypes !== undefined) impactArgs.relationTypes = params.relationTypes;
      if (params.includeTests !== undefined) impactArgs.includeTests = params.includeTests;
      if (params.minConfidence !== undefined) impactArgs.minConfidence = params.minConfidence;
      if (params.service !== undefined && params.service !== null)
        impactArgs.service = params.service;
      if (typeof params.subgroup === 'string') impactArgs.subgroup = params.subgroup;
      if (params.timeoutMs !== undefined) impactArgs.timeoutMs = params.timeoutMs;
      if (params.timeout !== undefined) impactArgs.timeout = params.timeout;
      // limit/offset/summaryOnly are not forwarded to group-mode impact:
      // runGroupImpact uses GROUP_LOCAL_PHASE_LIMIT internally for UID
      // collection and does not re-paginate the local result yet.
      return svc.groupImpact(impactArgs);
    }
    if (method === 'query') {
      const queryArgs: Record<string, unknown> = {
        name: groupName,
        query: params.query,
      };
      if (typeof params.task_context === 'string') queryArgs.task_context = params.task_context;
      if (typeof params.goal === 'string') queryArgs.goal = params.goal;
      if (typeof params.limit === 'number') queryArgs.limit = params.limit;
      if (typeof params.max_symbols === 'number') queryArgs.max_symbols = params.max_symbols;
      if (params.include_content !== undefined) queryArgs.include_content = params.include_content;
      if (params.service !== undefined && params.service !== null)
        queryArgs.service = params.service;
      if (memberRest !== undefined) {
        queryArgs.subgroup = memberRest;
        queryArgs.subgroupExact = true;
      }
      return svc.groupQuery(queryArgs);
    }
    if (method === 'context') {
      const targetSym =
        typeof params.target === 'string' && params.target.trim() !== ''
          ? params.target.trim()
          : typeof params.name === 'string' && params.name.trim() !== ''
            ? params.name.trim()
            : undefined;
      const contextArgs: Record<string, unknown> = {
        name: groupName,
        target: targetSym,
      };
      if (typeof params.uid === 'string') contextArgs.uid = params.uid;
      if (typeof params.file_path === 'string') contextArgs.file_path = params.file_path;
      if (params.include_content !== undefined)
        contextArgs.include_content = params.include_content;
      if (params.service !== undefined && params.service !== null)
        contextArgs.service = params.service;
      if (memberRest !== undefined) {
        contextArgs.subgroup = memberRest;
        contextArgs.subgroupExact = true;
      }
      return svc.groupContext(contextArgs);
    }
    throw new Error(`Internal: unsupported group-repo tool ${method}`);
  }

  private async groupList(params: Record<string, unknown>): Promise<unknown> {
    return this.getGroupService().groupList(params);
  }

  private async groupSync(params: Record<string, unknown>): Promise<unknown> {
    return this.getGroupService().groupSync(params);
  }

  /**
   * MCP resource body for `gitnexus://group/{name}/contracts` (Issue #794).
   */
  async readGroupContractsResource(
    groupName: string,
    filter: { type?: string; repo?: string; unmatchedOnly?: boolean },
  ): Promise<string> {
    try {
      const params: Record<string, unknown> = { name: groupName };
      if (filter.type !== undefined) params.type = filter.type;
      if (filter.repo !== undefined) params.repo = filter.repo;
      if (filter.unmatchedOnly === true) params.unmatchedOnly = true;
      const raw = await this.getGroupService().groupContracts(params);
      return LocalBackend.formatGroupResourcePayload(raw);
    } catch (e) {
      return `error: ${e instanceof Error ? e.message : String(e)}`;
    }
  }

  /**
   * MCP resource body for `gitnexus://group/{name}/status` (Issue #794).
   */
  async readGroupStatusResource(groupName: string): Promise<string> {
    try {
      const raw = await this.getGroupService().groupStatus({ name: groupName });
      return LocalBackend.formatGroupResourcePayload(raw);
    } catch (e) {
      return `error: ${e instanceof Error ? e.message : String(e)}`;
    }
  }

  private static formatGroupResourcePayload(raw: unknown): string {
    if (raw && typeof raw === 'object' && 'error' in raw) {
      const err = (raw as { error?: unknown }).error;
      if (typeof err === 'string' && err.length > 0) {
        return `error: ${err}`;
      }
    }
    return JSON.stringify(raw, null, 2);
  }

  /**
   * Fetch Route nodes with their consumers in a single query.
   * Shared by routeMap and shapeCheck to avoid N+1 query patterns.
   */
  private async fetchRoutesWithConsumers(
    repoId: string,
    routeFilter: string,
    params: Record<string, string>,
  ): Promise<
    Array<{
      id: string;
      name: string;
      filePath: string;
      responseKeys: string[] | null;
      errorKeys: string[] | null;
      middleware: string[] | null;
      consumers: Array<{
        name: string;
        filePath: string;
        accessedKeys?: string[];
        fetchCount?: number;
      }>;
    }>
  > {
    const rows = await executeParameterized(
      repoId,
      `
      MATCH (n:Route)
      WHERE n.id STARTS WITH 'Route:' ${routeFilter}
      OPTIONAL MATCH (consumer)-[r:CodeRelation]->(n)
      WHERE r.type = 'FETCHES'
      RETURN n.id AS routeId, n.name AS routeName, n.filePath AS handlerFile,
             n.responseKeys AS responseKeys, n.errorKeys AS errorKeys, n.middleware AS middleware,
             consumer.name AS consumerName, consumer.filePath AS consumerFile,
             r.reason AS fetchReason
    `,
      params,
    );

    // Strip wrapping quotes from DB array elements — CSV COPY stores ['key'] which
    // LadybugDB may return as "'key'" rather than "key"
    const stripQuotes = (keys: string[] | null): string[] | null =>
      keys ? keys.map((k) => k.replace(/^['"]|['"]$/g, '')) : null;

    const routeMap = new Map<
      string,
      {
        id: string;
        name: string;
        filePath: string;
        responseKeys: string[] | null;
        errorKeys: string[] | null;
        middleware: string[] | null;
        consumers: Array<{
          name: string;
          filePath: string;
          accessedKeys?: string[];
          fetchCount?: number;
        }>;
      }
    >();
    for (const row of rows) {
      const id = row.routeId ?? row[0];
      const name = row.routeName ?? row[1];
      const filePath = row.handlerFile ?? row[2];
      const responseKeys = stripQuotes(row.responseKeys ?? row[3] ?? null);
      const errorKeys = stripQuotes(row.errorKeys ?? row[4] ?? null);
      const middleware = stripQuotes(row.middleware ?? row[5] ?? null);
      const consumerName = row.consumerName ?? row[6];
      const consumerFile = row.consumerFile ?? row[7];
      const fetchReason: string | null = row.fetchReason ?? row[8] ?? null;

      if (!routeMap.has(id)) {
        routeMap.set(id, {
          id,
          name,
          filePath,
          responseKeys,
          errorKeys,
          middleware,
          consumers: [],
        });
      }
      if (consumerName && consumerFile) {
        // Parse accessed keys from reason field: "fetch-url-match|keys:data,pagination|fetches:3"
        let accessedKeys: string[] | undefined;
        let fetchCount: number | undefined;
        if (fetchReason) {
          const keysMatch = fetchReason.match(/\|keys:([^|]+)/);
          if (keysMatch) {
            accessedKeys = keysMatch[1].split(',').filter((k) => k.length > 0);
          }
          const fetchesMatch = fetchReason.match(/\|fetches:(\d+)/);
          if (fetchesMatch) {
            fetchCount = parseInt(fetchesMatch[1], 10);
          }
        }
        routeMap.get(id)!.consumers.push({
          name: consumerName,
          filePath: consumerFile,
          ...(accessedKeys ? { accessedKeys } : {}),
          ...(fetchCount && fetchCount > 1 ? { fetchCount } : {}),
        });
      }
    }

    return [...routeMap.values()];
  }

  /**
   * Batch-fetch execution flows linked to a set of Route or Tool nodes.
   * Single query instead of N+1.
   */
  private async fetchLinkedFlowsBatch(
    repoId: string,
    nodeIds: string[],
  ): Promise<Map<string, string[]>> {
    const result = new Map<string, string[]>();
    if (nodeIds.length === 0) return result;
    try {
      // Use list_contains to filter at DB level instead of fetching all and filtering in memory
      const rows = await executeParameterized(
        repoId,
        `
        MATCH (source)-[r:CodeRelation]->(proc:Process)
        WHERE r.type = 'ENTRY_POINT_OF'
          AND list_contains($nodeIds, source.id)
        RETURN source.id AS sourceId, proc.label AS name
      `,
        { nodeIds },
      );
      for (const row of rows) {
        const sourceId = row.sourceId ?? row[0];
        const name = row.name ?? row[1];
        if (!name) continue;
        let list = result.get(sourceId);
        if (!list) {
          list = [];
          result.set(sourceId, list);
        }
        list.push(name);
      }
    } catch {
      /* no ENTRY_POINT_OF edges yet */
    }
    return result;
  }

  private async routeMap(repo: RepoHandle, params: { route?: string }): Promise<any> {
    await this.ensureInitialized(repo);

    const routeFilter = params.route ? `AND n.name CONTAINS $route` : '';
    const queryParams = params.route ? { route: params.route } : {};
    const routes = await this.fetchRoutesWithConsumers(repo.lbugPath, routeFilter, queryParams);

    if (routes.length === 0) {
      return {
        routes: [],
        total: 0,
        message: params.route
          ? `No routes matching "${params.route}"`
          : 'No routes found in this project.',
      };
    }

    const flowMap = await this.fetchLinkedFlowsBatch(
      repo.lbugPath,
      routes.map((r) => r.id),
    );

    return {
      routes: routes.map((r) => ({
        route: r.name,
        handler: r.filePath,
        middleware: r.middleware || [],
        consumers: r.consumers,
        flows: flowMap.get(r.id) || [],
      })),
      total: routes.length,
    };
  }

  private async shapeCheck(repo: RepoHandle, params: { route?: string }): Promise<any> {
    await this.ensureInitialized(repo);

    const routeFilter = params.route ? `AND n.name CONTAINS $route` : '';
    const queryParams = params.route ? { route: params.route } : {};
    const allRoutes = await this.fetchRoutesWithConsumers(repo.lbugPath, routeFilter, queryParams);

    const results = allRoutes
      .filter(
        (r) =>
          ((r.responseKeys && r.responseKeys.length > 0) ||
            (r.errorKeys && r.errorKeys.length > 0)) &&
          r.consumers.length > 0,
      )
      .map((r) => {
        // Keys already normalized by fetchRoutesWithConsumers (quotes stripped)
        const responseKeys = r.responseKeys ?? [];
        const errorKeys = r.errorKeys ?? [];
        // Combined set: consumer accessing either success or error keys is valid
        const allKnownKeys = new Set([...responseKeys, ...errorKeys]);

        // Check each consumer's accessed keys against the route's response shape
        const responseKeySet = new Set(responseKeys);
        const consumers = r.consumers.map((c) => {
          if (!c.accessedKeys || c.accessedKeys.length === 0) {
            return { name: c.name, filePath: c.filePath };
          }
          const mismatched = c.accessedKeys.filter((k) => !allKnownKeys.has(k));
          // Keys in allKnownKeys but not in responseKeys — error-path access (e.g., .error from errorKeys)
          const errorPathKeys = c.accessedKeys.filter(
            (k) => allKnownKeys.has(k) && !responseKeySet.has(k),
          );
          const isMultiFetch = (c.fetchCount ?? 1) > 1;
          return {
            name: c.name,
            filePath: c.filePath,
            accessedKeys: c.accessedKeys,
            ...(mismatched.length > 0
              ? {
                  mismatched,
                  mismatchConfidence: isMultiFetch ? ('low' as const) : ('high' as const),
                }
              : {}),
            ...(errorPathKeys.length > 0 ? { errorPathKeys } : {}),
            ...(isMultiFetch
              ? {
                  attributionNote: `This file fetches ${c.fetchCount} routes — accessed keys may belong to a different route.`,
                }
              : {}),
          };
        });

        const hasMismatches = consumers.some(
          (c) => 'mismatched' in c && (c as any).mismatched.length > 0,
        );

        return {
          route: r.name,
          handler: r.filePath,
          ...(responseKeys.length > 0 ? { responseKeys } : {}),
          ...(errorKeys.length > 0 ? { errorKeys } : {}),
          consumers,
          ...(hasMismatches ? { status: 'MISMATCH' as const } : {}),
        };
      });

    const mismatchCount = results.filter((r) => r.status === 'MISMATCH').length;

    return {
      routes: results,
      total: results.length,
      routesWithShapes: results.length,
      ...(mismatchCount > 0 ? { mismatches: mismatchCount } : {}),
      message:
        results.length === 0
          ? 'No routes with both response shapes and consumers found.'
          : mismatchCount > 0
            ? `Found ${results.length} route(s) with response shape data. ${mismatchCount} route(s) have consumer/shape mismatches.`
            : `Found ${results.length} route(s) with response shape data and consumers.`,
    };
  }

  private async toolMap(repo: RepoHandle, params: { tool?: string }): Promise<any> {
    await this.ensureInitialized(repo);

    const toolFilter = params.tool ? `AND n.name CONTAINS $tool` : '';
    const queryParams = params.tool ? { tool: params.tool } : {};

    const rows = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (n:Tool)
      WHERE n.id STARTS WITH 'Tool:' ${toolFilter}
      RETURN n.id AS id, n.name AS name, n.filePath AS filePath, n.description AS description
    `,
      queryParams,
    );

    if (rows.length === 0) {
      return {
        tools: [],
        total: 0,
        message: params.tool ? `No tools matching "${params.tool}"` : 'No tool definitions found.',
      };
    }

    const toolIds = rows.map((r: any) => r.id ?? r[0]);
    const flowMap = await this.fetchLinkedFlowsBatch(repo.lbugPath, toolIds);

    return {
      tools: rows.map((r: any) => {
        const id = r.id ?? r[0];
        return {
          name: r.name ?? r[1],
          filePath: r.filePath ?? r[2],
          description: (r.description ?? r[3] ?? '').slice(0, 200),
          flows: flowMap.get(id) || [],
        };
      }),
      total: rows.length,
    };
  }

  private async apiImpact(
    repo: RepoHandle,
    params: { route?: string; file?: string },
  ): Promise<any> {
    await this.ensureInitialized(repo);

    if (!params.route && !params.file) {
      return { error: 'Either "route" or "file" parameter is required.' };
    }

    // If file is provided but route is not, look up the route by file path
    let routeFilter = '';
    const queryParams: Record<string, string> = {};

    if (params.route) {
      routeFilter = `AND n.name CONTAINS $route`;
      queryParams.route = params.route;
    } else if (params.file) {
      routeFilter = `AND n.filePath CONTAINS $file`;
      queryParams.file = params.file;
    }

    const routes = await this.fetchRoutesWithConsumers(repo.lbugPath, routeFilter, queryParams);

    if (routes.length === 0) {
      const target = params.route || params.file;
      return { error: `No routes found matching "${target}".` };
    }

    const flowMap = await this.fetchLinkedFlowsBatch(
      repo.lbugPath,
      routes.map((r) => r.id),
    );

    // Count how many routes share the same handler file (for middleware partial detection)
    const routeCountByHandler = new Map<string, number>();
    for (const r of routes) {
      if (r.filePath) {
        routeCountByHandler.set(r.filePath, (routeCountByHandler.get(r.filePath) ?? 0) + 1);
      }
    }

    const results = routes.map((r) => {
      // Keys already normalized by fetchRoutesWithConsumers (quotes stripped)
      const responseKeys = r.responseKeys ?? [];
      const errorKeys = r.errorKeys ?? [];
      const allKnownKeys = new Set([...responseKeys, ...errorKeys]);

      // Build consumer list with mismatch detection
      const consumers = r.consumers.map((c) => ({
        name: c.name,
        file: c.filePath,
        accesses: c.accessedKeys ?? [],
        ...(c.fetchCount && c.fetchCount > 1
          ? {
              attributionNote: `This file fetches ${c.fetchCount} routes — accessed keys may belong to a different route.`,
            }
          : {}),
      }));

      // Detect mismatches: consumer accesses keys not in response shape
      const mismatches: Array<{
        consumer: string;
        field: string;
        reason: string;
        confidence: 'high' | 'low';
      }> = [];
      if (allKnownKeys.size > 0) {
        for (const c of r.consumers) {
          if (!c.accessedKeys) continue;
          const isMultiFetch = (c.fetchCount ?? 1) > 1;
          for (const key of c.accessedKeys) {
            if (!allKnownKeys.has(key)) {
              mismatches.push({
                consumer: c.filePath,
                field: key,
                reason: 'accessed but not in response shape',
                confidence: isMultiFetch ? 'low' : 'high',
              });
            }
          }
        }
      }

      const flows = flowMap.get(r.id) || [];
      const consumerCount = r.consumers.length;

      // Risk level heuristic
      let riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
      if (consumerCount >= 10) {
        riskLevel = 'HIGH';
      } else if (consumerCount >= 4) {
        riskLevel = 'MEDIUM';
      } else {
        riskLevel = 'LOW';
      }
      // Bump up one level if mismatches exist
      if (mismatches.length > 0) {
        if (riskLevel === 'LOW') riskLevel = 'MEDIUM';
        else if (riskLevel === 'MEDIUM') riskLevel = 'HIGH';
      }

      const warning =
        consumerCount > 0
          ? `Changing response shape will affect ${consumerCount} component${consumerCount === 1 ? '' : 's'}`
          : undefined;

      // Flag when middleware was detected but handler exports multiple HTTP methods
      // (middleware chain may only reflect one export)
      const middlewareArr = r.middleware || [];
      const handlerRouteCount = r.filePath ? (routeCountByHandler.get(r.filePath) ?? 1) : 1;
      const middlewarePartial = middlewareArr.length > 0 && handlerRouteCount > 1;

      return {
        route: r.name,
        handler: r.filePath,
        responseShape: {
          success: responseKeys,
          error: errorKeys,
        },
        middleware: middlewareArr,
        ...(middlewarePartial
          ? {
              middlewareDetection: 'partial' as const,
              middlewareNote:
                'Middleware captured from first HTTP method export only — other methods in this handler may use different middleware chains.',
            }
          : {}),
        consumers,
        ...(mismatches.length > 0 ? { mismatches } : {}),
        executionFlows: flows,
        impactSummary: {
          directConsumers: consumerCount,
          affectedFlows: flows.length,
          riskLevel,
          ...(warning ? { warning } : {}),
        },
      };
    });

    // If a single route was targeted, return it directly (not wrapped in array)
    if (results.length === 1) {
      return results[0];
    }

    return { routes: results, total: results.length };
  }

  // ─── Direct Graph Queries (for resources.ts) ────────────────────

  /**
   * Query clusters (communities) directly from graph.
   * Used by getClustersResource — avoids legacy overview() dispatch.
   */
  async queryClusters(repoName?: string, limit = 100): Promise<{ clusters: any[] }> {
    const repo = await this.resolveRepo(repoName);
    await this.ensureInitialized(repo);

    try {
      const rawLimit = Math.max(limit * 5, 200);
      const clusters = await executeQuery(
        repo.lbugPath,
        `
        MATCH (c:Community)
        RETURN c.id AS id, c.label AS label, c.heuristicLabel AS heuristicLabel, c.cohesion AS cohesion, c.symbolCount AS symbolCount
        ORDER BY c.symbolCount DESC
        LIMIT ${rawLimit}
      `,
      );
      const rawClusters = clusters.map((c: any) => ({
        id: c.id || c[0],
        label: c.label || c[1],
        heuristicLabel: c.heuristicLabel || c[2],
        cohesion: c.cohesion || c[3],
        symbolCount: c.symbolCount || c[4],
      }));
      return { clusters: this.aggregateClusters(rawClusters).slice(0, limit) };
    } catch {
      return { clusters: [] };
    }
  }

  /**
   * Query processes directly from graph.
   * Used by getProcessesResource — avoids legacy overview() dispatch.
   */
  async queryProcesses(repoName?: string, limit = 50): Promise<{ processes: any[] }> {
    const repo = await this.resolveRepo(repoName);
    await this.ensureInitialized(repo);

    try {
      const processes = await executeQuery(
        repo.lbugPath,
        `
        MATCH (p:Process)
        RETURN p.id AS id, p.label AS label, p.heuristicLabel AS heuristicLabel, p.processType AS processType, p.stepCount AS stepCount
        ORDER BY p.stepCount DESC
        LIMIT ${limit}
      `,
      );
      return {
        processes: processes.map((p: any) => ({
          id: p.id || p[0],
          label: p.label || p[1],
          heuristicLabel: p.heuristicLabel || p[2],
          processType: p.processType || p[3],
          stepCount: p.stepCount || p[4],
        })),
      };
    } catch {
      return { processes: [] };
    }
  }

  /**
   * Query cluster detail (members) directly from graph.
   * Used by getClusterDetailResource.
   */
  async queryClusterDetail(name: string, repoName?: string): Promise<any> {
    const repo = await this.resolveRepo(repoName);
    await this.ensureInitialized(repo);

    const clusters = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (c:Community)
      WHERE c.label = $clusterName OR c.heuristicLabel = $clusterName
      RETURN c.id AS id, c.label AS label, c.heuristicLabel AS heuristicLabel, c.cohesion AS cohesion, c.symbolCount AS symbolCount
    `,
      { clusterName: name },
    );
    if (clusters.length === 0) return { error: `Cluster '${name}' not found` };

    const rawClusters = clusters.map((c: any) => ({
      id: c.id || c[0],
      label: c.label || c[1],
      heuristicLabel: c.heuristicLabel || c[2],
      cohesion: c.cohesion || c[3],
      symbolCount: c.symbolCount || c[4],
    }));

    let totalSymbols = 0,
      weightedCohesion = 0;
    for (const c of rawClusters) {
      const s = c.symbolCount || 0;
      totalSymbols += s;
      weightedCohesion += (c.cohesion || 0) * s;
    }

    const members = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (n)-[:CodeRelation {type: 'MEMBER_OF'}]->(c:Community)
      WHERE c.label = $clusterName OR c.heuristicLabel = $clusterName
      RETURN DISTINCT n.name AS name, labels(n)[0] AS type, n.filePath AS filePath
      LIMIT 30
    `,
      { clusterName: name },
    );

    return {
      cluster: {
        id: rawClusters[0].id,
        label: rawClusters[0].heuristicLabel || rawClusters[0].label,
        heuristicLabel: rawClusters[0].heuristicLabel || rawClusters[0].label,
        cohesion: totalSymbols > 0 ? weightedCohesion / totalSymbols : 0,
        symbolCount: totalSymbols,
        subCommunities: rawClusters.length,
      },
      members: members.map((m: any) => ({
        name: m.name || m[0],
        type: m.type || m[1],
        filePath: m.filePath || m[2],
      })),
    };
  }

  /**
   * Query process detail (steps) directly from graph.
   * Used by getProcessDetailResource.
   */
  async queryProcessDetail(name: string, repoName?: string): Promise<any> {
    const repo = await this.resolveRepo(repoName);
    await this.ensureInitialized(repo);

    const processes = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (p:Process)
      WHERE p.label = $processName OR p.heuristicLabel = $processName
      RETURN p.id AS id, p.label AS label, p.heuristicLabel AS heuristicLabel, p.processType AS processType, p.stepCount AS stepCount
      LIMIT 1
    `,
      { processName: name },
    );
    if (processes.length === 0) return { error: `Process '${name}' not found` };

    const proc = processes[0];
    const procId = proc.id || proc[0];
    const steps = await executeParameterized(
      repo.lbugPath,
      `
      MATCH (n)-[r:CodeRelation {type: 'STEP_IN_PROCESS'}]->(p {id: $procId})
      RETURN n.name AS name, labels(n)[0] AS type, n.filePath AS filePath, r.step AS step
      ORDER BY r.step
    `,
      { procId },
    );

    return {
      process: {
        id: procId,
        label: proc.label || proc[1],
        heuristicLabel: proc.heuristicLabel || proc[2],
        processType: proc.processType || proc[3],
        stepCount: proc.stepCount || proc[4],
      },
      steps: steps.map((s: any) => ({
        step: s.step || s[3],
        name: s.name || s[0],
        type: s.type || s[1],
        filePath: s.filePath || s[2],
      })),
    };
  }

  async disconnect(): Promise<void> {
    await closeLbug(); // close all connections
    // Note: we intentionally do NOT call disposeEmbedder() here.
    // ONNX Runtime's native cleanup segfaults on macOS and some Linux configs,
    // and importing the embedder module on Node v24+ crashes if onnxruntime
    // was never loaded during the session. Since process.exit(0) follows
    // immediately after disconnect(), the OS reclaims everything. See #38, #89.
    this.repos.clear();
    this.contextCache.clear();
    this.initializedRepos.clear();
  }
}
