This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/.gitignore, **/.dockerignore, **/*.lock, **/*.mod, **/*.module, **/*.patch, **/*.jsonc, **/*.example, **/*.png, **/*.svg, **/*.wasm, **/*.pyc, assets/**, site/public/**, telemetry-dashboard/public/**, telemetry-dashboard/scripts/**, telemetry-worker/scripts/**, telemetry-worker/migrations/**, codegraph-kernel/grammars/**, __tests__/fixtures/**, scripts/**
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
.claude/
  skills/
    add-lang/
      SKILL.md
    agent-eval/
      corpus.json
      SKILL.md
.cursor/
  rules/
    codegraph.mdc
codegraph-kernel/
  src/
    ccpp/
      mod.rs
    tsjs/
      extractors.rs
      fnref.rs
      mod.rs
    buffers.rs
    cfnptr.rs
    csharp.rs
    dart.rs
    docstring.rs
    go.rs
    ids.rs
    java.rs
    kotlin.rs
    langs.rs
    lib.rs
    lua.rs
    php.rs
    python.rs
    rlang.rs
    ruby.rs
    rustlang.rs
    scala.rs
    stack.rs
    swift.rs
    textutil.rs
  build.rs
  Cargo.toml
docs/
  benchmarks/
    agent-eval-feedback-metrics.md
    answer-directly-vs-explore-agent.md
    call-sequence-analysis.md
    codegraph-ab-matrix.md
    explore-allocation-ab-1500.md
    explore-allocation-efficiency.md
    explore-cluster-starvation-cg36.md
    explore-completeness-note.md
    explore-declaration-only-cg28.md
    explore-dedup-ab-cg20.md
    explore-displacement-guard-ab-cg31.md
    explore-factory-closure-cg27.md
    explore-noise-epic-cg24.md
    explore-oversize-member-ab-cg30.md
    explore-reservation-invariant-ab-cg26.md
    explore-sufficiency.md
    explore-tail-render-cg38.md
    index-drift-cg33.md
    regression-audit-2026-09.md
    residual-context-occupancy.md
  design/
    adaptive-explore-sizing.md
    agent-codegraph-adoption.md
    callback-edge-synthesis.md
    ccpp-kernel-port-checklist.md
    cg57-highlighting-parity.md
    chained-call-resolution.md
    codegraph-ui-design-spec.md
    csharp-kernel-port-checklist.md
    dart-kernel-port-checklist.md
    dispatch-synthesizer-backlog.md
    dynamic-dispatch-coverage-playbook.md
    explore-budget-allocation.md
    explore-session-dedup.md
    framework-coverage.md
    function-ref-capture.md
    generated-file-detection.md
    kotlin-kernel-port-checklist.md
    lua-luau-kernel-port-checklist.md
    main-thread-stall-followup.md
    mixed-ios-and-react-native-bridging.md
    native-extraction-kernel.md
    php-kernel-port-checklist.md
    r-kernel-port-checklist.md
    ruby-kernel-port-checklist.md
    rust-kernel-migration-plan.md
    rust-lang-kernel-port-checklist.md
    scala-kernel-port-checklist.md
    swift-kernel-port-checklist.md
    telemetry.md
    template-markup-parser.md
    value-reference-edges-playbook.md
    value-reference-edges.md
  from-chat/
    no-it-s-the-opposite.md
  grammars/
    tree-sitter-cobol.md
    tree-sitter-kotlin.md
    tree-sitter-vbnet.md
  plans/
    2026-04-24-framework-resolver-extract.md
    2026-08-28-steps-and-screens-for-apis-and-web.md
    2026-08-29-steps-in-code-order.md
  AGENTS.md
  SEARCH_QUALITY_LOOP.md
  viewer-launch-changelog.md
site/
  src/
    components/
      GraphDiagram.astro
      SiteTitle.astro
      SocialIcons.astro
    content/
      docs/
        core-concepts/
          how-it-works.md
          knowledge-graph.md
          resolution.md
        getting-started/
          configuration.md
          installation.md
          introduction.md
          next-steps.md
          quickstart.md
          your-first-graph.md
        guides/
          affected-tests.md
          framework-routes.md
          indexing.md
          viewer.md
        reference/
          api.md
          cli.md
          integrations.md
          languages.md
          mcp-server.md
        troubleshooting.md
    pages/
      index.astro
    content.config.ts
  astro.config.mjs
  package.json
  README.md
  tsconfig.json
src/
  context/
    formatter.ts
    index.ts
    markers.ts
  db/
    index.ts
    migrations.ts
    queries.ts
    schema.sql
    sqlite-adapter.ts
    synthesis-stage.ts
    wal-valve.ts
    wsl-shared-index.ts
  extraction/
    kernel/
      decode.ts
      index.ts
      layout.ts
      loader.ts
    languages/
      arkts.ts
      c-cpp.ts
      cfquery.ts
      cfscript.ts
      cobol.ts
      csharp.ts
      dart.ts
      erlang.ts
      go.ts
      index.ts
      java.ts
      javascript.ts
      kotlin.ts
      lua.ts
      luau.ts
      nix.ts
      objc.ts
      pascal.ts
      php.ts
      python.ts
      r.ts
      ruby.ts
      rust.ts
      scala.ts
      solidity.ts
      swift.ts
      terraform.ts
      typescript.ts
      vbnet.ts
    astro-extractor.ts
    cfml-extractor.ts
    dfm-extractor.ts
    extraction-version.ts
    function-ref.ts
    generated-detection.ts
    grammars.ts
    index.ts
    liquid-extractor.ts
    mybatis-extractor.ts
    parse-pool.ts
    parse-worker.ts
    razor-extractor.ts
    store-worker.ts
    store-writer.ts
    svelte-extractor.ts
    syntax-tokens.ts
    tree-sitter-helpers.ts
    tree-sitter-types.ts
    tree-sitter.ts
    vue-extractor.ts
    vue-options-api.ts
    wasm-runtime-flags.ts
  graph/
    branch-guards.ts
    dead-code.ts
    dynamic-boundary-report.ts
    index.ts
    named-symbol-flow.ts
    queries.ts
    symbol-lookup.ts
    traversal.ts
    type-hierarchy.ts
  installer/
    targets/
      antigravity.ts
      claude.ts
      codex.ts
      copilot-cli.ts
      copilot-jetbrains.ts
      copilot-vscode.ts
      cursor.ts
      gemini.ts
      hermes.ts
      kiro.ts
      opencode.ts
      registry.ts
      shared.ts
      toml.ts
      types.ts
    beta-signup.ts
    clack.d.ts
    config-writer.ts
    index.ts
    instructions-template.ts
  mcp/
    answer-freshness.ts
    daemon-manager.ts
    daemon-paths.ts
    daemon-registry.ts
    daemon.ts
    dynamic-boundaries.ts
    early-ppid.ts
    engine.ts
    explore-dedup.ts
    explore-diagnostics.ts
    explore-session-state.ts
    index-freshness-worker.ts
    index-freshness.ts
    index.ts
    liveness-watchdog.ts
    ppid-watchdog.ts
    project-lifecycle.ts
    proxy.ts
    query-pool.ts
    query-worker.ts
    server-instructions.ts
    session.ts
    startup-handshake.ts
    stdin-teardown.ts
    tools.ts
    transport.ts
    version.ts
    writer-lock.ts
  resolution/
    frameworks/
      angular-router.ts
      astro.ts
      cargo-workspace.ts
      cics.ts
      csharp.ts
      drupal.ts
      expo-modules.ts
      expo-router.ts
      express.ts
      fabric.ts
      go.ts
      goframe.ts
      index.ts
      java.ts
      laravel.ts
      name-heuristic.ts
      nestjs.ts
      nextjs.ts
      object-literal.ts
      package-deps.ts
      play.ts
      python.ts
      react-native.ts
      react-router.ts
      react.ts
      ruby.ts
      rust.ts
      svelte.ts
      sveltekit-router.ts
      swift-objc.ts
      swift.ts
      tanstack-router.ts
      terraform.ts
      vue-router.ts
      vue.ts
    alias-binding.ts
    angular-template-synthesizer.ts
    c-fnptr-synthesizer.ts
    callback-synthesizer.ts
    cooperative-yield.ts
    cpp-constructor.ts
    cpp-macro-visibility.ts
    expo-router-synthesizer.ts
    go-module.ts
    goframe-synthesizer.ts
    import-resolver.ts
    index.ts
    js-builtins.ts
    lru-cache.ts
    memory-budget.ts
    name-matcher.ts
    next-router-synthesizer.ts
    path-aliases.ts
    react-router-synthesizer.ts
    resolver-pool.ts
    resolver-worker.ts
    strip-comments.ts
    sveltekit-synthesizer.ts
    swift-objc-bridge.ts
    swift-type-visibility.ts
    synth-utils.ts
    tanstack-router-synthesizer.ts
    tier-synthesizer.ts
    type-parameters.ts
    types.ts
    vue-router-synthesizer.ts
    workspace-packages.ts
  search/
    identifier-segments.ts
    query-parser.ts
    query-paths.ts
    query-utils.ts
  sync/
    git-hooks.ts
    index.ts
    watch-policy.ts
    watcher.ts
    worktree.ts
  telemetry/
    index.ts
  ui/
    color.ts
    glyphs.ts
    shimmer-progress.ts
    shimmer-worker.ts
    types.ts
  ui-server/
    api/
      deadcode.ts
      effects.ts
      entrypoints.ts
      events.ts
      file.ts
      filecode.ts
      flow.ts
      hierarchy.ts
      index.ts
      map.ts
      node.ts
      nodes.ts
      program.ts
      respond.ts
      route-roots.ts
      routes.ts
      screens.ts
      search.ts
      session.ts
      source.ts
      stats.ts
      steps.ts
      trail-store.ts
      trails.ts
      when.ts
      wire.ts
    highlight/
      index.ts
      languages.ts
    assets.ts
    constants.ts
    index.ts
    open-browser.ts
    security.ts
    static.ts
  upgrade/
    index.ts
    remove-binary.ts
    update-check.ts
  directory.ts
  errors.ts
  file-limits.ts
  index.ts
  project-config.ts
  types.ts
  utils.ts
  web-tree-sitter.d.ts
telemetry-dashboard/
  src/
    api.ts
    auth.ts
    index.ts
    login-page.ts
  package.json
  README.md
  tsconfig.json
telemetry-worker/
  src/
    env.d.ts
    index.ts
    rollup.ts
  package.json
  README.md
  tsconfig.json
ui/
  src/
    components/
      entry/
        EntrySection.svelte
      file/
        CodeArcs.svelte
        FileCodeBlock.svelte
        FileCodeOutline.svelte
        FileCodeRail.svelte
        FileModeTabs.svelte
        FileOutline.svelte
        FileRail.svelte
      flow/
        FlowCard.svelte
        FlowEndCap.svelte
        FlowLink.svelte
      map/
        MapKey.svelte
        MapSidePanel.svelte
        ModuleEdge.svelte
        ModuleNode.svelte
      screens/
        ScreenEdge.svelte
        ScreenNode.svelte
      steps/
        DecisionCaption.svelte
        ForkPoint.svelte
        RegionCaption.svelte
        StepBox.svelte
        StepNode.svelte
        StepsKey.svelte
        StepStubs.svelte
      symbol/
        BlastStrip.svelte
        CalleeRail.svelte
        CallersRail.svelte
        Connectors.svelte
        MembersOutline.svelte
        SourceBlock.svelte
        SymbolHeader.svelte
        TypeHierarchy.svelte
      CodegraphUi.svelte
      DriftBanner.svelte
      ExportButtons.svelte
      KindGlyph.svelte
      PalettePanel.svelte
      PaletteRows.svelte
      SavedTrails.svelte
      SearchPalette.svelte
      Toast.svelte
      TopBar.svelte
      TrailBar.svelte
    views/
      DeadCodeView.svelte
      EntryView.svelte
      FileCodeView.svelte
      FileView.svelte
      FlowView.svelte
      HomeView.svelte
      MapView.svelte
      NotFoundView.svelte
      ScreensView.svelte
      StepsView.svelte
      SymbolView.svelte
    App.svelte
    index.ts
    main.ts
  index.html
  package.json
  README.md
  svelte.config.js
  tsconfig.json
  vite.config.ts
AGENTS.md
BUNDLING.md
CHANGELOG.md
CLAUDE.md
install.ps1
install.sh
LICENSE
package.json
README.md
TELEMETRY.md
tsconfig.json
vitest.config.mts
vitest.workspace.mts
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path=".claude/skills/add-lang/SKILL.md">
---
name: add-lang
description: Add tree-sitter language support to codegraph end-to-end — wire the grammar + extractor, write tests, then benchmark extraction quality and retrieval value on 3 popular real-world repos. Use when the user runs /add-lang <language> or asks to add/support a new language (e.g. Lua, Elixir, Zig, OCaml) in codegraph.
---

# Add a language to CodeGraph

Wire a new tree-sitter language into codegraph's extraction pipeline, prove it
extracts real symbols on popular repos, and prove it beats no-codegraph for an
agent. Runs **fully autonomously** — pick repos, benchmark, update docs, then
report. **Never commit, push, publish, or tag** (house rule); leave all changes
for the user to review.

The argument is the language token used throughout the `Language` union, e.g.
`lua`, `elixir`, `zig`. If none was given, ask which language. Use the lowercase
single-token form everywhere (`csharp`, not `c#`).

## Prerequisites
- Run from the codegraph repo root. `node`, `git`, `gh`, and a logged-in
  `claude` CLI (the benchmark spawns real `claude -p` runs).
- The benchmark uses the local dev build — Step 8 builds + links it on PATH.

## Workflow

Copy this checklist and work through it in order:
```
- [ ] 1. Resolve language; bail early if already supported (just benchmark)
- [ ] 2. Find a grammar + health-check it (ABI / heap corruption)
- [ ] 3. Discover the grammar's AST node types (dump-ast.mjs)
- [ ] 4. Wire the language (4 files; sometimes a 5th core touch)
- [ ] 5. Build + verify-extraction loop until PASS
- [ ] 6. Add extraction tests; make them green
- [ ] 7. Auto-pick 3 popular repos by size tier; add to corpus.json
- [ ] 8. Benchmark all 3: extraction + with/without A/B
- [ ] 9. Update README + CHANGELOG
- [ ] 10. Report; do NOT commit
```

### Step 1 — Resolve + short-circuit

Check whether the language is already wired: look for the token in the
`LANGUAGES` const (`src/types.ts`) and the `EXTRACTORS` map
(`src/extraction/languages/index.ts`). If it is already supported (e.g.
`typescript`, `rust`), **skip Steps 2–6** and go straight to benchmarking
(Steps 7–8) to validate/measure it — note in the report that no code changed.

### Step 2 — Find a grammar, then health-check it

```bash
ls node_modules/tree-sitter-wasms/out/ | grep -i <lang>   # csharp -> c_sharp
```
- **Present** → likely off-the-shelf; `grammars.ts` resolves it from
  `tree-sitter-wasms` automatically. (Many languages: elixir, zig, ocaml,
  solidity, toml, yaml, …)
- **Absent** → vendor a `.wasm` into `src/extraction/wasm/` (like `pascal` /
  `scala` / `lua`) and add the token to the vendored branch in Step 4.

**Always health-check before writing an extractor — a *present* grammar can
still be unusable:**
```bash
node scripts/add-lang/check-grammar.mjs <lang> path/to/valid-sample.<ext>
```
It prints the grammar's ABI version and parses a valid sample many times in a
multi-grammar runtime. If it **FAILs** (ERROR trees on valid code — an old ABI
corrupting the shared WASM heap, which silently drops nested calls/imports on
every file after the first; e.g. the tree-sitter-wasms **Lua** grammar is ABI 13
and fails), do NOT use that wasm. **Vendor a newer (ABI 14/15) build instead:**
```bash
npm pack @tree-sitter-grammars/tree-sitter-<lang>   # often ships a prebuilt *.wasm
# or build one: npx tree-sitter build --wasm   (needs Docker/emscripten)
cp <the>.wasm src/extraction/wasm/tree-sitter-<lang>.wasm
```
then add the token to the vendored branch in Step 4 and re-run check-grammar on
the vendored path until it PASSes. **If you cannot obtain a healthy wasm, STOP
and tell the user.**

### Step 3 — Discover AST node types

Get a representative source file (write a small sample covering functions,
classes/structs, imports, enums; or `curl` a raw file from a known repo), then:
```bash
node scripts/add-lang/dump-ast.mjs <lang> path/to/sample.<ext>
# vendored grammar: pass the wasm path instead of the token
node scripts/add-lang/dump-ast.mjs src/extraction/wasm/tree-sitter-<lang>.wasm sample.<ext>
```
The frequency table + field names (`name:`, `parameters:`, `body:`,
`return_type:`) tell you what to map. Open the existing extractor closest to the
language's paradigm as a model: `rust.ts`/`scala.ts` (functional, traits),
`java.ts`/`csharp.ts` (OO), `python.ts`/`ruby.ts` (scripting), `go.ts`
(top-level methods + receivers).

### Step 4 — Wire the language (4 files)

These are exact, fragile wiring — match the existing style precisely:

1. **`src/types.ts`** — TWO edits:
   - add `'<lang>',` to the `LANGUAGES` const (before `'unknown'`);
   - add `'**/*.<ext>',` to `DEFAULT_CONFIG.include`. **Don't skip this** — it's
     the file-scan allowlist; without the glob, `codegraph init` finds **0
     files** even though detection/extraction are wired.
... (120 lines truncated)
</file>

<file path=".claude/skills/agent-eval/corpus.json">
{
  "_comment": "Test corpus for /agent-eval. Add entries freely. size: Small (<~150 files), Medium (~150-1500), Large (>~1500). 'question' is a representative architectural question that exercises cross-file understanding.",
  "TypeScript": [
    {
      "name": "ky",
      "repo": "https://github.com/sindresorhus/ky",
      "size": "Small",
      "files": "~25",
      "question": "How does ky implement request retries and timeouts?"
    },
    {
      "name": "excalidraw",
      "repo": "https://github.com/excalidraw/excalidraw",
      "size": "Medium",
      "files": "~600",
      "question": "How does Excalidraw render and update canvas elements?"
    },
    {
      "name": "vscode",
      "repo": "https://github.com/microsoft/vscode",
      "size": "Large",
      "files": "~10000",
      "question": "How does the extension host communicate with the main process?"
    }
  ],
  "JavaScript": [
    {
      "name": "express",
      "repo": "https://github.com/expressjs/express",
      "size": "Small",
      "files": "~50",
      "question": "How does Express route a request through its middleware stack?"
    }
  ],
  "Go": [
    {
      "name": "cobra",
      "repo": "https://github.com/spf13/cobra",
      "size": "Small",
      "files": "~50",
      "question": "How does cobra parse commands and flags?"
    },
    {
      "name": "gin",
      "repo": "https://github.com/gin-gonic/gin",
      "size": "Medium",
      "files": "~150",
      "question": "How does gin route requests through its middleware chain?"
    },
    {
      "name": "terraform",
      "repo": "https://github.com/hashicorp/terraform",
      "size": "Large",
      "files": "~4000",
      "question": "How does Terraform build and walk the resource dependency graph?"
    },
    {
      "name": "cosmos-sdk",
      "repo": "https://github.com/cosmos/cosmos-sdk",
      "size": "Large",
      "files": "~5000",
      "question": "How does a bank module MsgSend message reach the account balance update? Trace the cross-module call path from the bank keeper's Send handler through to the account/balance store update."
    }
  ],
  "Python": [
    {
      "name": "click",
      "repo": "https://github.com/pallets/click",
      "size": "Small",
      "files": "~60",
      "question": "How does click parse command-line arguments into commands?"
    },
    {
      "name": "flask",
      "repo": "https://github.com/pallets/flask",
      "size": "Medium",
      "files": "~90",
      "question": "How does Flask dispatch a request to a view function?"
    },
    {
      "name": "django",
      "repo": "https://github.com/django/django",
      "size": "Large",
      "files": "~2700",
      "question": "How does Django's ORM build and execute a query from a QuerySet?"
    }
  ],
  "Rust": [
    {
      "name": "clap",
      "repo": "https://github.com/clap-rs/clap",
      "size": "Medium",
      "files": "~200",
      "question": "How does clap parse arguments against a derived command definition?"
    },
    {
      "name": "tokio",
      "repo": "https://github.com/tokio-rs/tokio",
      "size": "Large",
      "files": "~700",
... (512 lines truncated)
</file>

<file path=".claude/skills/agent-eval/SKILL.md">
---
name: agent-eval
description: Benchmark CodeGraph retrieval quality on a real codebase by comparing agent behavior with vs without CodeGraph. Use when the user runs /agent-eval or asks to test, benchmark, audit, or validate a codegraph version (the local dev build or a published npm version) against a language's repo.
---

# CodeGraph Quality Audit

Measures how much CodeGraph helps an agent versus plain grep/read, for a chosen
codegraph version on a chosen real-world repo. Drives the harness in
`scripts/agent-eval/`.

## Prerequisites
- `tmux` 3+, a logged-in `claude` CLI, `node`, `git` (macOS/Linux).
- Run from the codegraph repo root.

## Workflow

Copy this checklist:
```
- [ ] 1. Pick version (local or npm)
- [ ] 2. Pick language
- [ ] 3. Pick repo by size
- [ ] 4. Pick harness (headless / tmux / both)
- [ ] 5. Run audit.sh in the background
- [ ] 6. Report results
```

**Step 1 — version.** Ask with `AskUserQuestion`: which codegraph version to test.
Offer "Local dev build" and "Latest published"; the free-text "Other" lets the
user type a specific version (e.g. `0.7.10`). Map the answer to a VERSION token:
- "Local dev build" → `local`
- "Latest published" → `latest`
- a typed version → that string (e.g. `0.7.10`)

**Step 2 — language.** Read `.claude/skills/agent-eval/corpus.json`. Ask with
`AskUserQuestion` which language to test, listing the languages that have entries.

**Step 3 — repo.** From the chosen language's entries, ask which repo. Label each
option with its size and file count, e.g. `excalidraw — Medium (~600 files)`.
Each entry carries the `repo` URL and a representative `question`.

**Step 4 — harness.** Ask with `AskUserQuestion` which harness to run, and map
the answer to a MODE token:
- "Headless" → `headless` — `claude -p` with stream-json: exact tokens/cost and a
  clean tool sequence (2 runs, fast, no TTY).
- "Interactive (tmux)" → `tmux` — drives the real Claude TUI in tmux: faithful
  Explore-subagent behavior, metrics from session logs (2 runs, slower).
- "Both" → `all` — headless + interactive (4 runs).

**Step 5 — run.** Launch in the background (sets the version, clones if missing,
wipes + re-indexes, runs the chosen arms — several minutes):
```bash
scripts/agent-eval/audit.sh <VERSION> <repo-name> <repo-url> "<question>" <MODE>
```

**Step 6 — report.** When the job finishes, read the log and report per arm:
- Headless (`parse-run.mjs`): total tool calls, file `Read`s, Grep/Bash,
  codegraph-tool calls, duration, **total cost**.
- Interactive (`parse-session.mjs`): the `VERDICT: codegraph_explore used Nx |
  Read N | Grep/Bash N` and `TOKENS:` lines.
- Both paths also print the three feedback metrics — residual context occupancy,
  explore sufficiency, allocation efficiency — and a headless A/B ends with a
  side-by-side `ARM COMPARISON` table. Report that table, and check its
  contamination row first: `CLI calls that RETURNED output` > 0 means the arm
  reached codegraph through Bash and its numbers are void. How to read the rest:
  `docs/benchmarks/agent-eval-feedback-metrics.md`.

Lead with cost + tool/Read counts — they are the reliable signals; raw token
in/out are confounded by subagent delegation and prompt caching. State whether
codegraph reduced effort and whether both arms reached a correct answer.

## Notes
- The index is rebuilt every run (`audit.sh` wipes `.codegraph`) — different
  versions extract differently, so an index must be served by the same binary
  that built it.
- `audit.sh` temporarily mutates the global `codegraph` install for the test,
  then restores your dev link via `local-install.sh`.
- Corpus repos are cloned to `/tmp/codegraph-corpus` (reused if already present).
- Add or edit repos in `corpus.json` (fields: `name`, `repo`, `size`, `files`,
  `question`).
</file>

<file path=".cursor/rules/codegraph.mdc">
---
description: CodeGraph MCP usage guide — one tool, codegraph_explore
alwaysApply: true
---
<!-- CODEGRAPH_START -->
## CodeGraph

This project has a CodeGraph MCP server configured, exposing a single tool: `codegraph_explore`. CodeGraph is a tree-sitter-parsed knowledge graph of every symbol, edge, and file. Reads are sub-millisecond and return structural information grep cannot.

### Use codegraph_explore instead of reading files

Reach for `codegraph_explore` before grep/find or Read for any **structural** question — how does X work, how does X reach Y, what calls what, where is X defined, or surveying an area. It takes a natural-language question or a bag of symbol/file names and returns the relevant symbols' **verbatim, line-numbered source** grouped by file (the same `<n>\t<line>` shape Read gives you, safe to Edit from), plus the call paths between them — including dynamic-dispatch hops (callbacks, React re-render, JSX children) grep can't follow — and a blast-radius summary of what depends on them. Name a file or symbol in the query to read its current source.

### Rules of thumb

- **Answer directly — don't delegate exploration.** ONE `codegraph_explore` usually answers the whole question; follow up with another `codegraph_explore` naming more specific symbols if you need more. Codegraph IS the pre-built index, so spawning a separate file-reading sub-task/agent — or running a grep + read loop — repeats work codegraph already did and costs more for the same answer.
- **Trust codegraph results.** They come from a full AST parse. Do NOT re-verify them with grep — that's slower, less accurate, and wastes context.
- **Don't grep or Read first** to find or understand indexed code — one `codegraph_explore` returns the relevant source in a single round-trip. Reach for raw Read/Grep only to confirm a specific detail codegraph didn't cover, or for what it doesn't index (configs, docs).
- **Index lag — check the staleness banner, don't guess a wait.** When a codegraph response starts with "⚠️ Some files referenced below were edited since the last index sync…", the listed files are pending re-index — Read those specific files for accurate content. Files NOT in that banner are fresh and codegraph is authoritative for them.

### If `.codegraph/` doesn't exist

The MCP server returns "not initialized." Ask the user: *"I notice this project doesn't have CodeGraph initialized. Want me to run `codegraph init -i` to build the index?"*
<!-- CODEGRAPH_END -->
</file>

<file path="codegraph-kernel/src/ccpp/mod.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn macro_shaped_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$").unwrap())
⋮----
fn has_lower_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"[a-z]").unwrap())
⋮----
fn single_arg_macro_replacement_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(
⋮----
).unwrap())
⋮----
/// normalizeCppReturnType: smart-pointer/optional unwrap.
fn ret_wrapper_re() -> &'static Regex {
⋮----
fn ret_wrapper_re() -> &'static Regex {
⋮----
RE.get_or_init(|| {
⋮----
.unwrap()
⋮----
fn ret_keyword_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\b(?:const|volatile|typename|struct|class|enum)\b").unwrap())
⋮----
fn angle_group_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
fn ptr_ref_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"[*&]+").unwrap())
⋮----
fn ws_run_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\s+").unwrap())
⋮----
fn simple_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap())
⋮----
/// recoverMangledCppName's `Ret (name)` idiom guard.
fn ret_paren_name_re() -> &'static Regex {
⋮----
fn ret_paren_name_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^\S+\s+\([A-Za-z_][A-Za-z0-9_]*\)").unwrap())
⋮----
/// Operator-call receiver: simple identifier / dotted member chain.
fn operator_receiver_re() -> &'static Regex {
⋮----
fn operator_receiver_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_.]*$").unwrap())
⋮----
/// Symbolic operator tail (`/^[^\w\s]/` in JS).
fn symbolic_op_re() -> &'static Regex {
⋮----
fn symbolic_op_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[^A-Za-z0-9_\s]").unwrap())
⋮----
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// normalizeValue's qualified `&Cls::m` member-pointer test (`/^[A-Za-z_][\w:]*$/`).
fn qualified_ref_re() -> &'static Regex {
⋮----
fn qualified_ref_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_:]*$").unwrap())
⋮----
/// CPP_NON_CLASS_RETURN (languages/c-cpp.ts).
fn is_non_class_return(name: &str) -> bool {
⋮----
fn is_non_class_return(name: &str) -> bool {
matches!(
⋮----
fn is_cpp_primitive_name(name: &str) -> bool {
⋮----
fn is_stoplisted(name: &str) -> bool {
⋮----
fn is_literal_receiver(kind: &str) -> bool {
⋮----
fn strip_cpp_template_args(name: &str) -> String {
if !name.contains('<') {
return name.to_string();
... (1209 lines truncated)
</file>

<file path="codegraph-kernel/src/tsjs/extractors.rs">
use crate::buffers::edge_kind_index;
use tree_sitter::Node;
⋮----
pub(super) fn extract_function(&mut self, node: Node<'t>, name_override: Option<String>) {
⋮----
.clone()
.unwrap_or_else(|| self.extract_name(node));
⋮----
// Arrow/function-expression values: resolve the name from the parent
// variable_declarator (`export const useAuth = () => {}`), or from a
// CommonJS export assignment (`exports.getItems = async () => {}`,
// #1675). Mirrors TreeSitterExtractor.extractFunction.
⋮----
if name_override.is_none()
⋮----
&& matches!(node.kind(), "arrow_function" | "function_expression" | "generator_function")
⋮----
if let Some(parent) = node.parent() {
if parent.kind() == "variable_declarator" {
if let Some(var_name) = parent.child_by_field_name("name") {
name = self.text(var_name).to_string();
⋮----
} else if parent.kind() == "assignment_expression" {
if let Some(export_name) = self.common_js_export_name(parent, node) {
⋮----
// Still walk the body: module wrappers hold named inner functions
// and calls that would otherwise be lost (#528).
if let Some(body) = body_of(node) {
self.visit_function_body(body);
⋮----
signature: self.signature_of(node),
visibility: self.visibility_of(node),
is_exported: Some(common_js_export || self.is_exported(node)),
is_async: Some(self.is_async(node)),
is_static: self.is_static(node),
⋮----
let Some(row) = self.create_node("function", &name, node, extra) else {
⋮----
self.extract_type_annotations(node, row);
self.extract_decorators_for(node, row);
⋮----
self.stack.push(Scope { row, kind: "function", name });
⋮----
self.stack.pop();
⋮----
/// The property a CommonJS export assignment binds a function to —
    /// `exports.NAME = <node>` / `module.exports.NAME = <node>` — or None for
⋮----
/// `exports.NAME = <node>` / `module.exports.NAME = <node>` — or None for
    /// any other assignment. The node must be the assignment's whole
⋮----
/// any other assignment. The node must be the assignment's whole
fn common_js_export_name(&self, assignment: Node<'t>, value: Node<'t>) -> Option<String> {
let right = assignment.child_by_field_name("right")?;
if right.start_byte() != value.start_byte() || right.end_byte() != value.end_byte() {
⋮----
let left = assignment.child_by_field_name("left")?;
if left.kind() != "member_expression" {
⋮----
let object = left.child_by_field_name("object")?;
let property = left.child_by_field_name("property")?;
if property.kind() != "property_identifier" {
⋮----
if !matches!(self.text(object), "exports" | "module.exports") {
⋮----
Some(self.text(property).to_string())
⋮----
fn react_component_hoc(&self, value: Node<'t>) -> Option<Option<Node<'t>>> {
if value.kind() != "call_expression" {
⋮----
let callee = value.child_by_field_name("function")?;
let callee_text = self.text(callee);
if util::styled_callee().is_match(callee_text) {
return Some(None);
⋮----
if !is_react_hoc(callee_text) {
⋮----
if let Some(args) = value.child_by_field_name("arguments") {
for i in 0..args.named_child_count() {
if let Some(a) = args.named_child(i) {
if matches!(a.kind(), "arrow_function" | "function_expression") {
inner = Some(a);
⋮----
Some(inner)
⋮----
fn extract_react_component_node(
⋮----
let Some(row) = self.create_node("component", name, declarator, extra) else {
⋮----
self.stack.push(Scope { row, kind: "component", name: name.to_string() });
if let Some(body) = body_of(inner) {
⋮----
pub(super) fn extract_class(&mut self, node: Node<'t>) {
let resolved_body = body_of(node); // skipBodilessClass unset for TS/JS
let name = self.extract_name(node);
⋮----
is_exported: Some(self.is_exported(node)),
⋮----
let Some(row) = self.create_node("class", &name, node, extra) else {
⋮----
... (769 lines truncated)
</file>

<file path="codegraph-kernel/src/tsjs/fnref.rs">
use tree_sitter::Node;
⋮----
pub enum Mode {
⋮----
pub struct Candidate {
⋮----
fn stoplisted(name: &str) -> bool {
matches!(
⋮----
pub fn dispatch(kind: &str) -> Option<Mode> {
⋮----
"arguments" => Some(Mode::Args),
"assignment_expression" => Some(Mode::Rhs),
"variable_declarator" => Some(Mode::VarInit),
"pair" => Some(Mode::Value),
"array" => Some(Mode::List),
⋮----
"jsx_expression" => Some(Mode::List),
⋮----
"object" => Some(Mode::List),
⋮----
pub fn capture(container: Node, mode: Mode, src: &str) -> Vec<(Candidate, Mode)> {
⋮----
for i in 0..container.named_child_count() {
if let Some(c) = container.named_child(i) {
value_nodes.push(c);
⋮----
if let Some(rhs) = container.child_by_field_name("right") {
⋮----
.child_by_field_name("left")
.map(|l| &src[l.byte_range()])
.unwrap_or("");
⋮----
.captures(lhs_text)
.and_then(|c| c.get(1))
.map(|m| m.as_str());
let rhs_text = src[rhs.byte_range()].trim();
if !(lhs_last.is_some() && lhs_last == Some(rhs_text)) {
value_nodes.push(rhs);
⋮----
if let Some(v) = container.child_by_field_name("value") {
value_nodes.push(v);
⋮----
let name_node = container.child_by_field_name("name");
⋮----
.map(|n| matches!(n.kind(), "object_pattern" | "array_pattern"))
.unwrap_or(false);
⋮----
for (name, node) in normalize(v, src) {
if name.is_empty() || stoplisted(&name) {
⋮----
let p = node.start_position();
out.push((
⋮----
column_byte: node.start_byte(),
⋮----
fn normalize<'t>(node: Node<'t>, src: &str) -> Vec<(String, Node<'t>)> {
match node.kind() {
"identifier" | "shorthand_property_identifier" => vec![(src[node.byte_range()].to_string(), node)],
⋮----
let obj = node.child_by_field_name("object");
let prop = node.child_by_field_name("property");
⋮----
if o.kind() == "this" && p.kind() == "property_identifier" {
return vec![(format!("this.{}", &src[p.byte_range()]), p)];
⋮----
vec![]
⋮----
_ => vec![],
</file>

<file path="codegraph-kernel/src/tsjs/mod.rs">
mod extractors;
mod fnref;
⋮----
use crate::ids;
use crate::langs;
⋮----
pub enum Variant {
⋮----
impl Variant {
pub fn from_language(language: &str) -> Option<Variant> {
⋮----
"typescript" => Some(Variant::Typescript),
"tsx" => Some(Variant::Tsx),
"javascript" => Some(Variant::Javascript),
"jsx" => Some(Variant::Jsx),
⋮----
fn is_ts(self) -> bool {
matches!(self, Variant::Typescript | Variant::Tsx)
⋮----
fn value_refs(self) -> bool {
!matches!(self, Variant::Jsx)
⋮----
fn is_method_type(v: Variant, kind: &str) -> bool {
⋮----
|| (v.is_ts() && matches!(kind, "public_field_definition" | "method_signature"))
|| (!v.is_ts() && kind == "field_definition")
⋮----
fn is_property_type(v: Variant, kind: &str) -> bool {
v.is_ts() && kind == "property_signature"
⋮----
fn is_signature_method_type(kind: &str) -> bool {
⋮----
fn is_function_type(kind: &str) -> bool {
matches!(kind, "function_declaration" | "generator_function_declaration" | "arrow_function" | "function_expression" | "generator_function")
⋮----
fn is_class_type(v: Variant, kind: &str) -> bool {
kind == "class_declaration" || (v.is_ts() && kind == "abstract_class_declaration")
⋮----
fn is_variable_type(kind: &str) -> bool {
matches!(kind, "lexical_declaration" | "variable_declaration")
⋮----
fn is_literal_receiver(kind: &str) -> bool {
matches!(
⋮----
fn is_builtin_type(name: &str) -> bool {
⋮----
fn is_react_hoc(callee: &str) -> bool {
matches!(callee, "forwardRef" | "memo" | "React.forwardRef" | "React.memo")
⋮----
fn is_vue_collection_name(name: &str) -> bool {
matches!(name, "actions" | "mutations" | "getters")
⋮----
struct Scope {
⋮----
/// Extra node properties, per-extract-site (mirrors createNode's `extra`).
#[derive(Default)]
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
pub struct Walker<'t> {
⋮----
/// Node id string per row. Rows are unique but IDS COLLIDE for same
    /// (kind, name, line) nodes — routine in minified one-line files — and the
⋮----
/// (kind, name, line) nodes — routine in minified one-line files — and the
    /// TS extractor's fn-ref dedupe and value-ref self-checks key on the ID,
⋮----
/// TS extractor's fn-ref dedupe and value-ref self-checks key on the ID,
⋮----
pub fn extract(file_path: &str, source: &str, language: &str) -> Result<EmitOut, String> {
⋮----
.ok_or_else(|| format!("tsjs walker does not handle language: {language}"))?;
⋮----
.ok_or_else(|| format!("no grammar for language: {language}"))?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language({language}) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
⋮----
// Files with parse ERRORS defer to the wasm extractor (the `defer:` prefix
// tells the TS side this is expected routing, not a malfunction). Reason:
// tree-sitter's error RECOVERY — same grammar, same core version — resolves
⋮----
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
... (508 lines truncated)
</file>

<file path="codegraph-kernel/src/buffers.rs">
pub fn node_kind_index(kind: &str) -> Option<u8> {
NODE_KINDS.iter().position(|k| *k == kind).map(|i| i as u8)
⋮----
pub fn edge_kind_index(kind: &str) -> Option<u8> {
EDGE_KINDS.iter().position(|k| *k == kind).map(|i| i as u8)
⋮----
pub type StrRef = (u32, u32);
⋮----
pub struct Arena {
⋮----
impl Arena {
pub fn put(&mut self, s: &str) -> StrRef {
let off = self.buf.len() as u32;
self.buf.extend_from_slice(s.as_bytes());
(off, s.len() as u32)
⋮----
pub fn put_opt(&mut self, s: Option<&str>) -> StrRef {
⋮----
Some(s) => self.put(s),
⋮----
pub fn put_list(&mut self, items: &[String]) -> StrRef {
if items.is_empty() {
⋮----
let joined = items.join("\0");
self.put(&joined)
⋮----
pub fn len(&self) -> u32 {
self.buf.len() as u32
⋮----
pub fn into_vec(self) -> Vec<u8> {
⋮----
pub struct BoolFlags(pub u16);
⋮----
impl BoolFlags {
pub fn set(&mut self, pair: u16, value: bool) {
⋮----
pub struct NodeRow {
⋮----
pub struct EdgeRow {
⋮----
pub struct RefRow {
⋮----
fn push_str_ref(buf: &mut Vec<u8>, r: StrRef) {
buf.extend_from_slice(&r.0.to_le_bytes());
buf.extend_from_slice(&r.1.to_le_bytes());
⋮----
pub struct Tables {
⋮----
impl Default for Tables {
fn default() -> Self {
⋮----
impl Tables {
pub fn push_node(&mut self, r: &NodeRow) -> u32 {
⋮----
buf.push(r.kind);
buf.push(r.visibility);
buf.extend_from_slice(&r.flags.0.to_le_bytes());
buf.extend_from_slice(&r.start_line.to_le_bytes());
buf.extend_from_slice(&r.end_line.to_le_bytes());
buf.extend_from_slice(&r.start_column.to_le_bytes());
buf.extend_from_slice(&r.end_column.to_le_bytes());
push_str_ref(buf, r.name);
push_str_ref(buf, r.qualified_name);
push_str_ref(buf, r.id);
push_str_ref(buf, r.docstring);
push_str_ref(buf, r.signature);
push_str_ref(buf, r.decorators);
push_str_ref(buf, r.type_parameters);
push_str_ref(buf, r.return_type);
push_str_ref(buf, r.extra_json);
buf.extend_from_slice(&0u32.to_le_bytes());
⋮----
pub fn push_edge(&mut self, r: &EdgeRow) {
⋮----
buf.extend_from_slice(&r.source_idx.to_le_bytes());
buf.extend_from_slice(&r.target_idx.to_le_bytes());
⋮----
buf.push(r.provenance);
buf.extend_from_slice(&0u16.to_le_bytes());
buf.extend_from_slice(&r.line.to_le_bytes());
buf.extend_from_slice(&r.column.to_le_bytes());
push_str_ref(buf, r.metadata_json);
push_str_ref(buf, r.source_id_str);
push_str_ref(buf, r.target_id_str);
⋮----
pub fn push_ref(&mut self, r: &RefRow) {
self.push_ref_flagged(r, 0);
⋮----
pub fn push_ref_flagged(&mut self, r: &RefRow, flags: u8) {
⋮----
buf.extend_from_slice(&r.from_idx.to_le_bytes());
⋮----
buf.push(flags);
buf.extend_from_slice(&[0u8; 2]);
⋮----
push_str_ref(buf, r.reference_name);
push_str_ref(buf, r.candidates);
push_str_ref(buf, r.from_id_str);
⋮----
pub struct EmitOut {
... (31 lines truncated)
</file>

<file path="codegraph-kernel/src/cfnptr.rs">
pub struct StructExtent {
⋮----
pub struct RawField {
⋮----
pub struct StructFields {
⋮----
pub struct FileFacts {
⋮----
fn is_type_keyword(w: &[u8]) -> bool {
C_TYPE_KEYWORDS.iter().any(|k| *k == w)
⋮----
fn is_word(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
⋮----
fn is_word_at(s: &[u8], i: usize) -> bool {
i < s.len() && is_word(s[i])
⋮----
fn jsws_len(s: &[u8], i: usize) -> usize {
let Some(&b0) = s.get(i) else { return 0 };
⋮----
0xC2 if s.get(i + 1) == Some(&0xA0) => 2,
0xE1 if s.get(i + 1) == Some(&0x9A) && s.get(i + 2) == Some(&0x80) => 3,
0xE2 => match (s.get(i + 1), s.get(i + 2)) {
(Some(&0x80), Some(&b2)) if (0x80..=0x8A).contains(&b2) => 3,
⋮----
0xE3 if s.get(i + 1) == Some(&0x80) && s.get(i + 2) == Some(&0x80) => 3,
0xEF if s.get(i + 1) == Some(&0xBB) && s.get(i + 2) == Some(&0xBF) => 3,
⋮----
fn skip_jsws(s: &[u8], mut i: usize) -> usize {
⋮----
let l = jsws_len(s, i);
⋮----
fn word_end(s: &[u8], mut i: usize) -> usize {
while i < s.len() && is_word(s[i]) {
⋮----
fn boundary_before(s: &[u8], i: usize) -> bool {
i == 0 || !is_word(s[i - 1])
⋮----
fn find_bytes(s: &[u8], needle: &[u8], from: usize) -> Option<usize> {
if needle.is_empty() || s.len() < needle.len() {
⋮----
while i + needle.len() <= s.len() {
⋮----
match s[i..s.len() - needle.len() + 1].iter().position(|&b| b == needle[0]) {
⋮----
if &s[i..i + needle.len()] == needle {
return Some(i);
⋮----
fn contains_bytes(s: &[u8], needle: &[u8]) -> bool {
find_bytes(s, needle, 0).is_some()
⋮----
fn find_word(s: &[u8], word: &[u8], mut from: usize) -> Option<usize> {
⋮----
let t = find_bytes(s, word, from)?;
if boundary_before(s, t) && !is_word_at(s, t + word.len()) {
return Some(t);
⋮----
pub fn strip_c(src: &[u8]) -> Vec<u8> {
let n = src.len();
⋮----
out.extend_from_slice(&src[copied..start]);
emit_blank(out, &src[start..end]);
⋮----
blank_to(&mut out, start, i.min(n));
⋮----
blank_to(&mut out, start, i);
⋮----
out.extend_from_slice(&src[copied..]);
⋮----
/// One space per UTF-16 code unit (`\n` preserved): ASCII and 2-3-byte chars
/// are one unit, 4-byte (astral) chars are a surrogate pair — two units.
⋮----
/// are one unit, 4-byte (astral) chars are a surrogate pair — two units.
fn emit_blank(out: &mut Vec<u8>, region: &[u8]) {
⋮----
fn emit_blank(out: &mut Vec<u8>, region: &[u8]) {
⋮----
while i < region.len() {
⋮----
out.push(b'\n');
⋮----
1 // continuation byte at region start — invalid UTF-8; count singly
⋮----
out.push(b' ');
⋮----
i += len.min(region.len() - i);
⋮----
// ---------- shared regex tails ----------
⋮----
/// `\(\s*(?:\w+\s+)*\*\s*(\w+)\s*\)\s*\(` matched at `open` (which must hold
/// `(`). Returns (name_range, end_after_second_paren). The `(?:\w+\s+)*`
⋮----
/// `(`). Returns (name_range, end_after_second_paren). The `(?:\w+\s+)*`
/// group is greedy without backtracking: giving back an iteration repositions
⋮----
/// group is greedy without backtracking: giving back an iteration repositions
/// `\*` onto a word char, which can never match, so greedy ≡ backtracked.
⋮----
/// `\*` onto a word char, which can never match, so greedy ≡ backtracked.
fn fnptr_paren_tail(s: &[u8], open: usize) -> Option<((usize, usize), usize)> {
... (654 lines truncated)
</file>

<file path="codegraph-kernel/src/csharp.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_builtin_type(name: &str) -> bool {
matches!(
⋮----
fn is_stoplisted(name: &str) -> bool {
⋮----
fn trailing_nullable_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\?+$").unwrap())
⋮----
/// extractCsharpReturnType's generics strip (`/<[^>]*>/g`) — deliberately
⋮----
fn generic_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
/// `/^[A-Za-z_]\w*$/` with JS's ASCII `\w` (Rust's default `\w` is Unicode).
fn ascii_ident_re() -> &'static Regex {
⋮----
fn ascii_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
⋮----
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// JS `\s` (WhiteSpace ∪ LineTerminator) — differs from Rust's `\p{White_Space}`
⋮----
fn is_js_space(c: char) -> bool {
⋮----
fn strip_js_ws(s: &str) -> String {
s.chars().filter(|c| !is_js_space(*c)).collect()
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("csharp").ok_or("no csharp grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(csharp) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
// File node (TreeSitterExtractor.extract). Source here is the pre-blanked
// text (the route point hoists preParse), identical bytes on both arms.
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// extractFilePackage: a top-level file-scoped `namespace X;` mints ONE
// `namespace` node that stays pushed for the ENTIRE file, so every import
// ref in the file hangs off it (checklist §namespace). A block namespace
// scopes only its own body — visit_node.
let root = tree.root_node();
⋮----
for i in 0..root.named_child_count() {
let Some(child) = root.named_child(i) else { continue };
if child.kind() != "file_scoped_namespace_declaration" {
⋮----
if let Some(pkg) = namespace_name(&w, child) {
if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
w.stack.push(Scope { row, kind: "namespace", name: pkg });
⋮----
w.visit_node(root);
w.flush_fn_ref_candidates();
w.flush_value_refs(root);
⋮----
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
... (802 lines truncated)
</file>

<file path="codegraph-kernel/src/dart.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
fn is_builtin_type(name: &str) -> bool {
⋮----
fn simple_type_name_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
⋮----
fn cap_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// The chained-call re-encode gate (`/^[A-Z]/`).
fn starts_upper_re() -> &'static Regex {
⋮----
fn starts_upper_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z]").unwrap())
⋮----
/// extractDartReturnType's `<...>` strip (`/<[^>]*>/g`).
fn angle_args_re() -> &'static Regex {
⋮----
fn angle_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
struct Scope {
⋮----
struct Cand {
⋮----
struct ValueScope<'t> {
⋮----
struct Extra {
⋮----
/// 0 = absent; 1 public, 2 private.
    visibility: u8,
⋮----
/// resolveBody-driven endLine extension (LIVE for dart sibling bodies).
    end_line_override: Option<u32>,
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("dart").ok_or("no dart grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(dart) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
w.visit(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
⋮----
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
⋮----
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
⋮----
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
⋮----
... (748 lines truncated)
</file>

<file path="codegraph-kernel/src/docstring.rs">
use regex::Regex;
use std::sync::OnceLock;
use tree_sitter::Node;
⋮----
fn is_wrapper(kind: &str) -> bool {
matches!(
⋮----
fn is_comment(kind: &str) -> bool {
⋮----
struct Cleaners {
⋮----
fn cleaners() -> &'static Cleaners {
⋮----
C.get_or_init(|| Cleaners {
block_open: Regex::new(r"^/\*+!?").unwrap(),
block_close: Regex::new(r"\*+/$").unwrap(),
lua_open: Regex::new(r"^--\[=*\[").unwrap(),
lua_close: Regex::new(r"\]=*\]$").unwrap(),
paren_star_open: Regex::new(r"^\(\*").unwrap(),
paren_star_close: Regex::new(r"\*\)$").unwrap(),
brace_open: Regex::new(r"^\{").unwrap(),
brace_close: Regex::new(r"\}$").unwrap(),
slashes: Regex::new(r"\A//[/!]?\s?").unwrap(),
dashes: Regex::new(r"\A--\s?").unwrap(),
hash: Regex::new(r"\A#\s?").unwrap(),
percent: Regex::new(r"\A%+\s?").unwrap(),
star_cont: Regex::new(r"\A\s*\*\s?").unwrap(),
⋮----
/// JS multiline `^` anchors after \n, \r, U+2028, U+2029; the regex crate's
⋮----
fn is_js_line_terminator(ch: char) -> bool {
matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
⋮----
fn js_multiline_strip(s: &str, pat: &Regex) -> String {
let mut out = String::with_capacity(s.len());
⋮----
while pos <= s.len() {
⋮----
|| s[..pos].chars().next_back().is_some_and(is_js_line_terminator);
⋮----
if let Some(m) = pat.find(&s[pos..]) {
if !m.is_empty() {
out.push_str(&s[last..pos]);
last = pos + m.end();
⋮----
match s[pos..].chars().next() {
Some(c) => pos += c.len_utf8(),
⋮----
out.push_str(&s[last..]);
⋮----
pub fn clean_comment_markers(comment: &str) -> String {
let c = cleaners();
let mut s = comment.trim().to_string();
if s.starts_with("/*") {
s = c.block_open.replace(&s, "").into_owned();
s = c.block_close.replace(&s, "").into_owned();
} else if s.starts_with("--[") {
s = c.lua_open.replace(&s, "").into_owned();
s = c.lua_close.replace(&s, "").into_owned();
} else if s.starts_with("(*") {
s = c.paren_star_open.replace(&s, "").into_owned();
s = c.paren_star_close.replace(&s, "").into_owned();
} else if s.starts_with('{') {
s = c.brace_open.replace(&s, "").into_owned();
s = c.brace_close.replace(&s, "").into_owned();
⋮----
s = js_multiline_strip(&s, &c.slashes);
s = js_multiline_strip(&s, &c.dashes);
s = js_multiline_strip(&s, &c.hash);
s = js_multiline_strip(&s, &c.percent);
s = js_multiline_strip(&s, &c.star_cont);
s.trim().to_string()
⋮----
/// getPrecedingDocstring — collect the comment run immediately preceding the
/// node (climbing out of declaration wrappers first), cleaned and joined.
⋮----
/// node (climbing out of declaration wrappers first), cleaned and joined.
/// Returns None when there is no preceding comment (a PRESENT-but-empty
⋮----
/// Returns None when there is no preceding comment (a PRESENT-but-empty
/// docstring after cleaning still returns Some(""), matching the TS helper).
⋮----
/// docstring after cleaning still returns Some(""), matching the TS helper).
pub fn preceding_docstring(node: Node, src: &str) -> Option<String> {
⋮----
pub fn preceding_docstring(node: Node, src: &str) -> Option<String> {
⋮----
while let Some(parent) = anchor.parent() {
if is_wrapper(parent.kind()) {
⋮----
let mut sibling = anchor.prev_named_sibling();
⋮----
if is_comment(s.kind()) {
comments.push(&src[s.byte_range()]);
sibling = s.prev_named_sibling();
⋮----
if comments.is_empty() {
⋮----
comments.reverse(); // collected nearest-first; TS unshifts to keep source order
Some(
... (17 lines truncated)
</file>

<file path="codegraph-kernel/src/go.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn receiver_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\(\s*(?:[A-Za-z_]\w*\s+)?\*?\s*([A-Za-z_]\w*)").unwrap())
⋮----
fn simple_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
⋮----
fn go_two_hop_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*\.[A-Za-z_]\w*$").unwrap())
⋮----
fn generic_angle_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
fn bracket_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\[[^\]]*\]").unwrap())
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
/// Per-node metadata for the receiver-method owner lookup (mirrors the TS
/// side's scan over `this.nodes` — FIRST match wins, earlier-in-file only).
⋮----
/// side's scan over `this.nodes` — FIRST match wins, earlier-in-file only).
struct NodeMeta {
⋮----
struct NodeMeta {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("go").ok_or("no go grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(go) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
w.visit_node(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
⋮----
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
⋮----
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
⋮----
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
⋮----
fn inside_class_like(&self) -> bool {
⋮----
.last()
.map(|s| matches!(s.kind, "class" | "struct" | "interface" | "trait" | "enum" | "module"))
... (605 lines truncated)
</file>

<file path="codegraph-kernel/src/ids.rs">
use std::collections::HashMap;
⋮----
pub struct NodeIdAllocator {
⋮----
impl NodeIdAllocator {
pub fn generate(
⋮----
let id = node_id(file_path, kind, name, line);
⋮----
let first_column = self.first_columns.entry(id.clone()).or_insert(column);
⋮----
format!("{id}:{column}")
⋮----
pub fn node_id(file_path: &str, kind: &str, name: &str, line: u32) -> String {
⋮----
hasher.update(file_path.as_bytes());
hasher.update(b":");
hasher.update(kind.as_bytes());
⋮----
hasher.update(name.as_bytes());
⋮----
hasher.update(line.to_string().as_bytes());
let digest = hasher.finalize();
// 32 hex chars = first 16 bytes.
let mut hex = String::with_capacity(kind.len() + 1 + 32);
hex.push_str(kind);
hex.push(':');
⋮----
hex.push_str(&format!("{b:02x}"));
⋮----
pub fn file_node_id(file_path: &str) -> String {
format!("file:{file_path}")
⋮----
mod tests {
⋮----
fn collision_only_identity_vectors() {
⋮----
(2, base.to_string()),
(24, format!("{base}:24")),
(48, format!("{base}:48")),
⋮----
assert_eq!(
⋮----
fn matches_known_ts_output() {
</file>

<file path="codegraph-kernel/src/java.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_method_type(kind: &str) -> bool {
matches!(kind, "method_declaration" | "constructor_declaration")
⋮----
fn is_interface_type(kind: &str) -> bool {
matches!(kind, "interface_declaration" | "annotation_type_declaration")
⋮----
fn is_non_class_return(kind: &str) -> bool {
matches!(kind, "void_type" | "integral_type" | "floating_point_type" | "boolean_type")
⋮----
fn is_builtin_type(name: &str) -> bool {
matches!(
⋮----
fn is_lombok_log_annotation(name: &str) -> bool {
⋮----
fn generic_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
fn simple_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
fn method_ref_type_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^([A-Z][A-Za-z0-9_]*)\s*::").unwrap())
⋮----
fn is_prefix_re(word: &str) -> bool {
// /^is[A-Z]/ for Lombok boolean getters.
word.len() > 2 && word.starts_with("is") && word.as_bytes()[2].is_ascii_uppercase()
⋮----
struct Scope {
⋮----
/// Per-node metadata kept for the Lombok synthesizer's taken-member scan
struct NodeMeta {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("java").ok_or("no java grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(java) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
// File node (TreeSitterExtractor.extract).
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(crate::buffers::FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.nodes_meta.push(NodeMeta {
⋮----
name: base_name.to_string(),
qualified_name: file_path.to_string(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// extractFilePackage: wrap top-level declarations in a `namespace` node
// carrying the package FQN.
let root = tree.root_node();
⋮----
for i in 0..root.named_child_count() {
let Some(child) = root.named_child(i) else { continue };
if child.kind() != "package_declaration" {
⋮----
let id_node = (0..child.named_child_count())
.filter_map(|j| child.named_child(j))
.find(|c| matches!(c.kind(), "scoped_identifier" | "identifier"));
⋮----
let pkg = w.text(id_node).trim().to_string();
if !pkg.is_empty() {
if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
w.stack.push(Scope { row, kind: "namespace", name: pkg });
... (841 lines truncated)
</file>

<file path="codegraph-kernel/src/kotlin.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
fn is_literal_receiver(kind: &str) -> bool {
⋮----
fn ascii_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
⋮----
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// JS `\s` for the #750 inner-callee strip.
fn is_js_space(c: char) -> bool {
⋮----
fn is_js_space(c: char) -> bool {
⋮----
fn strip_js_ws(s: &str) -> String {
s.chars().filter(|c| !is_js_space(*c)).collect()
⋮----
fn property_initializers<'t>(node: Node<'t>) -> Vec<Node<'t>> {
⋮----
for i in 0..node.child_count() {
let Some(c) = node.child(i) else { continue };
if !c.is_named() {
if c.kind() == "=" {
⋮----
out.push(c);
⋮----
} else if matches!(c.kind(), "property_delegate" | "getter" | "setter") {
⋮----
fn accessor_owner<'t>(node: Node<'t>) -> Option<Node<'t>> {
let mut p = node.prev_named_sibling();
⋮----
if matches!(n.kind(), "getter" | "setter") {
p = n.prev_named_sibling();
⋮----
return if n.kind() == "property_declaration" { Some(n) } else { None };
⋮----
/// The sibling accessors that follow a property declaration, in source order.
fn following_accessors<'t>(node: Node<'t>) -> Vec<Node<'t>> {
⋮----
fn following_accessors<'t>(node: Node<'t>) -> Vec<Node<'t>> {
⋮----
let mut n = node.next_named_sibling();
⋮----
if !matches!(c.kind(), "getter" | "setter") {
⋮----
n = c.next_named_sibling();
⋮----
struct Scope {
⋮----
/// Per-node metadata for the extension-fn owner-contains lookup.
struct NodeMeta {
⋮----
struct NodeMeta {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("kotlin").ok_or("no kotlin grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(kotlin) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
⋮----
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
... (874 lines truncated)
</file>

<file path="codegraph-kernel/src/langs.rs">
use tree_sitter::Language;
⋮----
pub fn grammar_for(language: &str) -> Option<Language> {
⋮----
"typescript" => Some(tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into()),
"tsx" => Some(tree_sitter_typescript::LANGUAGE_TSX.into()),
"javascript" | "jsx" => Some(tree_sitter_javascript::LANGUAGE.into()),
"java" => Some(tree_sitter_java::LANGUAGE.into()),
"python" => Some(tree_sitter_python::LANGUAGE.into()),
"go" => Some(tree_sitter_go::LANGUAGE.into()),
⋮----
"c" => Some(tree_sitter_c::LANGUAGE.into()),
"cpp" => Some(tree_sitter_cpp::LANGUAGE.into()),
⋮----
"rust" => Some(tree_sitter_rust::LANGUAGE.into()),
⋮----
"csharp" => Some(tree_sitter_c_sharp::LANGUAGE.into()),
⋮----
"ruby" => Some(tree_sitter_ruby::LANGUAGE.into()),
⋮----
"php" => Some(tree_sitter_php::LANGUAGE_PHP.into()),
⋮----
"swift" => Some(tree_sitter_swift::LANGUAGE.into()),
⋮----
Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_kotlin) }.into())
⋮----
"r" => Some(tree_sitter_r::LANGUAGE.into()),
⋮----
Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_lua) }.into())
⋮----
"luau" => Some(tree_sitter_luau::LANGUAGE.into()),
⋮----
Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_scala) }.into())
⋮----
Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_dart) }.into())
</file>

<file path="codegraph-kernel/src/lib.rs">
macro_rules! stack_guard {
⋮----
mod buffers;
mod ccpp;
mod cfnptr;
mod csharp;
mod dart;
mod docstring;
mod ids;
mod go;
mod java;
mod kotlin;
mod langs;
mod lua;
mod php;
mod rlang;
mod ruby;
mod rustlang;
mod scala;
mod stack;
mod swift;
mod textutil;
mod python;
mod tsjs;
⋮----
use napi_derive::napi;
⋮----
pub struct ExtractBuffers {
⋮----
pub struct ContractInfo {
⋮----
pub struct GrammarInfo {
⋮----
pub fn contract_info() -> ContractInfo {
⋮----
kernel_version: env!("CARGO_PKG_VERSION").to_string(),
node_kinds: buffers::NODE_KINDS.iter().map(|s| s.to_string()).collect(),
edge_kinds: buffers::EDGE_KINDS.iter().map(|s| s.to_string()).collect(),
languages: langs::LANGUAGES.iter().map(|s| s.to_string()).collect(),
⋮----
pub fn grammar_info(language: String) -> Option<GrammarInfo> {
⋮----
let node_kind_count = lang.node_kind_count();
let field_count = lang.field_count();
⋮----
.map(|i| lang.node_kind_for_id(i as u16).unwrap_or("").to_string())
.collect();
// Field ids are 1-based in tree-sitter.
⋮----
.map(|i| lang.field_name_for_id(i as u16).unwrap_or("").to_string())
⋮----
Some(GrammarInfo {
abi_version: lang.abi_version() as u32,
⋮----
/// One struct node's extent for the cFnPtr sweep (mirror of the TS caller's
/// `{ id, startLine, endLine }`, with `endLine ?? startLine` applied TS-side).
⋮----
/// `{ id, startLine, endLine }`, with `endLine ?? startLine` applied TS-side).
#[napi(object)]
pub struct CfnptrStructIn {
⋮----
pub struct CfnptrFileIn {
/// RAW file text, exactly as the resolver's readFile returned it.
    pub text: String,
⋮----
pub struct CfnptrField {
⋮----
pub struct CfnptrStructOut {
⋮----
pub struct CfnptrFacts {
⋮----
pub fn cfnptr_scan_files(files: Vec<CfnptrFileIn>) -> Vec<CfnptrFacts> {
⋮----
.into_iter()
.map(|f| {
⋮----
.map(|s| cfnptr::StructExtent { id: s.id, start_line: s.start_line, end_line: s.end_line })
⋮----
.map(|s| CfnptrStructOut {
⋮----
.map(|fl| CfnptrField { name: fl.name, index: fl.index, ptr: fl.ptr, ty: fl.ty })
.collect(),
⋮----
.collect()
⋮----
pub fn cfnptr_strip_c(text: String) -> String {
String::from_utf8_lossy(&cfnptr::strip_c(text.as_bytes())).into_owned()
⋮----
pub fn extract_file(file_path: String, content: String, language: String) -> Result<ExtractBuffers> {
⋮----
let out = stack::run_guarded(|| match language.as_str() {
⋮----
.map_err(Error::from_reason)?;
Ok(ExtractBuffers {
meta: out.meta.into(),
nodes: out.nodes.into(),
edges: out.edges.into(),
refs: out.refs.into(),
arena: out.arena.into(),
</file>

<file path="codegraph-kernel/src/lua.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
struct Scope {
⋮----
struct Cand {
⋮----
struct Extra<'a> {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str, language: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for(language).ok_or("no lua/luau grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language({language}) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// No packageTypes → no namespace node. Value-refs are language-gated off.
w.visit(tree.root_node());
w.flush_fn_ref_candidates();
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
⋮----
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
⋮----
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
⋮----
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
⋮----
fn push_ref_at(&mut self, from_row: u32, name: &str, kind: &str, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
⋮----
kind: edge_kind_index(kind).unwrap(),
line: self.line_of(node),
column: self.col_of(node),
⋮----
if util::simple_name().is_match(name) {
self.imported_names.insert(name.to_string());
} else if let Some(c) = util::qualified_import().captures(name) {
self.imported_names.insert(c[1].to_string());
⋮----
fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, extra: Extra) -> Option<u32> {
if name.is_empty() {
⋮----
let start_line = self.line_of(node);
let column = self.col_of(node);
let id = self.node_id_allocator.generate(self.file_path, kind, name, start_line, column);
⋮----
Some(qn) => qn.clone(),
⋮----
parts.push(&s.name);
⋮----
let mut qn = parts.join("::");
if !qn.is_empty() {
qn.push_str("::");
⋮----
qn.push_str(name);
⋮----
let qn_ref = self.arena.put(&qualified);
let id_ref = self.arena.put(&id);
let doc_ref = opt_str(&mut self.arena, extra.docstring.as_deref());
let sig_ref = opt_str(&mut self.arena, extra.signature.as_deref());
⋮----
flags.set(FLAG_IS_EXPORTED, v);
... (428 lines truncated)
</file>

<file path="codegraph-kernel/src/php.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
fn is_php_non_class_return(lc: &str) -> bool {
⋮----
fn is_php_pseudo_type(name: &str) -> bool {
⋮----
fn is_php_type_node(kind: &str) -> bool {
⋮----
fn is_php_callable_hof(name: &str) -> bool {
⋮----
fn ascii_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
⋮----
/// String-callable simple-name shape (`/^[A-Za-z_][A-Za-z0-9_]*$/`).
fn simple_callable_re() -> &'static Regex {
⋮----
fn simple_callable_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_]*$").unwrap())
⋮----
/// String-callable qualified shape (`/^\w+::\w+$/`, JS ASCII `\w`).
fn qualified_callable_re() -> &'static Regex {
⋮----
fn qualified_callable_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[0-9A-Za-z_]+::[0-9A-Za-z_]+$").unwrap())
⋮----
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("php").ok_or("no php grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(php) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// extractFilePackage: the FIRST namespace_definition among the root's
⋮----
let root = tree.root_node();
⋮----
for i in 0..root.named_child_count() {
let Some(child) = root.named_child(i) else { continue };
if child.kind() != "namespace_definition" {
⋮----
let ns_name = (0..child.named_child_count())
.filter_map(|j| child.named_child(j))
.find(|c| c.kind() == "namespace_name");
let has_body = (0..child.named_child_count())
⋮----
.any(|c| matches!(c.kind(), "compound_statement" | "declaration_list"));
⋮----
let pkg = w.text(ns_name).to_string();
if !pkg.is_empty() {
if let Some(row) = w.create_node("namespace", &pkg, child, Extra::default()) {
w.stack.push(Scope { row, kind: "namespace", name: pkg });
⋮----
w.visit_node(root);
w.flush_fn_ref_candidates();
w.flush_value_refs();
... (722 lines truncated)
</file>

<file path="codegraph-kernel/src/python.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
fn body_docstring(node: Node, src: &str) -> Option<String> {
let body = if node.kind() == "module" { node } else { node.child_by_field_name("body")? };
let first = (0..body.named_child_count())
.filter_map(|i| body.named_child(i))
.find(|c| c.kind() != "comment")?;
if first.kind() != "expression_statement" {
⋮----
if first.named_child_count() != 1 || (0..first.child_count())
.filter_map(|i| first.child(i)).any(|c| c.kind() == ",") {
⋮----
let mut literal = first.named_child(0)?;
while literal.kind() == "parenthesized_expression" {
literal = (0..literal.named_child_count())
.filter_map(|i| literal.named_child(i))
⋮----
let strings = if literal.kind() == "concatenated_string" {
(0..literal.named_child_count()).filter_map(|i| literal.named_child(i))
.filter(|c| c.kind() != "comment").collect::<Vec<_>>()
⋮----
vec![literal]
⋮----
if string.kind() != "string" {
⋮----
let start = (0..string.named_child_count()).filter_map(|i| string.named_child(i))
.find(|c| c.kind() == "string_start")?;
if src[start.byte_range()].bytes().any(|b| matches!(b, b'b' | b'B' | b'f' | b'F')) {
⋮----
if !(0..string.named_child_count()).filter_map(|i| string.named_child(i))
.any(|c| c.kind() == "string_end") {
⋮----
for i in 0..string.named_child_count() {
if let Some(content) = string.named_child(i).filter(|c| c.kind() == "string_content") {
raw.push_str(&src[content.byte_range()]);
⋮----
let cleaned = dedent_docstring(&raw);
if cleaned.is_empty() { None } else { Some(cleaned) }
⋮----
fn docstring_space(c: char) -> bool {
⋮----
(c.is_whitespace() && c != '\u{85}') || c == '\u{feff}'
⋮----
fn dedent_docstring(raw: &str) -> String {
let normalized = raw.replace("\r\n", "\n").replace('\r', "\n");
let lines: Vec<String> = normalized.split('\n').map(|line| {
⋮----
for c in line.chars() {
⋮----
if c == '\t' { expanded.push_str(&" ".repeat(width)); } else { expanded.push(c); }
⋮----
}).collect();
let indent = lines.iter().skip(1).filter(|l| !l.trim_matches(docstring_space).is_empty())
.map(|l| l.chars().take_while(|c| docstring_space(*c)).count()).min().unwrap_or(0);
let out: Vec<String> = lines.iter().enumerate().map(|(i, l)| {
if i == 0 { l.trim_matches(docstring_space).to_string() } else {
l.chars().skip(indent).collect::<String>().trim_end_matches(docstring_space).to_string()
⋮----
let start = out.iter().position(|l| !l.trim_matches(docstring_space).is_empty()).unwrap_or(out.len());
let end = out.iter().rposition(|l| !l.trim_matches(docstring_space).is_empty()).map_or(start, |i| i + 1);
out[start..end].join("\n")
⋮----
fn docstring_for(node: Node, src: &str) -> Option<String> {
let preceding = preceding_docstring(node, src);
let body = body_docstring(node, src);
⋮----
(Some(a), Some(b)) if !a.is_empty() => Some(format!("{a}\n\n{b}")),
(a, b) => b.or(a),
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("python").ok_or("no python grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(python) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(crate::buffers::FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
let docstring = body_docstring(tree.root_node(), source)
.map(|doc| w.arena.put(&doc)).unwrap_or(NONE_STR);
... (525 lines truncated)
</file>

<file path="codegraph-kernel/src/rlang.rs">
use crate::ids;
⋮----
use regex::Regex;
use std::sync::OnceLock;
⋮----
fn constant_name_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Z0-9._]*$").unwrap())
⋮----
/// ASSIGN_LEFT / ASSIGN_RIGHT (r.ts:37-38).
fn is_assign_left(op: &str) -> bool {
⋮----
fn is_assign_left(op: &str) -> bool {
matches!(op, "<-" | "<<-" | "=")
⋮----
fn is_assign_right(op: &str) -> bool {
matches!(op, "->" | "->>")
⋮----
/// IMPORT_FNS (r.ts:39) — `source` is checked alongside (r.ts:189).
fn is_import_fn(name: &str) -> bool {
⋮----
fn is_import_fn(name: &str) -> bool {
matches!(name, "library" | "require" | "requireNamespace" | "loadNamespace")
⋮----
/// CLASS_FNS (r.ts:40).
fn is_class_fn(name: &str) -> bool {
⋮----
fn is_class_fn(name: &str) -> bool {
matches!(name, "setClass" | "setRefClass" | "R6Class" | "ggproto")
⋮----
/// GENERIC_FNS (r.ts:41).
fn is_generic_fn(name: &str) -> bool {
⋮----
fn is_generic_fn(name: &str) -> bool {
matches!(name, "setGeneric" | "setMethod")
⋮----
struct Scope {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("r").ok_or("no r grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(r) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
// File node (tree-sitter.ts:508-521) — the only node with isExported set.
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// extractFilePackage returns null (no packageTypes); both end-of-file
// flushes are no-ops for R (no fnRefSpec, VALUE_REF_LANGS gate).
w.visit(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
⋮----
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
⋮----
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
⋮----
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
⋮----
fn push_ref_at(&mut self, from_row: u32, name: &str, kind: &str, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
⋮----
kind: edge_kind_index(kind).unwrap(),
line: self.line_of(node),
column: self.col_of(node),
⋮----
fn create_node(&mut self, kind: &'static str, name: &str, node: Node<'t>, signature: Option<&str>) -> Option<u32> {
if name.is_empty() {
... (244 lines truncated)
</file>

<file path="codegraph-kernel/src/ruby.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
fn is_ruby_hook_call(name: &str) -> bool {
⋮----
let re = RE.get_or_init(|| Regex::new(r"^(skip_)?(before|after|around)_[a-z_]+$").unwrap());
re.is_match(name)
|| matches!(name, "validate" | "set_callback" | "helper_method" | "rescue_from")
⋮----
fn ruby_sym_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][A-Za-z0-9_?!]*$").unwrap())
⋮----
/// Node `path.posix.normalize` for the require_relative path join
/// (emitRubyRequireRefs): resolve `.`/`..` lexically, collapse `//`, keep
⋮----
/// (emitRubyRequireRefs): resolve `.`/`..` lexically, collapse `//`, keep
/// unresolvable leading `..`s, preserve a trailing slash.
⋮----
/// unresolvable leading `..`s, preserve a trailing slash.
fn posix_normalize(p: &str) -> String {
⋮----
fn posix_normalize(p: &str) -> String {
let is_abs = p.starts_with('/');
let had_trailing = p.len() > 1 && p.ends_with('/');
⋮----
for seg in p.split('/') {
⋮----
if matches!(out.last(), Some(&last) if last != "..") {
out.pop();
⋮----
out.push("..");
⋮----
s => out.push(s),
⋮----
let mut joined = out.join("/");
⋮----
joined = format!("/{joined}");
⋮----
if joined.is_empty() || joined == "/" {
return if is_abs { "/".to_string() } else { ".".to_string() };
⋮----
joined.push('/');
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("ruby").ok_or("no ruby grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(ruby) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
w.visit_node(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
... (520 lines truncated)
</file>

<file path="codegraph-kernel/src/rustlang.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn generic_angle_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
/// JS `/^[A-Za-z_]\w*$/` (ASCII \w — the regex crate's \w is Unicode).
fn simple_ident_re() -> &'static Regex {
⋮----
fn simple_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
struct NodeMeta {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("rust").ok_or("no rust grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(rust) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.nodes_meta.push(NodeMeta { kind: "file", name: base_name.to_string() });
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
w.visit_node(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
fn text(&self, node: Node) -> &'t str {
&self.src[node.byte_range()]
⋮----
fn line_of(&self, node: Node) -> u32 {
node.start_position().row as u32 + 1
⋮----
fn col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.start_position().row, node.start_byte())
⋮----
fn end_col_of(&self, node: Node) -> u32 {
util::col16(self.src, &self.line_starts, node.end_position().row, node.end_byte())
⋮----
fn top_row(&self) -> u32 {
self.stack.last().map(|s| s.row).unwrap_or(0)
⋮----
fn inside_class_like(&self) -> bool {
⋮----
.last()
.map(|s| matches!(s.kind, "class" | "struct" | "union" | "interface" | "trait" | "enum" | "module"))
.unwrap_or(false)
⋮----
fn push_ref_at(&mut self, from_row: u32, name: &str, kind_code: u8, node: Node) {
let name_ref = self.arena.put(name);
self.tables.push_ref(&RefRow {
⋮----
line: self.line_of(node),
column: self.col_of(node),
⋮----
if kind_code == edge_kind_index("imports").unwrap() {
if util::simple_name().is_match(name) {
self.imported_names.insert(name.to_string());
} else if let Some(c) = util::qualified_import().captures(name) {
⋮----
self.imported_names.insert(c[1].to_string());
... (734 lines truncated)
</file>

<file path="codegraph-kernel/src/scala.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_stoplisted(name: &str) -> bool {
matches!(
⋮----
fn is_literal_receiver(kind: &str) -> bool {
⋮----
fn is_builtin_type(name: &str) -> bool {
⋮----
fn is_scala_builtin(name: &str) -> bool {
⋮----
fn simple_type_name_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_]\w*$").unwrap())
⋮----
/// extractScalaReturnType's generic-args strip (`/\[[^\]]*\]/g`).
fn bracket_args_re() -> &'static Regex {
⋮----
fn bracket_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\[[^\]]*\]").unwrap())
⋮----
/// Static-member receiver gate (`/^[A-Z][A-Za-z0-9_]*$/`).
fn cap_ident_re() -> &'static Regex {
⋮----
fn cap_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// The #750 re-encode gate (`/^[A-Z]/`).
fn starts_upper_re() -> &'static Regex {
⋮----
fn starts_upper_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z]").unwrap())
⋮----
/// JS `\s+` for the re-encode/return-type strips (Unicode whitespace).
fn ws_re() -> &'static Regex {
⋮----
fn ws_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"\s+").unwrap())
⋮----
struct Scope {
⋮----
struct Cand {
⋮----
struct ValueScope<'t> {
⋮----
struct Extra {
⋮----
/// 0 = absent; 1 public, 2 private, 3 protected.
    visibility: u8,
/// (present, value) — isAsync/isStatic are literal-false hooks for scala.
    is_async: Option<bool>,
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("scala").ok_or("no scala grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(scala) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
⋮----
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// No packageTypes → no namespace node, ever.
w.visit(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
... (685 lines truncated)
</file>

<file path="codegraph-kernel/src/stack.rs">
use std::cell::Cell;
⋮----
thread_local! {
⋮----
fn current_sp() -> usize {
⋮----
fn os_stack_low() -> Option<usize> {
⋮----
if rc != 0 || addr.is_null() || size == 0 {
⋮----
Some(addr as usize)
⋮----
Some(high - size)
⋮----
unsafe { GetCurrentThreadStackLimits(&mut low, &mut high) };
⋮----
Some(low)
⋮----
pub fn begin() {
OVERFLOWED.with(|o| o.set(false));
let cached = THRESHOLD.with(|t| t.get());
if cached != 0 && THRESHOLD_IS_OS.with(|f| f.get()) {
⋮----
match os_stack_low() {
⋮----
THRESHOLD.with(|t| t.set(low.saturating_add(RED_ZONE)));
THRESHOLD_IS_OS.with(|f| f.set(true));
⋮----
THRESHOLD.with(|t| t.set(current_sp().saturating_sub(FALLBACK_BUDGET).max(1)));
THRESHOLD_IS_OS.with(|f| f.set(false));
⋮----
pub fn exhausted() -> bool {
let threshold = THRESHOLD.with(|t| t.get());
⋮----
begin();
return exhausted();
⋮----
if current_sp() < threshold {
OVERFLOWED.with(|o| o.set(true));
⋮----
pub fn overflowed() -> bool {
OVERFLOWED.with(|o| o.get())
⋮----
pub fn run_guarded<T>(f: impl FnOnce() -> Result<T, String>) -> Result<T, String> {
⋮----
let out = f();
if overflowed() {
return Err(
"defer: nesting too deep for the native walker — wasm recovery handles it".to_string(),
⋮----
mod tests {
⋮----
fn on_small_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
⋮----
.stack_size(SMALL_STACK)
.spawn(f)
.expect("spawn")
.join()
.expect("walker thread panicked")
⋮----
fn nested_parens(prefix: &str, suffix: &str) -> String {
format!("{prefix}{}1{}{suffix}", "(".repeat(DEPTH), ")".repeat(DEPTH))
⋮----
fn os_bounds_are_sane_on_this_platform() {
⋮----
let low = os_stack_low().expect("OS stack bounds available");
let sp = current_sp();
assert!(low < sp, "stack low {low:#x} must be below the current sp {sp:#x}");
assert!(sp - low < 1 << 31, "implausible stack size {}", sp - low);
⋮----
fn small_stack_reports_its_own_bounds() {
on_small_stack(|| {
⋮----
let used = current_sp() - low;
⋮----
assert!(
⋮----
fn deep_braces_c_defer_instead_of_crashing() {
let src = format!("void foo(void) {{\n{}{}\n}}\n", "{".repeat(DEPTH), "}".repeat(DEPTH));
let r = on_small_stack(move || run_guarded(|| crate::ccpp::extract("deep.c", &src, "c")));
let err = r.err().expect("deep nesting must defer");
assert!(err.starts_with("defer:"), "unexpected error: {err}");
⋮----
type Extract = fn(&str) -> Result<crate::buffers::EmitOut, String>;
⋮----
fn deep_parens_cpp_rust_ts_python_defer_instead_of_crashing() {
⋮----
("deep.cpp", |s| crate::ccpp::extract("deep.cpp", s, "cpp"), nested_parens("int f() { return ", "; }\n")),
("deep.rs", |s| crate::rustlang::extract("deep.rs", s), nested_parens("fn f() -> i32 { ", " }\n")),
("deep.ts", |s| crate::tsjs::extract("deep.ts", s, "typescript"), nested_parens("function f() { return ", "; }\n")),
("deep.py", |s| crate::python::extract("deep.py", s), nested_parens("def f():\n    return ", "\n")),
⋮----
let r = on_small_stack(move || run_guarded(|| extract(&src)));
let err = r.err().unwrap_or_else(|| panic!("{name}: deep nesting must defer"));
assert!(err.starts_with("defer:"), "{name}: unexpected error: {err}");
⋮----
fn normal_files_are_untouched_by_the_guard() {
⋮----
let r = on_small_stack(move || run_guarded(|| crate::ccpp::extract("ok.c", src, "c")));
assert!(r.is_ok(), "a shallow file must not defer: {:?}", r.err());
... (10 lines truncated)
</file>

<file path="codegraph-kernel/src/swift.rs">
use crate::docstring::preceding_docstring;
use crate::ids;
⋮----
use regex::Regex;
⋮----
use std::sync::OnceLock;
⋮----
fn is_builtin_type(name: &str) -> bool {
matches!(
⋮----
fn is_stoplisted(name: &str) -> bool {
⋮----
fn is_literal_receiver(kind: &str) -> bool {
⋮----
fn ascii_ident_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Za-z_][0-9A-Za-z_]*$").unwrap())
⋮----
/// getReturnType's generics strip (`/<[^>]*>/g`) — non-nesting (rust-class quirk).
fn generic_args_re() -> &'static Regex {
⋮----
fn generic_args_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"<[^>]*>").unwrap())
⋮----
/// extractStaticMemberRef's capitalized-receiver test.
fn capitalized_re() -> &'static Regex {
⋮----
fn capitalized_re() -> &'static Regex {
⋮----
RE.get_or_init(|| Regex::new(r"^[A-Z][A-Za-z0-9_]*$").unwrap())
⋮----
/// JS `\s` for the chained-call inner-callee strip (`.replace(/\s+/g, '')`).
fn is_js_space(c: char) -> bool {
⋮----
fn is_js_space(c: char) -> bool {
⋮----
fn strip_js_ws(s: &str) -> String {
s.chars().filter(|c| !is_js_space(*c)).collect()
⋮----
fn is_type_path(s: &str) -> bool {
if s.starts_with("Self.") {
⋮----
for seg in s.split('.') {
let b = seg.as_bytes();
if b.is_empty() || !b[0].is_ascii_uppercase() || !b[1..].iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_') {
⋮----
struct Scope {
⋮----
struct Extra {
⋮----
struct ValueScope<'t> {
⋮----
struct Cand {
⋮----
struct SwiftPropInfo<'t> {
⋮----
pub struct Walker<'t> {
⋮----
pub fn extract(file_path: &str, source: &str) -> Result<EmitOut, String> {
let grammar = crate::langs::grammar_for("swift").ok_or("no swift grammar")?;
⋮----
.set_language(&grammar)
.map_err(|e| format!("set_language(swift) failed: {e}"))?;
⋮----
.parse(source, None)
.ok_or_else(|| "parser returned null tree".to_string())?;
if tree.root_node().has_error() {
return Err("defer: parse tree contains errors — wasm recovery is canonical".to_string());
⋮----
let line_count = source.bytes().filter(|b| *b == b'\n').count() as u32 + 1;
let base_name = file_path.rsplit(['/', '\\']).next().unwrap_or(file_path);
⋮----
flags.set(FLAG_IS_EXPORTED, false);
let file_id = w.arena.put(&ids::file_node_id(file_path));
let name_ref = w.arena.put(base_name);
let qn_ref = w.arena.put(file_path);
w.tables.push_node(&NodeRow {
kind: node_kind_index("file").unwrap(),
⋮----
w.node_ids.push(ids::file_node_id(file_path));
w.stack.push(Scope { row: 0, kind: "file", name: base_name.to_string() });
⋮----
// No packageTypes — swift has no namespace node; top-level QNs are bare.
w.visit_node(tree.root_node());
w.flush_fn_ref_candidates();
w.flush_value_refs(tree.root_node());
w.stack.pop();
⋮----
let duration_ms = t0.elapsed().as_secs_f64() * 1000.0;
let meta = build_meta(&w.tables, w.arena.len(), NONE_STR, duration_ms);
Ok(EmitOut {
⋮----
arena: w.arena.into_vec(),
⋮----
/// firstSimpleIdentifier (tree-sitter.ts:261): BFS (FIFO), at most 40 nodes
/// popped, first `simple_identifier` wins.
⋮----
/// popped, first `simple_identifier` wins.
fn first_simple_identifier<'t>(node: Option<Node<'t>>) -> Option<Node<'t>> {
... (795 lines truncated)
</file>

<file path="codegraph-kernel/src/textutil.rs">
use regex::Regex;
use std::sync::OnceLock;
⋮----
macro_rules! re {
⋮----
// RTK_HOOK_NAME_RE (tree-sitter.ts)
re!(rtk_hook_name, r"^use[A-Z][A-Za-z0-9]*(?:Query|Mutation)$");
// reactComponentHoc's styled test
re!(styled_callee, r"^styled\b");
⋮----
re!(pascal_case, r"^[A-Z]");
// extractCall parenthesized-conversion normalization
re!(paren_conversion, r"^\(\s*\*?\s*([A-Za-z_][\w.]*)\s*\)$");
// flushFnRefCandidates SIMPLE_NAME
re!(simple_name, r"^[A-Za-z_$][A-Za-z0-9_$]*$");
// flushFnRefCandidates QUALIFIED_IMPORT
re!(qualified_import, r"^[A-Za-z_$][A-Za-z0-9_$.\\]*[.\\]([A-Za-z_$][A-Za-z0-9_$]*)$");
// captureFnRefCandidates rhs param-storage skip — trailing identifier of LHS
re!(lhs_last_name, r"([A-Za-z_$][A-Za-z0-9_$]*)\s*$");
// extractTsTupleContractNames identifier test
re!(ident_dollar, r"^[A-Za-z_$][A-Za-z0-9_$]*$");
// looksLikeVueStoreFile signal (VUE_STORE_FILE_SIGNAL)
re!(
⋮----
re!(has_upper_or_underscore, r"[A-Z_]");
⋮----
/// isGeneratedFile (src/extraction/generated-detection.ts) — full pattern list
/// ported so future language walkers share it.
⋮----
/// ported so future language walkers share it.
pub fn is_generated_file(file_path: &str) -> bool {
⋮----
pub fn is_generated_file(file_path: &str) -> bool {
⋮----
let patterns = RES.get_or_init(|| {
⋮----
.iter()
.map(|p| Regex::new(p).expect("generated pattern"))
.collect()
⋮----
patterns.iter().any(|p| p.is_match(file_path))
⋮----
pub fn line_starts(src: &str) -> Vec<usize> {
let mut out = vec![0usize];
for (i, b) in src.bytes().enumerate() {
⋮----
out.push(i + 1);
⋮----
pub fn utf16_len(s: &str) -> usize {
s.chars().map(|c| c.len_utf16()).sum()
⋮----
pub fn col16(src: &str, starts: &[usize], row: usize, byte_pos: usize) -> u32 {
let ls = starts.get(row).copied().unwrap_or(0);
⋮----
utf16_len(&src[ls..byte_pos]) as u32
⋮----
pub fn slice_utf16(s: &str, n: usize) -> (String, bool) {
⋮----
for c in s.chars() {
let w = c.len_utf16();
⋮----
out.push(c);
⋮----
let truncated = out.len() < s.len();
⋮----
pub fn object_key_name(s: &str) -> String {
⋮----
if let Some(first) = out.chars().next() {
⋮----
out = &out[first.len_utf8()..];
⋮----
if let Some(last) = out.chars().last() {
⋮----
out = &out[..out.len() - last.len_utf8()];
⋮----
out.to_string()
⋮----
pub fn init_signature(value_text: &str) -> String {
let (sliced, _) = slice_utf16(value_text, 100);
if utf16_len(&sliced) >= 100 {
format!("= {sliced}...")
⋮----
format!("= {sliced}")
⋮----
mod tests {
⋮----
fn utf16_cols() {
⋮----
assert_eq!(utf16_len(src), 5);
let starts = line_starts(src);
assert_eq!(col16(src, &starts, 0, 1), 1);
assert_eq!(col16(src, &starts, 0, 3), 2);
assert_eq!(col16(src, &starts, 0, 7), 4);
⋮----
fn init_sig_short_and_long() {
assert_eq!(init_signature("[1, 2]"), "= [1, 2]");
let long = "x".repeat(150);
let sig = init_signature(&long);
assert!(sig.starts_with("= "));
assert!(sig.ends_with("..."));
... (7 lines truncated)
</file>

<file path="codegraph-kernel/build.rs">
fn main() {
⋮----
c.include("grammars/kotlin");
c.file("grammars/kotlin/parser.c");
c.file("grammars/kotlin/scanner.c");
c.flag_if_supported("-Wno-unused-parameter");
c.flag_if_supported("-Wno-unused-but-set-variable");
c.flag_if_supported("-Wno-trigraphs");
c.flag_if_supported("-utf-8");
c.compile("tree-sitter-kotlin");
println!("cargo:rerun-if-changed=grammars/kotlin");
⋮----
lua.include("grammars/lua");
lua.file("grammars/lua/parser.c");
lua.file("grammars/lua/scanner.c");
lua.flag_if_supported("-Wno-unused-parameter");
lua.flag_if_supported("-Wno-unused-but-set-variable");
lua.flag_if_supported("-Wno-trigraphs");
lua.flag_if_supported("-utf-8");
lua.compile("tree-sitter-lua");
println!("cargo:rerun-if-changed=grammars/lua");
⋮----
scala.include("grammars/scala");
scala.file("grammars/scala/parser.c");
scala.file("grammars/scala/scanner.c");
scala.flag_if_supported("-Wno-unused-parameter");
scala.flag_if_supported("-Wno-unused-but-set-variable");
scala.flag_if_supported("-Wno-trigraphs");
scala.flag_if_supported("-utf-8");
scala.compile("tree-sitter-scala");
println!("cargo:rerun-if-changed=grammars/scala");
⋮----
dart.include("grammars/dart");
dart.file("grammars/dart/parser.c");
dart.file("grammars/dart/scanner.c");
dart.flag_if_supported("-Wno-unused-parameter");
dart.flag_if_supported("-Wno-unused-but-set-variable");
dart.flag_if_supported("-Wno-trigraphs");
dart.flag_if_supported("-Wno-unused-function");
dart.flag_if_supported("-utf-8");
dart.compile("tree-sitter-dart");
println!("cargo:rerun-if-changed=grammars/dart");
</file>

<file path="codegraph-kernel/Cargo.toml">
[package]
name = "codegraph-kernel"
version = "0.1.0"
edition = "2021"
license = "MIT"
publish = false
description = "Native extraction kernel for CodeGraph — tree-sitter parse+extract with one JS boundary crossing per file"

[lib]
crate-type = ["cdylib"]

[dependencies]
napi = { version = "3", default-features = false, features = ["napi8"] }
napi-derive = "3"
tree-sitter = "0.25"
sha2 = "0.10"
regex = "1"

# Grammars — MUST stay revision-matched with the wasm grammars the fallback
# path loads (tree-sitter-wasms npm package / src/extraction/wasm/). The
# kernel-grammar-parity test asserts node-kind-table equality at test time;
# bump these together with the wasm side or that gate fails.
tree-sitter-typescript = "0.23"
tree-sitter-javascript = "0.25"
tree-sitter-java = "0.23"
tree-sitter-python = "0.23"
tree-sitter-go = "0.23"
# Pinned exact: the vendored wasm (src/extraction/wasm/) was built from these
# tags' checked-in parser.c, sha-matched against these registry tarballs
# (R7a prep, #1345). A patch bump here without re-vendoring breaks the match.
tree-sitter-c = "=0.24.2"
tree-sitter-cpp = "=0.23.4"
tree-sitter-rust = "=0.24.2"
# csharp: the vendored wasm (#717) predates the kernel and was verified
# table-identical to this crate's tarball (ABI 15, STATE_COUNT 8053, node-kind
# and field tables — csharp checklist header). Bump crate + wasm together.
tree-sitter-c-sharp = "=0.23.5"
# ruby: content bump, ABI stays 14 (the v0.23.1 tag predates the ABI-15
# generator) — kernel-grammar-parity asserts same-revision, not same-ABI.
tree-sitter-ruby = "=0.23.1"
# php: the walker calls LANGUAGE_PHP (the full HTML-interleaving variant the
# wasm ships) — NEVER LANGUAGE_PHP_ONLY, which errors on leading HTML.
tree-sitter-php = "=0.24.2"
# swift: the vendored wasm is built from THIS crate's tarball src/ (the tag's
# checked-in parser.c is an older ABI-14 generation that can never sha-match;
# grammar.json rules are JSON-equal — swift checklist header). parser.c is
# ~20MB generated — expect slow compiles.
tree-sitter-swift = "=0.7.3"
# r: the vendored wasm IS r-lib v1.2.0 and this crate's tarball ships both
# generated artifacts sha-identical to the tag (parser.c 6221657347…,
# scanner.c 1209d11076… — r checklist §Grammar prep). ABI 14 (the tag
# predates the ABI-15 generator) — parity asserts same-revision, not
# same-ABI (ruby precedent). Bump crate + wasm together.
tree-sitter-r = "=1.2.0"
# luau: the vendored wasm IS tree-sitter-grammars v1.2.0 and this crate's
# tarball ships parser.c/scanner.c sha-identical to the tag (8f25bc17… /
# a157bb52… — lua-luau checklist §Grammar prep). ABI 14. Lua itself is
# vendored C (build.rs) — its v0.4.1 revision is not on crates.io.
tree-sitter-luau = "=1.2.0"

# tree-sitter-language: the version-agnostic LanguageFn shim for the vendored
# kotlin grammar C (see build.rs — no kotlin crate dep is possible).
tree-sitter-language = "0.1"

# Stack-bounds queries for the walker stack guard (src/stack.rs, #1581):
# pthread_getattr_np / pthread_get_stackaddr_np. Already in the lock file
# transitively; Windows uses a hand-declared kernel32 extern instead.
[target.'cfg(unix)'.dependencies]
libc = "0.2"

[build-dependencies]
napi-build = "2"
cc = "1"

[profile.release]
lto = true
codegen-units = 1
strip = "symbols"
</file>

<file path="docs/benchmarks/agent-eval-feedback-metrics.md">
# The three explore feedback metrics — start here

The agent-eval harness reports three metrics on every run. They are not three
views of one number; each answers a different question, and a retrieval change
can move one without moving the others. This page says which is which, which
harness to run, and how to read the output. The per-metric docs carry the
derivations and the caveats — read the one that matters once a number moves.

| Metric | The question it answers | Doc |
|---|---|---|
| **Residual context occupancy** (CG-7) | How much of the window does this arm's retrieval still hold when the run ends — i.e. what does every following turn have to work in? | [`residual-context-occupancy.md`](residual-context-occupancy.md) |
| **Explore sufficiency** (CG-8) | Was a response *enough*? Read off what the agent did next: explored again, read a file, or answered. | [`explore-sufficiency.md`](explore-sufficiency.md) |
| **Allocation efficiency** (CG-9) | Of the bytes a response spent, what share went to files the answer actually drew on? | [`explore-allocation-efficiency.md`](explore-allocation-efficiency.md) |

All three are **harness-only**: parsed out of transcripts we already write.
Nothing is emitted from the product and nothing leaves the machine.

---

## Which harness

Pick by the question you are actually asking. All three metrics print in both.

**Isolating a retrieval change — `ab-new-vs-baseline.sh`.** New build (HEAD) vs
a baseline build (a git ref), **both arms codegraph-on**, same task. This is
the harness the three metrics were built for: with codegraph on in both arms,
every number is measuring the change rather than adoption.

```bash
RUNS=3 scripts/agent-eval/ab-new-vs-baseline.sh /tmp/codegraph-corpus/express \
  "Add a charset option to res.send and wire it through" main
```

It builds each arm, indexes a throwaway copy of the target, **pre-warms a
codegraph daemon per run**, runs the task `RUNS` times per arm, prints the three
metric blocks under each run, and ends with the side-by-side table below. The
pre-warm is load-bearing and must not be removed: without it the agent dives
into Read/grep before codegraph finishes its ~2–3s startup, and the run measures
attach latency instead of retrieval.

**With vs without codegraph — `run-all.sh`.** Codegraph-on against an empty MCP
config. A different question: displacement and adoption, not the effect of a
change. Multi-turn is where occupancy is actually charged, so separate turns
with `||`.

```bash
scripts/agent-eval/run-all.sh /tmp/codegraph-corpus/gin \
  "How does gin route requests through its middleware chain?||\
Where is the 404 / no-route case handled in that same chain?"
```

`CG_ARMS=with|without` re-runs one arm without redoing the other; the comparison
table still renders against whichever arm's logs are already in `$AGENT_EVAL_OUT`.

**A campaign — `bench-readme.sh`.** The 7 README repos, three turns each,
`RUNS` per arm, through `run-all.sh` — so every run in a campaign carries all
three metrics. Aggregate with `parse-bench-readme.mjs`. One has been run:
[the 2026-08-05 baseline](residual-context-occupancy.md#baseline-the-7-readme-repos)
(sonnet, 3 turns, 4 runs/arm) — read its regime box before comparing anything to
it, and note that it is **not** the regime the README's table was published in.

**A log you already have.** `parse-run.mjs <run.jsonl> [run.tN.jsonl …]` prints
the three blocks for any stream-json log; `--brief` drops the numbered call
transcript. `parse-session.mjs <project-dir>` does sufficiency and allocation
for an *interactive* session. `compare-arms.mjs <out-dir> <label>…` builds the
table from logs on disk, at any time, for any labels.

**Model policy, both harnesses, not negotiable:** `--model sonnet --effort high`
on every arm, both arms the same model. Sonnet is the deliberate floor — an
affordance that lands on it generalizes up to every host; one that only works on
a stronger model does not generalize down to the agents most users have.

---

## Reading the output

Each run prints its three blocks (see the per-metric docs for the shape of
each), then one table puts the arms side by side:

```
====== ARM COMPARISON — /private/tmp/cg22/ab-express ======
                                                           new                baseline
  runs                                                       3                       3

  behavior
    duration (s)                                    24 [18–35]              26 [24–30]
    Read                                                     0                       1
    codegraph calls                                    2 [1–2]                       2

  residual context occupancy (CG-7) — tokens still resident at end of run
    codegraph residual (tok)             11,549 [7,193–12,591]  10,388 [10,373–10,447]
    file-access residual (tok)                     231 [0–242]     1,661 [1,306–1,663]
    → retrieval residual (tok)           11,780 [7,193–12,833]  12,034 [11,753–12,051]
    → share of final context               23.3% [15.8%–24.9%]     23.8% [23.4%–23.9%]

  explore sufficiency (CG-8) — pooled over every answered explore call
    answered explore calls                                   5                       6
    explore again                                       2  40%                  3  50%
    Read a file we returned                              0  0%                  3  50%
    Read a file we did not return                        0  0%                   0  0%
... (122 lines truncated)
</file>

<file path="docs/benchmarks/answer-directly-vs-explore-agent.md">
# Answer directly vs. delegate to an Explore agent (interactive A/B)

**Question:** Does answering a "how does X work?" question *directly* with CodeGraph in the
main session bloat main-session context — and would Claude Code be better off delegating that
exploration to a disposable **Explore agent** (which keeps main context lean by absorbing the
file reads in a sub-transcript)? And critically: **does the answer change at scale**, on a
codebase far larger than Excalidraw?

**Short answer:** No. With CodeGraph, main-session context is roughly **scale-invariant (~50k)**
because the retrieval is targeted and the `explore` payload is budget-capped — it does not
balloon on a 16× larger repo. Answering directly wins at **every** scale: same-or-leaner main
context than the delegation path, **zero file reads**, and ~28% fewer tokens. The
delegation-for-hygiene advantage stays marginal even on a large codebase.

> **Token figures here are unverified** (flagged 2026-08-05). This run predates the
> `result.usage` fix in `parse-run.mjs` (`04c0f8e`), so its "~28% fewer tokens" was
> likely measured off a field that reports only the last turn — see the gotcha in
> [`call-sequence-analysis.md`](call-sequence-analysis.md). The error under-counts
> whichever arm takes more turns, so if the delegation arm ran longer the real gap is
> *wider* than 28%; if turn counts were similar the figure is roughly right. The raw
> logs are gone, so this cannot be re-derived — treat the token number as indicative
> and the turn/read/context findings, which don't depend on that field, as sound.

## Methodology

- **Harness:** interactive Claude Code TUI driven via `scripts/agent-eval/itrun.sh` (tmux),
  **not** headless `claude -p`. This matters: headless spawns **0** Explore agents, so it cannot
  measure delegation behavior at all; only the interactive TUI does.
- **Arms:** `WITH` = CodeGraph in the MCP config; `WITHOUT` = empty MCP config (`--strict-mcp-config`).
- **Model:** `opus`. **n = 3 runs per arm.** Main **and** sub-agent transcripts parsed
  (`scripts/agent-eval/parse-session.mjs`); reads/bash are summed across main + sub-agents.
- **Repos:** Excalidraw (643 files, medium) and VS Code (~10.7k files, large — ~16× Excalidraw).
- **Build:** 0.9.4. **Date:** 2026-05-24.
- "main-session context" is the TUI's reported `Context X/Y` for the *main* thread (sub-agent
  context does not count against it). "billable tokens" = summed per-turn assistant usage
  (input + output + cache read + cache creation).

## Excalidraw (643 files, medium)

Question: *"How does Excalidraw render and update canvas elements?"*

| metric | WITH codegraph | WITHOUT |
|---|---|---|
| Explore agents spawned | 0 / 0 / 0 | 0 / 1 / 1 (delegated 2 of 3) |
| main-session context | 51k / 49k / 50k (~50k) | 48k / 34k / 26k (~36k) |
| total tool calls | 4 / 4 / 4 | 16 / 55 / 37 |
| Reads (main+sub) | 0 / 0 / 0 | 6 / 25 / 16 |
| billable tokens | ~127k | ~175k |

## VS Code (~10.7k files, large — ~16× Excalidraw)

Question: *"How does the extension host communicate with the main process?"*

| metric | WITH codegraph | WITHOUT |
|---|---|---|
| main-session context | 47k / 43k / 50k (~47k) | 54k / 29k / 31k (~38k) |
| Explore agents | 0 / 0 / 0 | 0 / 1 / 1 (delegated 2/3) |
| codegraph calls | ~8 (search + explore×2–3 + context) | 0 |
| Reads (main+sub) | 0 / 1 / 0 | 6 / 26 / 19 |
| billable tokens | ~126k | ~176k |

## Findings

**Main-session context is scale-invariant with CodeGraph.** With codegraph, main-session
context was **~47k on VS Code — essentially identical to Excalidraw's ~50k**, despite a 16×
bigger repo. It didn't balloon. Reason: codegraph's `explore` payload is **budget-capped** and
retrieval is **targeted** — answering one question pulls in the relevant *flow/area*, not more
just because the repo is huge. So codegraph makes main-session context roughly scale-invariant
(~50k). The delegation-for-hygiene advantage stays marginal even on a large codebase — exactly
the opposite of "it gets significant at scale."

The thing that *would* balloon at scale is reading many big files directly into main — and
Claude Code avoids that **without** codegraph by delegating to an Explore agent (29–31k main),
but at the cost of **17–26 reads** and ~28% more tokens. CodeGraph keeps main lean a *better*
way: a capped, targeted payload — no delegation, **0 reads**.

**On "the Explore agents use codegraph."** I couldn't reproduce it: across **6/6**
with-codegraph runs (both repos), Claude Code **never delegated** — it answered directly every
time. The Explore-agent path only appeared in the `without` arm (using grep/read, since codegraph
wasn't in that config). So with the current instructions + codegraph present, Claude Code stays
in the main session — the lean-main-via-Explore-agent best case simply isn't what happens;
lean-main-via-capped-codegraph is, and it's cheaper.

## Verdict

**"Answer directly with codegraph" wins for Claude Code too — at every scale.** No per-agent
split is needed; the unified "answer directly" instruction is right for Claude Code *and* for
Codex / Cursor / opencode (which have no Explore-agent mechanism and would otherwise read files
directly). This conclusion drove updating the README's `## CodeGraph` example block, which
previously told agents to "NEVER call `codegraph_explore` directly / ALWAYS spawn an Explore
agent" — i.e., it steered Claude Code toward the *worse* (17–26 read, ~28%-more-token) path.

**Caveat / future work (not a blocker):** an Explore agent that *itself uses codegraph* could in
principle get lean-main *and* low-work. But the "answer directly" instruction prevents delegation
in practice (0 delegations observed across 6 runs), the main-context gain would be marginal
(~50k → ~30k, both a few percent of a 1M window), and it adds a sub-agent round-trip. Worth a
future experiment, not a default.
</file>

<file path="docs/benchmarks/call-sequence-analysis.md">
# Call-sequence analysis — why read savings don't convert to wall-clock

**Date:** 2026-05-23 · **Branch:** `architectural-improvements` · **Source data:** the surviving
stream-json logs from the A/B matrix (`/tmp/ab-matrix/<Cell>/run-headless-{with,without}.jsonl`,
37 cells × 2 arms). Re-mined — **no re-runs** — with `scripts/agent-eval/seq-matrix.mjs`.

## Why this exists

The [A/B matrix](codegraph-ab-matrix.md) showed codegraph cuts **reads 75%** but **wall-clock only
~16%**, and 63% of the wall-clock win comes from just 3 large-repo cells. Reads are at the floor
(~0), so the remaining wall-clock is **round-trips + the synthesis turn** — neither of which read
count can explain. The matrix records tool *counts*, not the call **sequence** or per-call
**payload size**. This analysis recovers both, to find where the wall-clock actually goes.

## TL;DR — the bottleneck is trace ADOPTION, not trace completeness

1. **Trace is called in 3 of 37 cells** — even though every question is a canonical flow question
   ("trace the controller → service → repository", "how does X reach Y"). The agent overwhelmingly
   reaches for **`context → search → search → explore`** instead — the exact path-reconstruction
   anti-pattern the instructions tell it to avoid.
2. **`explore` averages 17.9K chars/call; `trace` averages 0.8K** — a **22× payload difference**.
   The path-scoped tool that solves the small-repo-bloat problem exists and is tiny. It's just not
   being invoked.
3. **Small repos still get bloated payloads** because of the explore-default: a **6-file** repo
   (`flutter_module_books`) pulls **17.4K**; a 10-file repo pulls 18.0K. This is precisely the
   "too much context on small codebases" failure mode — happening right now, via explore.
4. **Round-trips are 25% fewer with codegraph (283 vs 375 turns)** but wall-clock is only 16%
   faster — because the with-arm's turns each carry a ~18K explore payload, inflating TTFT and
   eroding the turn savings.
5. **Root cause:** `src/mcp/server-instructions.ts` leads with *"answer directly … `codegraph_context`
   first, then ONE `codegraph_explore`"* as the headline pattern. The trace-first guidance is buried
   in a table + a chain list below it. Agents anchor on the prominent headline → context→explore.

**Decision:** the next experiment is **trace-first steering / adoption**, not enriching trace. We
can't evaluate trace's completeness when it's used 3/37 times. Get adoption up first, then measure
whether the residual `node`/`explore` follow-ups need a richer trace.

## Finding 1 — trace adoption: 3/37

| metric | value |
|---|---|
| flow-question cells | 37 (all of them) |
| cells that called `codegraph_trace` | **3** (`cpp-leveldb`, `excalidraw`, `c-redis`) |
| dominant pattern instead | `context` → `search`×N → `explore` |

The 3 trace cells, and what followed the trace call:

| repo | files | cg sequence | turns (with/without) |
|---|--:|---|---|
| cpp-leveldb | 134 | `trace, node, node` | 5 / 8 |
| excalidraw | 643 | `context, trace, trace, explore` | 6 / **19** |
| c-redis | 884 | `context, trace, explore, node` | 10 / 15 |

Even when trace *is* used, the agent follows it with `node`/`explore` to fetch bodies — so a
secondary lever (after adoption) is making one trace call self-sufficient enough to kill those
follow-ups. But that's step 2.

## Finding 2 — payload size: path-scoped trace (0.8K) vs breadth-scoped explore (17.9K)

Across all cells, per codegraph tool — call count and **average payload per call**:

| tool | calls | avg/call | total |
|---|--:|--:|--:|
| `explore` | 32 | **17.9K** | 573K |
| `context` | 36 | 4.3K | 156K |
| `search` | 39 | 1.3K | 50K |
| `files` | 5 | 3.4K | 17K |
| `node` | 19 | 2.0K | 38K |
| `trace` | 4 | **0.8K** | 3.4K |

`context` (used in 36/37 cells) is the default opener; `explore` is the default closer. Together
they are the ~22K breadth dump. `trace` — the tool that would replace that with the actual path —
is 22× smaller and barely used. This is the user's premise confirmed in numbers: explore is
breadth-scoped (returns the neighborhood), trace is path-scoped (returns the line).

## Finding 3 — payload grows with repo size, and over-returns on small repos

With-arm **total** codegraph payload by repo-size tier:

| tier | cells | avg total payload | range |
|---|--:|--:|--:|
| S (<200 files) | 19 | 12.7K | 3.0–31.2K |
| M (<2000) | 9 | 32.4K | 5.4–58.2K |
| L (≥2000) | 9 | 34.0K | 20.2–43.1K |

The small-repo waste is concrete — these all have a 2–3 file flow but pull a full neighborhood:

| repo | files | with-arm payload | sequence |
|---|--:|--:|---|
| flutter_module_books | 6 | 17.4K | `context, explore` |
| computer-database | 10 | 18.0K | `context, search, status, explore` |
| aspnet-realworld | 78 | 22.2K | `context, explore` |
| django-realworld | 44 | 14.8K | `context, explore` |

`explore`'s per-call budget is already adaptive (#185), but it doesn't help here because the agent
isn't choosing the path-scoped tool — it's choosing breadth.

## Finding 4 — round-trips, and the ToolSearch tax

| metric | with | without |
... (336 lines truncated)
</file>

<file path="docs/benchmarks/codegraph-ab-matrix.md">
# CodeGraph A/B benchmark — with vs without, every language × S/M/L

**Date:** 2026-05-24 · **Branch:** `main` · **codegraph 0.9.4**

A headless agent (Claude Opus, `--permission-mode bypassPermissions`) answers one
**canonical flow question** per repo — twice: **with** the codegraph MCP server, and
**without** any MCP (built-in Read/Grep/Glob/Bash only). Same model, same prompt; codegraph
is the only variable. Each cell was **re-indexed fresh** first (against a `dist/` build of the
current `main` HEAD), so the "with" arm reflects the shipped 0.9.4 resolvers.

## Headline

**Across 37 cells, codegraph cut total file reads from 159 → 38 — 76% fewer.** It never
*increased* reads in any cell (0 regressions). The mechanism: a few sub-millisecond codegraph
calls replace a read-and-grep exploration.

**Cost stays roughly flat — marginally higher on the with-arm here** (summed across the 37
cells: with `$15.4` vs without `$13.8`). On these short single-flow questions the without-arm
resolves in <10 calls and never balloons, so it doesn't reach the regime where codegraph's cost
savings compound, while the with-arm pays fixed MCP overhead (tool definitions in context +
tool-loading) that short tasks don't amortize. The win is **fewer tool calls (189 vs 321, −41%)
+ lower wall-clock** (mean **38s vs 48s**), which is the design target. On harder multi-turn
investigations cost flips to a net saving as the without-arm's accumulated context balloons —
see `docs/benchmarks/call-sequence-analysis.md`.

The gap widens with repo size and flow complexity: on medium/large repos the without-codegraph
arm often **thrashes** — many greps/globs, shell `find`/`grep` (Bash), and occasionally spawning
a **sub-agent** — while the with-codegraph arm answers in 2–8 calls. On tiny repos (a handful of
files) the two arms tie or codegraph is marginally slower (MCP/index overhead doesn't pay off
when the whole flow fits in one or two files) — but reads still drop.

## How to read the table

- **R / G / Gl / B / Ag** = Read / Grep / Glob / Bash / sub-agent (Task) tool calls.
- **cg-calls** = codegraph MCP calls in the "with" arm (the trade for reads/greps).
- **dur** = wall-clock seconds. **files** = indexed file count (the size proxy).
- **reads saved** = without-reads − with-reads.
- One run per arm (a **snapshot** — run-to-run variance is real; treat ±1–2 reads and ±10s as
  noise, look at the pattern across cells). 2-runs/arm headline numbers for several of these flows
  live in `docs/design/dynamic-dispatch-coverage-playbook.md` §7.

## Results

| Language | Size | Repo | files | **with** R/G | cg-calls | dur | **without** R/G | dur | reads saved |
|---|---|---|--:|---|--:|--:|---|--:|--:|
| C | L | `c-redis` | 884 | 0R / 2G | 4 | 42s | 5R / 6G | 51s | 5 |
| C# | S | `aspnet-realworld` | 78 | 0R / 0G | 2 | 27s | 5R / 3G / 2Gl | 54s | 5 |
| C# | M | `aspnet-eshop` | 262 | 0R / 1G | 5 | 39s | 9R / 2G / 5Gl | 58s | 9 |
| C# | L | `aspnet-jellyfin` | 2081 | 3R / 0G | 4 | 51s | 17R / 1G / 2Gl / 17B / 1Ag | 212s | 14 |
| C++ | M | `cpp-leveldb` | 134 | 0R / 0G | 3 | 26s | 4R / 2G | 37s | 4 |
| Dart | S | `flutter_module_books` | 6 | 1R / 0G | 2 | 24s | 2R / 0G / 1Gl | 29s | 1 |
| Dart | M | `compass_app` | 212 | 2R / 0G / 1Gl | 2 | 42s | 3R / 0G / 2Gl | 30s | 1 |
| Go | S | `gin-realworld` | 21 | 0R / 0G | 5 | 35s | 4R / 3G / 1Gl | 57s | 4 |
| Go | M | `gin-vueadmin` | 625 | 1R / 1G | 4 | 47s | 3R / 3G / 1Gl | 44s | 2 |
| Go | L | `gin-gitness` | 4438 | 4R / 3G | 4 | 64s | 8R / 7G / 2Gl | 57s | 4 |
| Java | S | `spring-realworld` | 117 | 2R / 0G | 3 | 35s | 8R / 1G / 5B | 57s | 6 |
| Java | M | `spring-mall` | 536 | 1R / 0G | 5 | 39s | 2R / 4G / 2Gl | 49s | 1 |
| Java | L | `spring-halo` | 2444 | 1R / 2G | 8 | 60s | 4R / 1G / 6B | 52s | 3 |
| Kotlin | S | `kotlin-petclinic` | 43 | 0R / 0G | 2 | 37s | 3R / 0G / 1Gl | 23s | 3 |
| Kotlin | M | `Jetcaster` | 166 | 1R / 0G | 3 | 36s | 1R / 0G / 2Gl | 46s | 0 |
| Lua | S | `lualine.nvim` | 123 | 1R / 1G | 4 | 48s | 4R / 0G / 2Gl | 49s | 3 |
| Lua | M | `telescope.nvim` | 84 | 0R / 0G | 1 | 15s | 1R / 0G / 1Gl | 20s | 1 |
| Luau | S | `Knit` | 11 | 0R / 0G | 2 | 30s | 5R / 0G / 2Gl | 37s | 5 |
| PHP | S | `laravel-realworld` | 114 | 1R / 0G | 6 | 40s | 5R / 1G / 3Gl | 39s | 4 |
| PHP | M | `laravel-firefly` | 2047 | 2R / 1G | 4 | 47s | 4R / 5G / 3Gl | 75s | 2 |
| PHP | L | `laravel-bookstack` | 2160 | 1R / 2G | 2 | 41s | 2R / 4G / 1Gl | 50s | 1 |
| Python | S | `django-realworld` | 44 | 2R / 1G | 2 | 47s | 9R / 0G / 1B | 38s | 7 |
| Python | M | `django-wagtail` | 1672 | 2R / 0G | 4 | 45s | 8R / 3G / 3Gl / 1B | 66s | 6 |
| Python | L | `django-saleor` | 4429 | 2R / 2G | 4 | 52s | 4R / 6G / 1Gl | 64s | 2 |
| Ruby | S | `rails-realworld` | 59 | 0R / 0G | 2 | 30s | 3R / 0G / 2B | 33s | 3 |
| Ruby | M | `rails-spree` | 2905 | 2R / 3G / 1Gl | 5 | 43s | 3R / 3G / 2Gl / 1B | 55s | 1 |
| Ruby | L | `rails-forem` | 4658 | 3R / 1G | 3 | 43s | 4R / 2G / 3Gl | 48s | 1 |
| Rust | S | `rust-axum-realworld` | 13 | 0R / 0G | 2 | 21s | 3R / 0G / 1Gl | 38s | 3 |
| Rust | M | `rust-actix-examples` | 176 | 0R / 1G | 3 | 42s | 3R / 0G / 3B | 36s | 3 |
| Rust | L | `rust-cratesio` | 1053 | 1R / 0G | 3 | 22s | 1R / 2G | 18s | 0 |
| Scala | S | `computer-database` | 10 | 1R / 0G | 2 | 27s | 3R / 0G / 1Gl | 25s | 2 |
| Swift | S | `vapor-template` | 14 | 0R / 0G | 2 | 21s | 2R / 0G / 2Gl | 22s | 2 |
| Swift | M | `vapor-steampress` | 100 | 0R / 0G | 5 | 49s | 3R / 1G / 2Gl | 39s | 3 |
| Swift | L | `vapor-spi` | 542 | 1R / 1G | 4 | 27s | 2R / 5G | 34s | 1 |
| TypeScript/JS | S | `express-realworld` | 39 | 1R / 0G | 1 | 25s | 2R / 2G | 19s | 1 |
| TypeScript/JS | M | `excalidraw` | 643 | 1R / 0G | 3 | 55s | 7R / 5G / 3Gl / 1B | 87s | 6 |
| TypeScript/JS | L | `nest-immich` | 2759 | 1R / 0G | 7 | 50s | 3R / 0G / 1Gl | 44s | 2 |

**Totals (37 cells):** with codegraph **38 reads / 22 greps**, without **159 reads / 72 greps** —
**76% fewer reads, ~69% fewer greps.** Codegraph never increased reads in any cell, and the
without-arm additionally ran **52 globs + 37 shell `find`/`grep` (Bash) + 1 sub-agent** that the
with-arm (**0 Bash, 0 sub-agents**) never needed. (74 agent runs, $29.18 total.)

## Observations

- **Biggest wins are medium/large backends with a real route→handler→service flow:** aspnet-jellyfin
  (3R / 51s vs **17R + 17 Bash + a spawned sub-agent / 212s** — the single most dramatic cell),
  aspnet-eshop (0R vs 9R), django-realworld (2R vs 9R), spring-realworld (2R vs 8R + 5 Bash),
  django-wagtail (2R vs 8R), excalidraw (1R / 55s vs 7R / 87s), Luau Knit (0R vs 5R), aspnet-realworld
  (0R vs 5R), c-redis (0R vs 5R).
- **Without codegraph, large repos make the agent thrash:** it falls back to shell `find`/`grep`
  (37 Bash calls across the matrix) and on jellyfin even spawned a sub-agent — exactly the behavior
  codegraph is meant to prevent. The with-arm answers those in 2–8 codegraph calls and used **0 Bash
  and 0 sub-agents** anywhere.
- **Tie zone = tiny repos** (Kotlin Jetcaster 1R/1R, Rust cratesio 1R/1R, express 1R/2R, Swift template
... (26 lines truncated)
</file>

<file path="docs/benchmarks/explore-allocation-ab-1500.md">
# Agent A/B — score-proportional explore allocation (#1500 / epic CG-1)

Three measurements, in order. **The epic's gate is the last one** ([§CG-22](#cg-22--the-gate-re-run-at-cg-15s-exact-setup)):

| § | Task | Build | Verdict |
|---|---|---|---|
| [CG-15](#method) | first run of the gate | `edce18f` | **FAILS** bars 1 + 4 on express — routed the defect to CG-21 |
| [CG-21](#re-run-after-cg-21--the-gate-passes) | re-run while fixing | `fca7d87` | passes, n=6 on two repos, n=3 on client-go |
| [CG-22](#cg-22--the-gate-re-run-at-cg-15s-exact-setup) | **the gate** | `abee46c` | **PASSES** all four bars, CG-15's exact setup |

---

## CG-15 — the run that failed

**Date:** 2026-08-04 · **New:** `feature/CG-1` @ `edce18f` · **Baseline:** `main` @ `49c11fc`
· **Harness:** `scripts/agent-eval/ab-new-vs-baseline.sh`, `RUNS=3`, `--model sonnet --effort high`
on every arm · **Both arms codegraph-on.**

This is the epic's pass gate. The deterministic probes (CG-6/CG-14) prove the budget moved;
only an agent A/B proves the agent stopped reading.

**Verdict: the gate does not pass.** Bars 2 and 3 hold; **bar 1 (Read stays at 0) and bar 4
(no regression on the control) fail on express**, with a reproducible, non-agent cause. Per
the CG-15 acceptance rule the allocation design goes back to CG-12 — the budget is *not* to be
widened to compensate. Root cause and the smallest honest fix are in [§Root cause](#root-cause).

> **Superseded.** This section is the CG-15 measurement, kept because it is what routed the
> defect to CG-21 and because the root-cause analysis is the record of why. The defect was
> fixed and the A/B re-run twice: [§CG-21](#re-run-after-cg-21--the-gate-passes) alongside the
> fix, and [§CG-22](#cg-22--the-gate-re-run-at-cg-15s-exact-setup) — the epic's gate — at this
> section's exact setup. Nothing below was re-baselined.

---

## Method

`ab-new-vs-baseline.sh` builds and indexes each arm separately (CG-5's generated-file flag is
an index-time decision, so each arm must index with its own build), pre-warms a persistent
daemon per run, and runs the same flow question 3× per arm. Both arms run with
`CODEGRAPH_NO_PROMPT_HOOK=1` — the machine's ambient front-load hook resolves to whatever is
in `dist/` and would inject context through a second, uncontrolled channel.

Each prompt names codegraph as the lookup tool. That is **not** a forced-Read-0: the agent
stays free to Read whenever explore's answer is insufficient, which is exactly what bar 1
measures. It removes the one noise source that would otherwise swamp the signal — in a
pre-run without it, one express run made **0 codegraph calls and 3 Reads**, measuring adoption
(an axis this change does not touch) rather than allocation.

Envelope share is measured with `parse-run.mjs --envelope --answer <glob>`, which parses the
rendered markdown of the responses the agent actually received. The CG-4 diagnostic sidecar
only exists on the new build, so it cannot measure the baseline arm; the markdown parse is the
only instrument that measures both arms the same way.

That `--answer <glob>` is hand-specified ground truth. Every run now also reports the same
intersection inferred from the agent's own final answer, so it needs no per-question setup —
see [`explore-allocation-efficiency.md`](explore-allocation-efficiency.md), which re-scores
the arms below (express: 82% baseline → 100% new).

| Repo | Lang | Files | Generated | Tier | Role |
|---|---|---|---|---|---|
| `kubernetes/client-go` | Go | 2,454 | 2,001 | medium (2 calls / 28K) | **the #1500 shape** — generated CRUD beside hand-written machinery |
| `excalidraw/excalidraw` | TS/React | 672 | 0 | medium (2 calls / 28K) | god-file concentration (`App.tsx`, 450 KB) |
| `expressjs/express` | JS | 147 | 0 | small (1 call / 18K) | **control** |

---

## Results

`explore` = codegraph_explore calls · `Read` = Read tool calls · `answer%` = share of the
source envelope going to the files that answer the question. Three runs per arm, reported as
the range — run-to-run variance is large and a single run means nothing.

### client-go — "how does a shared informer keep its cache in sync and deliver events?"

Answer set `tools/cache/**`; generated set `kubernetes/**`, `listers/**`, `applyconfigurations/**`,
`informers/**`, `**/fake/**`.

| arm | explore | **Read** | duration | answer% | generated% |
|---|---|---|---|---|---|
| **new** | 2 / 2 / 6 | **0 / 0 / 0** | 39–61s (med 50) | 74.2 / 96.9 / 82.6 | 4.0 / 0.0 / 5.2 |
| baseline | 3 / 2 / 3 | 0 / 0 / 0 | 48–52s (med 49) | 78.1 / 97.1 / 71.3 | 10.5 / 0.0 / 5.1 |

No Read in either arm. The medians overlap: on this query `tools/cache/**` already dominates
graph relevance, so the baseline concentrated well without help. The #1500 signal is visible
but small — the generated clientsets and per-resource informers
(`informers/events/v1beta1/interface.go`, `kubernetes/typed/events/v1/fake/…`) take 10.5% of
one baseline run's envelope and **never appear in any new run**.

### excalidraw — "how does updating an element re-render the canvas on screen?"

Answer set: `mutateElement.ts`, `App.tsx`, `renderer/**`, `scene/**`, `components/canvases/**`.

| arm | explore | **Read** | duration | answer% |
|---|---|---|---|---|
| **new** | 2 / 3 / 2 | **0 / 0 / 0** | **23–32s (med 24)** | 74.4 / 67.8 / 84.7 |
| baseline | 3 / 3 / 4 | 0 / 0 / 0 | 33–39s (med 34) | 74.1 / 64.0 / 79.5 |

The clearest win: **29% faster at the median with one fewer explore call per run**, no Read in
either arm. Concentration is why — the new arm resolves the flow in 2 calls where the baseline
takes 3–4. (One baseline run burned a turn on a hallucinated `codegraph_..._explore` tool name;
... (372 lines truncated)
</file>

<file path="docs/benchmarks/explore-allocation-efficiency.md">
# Explore allocation efficiency

> One of three feedback metrics the agent-eval harness reports on every run.
> [`agent-eval-feedback-metrics.md`](agent-eval-feedback-metrics.md) is the entry
> point: which metric answers which question, which harness to run, and how to
> read the arm-comparison table.

**What it measures:** of the bytes a `codegraph_explore` response spent, what
share went to files the agent's answer actually drew on.

```
allocation efficiency = bytes returned for files the final answer cited
                        ───────────────────────────────────────────────
                        all bytes returned
```

That is issue #1500 as a number. The envelope view
([`explore-allocation-ab-1500.md`](explore-allocation-ab-1500.md)) already
showed *how* a response was divided across files, but deciding which of those
files mattered took a human writing `--answer 'lib/response.js'` per question.
This reads the same intersection off the agent's own final answer, so every run
reports it for free.

**Read it as a relative metric.** Attribution is by citation, and an agent can
use a file's source without ever naming it — to rule the file out, or to build a
mental model it then writes up from somewhere else. So this compares two builds
on the *same* question; it is not an absolute claim that 15% of an envelope was
waste. [What it does not say](#what-it-does-not-say) is the full list.

Harness-only, like the other two feedback metrics: nothing is emitted from the
product, nothing leaves the machine. It is parsed out of transcripts we already
write.

---

## Running it

Every run prints it — `run-all.sh` and anything else that calls `parse-run.mjs`:

```bash
node scripts/agent-eval/parse-run.mjs /private/tmp/cg22/ab-express/run-baseline-1.jsonl
```

```
  Explore allocation — share of returned bytes the answer used (2 calls, 4 files):
    efficiency  81.9%  17,465 of 21,319 chars   (3/4 files cited; path-cited alone 64.9%)
    call 1:  84.0%  10,121/12,048 chars  2/3 files
    call 2:  79.2%  7,344/9,271 chars  2/3 files
    *  34.9%   7447  lib/response.js  path
    *  30.0%   6396  lib/utils.js  path
       18.1%   3854  lib/express.js  —
    *  17.0%   3622  lib/application.js  symbol `compileETag`
```

Interactive runs get the same block from `parse-session.mjs <project-dir>`.

**Per call as well as per run.** A run-level number hides the shape that matters
most — call 1 on target, call 3 pure noise. The per-call lines name which call
spent its budget on files nothing came back to.

`--answer <glob>` and `--envelope` still work and are unchanged: they are the
*hand-specified* ground truth, useful when you want to score against the files
you know answer the question rather than the ones the agent happened to name.

---

## How a file is judged used

Two citation channels, ranked so the weaker one stays separable — the summary
line always reports **path-cited alone** next to the combined number.

**1. Path.** The answer names the file: `lib/response.js:126-220`, an absolute
path, or the bare `utils.js:225` agents drop into prose. Bare basenames are
accepted only when the extension is one the envelope actually shipped, which is
what keeps `res.send` and `mime.contentType` — the same token shape — from
reading as file citations.

**2. Symbol.** The answer cites, inside a code span, a symbol that the file's
section header lists as **defined**. This catches answers written almost
entirely in symbol names. It is guarded three ways, all in the direction that
costs us efficiency rather than inflating it:

- **Definitions only.** The header renders `name(kind)` for every node in the
  shipped clusters, and that includes call sites (`mutateElement(calls)` on a
  file that merely calls it). Crediting those marked excalidraw's
  `dragElements.ts` used because the answer named `mutateElement`.
- **A definition beats an import alias.** `var compileETag = require('./utils')`
  is a `variable` node, so a file that only re-binds a name loses to the file
  that defines it, when both are in the envelope.
- **A name on 3+ returned files identifies none of them.** Without this,
  `send` or `get` marks half an envelope used.

Prose mentions do not count — only code spans. A backtick is the agent marking
the token as code, and that is the whole signal.

**A file returned twice is charged twice**, because it occupied the window
twice. Same accounting as the envelope view.

**The answer** is the `result` event's text (one per resumed segment of a
multi-turn session — all of them are answers, so all are pooled). An interactive
... (101 lines truncated)
</file>

<file path="docs/benchmarks/explore-cluster-starvation-cg36.md">
# Deterministic measurement — cluster starvation inside one file (task CG-36)

**Date:** 2026-08-06 · **Baseline:** `feature/CG-24` @ `76ab1fe` (the CG-24 epic tip) ·
**Harness:** `scripts/agent-eval/probe-file-spend.mjs` and `probe-suite-envelope.mjs` over the
deterministic 6-repo corpus at `/tmp/codegraph-corpus`, clean full-rebuilt indexes (CG-33), plus
two hermetic fixtures through `probe-allocation.mjs`. No agent A/B: the claim is which bytes go
to which file, and the agent runs are far too noisy to see a 2K shift.

**Verdict: the defect is real, the diagnosis in the issue was half wrong, and the fix holds.**
All 8 starvation flags across the suite clear; net **+1,012 source chars**. One repo (okhttp)
trades its weakest file for +7,196 chars in the two that answer the question — stated in full
below rather than smoothed over.

---

## The defect

A file's ranked clusters were all-or-nothing past the first one. The top-ranked cluster was
always taken — shrunk to the highest-importance whole symbol ranges that fit when it overran —
and every cluster below it was rendered **whole** and then either fit the remainder or was
dropped entirely. On a file whose top-ranked cluster is trivial, that discards the answer.

What made it invisible: the response stays FULL. The unspent reservation carries forward exactly
as CG-31 designed, so a lower-scoring file takes the bytes and every envelope-share measure still
reads healthy. Measured on the epic tip:

| repo | file | score | reserved | spent | share |
|---|---|---|---|---|---|
| django | `db/models/sql/query.py` | 83 | 7,947 | 1,923 | **24%** |
| django | `contrib/admin/filters.py` | 18 | 2,271 | 8,057 | **355%** |
| okhttp | `.../RealInterceptorChain.kt` | 86 | 6,058 | 1,474 | **24%** |
| okhttp | `.../CallServerInterceptor.kt` | 20 | 1,974 | 5,832 | **295%** |

A score-83 file spends a quarter of its reservation while a score-18 file takes 3.5× its own.

## What the issue got wrong

The issue named two candidate fix points and suspected the first: cluster ranking breaks ties on
**density** (`score / span`) after `hasSpine` → `maxImportance`, which structurally favours a
small trivial cluster over a large answer-bearing one. Dumping the cluster set says otherwise —
in **both** real cases the loser lost on `maxImportance`, not on density:

```
django/db/models/sql/query.py   budget 10,135   spent 1,923
  KEPT    1379–1400   span   22   score  14   maxImp 6   (check_related_objects — a glue symbol)
  DROPPED  306– 929   span  624   score 290   maxImp 3   (133 members: the whole Query class)

okhttp .../RealInterceptorChain.kt   budget 6,058   spent 1,474
  KEPT      16–  44   span   29   score  44   maxImp 6   (package decl + import block)
  DROPPED  113– 373   span  261   score 171   maxImp 3   (73 members: the chain itself)
```

`maxImportance` first is deliberate and protective — it is what stops Alamofire's `Session.swift`
from losing its budget to the top-of-file property list — so **ranking was not touched**. The
lever is the second fix point: stop dropping the loser whole.

## The change

Two sites, one rule — *hold the remainder while it is still worth a section*, which is CG-26's
between-FILES lesson applied between CLUSTERS.

1. **Selection.** A later cluster is now shrunk into what is left of the file's budget, by the
   same whole-member rule the first cluster already used. Below `MIN_CHARS` (700) the remainder
   cannot hold a readable block, so it stays a drop rather than a stutter of fragments the next
   call's dedup has to shred around. The never-empty windowing floors may overrun that room; the
   first cluster is allowed that overshoot, a later one is not.
2. **The ceiling trim.** When the exact section cost overruns `renderCeiling`, the weakest chosen
   cluster is re-rendered into the room that remains before being dropped. This one is worth
   naming on its own: on excalidraw's `typeChecks.ts` the section-cost estimate missed by
   **13 chars** and a 1,512-char cluster — the file's highest-*scoring* one, last in rank order
   only because rank breaks ties on density — was thrown away to pay for it. Recovered 1,501 of
   excalidraw's 1,449-char loss.

## Suite result

`node scripts/agent-eval/probe-file-spend.mjs`, 6 repos, clean rebuilds. Only files whose spend
moved are listed; score is the candidate's ranking score, reserved its allocation.

| repo | file | score | reserved | before | after |
|---|---|---|---|---|---|
| django | `db/models/sql/query.py` | 83 | 7,947 | 1,923 | **10,082** |
| django | `contrib/admin/filters.py` | 18 | 2,271 | 8,057 | 2,198 |
| django | `utils/autoreload.py` | 12 | 1,747 | 3,145 | 1,709 |
| django | `db/models/fields/related_descriptors.py` | 11 | 1,660 | 2,516 | 1,493 |
| excalidraw | `element/src/typeChecks.ts` | 23 | 2,740 | 3,102 | 2,573 |
| excalidraw | `excalidraw/types.ts` | 14 | 1,942 | 819 | 1,372 |
| okhttp | `.../RealInterceptorChain.kt` | 86 | 6,058 | 1,474 | **6,038** |
| okhttp | `.../Interceptor.kt` | 64 | 4,697 | 2,027 | **4,659** |
| okhttp | `.../RealCall.kt` | 52 | 3,972 | 3,628 | 3,922 |
| okhttp | `.../Call.kt` | 54 | 4,097 | 4,097 | 2,073 |
| okhttp | `.../CallServerInterceptor.kt` | 20 | 1,974 | 5,832 | 1,959 |
| okhttp | `androidMain/.../AndroidDns.kt` | 21 | 1,999 | 1,812 | **0** |
| tokio | `task/local.rs` | 40 | 4,361 | 4,599 | 4,798 |
| tokio | `runtime/task/harness.rs` | 14 | 1,981 | 2,565 | 2,341 |
| gin | `routergroup.go` | 87 | 5,782 | 3,273 | **5,632** |
| gin | `tree.go` | 17 | 1,693 | 892 | 1,969 |
| gin | `ginS/gins.go` | 26 | 2,213 | 4,431 | 2,171 |
| alamofire | `Source/Core/Session.swift` | 34 | 2,792 | 2,797 | 3,396 |
| alamofire | `Source/Core/Request.swift` | 148 | 9,100 | 8,865 | 8,453 |

... (65 lines truncated)
</file>

<file path="docs/benchmarks/explore-completeness-note.md">
# The completeness note claims only what was sent

**Date:** 2026-09-28 · **New:** `claude/nostalgic-mccarthy-31c89d` (measured at `024d88b9`, then
rebased onto #2071) · **Baseline:** `main` @ `724b5dee` (#2068) · **Harness:** `scripts/agent-eval/ab-new-vs-baseline.sh`, `--model
sonnet --effort high`, both arms codegraph-on, CLI blocked, `CODEGRAPH_NO_PROMPT_HOOK=1`, every
index rebuilt per arm.

## The defect

On the tiers with `includeCompletenessSignal` (>= 500 indexed files), every `codegraph_explore`
response ended with the same line:

> **Complete source for N files is included above — do NOT re-read them.** … Reserve Read for a
> single specific line range explore can't surface.

It was printed whatever the render had cut. The small tiers switch to a "trimmed for size" note on
`anyFileTrimmed`, but that flag is set at individual trim sites, and before #2068 one of them, the
oversize-spine window, set nothing. That is how a 62-line slice of vscode's 968-line
`rpcProtocol.ts` went out as complete. Even with every site flagged, the large tiers never read the
flag. The last sentence also offered Read, which explore output must never do.

## The change

- **Completeness is measured, not flagged.** Each file section passes the symbols it set out to
  deliver (the cluster members, or the per-symbol view's symbols) to `emitFileSection`.
  `elidedWantedSpans` checks them against the ranges actually sent, plus back-referenced ones. A
  span not fully covered marks the file trimmed. Any path that elides source is caught this way,
  including paths added later.
- **The note says what is true.** When no section was trimmed it is the old line, without the
  Read sentence. Otherwise it keeps the guarantee that still holds and names what was cut:

  > **Verbatim source for 2 files is included above — treat it as already Read.** Trimmed for
  > size: `rpcProtocol.ts`; gap markers and file headers name what was elided (e.g.
  > `RPCProtocol._receiveOneMessage`, `MessageIO.serializeReplyOK`, …). For those, or anything
  > under "Not shown above", make ANOTHER codegraph_explore with those exact names instead of
  > reading the files — it returns their source with line numbers.

  Elided methods are offered as `Owner.member` (django has 110 `as_sql`s). Containers are never
  offered, because a class too big for one section comes back trimmed on a follow-up too.
- **Fitted like the rest of the epilogue (CG-26), in `fitExploreEpilogue`.** The note comes in
  three sizes: with names, with files, and generic. The generic one (≈340 chars) is shorter than
  the line it replaced (401). A complete-source note keeps its old precedence. A trimmed note
  yields to the pointer list, which names files the response does not show at all, while a
  trimmed section already names its elisions in its own gap markers. It leaves the list's header
  and first entry, and its optional detail never costs an entry the generic note would have left.
- **The fallback notes follow.** The lost-pointer note, the epilogue-cut note and the truncation
  note drop "complete" when a section they vouch for was trimmed. Each trimmed variant is no longer
  than the original, so the epilogue floor is unchanged.

## Deterministic replay

39 agent-shaped queries (the vscode and django queries from the named-concentration A/B, the
README questions, and pinned / stress queries), replayed through both builds on one index with a
fresh `ToolHandler` per query.

| | `main` @ `724b5dee` | new |
|---|---|---|
| source sections byte-identical | — | **39 / 39** (only the epilogue changed) |
| responses claiming "Complete source" | 24 | 1 |
| … of which a section was actually trimmed | **23** | 0 |
| responses with the trimmed note | 0 | 16 (1 naming elided symbols) |
| responses with a pointer list | 23 | 33 |
| pointer entries, total | 71 | 102 (no list shorter than baseline) |
| responses offering Read | 24 | 0 |
| responses over the 25K inline cap | 0 | 0 |

The named variant is rare because the fit spends leftover room on pointer entries first. In
saturated responses the names cost an entry, and the gap markers already carry them.

Re-run after rebasing onto `290e03f7` (#2071, same-named file pinning), against that build: source
identical 39 / 39, "Complete source" 23 → 1, trimmed note 16, pointer entries 67 → 93 (none
shorter), Read offered 23 → 0, nothing over the cap.

## Agent A/B

Four questions, three runs per arm, against `724b5dee`.

| question | Read runs (new / base) | Grep/Glob | explore calls (new / base) | duration median (s) |
|---|---|---|---|---|
| vscode: rpcProtocol serialize + dispatch | 0 / 0 | 0 / 0 | 7 / 6 | 45 / 36 |
| vscode: extension host ↔ main process | 0 / 0 | 0 / 0 | 12 / 12 | 61 / 58 |
| django: `SQLCompiler.as_sql` / `pre_sql_setup` / `get_select` | 0 / 0 | 0 / 0 | 6 / 6 | 31 / 32 |
| django: QuerySet → SQL | 0 / 0 | 0 / 0 | 4 / 5 | 22 / 23 |
| **pooled, 12 runs** | **0 / 0** | **0 / 0** | **29 / 29** | 36 / 36 |

The change was exercised. Of the 29 explore responses the new arm's agents received, 20 carried
the trimmed note (4 naming elided methods). The baseline agents received "Complete source … Reserve
Read" on 26 of 29, and on this build all but one of those are false. One pre-explore Bash call in
the new arm happens before any codegraph output and is noise. Load average was 30–95 from other
work on the machine, so durations are indicative only.

### Earlier round, against `e63fe2ec`

Before #2062 / #2063 / #2068 landed, the same four questions (the django pair run twice, 18 runs
per arm) showed Read in 8 new runs vs 7 baseline runs, Grep/Glob 0 / 0, explore 42 / 49. Every
django Read targeted `SQLCompiler.as_sql`, which no build returned for the query shape the agents
wrote (`SQLCompiler.as_sql … compiler.py:776`). Naming the file pinned it and dropped the method:
175 of 228 lines for the bare name, 0 with the path. #2063 fixed that, and on current `main` no run
in either arm reads.

... (33 lines truncated)
</file>

<file path="docs/benchmarks/explore-declaration-only-cg28.md">
# Deterministic measurement — declaration-only files in the explore envelope (task CG-28)

**Date:** 2026-08-06 · **Baseline:** `feature/CG-24` @ `463f6e7` ·
**Harness:** `scripts/agent-eval/probe-decl-only.mjs` against a hermetic fixture
(`__tests__/fixtures/ambient-decls-ts/`, copied to a temp dir and indexed per run, so two runs on
one build give identical numbers), plus `probe-suite-envelope.mjs` and a corpus-wide flag-rate
survey for the regression side. No agent A/B: the claim under test is which FILES get selected and
in what order, and the agent runs are far too noisy to see that.

**Verdict, both halves:**

- **The motivating file is already handled — CG-25 credited.** The Wrangler `worker-configuration.d.ts`
  that opened this issue is demoted by the generated penalty alone, worth 15–46 points of envelope
  share on the four flow queries measured. No new mechanism needed for it.
- **The narrower gap is real and was fixed.** A declaration file with NO banner carried `pen 1.00`,
  took **rank #1 and 51% of delivered source** on a prose flow query, and displaced the flow's own
  entry file out of the response entirely. It is now damped — but only when nothing in the index
  depends on it, which is the condition that makes the rule safe.

---

## The fixture

`__tests__/fixtures/ambient-decls-ts/` — an upload path (route → stream → metadata → queue) with
four declaration-shaped files competing against it for one envelope. All four declare nothing but
`interface`/`type_alias` and have no bodies; they differ only in the two properties under test.

| file | banner | depended on | lines |
|---|---|---|---|
| `types/worker-configuration.d.ts` | Wrangler | no | 271 |
| `types/platform-shims.d.ts` | none | no | 212 |
| `src/storage/types.ts` | none | **yes** (2 imports, 3 references) | 18 |
| implementation (`routes/`, `storage/`, `lib/`) | — | — | 37–71 each |

The declaration files carry the same generic identifiers the prose queries use — `Body`, `Message`,
`ImageMetadata`, `ReadableStream`, `Upload*` — which is the whole mechanism of the original report.

## Result 1 — what CG-25 is worth (the obsolescence leg)

Same fixture, same queries, one variable: `--variant strip-banner` deletes the two banner COMMENT
lines from `worker-configuration.d.ts` and changes nothing else, so the two declaration files become
indistinguishable to the ranker. Delivered share of the envelope for that file:

| query | with banner | banner stripped |
|---|---|---|
| flow-upload | not a candidate | 15.1% (2,271 chars) |
| flow-pipe | not a candidate | 38.5% (4,398 chars) |
| flow-generic | cliffed to a pointer, 0 chars | 35.1% (3,076 chars) |
| flow-queue | 9.4% via clusters (1,264 chars) | **46.1%, rank #1, whole file** (7,390 chars) |

The generated penalty alone is the difference between "rank #1 and nearly half the answer" and
"named in the not-shown list". **The file this issue was filed about needs nothing further.**

## Result 2 — the gap that survived

`platform-shims.d.ts` — hand-written, no banner — on the `feature/CG-24` tip:

| query | rank | score | pen | delivered |
|---|---|---|---|---|
| flow-upload | **#1** | 53.0 | 1.00 | 6,044 chars (**50.7%**) |
| flow-queue | **#1** | 21.0 | 1.00 | 6,044 chars (44.9%) |

On `flow-upload` the response carried three files and `src/routes/upload.ts` — the handler the
question is *about* — was not one of them. That is the CG-24 epic symptom, reproduced with no
generated banner anywhere in it.

Note also: `.pyi` is **not an indexed extension**, so Python stubs never enter the graph and cannot
take an envelope. That third of the issue's premise does not occur today.

## The mechanism, and why it is drawn this tight

`AMBIENT_DECLARATION_RANK_PENALTY` (0.5) multiplies score and graph mass in `rankPenalty`, for files
`QueryBuilder.getAmbientDeclarationPathsAmong` flags. Four conditions, all required — the first
three were the obvious rule, the fourth is the one that makes it safe:

1. declares ≥1 symbol;
2. **every** declared symbol is type-level (`interface`, `type_alias`, `enum`, `enum_member`,
   `namespace`);
3. originates no `calls`/`instantiates` edge;
4. **nothing outside the file points at it.**

Conditions 2 and 4 were both forced by measurement, not taste:

**Why not just "no callables" (condition 2).** Surveyed across the corpus, a rule of "declares no
callable and calls nothing" flags **1.1%–18.0%** of files, and what it catches is real source:
okhttp's `SocketPolicy.kt` (19 declarations, a Kotlin sealed hierarchy), `BrotliInterceptor.kt`,
`tokio/src/runtime/mod.rs`, Alamofire's umbrella `Alamofire.swift`, and all 500+ of django's
`conf/locale/*/formats.py` constant tables. Requiring every symbol to be type-level drops that to
**0%–4%**.

**Why "nothing depends on it" (condition 4).** Without it the rule also flags
`__tests__/fixtures/displacement-ts/src/pipeline/types.ts` — pure interfaces, no bodies, structurally
identical to an ambient shim — and demoting it **broke the CG-31 displacement gate**, which is a
different invariant entirely. That file carries 13 inbound imports and 21 references: the pipeline
stages that answer a query about the pipeline are typed *by* it, so it is part of that answer's
structure. The ambient shims carry **zero** inbound edges — reachable by name, attached to nothing.
That is the real distinction, and the graph already holds it.

**The counter-case guard.** A query that NAMES a declared type is a question about the declaration,
so its file is exempt and ranks at full weight. Only shape-precise tokens count (the same
... (50 lines truncated)
</file>

<file path="docs/benchmarks/explore-dedup-ab-cg20.md">
# Agent A/B — cross-call explore dedup (epic CG-2 / task CG-20)

**Date:** 2026-08-05 · **New:** `feature/CG-2` @ `7a7ea30` (CG-17 session state + CG-18 dedup)
· **Baseline:** `c65d56c` **by SHA** (main's tip when the epic branched) · **Harness:**
`scripts/agent-eval/ab-new-vs-baseline.sh`, `--model sonnet --effort high`, **both arms
codegraph-on**, `CODEGRAPH_NO_PROMPT_HOOK=1` on both.

This is the epic's hard gate. Returning *less* on a repeat call is the exact shape CLAUDE.md
says drives Read fallback and then teaches the agent to abandon codegraph for the rest of the
session, so the gate is about risk first and win second.

**Verdict: bars 1–3 pass cleanly and bar 4 is not met.** Read is **0 in all 24 runs of both
arms**, nothing abandons, and the two failure buckets never fire once. Residual context
occupancy is **flat** — and the measurement below shows it could never have been anything else,
because CG-18's own acceptance requires reclaimed bytes to be **re-spent on files the agent has
not seen** rather than banked. What the change actually moves is the *duplicate fraction* of
that residual: **−87% across the agent runs**, −86%/−94% deterministic.

Recommendation: **keep**, with bar 4 restated. Reasoning and the counter-case in
[§Verdict](#verdict).

---

## Method

Dedup only exists inside one MCP session, so a single-call task cannot exercise it at all. Both
targets were driven with the drill-down question from the CG-1/CG-22 A/B, which reliably
produces a second and third explore whose symbol bags overlap the first:

| Repo | Lang | Files | Tier | Question |
|---|---|---|---|---|
| `kubernetes/client-go` | Go | 2,454 | medium (2 calls / 28K) | "how does a shared informer keep its cache in sync and deliver events?" |
| `excalidraw/excalidraw` | TS/React | 672 | medium (2 calls / 28K) | "how does updating an element re-render the canvas on screen?" |

Each prompt is wrapped `Use codegraph to answer: <question>` — identical on every arm, the CG-22
wrapper. That is **not** a forced-Read-0: fallback stays free, which is exactly what bar 1
measures.

`RUNS=3` per invocation. client-go ran one batch (n=3/arm); excalidraw ran **two** (n=6/arm,
pooled) because it is where dedup bites hardest and therefore where the abandonment risk is
highest — its baseline sequence duplicates ~21% of the source it serves.

### Instruments

Three, because no single one answers the gate:

- **CG-7 residual occupancy** and **CG-8 sufficiency buckets**, from the `feature/CG-3` copy of
  `parse-run.mjs` (that branch is where all three feedback metrics live; this branch's copy
  predates them). Bars 2–4.
- **A duplicate-residual measure**, written for this gate. CG-7's occupancy counts the chars of
  codegraph results resident in the window but **cannot tell a byte the agent already holds from
  one it has never seen** — which is the only distinction dedup makes. This one reads the
  *rendered markdown* of every explore response in a run (so it measures both arms the same way;
  the CG-4 diagnostic sidecar exists only on the new build), reconstructs the `(file, source
  line)` pairs each call put in the window from the `<n>\t<text>` fences, and charges a line
  already delivered by an earlier call as a duplicate byte.

  It is deliberately **not** committed as a new `scripts/agent-eval/*.mjs`: a new file there
  scores into the self-query eval fixture's own corpus and moves its numbers (the CG-15 observer
  effect), and the natural home is `parse-run.mjs` **on `feature/CG-3`** beside the other three
  metrics. Fold it in there; the rule above is the whole specification.

---

## Deterministic core — no agent

Same index, same query sequence (lifted verbatim from a prior new-arm agent run), replayed
through **one** `ToolHandler` + **one** `ExploreSessionState` on each build. Re-measured on both
builds in this session rather than quoted.

### client-go — 3 calls

| | baseline `c65d56c` | new `7a7ea30` |
|---|---|---|
| response chars | 65,218 | **67,289 (+3.2%)** |
| source chars | 46,555 | 47,209 |
| **unique source** | 44,740 | **46,957 (+5.0%)** |
| **duplicate source** | **1,815 (3.9%)** | **252 (0.5%) — −86%** |

### excalidraw — 3 calls

| | baseline `c65d56c` | new `7a7ea30` |
|---|---|---|
| response chars | 72,364 | **68,442 (−5.4%)** |
| source chars | 50,063 | 44,578 |
| **unique source** | 39,575 | **43,973 (+11.1%)** |
| **duplicate source** | **10,488 (20.9%)** | **605 (1.4%) — −94%** |

The two repos bracket the mechanism. Where the baseline barely duplicates (client-go, 3.9%)
there is almost nothing to reclaim, and the reclaimed bytes plus the pointer text make the
response marginally *larger*. Where it duplicates heavily (excalidraw, 20.9%) the response gets
**smaller and denser at the same time** — 5.4% fewer bytes carrying 11.1% more unique source.

**The ceiling on any occupancy win is the baseline's duplicate fraction**, and that is the whole
argument about bar 4: even a design that banked every reclaimed byte instead of re-spending it
could not have removed more than 3.9% / 20.9% of the source in these two sequences.

### Explore latency — the change is not a slowdown

Median of 5 replays of the 3-call sequence, per build (CG-18 adds a truncated SHA256 per served
... (141 lines truncated)
</file>

<file path="docs/benchmarks/explore-displacement-guard-ab-cg31.md">
# Agent A/B — cluster-path displacement guard (task CG-31)

**Date:** 2026-08-06 · **New:** `bugfix/CG-31` · **Baseline:** `bugfix/CG-30` @ `0d014a6` ·
**Harness:** `scripts/agent-eval/ab-new-vs-baseline.sh`, `--model sonnet --effort high`,
**both arms codegraph-on**, CLI blocked (0 contamination in every run),
`CODEGRAPH_NO_PROMPT_HOOK=1`. Every index measured on was **fully rebuilt**, never
incrementally synced (CG-33).

Baseline is the CG-30 tip, not `main`, so every number here isolates CG-31. CG-30's own A/B
against `main` is `explore-oversize-member-ab-cg30.md`; read them in sequence for the combined
picture the two issues asked for.

CG-31 stops a clustered render from spending a reservation still owed to a file the render loop
has not reached. The whole-file BUY arm has always refused that trade (`owedBelow`); the cluster
path read what was left before the hard ceiling instead of what was still promised.

**Verdict: no regression, and this one is a straight win on both halves.** Four of six suite
repos deliver MORE source and one more file each; the other two are byte-identical. The agent
runs are faster in all three repos measured, with Read at or below baseline.

---

## The two corrections the measurement forced

Worth recording, because the first version of the guard was **wrong in the direction the guard
itself is about**, and only a suite measurement showed it.

**1. Holding back the full owed sum was too much.** The allocator splits the envelope; the render
loop spends against a ceiling that also has to hold the response's own prose, so on a saturated
response the promises are over-subscribed and the tail is going to be dropped whatever happens
above it. Bytes held for a file that is then dropped are bytes nobody receives. Measured: django
−2,319 source, tokio −1,298, both handed to a section the ceiling threw away.
`owedPayableBelow` now holds back only the prefix of what is owed below that the response can
still pay, in rank order.

**2. The final truncation was eating the guard's work.** It cut at the last file-section header,
which drops that whole section *and* the trailing notes. Dropping the notes alone is almost
always enough. The epilogue is a pointer list and two reminders; a section is source the agent
otherwise has to Read. Cutting the epilogue first is what turned the remaining deficits into
gains — and it is the same starvation CG-31 is about, arriving one layer below the guard.

A third, smaller fix: `flow.text` is prepended to `lines` to make the final output but was never
counted in `totalChars`, so the render loop spent against a ceiling it was ~2K under on
symbol-bag queries.

## Deterministic measurement — the primary evidence

Same clean-rebuilt index, same query, both builds. One `codegraph_explore` per repo.

| repo | base source | new source | Δ | base files | new files |
|---|---|---|---|---|---|
| django | 20,033 | **20,791** | +758 | 5 (truncated) | **6** |
| excalidraw | 18,776 | **20,204** | +1,428 | 7 (truncated) | **8** |
| okhttp | 15,628 | **19,034** | +3,406 | 4 (truncated) | **5** |
| tokio | 20,340 | **21,521** | +1,181 | 4 (truncated) | **5** |
| gin | 10,776 | 10,776 | 0 | 4 | 4 |
| alamofire | 11,662 | 11,662 | 0 | 2 | 2 |

Queries: django "How does a QuerySet turn into SQL and fetch rows from the database?";
excalidraw "How does updating an element re-render the canvas on screen?"; gin "How does a
registered route handler get invoked for an incoming HTTP request?"; alamofire "How does a
request get built and sent through the session?"; okhttp "How does a call go through the
interceptor chain to the network?"; tokio "How does a spawned task get scheduled and run by a
worker?".

No repo delivers less. **Four of six stopped truncating**, which is where the extra file comes
from: each of those responses had been throwing a fully-rendered section away.

**gin and alamofire are byte-identical between the builds** — nothing in them is oversize enough
for the guard to engage and neither response was truncated. That is what a control should show,
and it means every gin number in the agent table below is run-to-run variance.

**Fixture** — `__tests__/fixtures/displacement-ts`, four pipeline stages competing for one
envelope, the first a single ~20K function. Padded past 500 indexed files on purpose: the
displacement only exists on the 24K tier, where the reservations plus the preamble genuinely
saturate the render ceiling.

| | baseline | new |
|---|---|---|
| `ingest.ts` | 9,301 chars on a 6,289 spendable, then **dropped whole** by the ceiling — 0 delivered | 4,851, bounded |
| `types.ts` / `sink.ts` | skipped `budget-whole-file` | delivered |
| admitted files delivered | **3 of 6** | **6 of 6** |
| envelope | 14,908 | 22,066 |

Pinned by `__tests__/explore-displacement-guard.test.ts` (11 tests; 3 fail on the baseline).

**Allocation fixtures** — `scripts/agent-eval/allocation-fixtures.json` flips back to
**BOTH PASS**. Its `afterCG30` verdict blamed an over-RESERVED incidental file; the reservation
is identical in both arms — the file was over-SPENDING, which is exactly this defect. Recorded
honestly in `afterCG31`.

## Agent runs

| | django new | django base | okhttp new | okhttp base | gin new | gin base |
|---|---|---|---|---|---|---|
| runs | 3 | 3 | 2 | 2 | 2 | 2 |
| duration (s) | **36** [33–51] | 46 [35–49] | **42** [40–44] | 52 [50–53] | **33** [31–35] | 39 |
| tool calls | 3 [3–4] | 3 [3–4] | **4** [3–4] | 5 [4–5] | **4** [3–4] | 5 [4–5] |
| Read | 0 [0–1] | 0 | **0** | 1 [0–2] | 1 [0–1] | 1 [0–2] |
| Grep/Glob | 0 | 0 | 0 | 0 | 0 | 0 |
... (41 lines truncated)
</file>

<file path="docs/benchmarks/explore-factory-closure-cg27.md">
# Deterministic measurement — the factory-closure envelope (task CG-27)

**Date:** 2026-08-06 · **Baseline:** `feature/CG-24` @ `dc4fd75` ·
**Harness:** `scripts/agent-eval/probe-factory-closure.mjs` against a hermetic fixture
(`__tests__/fixtures/factory-closure-ts/`, copied to a temp dir and indexed per run, so two runs
on one build give identical numbers). No agent A/B: the claim under test is which SYMBOLS get
selected inside one file, and the agent runs are far too noisy to see that.

**Verdict: the premise does not survive measurement. CG-27 is closed as obsolete, CG-30 credited.**
The literal change the issue proposes is a large REGRESSION, and a more careful mechanism reaching
the same intent is noise (69 vs 68 inner definitions delivered across nine query shapes).

---

## The claim

`ENVELOPE_KINDS` in `src/mcp/tools.ts` drops a node covering >50% of its file from the cluster
ranges, so the granular symbols inside form their own clusters instead of merging into one blob.
It lists container kinds — `class`, `struct`, `interface`, `enum`, … — and **not `function` or
`method`**. A factory closure (`createFoo()` returning an object of closures) therefore survives
as a file-spanning range. That shape is common, not a one-repo quirk: Svelte 5 `.svelte.ts` rune
stores, React custom-hook modules, IIFE/module-pattern JS, and Zustand's
`create((set, get) => ({ … }))`.

CG-30 already bounds the BYTES such a member may spend, so what remained was a ranking claim:
a file-spanning range merges every inner symbol into one cluster, so selection cannot rank and
pick the relevant closures independently. The issue required that claim be measured before any fix.

## The fixture

`__tests__/fixtures/factory-closure-ts/` — a dashboard app with three stores written as factory
closures, two stateless services and a UI consumer competing for one envelope.

| file | lines | shape |
|---|---|---|
| `src/stores/dashboard-store.ts` | 385 | `createDashboardStore` spans 15–376 (**94%**), 11 closures inside; a tail type alias + helper at file scope |
| `src/stores/alerts-store.ts` | 141 | `createAlertsStore` spans 19–138 (**85%**), 9 closures inside |
| `src/stores/session-store.ts` | 148 | a factory and NOTHING else at file scope — no companion type, no tail helper |
| `src/services/metric-service.ts`, `src/services/filter-parser.ts` | 105, 62 | ordinary top-level functions — the control |

Both factory files are past `WHOLE_FILE_MAX_LINES` where it matters, so they render through the
cluster path and the envelope actually bites.

## Result 1 — the envelope is almost never selected in the first place

`shrinkCluster` orders a cluster's members by **(importance desc, size ASC)** and refuses any
member that overruns the cap once something is kept. A file-spanning member is therefore only ever
selected when it is the FIRST candidate — which requires it to be the *sole* member of the top
importance tier. In eight of the nine query shapes measured, some smaller member shared that tier
(a one-line type alias, a tail helper, another closure), so the factory sorted last and was never
kept. The envelope was inert.

## Result 2 — the proposed change is a large regression

Making the >50% drop kind-independent, measured on the primary query
(*"how does the dashboard store refresh its metrics and apply a filter"*):

| | baseline | drop the range |
|---|---|---|
| `dashboard-store.ts` (rank #1) delivered | 7,539 chars | **397** |
| inner closure definitions delivered | 7 of 11 | **0 of 11** |
| its own reservation left unspent | 0 | ~5,200 of 5,601 |

The mechanism, from the cluster dump: dropping the range **splits** the file into two clusters —
`378-384` (a one-line type alias plus a four-line helper, score 15, span 7) and `4-362` (every
closure, score 116, span 359). Cluster ranking breaks the `maxImportance` tie on **density**, so
the trivial cluster wins, is taken first, and is the only one that may be shrunk. The
answer-bearing cluster then does not fit the remainder and is **dropped whole** — later clusters
are never shrunk, by design.

The enclosing range is what was holding the file together as one cluster, inside which
`shrinkCluster` was already doing exactly the per-symbol ranking the issue asked for.

## Result 3 — the careful version of the same intent is noise

Deferring the envelope MEMBER inside `shrinkCluster` (leaving clustering granularity untouched, so
Result 2's split never happens) reaches the issue's intent by a better mechanism. Nine query
shapes, same fixture, same indexes — inner closure definitions delivered:

| query | target | baseline | deferred |
|---|---|---|---|
| how does the dashboard store refresh its metrics and apply a filter | dashboard | 7/11 | **8/11** |
| createDashboardStore | dashboard | 8/11 | 8/11 |
| how is the dashboard store created and wired up | dashboard | **9/11** | 8/11 |
| createDashboardStore exportCsv summarize | dashboard | 9/11 | 9/11 |
| where is the dashboard store constructed | dashboard | 7/11 | 7/11 |
| how are widgets loaded and the layout reconciled | dashboard | 4/11 | 4/11 |
| createSessionStore (adverse: the factory IS the sole top-tier member) | alerts | 6/9 | **7/9** |
| how are alerts refreshed and acknowledged | alerts | 9/9 | 9/9 |
| createAlertsStore | alerts | 9/9 | 9/9 |
| **total** | | **68** | **69** |

One better, one worse, seven unchanged — on a fixture built specifically to make this pattern
maximally visible. That is not a measurable selection improvement, so nothing shipped.

## Where the envelope DOES get selected, and why CG-30 already covers it

The adverse row above is the one configuration the ordering cannot neutralise: `createAlertsStore`
was the sole importance-10 member, so it was kept first at 3,939 chars against a 2,468 cap and
every closure was skipped. CG-30 then **windowed it on whole lines** rather than emitting it whole
... (34 lines truncated)
</file>

<file path="docs/benchmarks/explore-noise-epic-cg24.md">
# Epic resolution — explore response noise (CG-24)

Worked 2026-08-05 → 2026-08-06. Started from one bad `codegraph_explore` response
in a real session and ended with four shipped fixes, one open defect, and five
issues closed because measurement contradicted them.

**The headline: the reported symptom was not an explore bug.** It was a degraded
index. The explore defects the investigation found are real and were fixed, but
none of them caused the report.

## The report

A prose flow query returned an unusable response: the symbol the agent had named
never rendered, and a 12k-line generated Cloudflare ambient-types file took 60.7%
of the output envelope.

```
#  deliv%   bytes  reserved  score  pen  flags                file
1    1.0%     251    10,970   87.0  1.00 named entry central  <the named file>
2   60.7%  15,043     6,484   49.0  1.00 entry central        worker-configuration.d.ts
4      —        —         —   19.9  1.00 dropped: budget      <a third file>
```

## Root cause

**Index drift ([CG-33](index-drift-cg33.md)).** The live incrementally-synced index
diverged from a clean rebuild by 4.3% of distinct edges, bidirectionally,
overwhelmingly `calls`. RWR graph mass is relative and normalized, so call edges
missing elsewhere inflate an unaffected file's share — the `.d.ts` carried mass
0.24750 drifted vs 0.13119 rebuilt (~1.9×), score 49.0 vs 27.0.

Two causes, both fixed: incremental sync re-resolved only references *in* changed
files, and `getNodesByName` had no `ORDER BY`, so ties broke by rowid — i.e. by
the order files happened to be **written**. The second is why scope alone could
never converge. Stale edges dropped 671 → 2 across an 80-commit replay.

On a freshly rebuilt index the reported query answers correctly **with no explore
change at all**.

## Shipped

| | what |
|---|---|
| **CG-30** | Bounded how far an oversize cluster member may overshoot; windows on whole lines past 1.5× instead of emitting whole — or, when larger than the response ceiling, dropping the file silently. |
| **CG-31** | Gave the cluster path the `owedBelow` displacement guard the whole-file BUY arm always had, holding back only the prefix of what is owed below that the response can actually pay. |
| **CG-26** | Closed the remaining holes: whole-file arms had no displacement guard at all, section overhead was charged at a flat 200 against a real 300–500, and `owedPayableBelow` held all-or-nothing. |
| **CG-25** | Recognize `Generated by <tool> by running <command>` banners. Precision held by requiring two `by` clauses, so ordinary prose does not match. |
| **CG-28** | Damp declaration-only files that nothing in the index depends on. Does not stack with the generated penalty (`Math.min`), and naming a declaration symbol exempts its file. |
| **CG-33 / CG-35** | Incremental sync converges with a rebuild, plus a regression suite that fails when the fix is disabled. |
| **CG-36** | A later cluster is shrunk into the remainder rather than dropped whole — at selection, and again in the ceiling trim. All 8 starvation flags across the suite clear; +1,012 source chars net. `explore-cluster-starvation-cg36.md`. |

Deterministic across the 6-repo suite: no repo truncates, none loses a file,
okhttp gains one, every repo lands at or under the 25,000 hard ceiling.

## Follow-up — CG-38 (closed)

**Agent-named symbols in the tail of a large file never rendered.** On the
motivating repo, `queueMessage` (line 1087) and `flushQueuedMessages` (1102) in a
1,414-line file were absent from the response on both prose and symbol-bag
queries, even when that file won rank #1 with 67% of the envelope. The response
returned the `QueuedMessage` *interface* at line 70 — a fuzzy near-match on the
query token — instead of the function.

**Pre-existing, not caused by this epic.** A controlled bisect (index held fixed,
engine varied across every merge point) shows the pre-epic engine rendering 12
lines here and CG-36 rendering 463; the symbols render at neither. The epic
strictly improves the case. An earlier claim that the epic regressed it was
wrong — it compared runs across two different indexes.

Two independent causes, both longstanding: `buildFlowFromNamedSymbols` discarded
the named-symbol IDENTITY along with the narrative whenever the named symbols did
not form a call chain, so the importance-9 injection never ran; and the ceiling
trim cut in SOURCE order, so a named def at the end of a large file was always the
first thing dropped. Full account, plus the ranker-penalty lead (real, and
orthogonal — the defs are absent at both `generated` flag states on the old build
and present at both on the new one): `explore-tail-render-cg38.md`.

This epic's probes measure envelope share, starvation, source totals and file
counts. **None measured "did the agent-named symbol render"** — which is why this
survived the whole epic. `scripts/agent-eval/probe-named-symbol.mjs`,
`__tests__/fixtures/tail-render-ts` and
`__tests__/explore-named-symbol-render.test.ts` close that gap: per-symbol and
binary, checking the definition LINE against the response's rendered lines.

CG-36's own measurement is worth carrying forward, because the issue named the wrong
fix point: both real cases (`query.py`, `RealInterceptorChain.kt`) lost on
`maxImportance`, **not** on the density tiebreak the issue suspected. Ranking was
left alone; the never-shrink rule was the lever. Full numbers and the one cost
(okhttp trades its rank-6 file for +7,196 chars in the two that answer the
question) in `explore-cluster-starvation-cg36.md`.

## Closed because measurement contradicted them

Five, which is the story of this epic as much as the fixes are.

| | why |
|---|---|
| **CG-32** | Named file "didn't render first." Drift artifact; on a clean index it renders first and takes 89%. |
| **CG-34** | "Allocator over-reserves for low-scoring files." Filed on a runner's diagnosis without checking the numbers. The file was never over-reserved (4,314 in both arms) — it was over-*spending*, which is CG-31. |
| **CG-27** | Adding `function`/`method` to `ENVELOPE_KINDS` measured as a **large regression** — rank #1 fell from 7,539 delivered chars to 397, 7 of 11 inner closures to 0. The enclosing range was holding the file together as one cluster, inside which `shrinkCluster` already did the per-symbol ranking the issue wanted. A careful version was noise (69 vs 68 across nine queries). |
... (25 lines truncated)
</file>

<file path="docs/benchmarks/explore-oversize-member-ab-cg30.md">
# Agent A/B — bounded oversize cluster member (task CG-30)

**Date:** 2026-08-06 · **New:** `bugfix/CG-30` · **Baseline:** `main` @ `d6d1728` ·
**Harness:** `scripts/agent-eval/ab-new-vs-baseline.sh`, `--model sonnet --effort high`,
**both arms codegraph-on**, CLI blocked (0 contamination in every run),
`CODEGRAPH_NO_PROMPT_HOOK=1`.

CG-30 bounds how far a cluster's top member may overshoot what its file may spend: past 1.5x it
is windowed on whole lines instead of emitted whole. The risk the A/B exists to price is the one
CLAUDE.md names — a section that is no longer sufficient sends the agent to Read, and one or two
of those teach it to stop calling codegraph at all.

**Verdict: no regression, and the deterministic win is unambiguous.** The behavioural bar holds
(Read/Grep ~0, no abandonment, allocation efficiency 100% on the repo where the bound engages),
the cost is a ~10% median duration increase on django inside overlapping ranges, and the one
allocation-miss call the new arm produced is matched by two recall-miss calls in the baseline.

> **Harness note, recorded because it cost a re-run:** `ab-new-vs-baseline.sh` checks the engine
> out at the BASELINE ref while its baseline arm runs and restores it on exit. **Do not commit
> while it is running** — a commit made mid-run captures baseline sources. The first django/gin
> batches were void for exactly this reason (their `changed:` line listed only
> `explore-diagnostics.ts`, i.e. both arms ran identical retrieval code) and were re-run. Check
> that line before believing any A/B in this harness.

---

## Deterministic measurement — where the bound actually engages

Same index, same query, both builds. This is the primary evidence; the agent runs below only
price the risk.

**django** — `codegraph explore "How does a QuerySet turn into SQL and fetch rows from the
database?"`

| | baseline | new |
|---|---|---|
| `django/db/models/query.py` | 7,784 chars on a 3,669 budget — **2.12x** | 5,464 — **1.49x**, windowed |
| `django/contrib/admin/filters.py` | 3,633 (inherited 2,271 spendable) | **8,057** (inherited 9,160) |
| source delivered | 17,929 chars, 5 files | **20,033** chars, 5 files |

The reported CG-30 signature, reproduced on a public repo and then closed: the rank-#1 file took
2.12x its budget, and the files below it inherited the shortfall. Bounding it hands those bytes
straight down the rank order — the response carries the same five files and 2,104 more chars of
actual source.

**gin (control)** — the two builds produce **byte-identical** explore output (13,457 chars) for
the route-dispatch query. Nothing in gin is oversize enough for the bound to engage (max
observed 0.94x of spendable), which is exactly what a control should show — and it means every
gin number in the agent table below is run-to-run variance, not the change.

**Fixture** — `__tests__/fixtures/oversize-member-ts`, three report builders competing for one
envelope, each a single long function:

| File | baseline | new |
|---|---|---|
| `monthly.ts` (24.5K, one ~490-line function) | 12,391 chars on a 3,334 budget — **3.7x** | 4,941 — **1.48x**, windowed |
| `quarterly.ts` (11.4K, one ~200-line function) | **dropped** — `budget-clusters`, no headroom left | 4,004 delivered |
| response | 19,223 chars, 3 files | 15,852 chars, 4 files |

The two rows are the same defect from both sides: a member bigger than the file's share eats the
envelope, and a member bigger than the whole response ceiling makes the file vanish. Pinned by
`__tests__/explore-oversize-member.test.ts` (9 tests; 4 fail on `main`).

## Agent runs

| | django new | django base | gin new | gin base | excalidraw new | excalidraw base |
|---|---|---|---|---|---|---|
| runs | 5 | 5 | 3 | 3 | 2 | 2 |
| duration (s) | 39 [36–71] | 35 [35–60] | 39 [37–51] | 34 [28–46] | 52 [43–60] | 41 [40–42] |
| tool calls | 3 [3–10] | 4 [3–23] | 4 [3–4] | 3 | 4 [3–5] | 4 [3–4] |
| codegraph calls | 2 [2–3] | 2 [0–3] | 2 [2–3] | 2 | 3 [2–4] | 3 [2–3] |
| Read | 0 [0–5] | 0 [0–13] | 0 [0–1] | 0 | 0 | 0 |
| Grep/Glob | 0 | 0 | 0 | 0 | 0 | 0 |
| occupancy share | 33.1% [30.7%–49.5%] | 34.4% [29.3%–47.3%] | 28.9% [26.4%–37.3%] | 30.1% [28.6%–31.9%] | 43.0% | 39.3% |
| allocation efficiency | 100.0% | 98.6% | 88.5% | 98.3% | 85.8% | 90.5% |

django is pooled over two batches (n=2 + n=3). Questions: django "How does a QuerySet turn into
SQL and fetch rows from the database? Trace the flow end to end."; gin "How does a registered
route handler get invoked for an incoming HTTP request?…"; excalidraw "How does updating an
element re-render the canvas on screen?…".

**Sufficiency, pooled per call — the bar that matters.** django: new 1 "Read a file we returned"
in 10 answered calls (the allocation-miss signal a window would trip first) against the
baseline's 1 "Read a file we did not return" + 1 Grep in 10 — a shift in miss type, not an
increase. gin: 1 allocation miss in 7 against 0 in 6, on a repo where the two builds emit
identical bytes, so it is variance by construction. excalidraw: 0 misses in either arm.

**Where the new arm looks worse, and why it is not read as a regression:**

- *django duration, ~10% slower median.* Ranges overlap (36–71 vs 35–60) at n=5, and one
  baseline run lost its codegraph attach entirely (0 codegraph calls, 13 Reads, 23 tool calls),
  which distorts that arm's spread in both directions.
- *gin allocation efficiency 88.5% vs 98.3%.* The builds are byte-identical on gin. This is the
  metric's documented relativity — attribution is by citation and the agent's follow-up queries
  differ per run — not an effect of the change.
- *excalidraw occupancy/duration.* Call-count noise: one of the two new-arm runs made a 4th
  explore call where the baseline made 2–3, and duration, envelope and occupancy all follow it.
  Per-call envelope is flat (20,015 vs 19,446 chars/call), Read/Grep stay 0, tool calls match.
  CLAUDE.md's own worked example records 3–10 codegraph calls on this prompt.

... (9 lines truncated)
</file>

<file path="docs/benchmarks/explore-reservation-invariant-ab-cg26.md">
# Agent A/B — the end-to-end reservation invariant (task CG-26)

**Date:** 2026-08-06 · **New:** `bugfix/CG-26` @ `7cbde95` · **Baseline:** `bugfix/CG-31` @ `c54e008` ·
**Harness:** `scripts/agent-eval/ab-new-vs-baseline.sh`, `--model sonnet --effort high`,
**both arms codegraph-on**, CLI blocked (0 contamination in every run),
`CODEGRAPH_NO_PROMPT_HOOK=1`. Every index measured on was **fully rebuilt**, never
incrementally synced (CG-33).

Baseline is the CG-31 tip, not `main`, so every number here isolates CG-26. Read the three
in sequence: `explore-oversize-member-ab-cg30.md` → `explore-displacement-guard-ab-cg31.md` →
this one.

**The invariant:** every admitted file receives at least its reservation before any file draws
on carry-forward slack. CG-30 bounded an oversize cluster member; CG-31 gave the cluster path a
displacement guard. This closes the three holes left over — and each one was starving a file that
had been admitted, reserved, and in the worst case *rendered*.

**Verdict: no behavioural regression on three repos, and the response is honest about its own
budget for the first time.** No repo truncates. No repo loses a file; okhttp gains one. Two repos
trade a few hundred source chars on their LAST-ranked file for the pointer list that names what
the response could not cover — bytes the CG-31 tip only had because it over-filled a ceiling it
mis-measured and then discarded the whole epilogue.

---

## The three holes

**1. The whole-file arms had no displacement guard.** The BUY arm's fit test read
`totalChars + fileContent.length + FILE_OVERHEAD <= renderCeiling` — room before the ceiling,
which belongs to every file the loop has not reached — while its own source-space sibling
(`owedBelow`) refused exactly that trade. GRACE was not fit-tested at all. Measured on okhttp:
`CallServerInterceptor.kt` shipped **8,499 chars against a 5,964 funded ceiling**, and the rank-6
file below it delivered nothing. Both arms now test the render they actually produce against
`fundedHeadroom`, and a whole render that does not fit **falls through to clustering** instead of
skipping the file — a clustered section traded for no section is the trade the funding pool exists
to refuse.

**2. Section overhead was charged at a flat 200 chars.** A real header — path plus up to
`maxSymbolsInFileHeader` symbol names — runs 300–500. Everything downstream is expressed in those
units (`headroom`, `fundedHeadroom`, every fit test), so the under-count was not a rounding error:
it funded promises out of bytes that did not exist. okhttp allocated **26,601 chars against a
24,400 ceiling** and the final truncation threw a fully-rendered section away. Sections are
charged their real cost now; `owedPayableBelow` holds back each pending file's reservation *plus a
per-file overhead estimated from that file's own symbols*; and a marginal overrun **trims the
weakest cluster** — or windows the last one into the room that is left — rather than skipping a
file over a ~300-char accounting difference.

**3. `owedPayableBelow` held all-or-nothing.** CG-31 was right that a promise the ceiling cannot
reach is not a claim on this file's bytes — but it dropped the *partial* case. When the last
admitted file's FULL reservation no longer fit, nothing at all was held for it. On the
precise-query fixture the rank-5 file took 4,134 chars against a 2,948 reservation while rank 6 —
admitted, reserved 2,539 — was left **4 chars** and skipped. It now holds the remainder, while
that remainder is still worth a section (`MIN_CHARS`).

## The epilogue, budgeted instead of discarded

CG-31 handed this forward: the loop reserved a flat **600** chars for an epilogue that measures
1,064 (gin), 1,788 (django), 2,231 (excalidraw), and four of six suite repos survived by
discarding the epilogue **whole** — shipping with no pointer list and no reminders at all. A
margin sweep was run and deliberately not shipped, because tuning one constant against the suite
is the trap CG-30's record warns about.

The fix is not a bigger constant. The epilogue is **two things**:

- a **floor** the render loop reserves, sized from the real strings: the one line that says an
  uncovered area exists and that another explore — not a Read — reaches it, plus a pointer for
  every file whose bytes were deliberately WITHHELD (a cliffed file's bytes were traded away on
  the promise that the agent can still name it — CG-12; if the ceiling eats that name the trade
  was a silent drop);
- an **elastic tail** — the rest of the pointer list and the reminders — fitted, in priority
  order and entry by entry, to the room that is actually left once the loop is done.

So a saturated response now lands with as much of its epilogue as it can pay for, instead of none
of it, and `renderCeiling` is `hardCeiling − floor` rather than `hardCeiling − 600`.

## Deterministic measurement — the primary evidence

Same clean-rebuilt index, same query, both builds. One `codegraph_explore` per repo.
Reproduce with `node scripts/agent-eval/probe-suite-envelope.mjs` (added by this task).

| repo | base source | new source | Δ | base files | new files | ceiling behaviour |
|---|---|---|---|---|---|---|
| django | 20,791 | **20,878** | +87 | 6 | 6 | was discarding its epilogue |
| tokio | 21,521 | **21,607** | +86 | 5 | 5 | was discarding its epilogue |
| okhttp | 19,034 | 18,870 | −164 | 5 | **6** | +1 file delivered; keeps its pointer list |
| excalidraw | 20,204 | 19,652 | −552 | 8 | 8 | keeps its pointer list |
| gin | 10,776 | 10,776 | 0 | 4 | 4 | byte-identical |
| alamofire | 11,662 | 11,662 | 0 | 2 | 2 | byte-identical |

Queries are the CG-30/CG-31 ones, unchanged.

**Read the two negatives honestly.** They are not starvation — they are the reverse. At the CG-31
tip both responses were *over-filled*: the loop under-counted its own section overhead, spent past
the render ceiling, and the hard-ceiling cut then took the epilogue away to pay for it. okhttp
also had a file rendered and dropped. Now the accounting is exact, so the loop stops where it
said it would, and the ~500 chars go to the pointer list naming the files the response could not
cover (2 on excalidraw, both `max-files` skips). No admitted file is starved in either.

**gin and alamofire are byte-identical between the builds** — neither saturates, so neither the
guard nor the epilogue fit engages. That is what a control should show.
... (57 lines truncated)
</file>

<file path="docs/benchmarks/explore-sufficiency.md">
# Explore sufficiency

> One of three feedback metrics the agent-eval harness reports on every run.
> [`agent-eval-feedback-metrics.md`](agent-eval-feedback-metrics.md) is the entry
> point: which metric answers which question, which harness to run, and how to
> read the arm-comparison table.

**What it measures:** whether a `codegraph_explore` response was *enough* — read
off what the agent did next, which the harness was throwing away.

The agent tells us on every call. It reads a file, or it explores again, or it
answers. That next action is free ground truth, and it splits into buckets that
each point at a different fix:

| Next action | Bucket | What it means |
|---|---|---|
| another codegraph call | `explore again` | insufficient — the response did not answer |
| `Read` of a file we **returned** | `Read a file we returned` | **allocation**: right file, wrong bytes |
| `Read` of a file we did **not** return | `Read a file we did not return` | **recall**: the file never surfaced |
| `Grep` / `Glob` | `Grep/Glob` | recall, weaker signal — still hunting |
| `Edit`, a build, the final answer | `moved on / answered` | sufficient |

Harness-only. Nothing is emitted from the product and nothing leaves the machine
(decided 2026-08-03); it is parsed out of transcripts we already write.

---

## Running it

Every run prints it — `run-all.sh` and anything else that calls `parse-run.mjs`:

```bash
scripts/agent-eval/run-all.sh /tmp/codegraph-corpus/express \
  "How does res.send decide the Content-Type and ETag?"

# Or over a log you already have:
node scripts/agent-eval/parse-run.mjs /tmp/agent-eval/run-headless-with.jsonl
```

```
  Explore sufficiency — what the agent did NEXT (2 answered calls):
      1  50%  explore again                  insufficient: did not answer
      1  50%  Read a file we returned        allocation: right file, wrong bytes
      0   0%  Read a file we did not return  recall: file never surfaced
      0   0%  Grep/Glob                      recall (weak): still hunting for the file
      0   0%  moved on / answered            sufficient
    1. "res.send Content-Type ETag generation" [3 files] → codegraph_explore
    2. "response.js res.send function body" [3 files] → Read response.js
```

Interactive runs get the same block from `parse-session.mjs <project-dir>`.

The per-call lines matter as much as the counts: they name the query that fell
short and the file the agent went and read instead, which is usually enough to
reproduce the miss with `probe-explore.mjs`.

---

## The rules that keep it honest

**Only a later message counts as a reaction.** A `Read` fired in the *same*
assistant message as the explore was issued before the response existed, so it
is not a verdict on it. Those are stepped over and counted separately as
`concurrent`.

**Bookkeeping is stepped over.** `ToolSearch` (pulling a deferred tool schema)
and `TodoWrite` say nothing about the response; the call behind them is the
verdict.

**Subagents are a separate thread.** Claude Code interleaves a subagent's tool
calls into the same stream-json output, tagged `parent_tool_use_id` — verified
on a real excalidraw run where a delegated search's greps landed between the
parent's own calls. Reactions are matched within one thread, or a subagent's
first grep gets scored as the parent's verdict on an explore it never saw. In
interactive sessions the subagent lives in its own file instead; each
`agent-*.meta.json` carries the `toolUseId` of the Task that spawned it, and
`parse-session.mjs` stitches the threads back together with it.

**A delegation is judged by what the subagent did first.** `Agent`/`Task` →
first substantive call, shown as `Agent → Bash search`. Scoring the delegation
itself as "moved on" is the one error a tuning metric must not make: on the
excalidraw run below it reported 33% sufficient while the subagent was off
grepping for the file. A delegation that never runs a tool stays "moved on".

**Shell file access counts.** Both arms have Bash, and agents reach for
`sed -n '100,200p' lib/x.js` as readily as for `Read`; `grep`/`rg`/`find`/`ls`
count as search. Counting only the `Read` and `Grep` tools would score those
explores as sufficient. A heredoc or a redirect is writing, not reading.

**Returned means we shipped the source.** A file is "returned" if the response
carried its per-file section (the ``**` `` marker). A file the response only
*named* — a flow step, a blast-radius entry — is still a recall miss, flagged
`(named, not returned)`, because pointing without delivering is its own failure.

**A file an earlier explore shipped still counts as returned.** Re-reading it is
an allocation miss wherever we shipped it; filing that as recall would aim the
fix at the wrong end of the pipeline. The line says which
(`Read utils.js (returned by an earlier explore)`).

**Errored calls are counted, not bucketed.** An explore that came back
... (81 lines truncated)
</file>

<file path="docs/benchmarks/explore-tail-render-cg38.md">
# CG-38 — an agent-named symbol in the tail of a large file never rendered

**Status: fixed.** Two independent causes, both longstanding. Not a CG-24 regression —
the controlled bisect (index held fixed, engine varied across every epic merge point)
found the symptom at every build including pre-epic.

## The report

On a 1,414-line Svelte store, `codegraph_explore` never returned `queueMessage`
(L1087) or `flushQueuedMessages` (L1102) — on a bare symbol bag *or* a prose
question — even though their file won rank #1 with score 127 and 67.3% of the
envelope. What came back instead was the same-stem `QueuedMessage` **interface** at
L70. The agent had to Read the file to find the two functions it had asked for by
name, which is the one outcome explore exists to prevent.

CLAUDE.md's *"guarantee named symbols render"* — the importance-9 named-def
injection — was not holding.

## What it actually was

### 1. The named-symbol IDENTITY was discarded with the narrative

`buildFlowFromNamedSymbols` returns two unrelated things: the Flow prose, and the
SET of node ids the agent named. Downstream, that set is what injects a named def
into its file's cluster ranges and ranks it **importance 9** — the entire mechanism
behind the guarantee.

Its last gate was:

```ts
if (!hasMain && synthLines.length === 0 && !boundaryText && !polyText) return EMPTY;
```

`EMPTY` zeroes `namedNodeIds` too. So whenever the named symbols happened not to
produce anything to *print*, the guarantee silently switched off. Two sibling
closures in one factory are exactly that case: `queueMessage` and
`flushQueuedMessages` never call each other, so there is no chain, no synthesized
hop and no dispatch boundary — and both defs lost importance 9. The file then
rendered from its head, which is how a 6-line interface displaced two functions
1,000 lines below it.

Measured: `flow.namedNodeIds` was **empty** on the reported query, while
`findAllSymbols` resolved both tokens to exactly 1 node each.

The fix separates the two outputs (`identityOnly()`), restricted to **shape-precise
tokens** (camelCase / PascalCase / snake_case / qualified — the same test the gather
path uses). With a narrative present, the prose is itself corroboration and that path
is unchanged; with nothing corroborating it, only an unambiguous symbol reference may
promote, so an English word in a prose question that happens to exact-match a
callable cannot earn importance 9.

### 2. The ceiling trim cut in SOURCE ORDER

Restoring importance 9 was not enough — the symbols still did not render.

`shrinkCluster` *had* kept them: on the reported query it emitted a block spanning
`1022-1121`, which covers both. But the shrink's output measured **26,297 chars
against a 16,532 cap**, so `windowToCeiling` fired, and it fills parts in source
order and drops everything after the first overrun:

```
shrunk:   101-107, 197-226, ..., 648-989, 1022-1121      (26,297)
windowed: 101-107, 197-226, ..., 648-839                 (16,532)   ← tail gone
```

A trim that cuts in source order will always take the END of a large file first —
which is precisely where an agent-named symbol is most likely to be, and least
likely to be reachable any other way. `windowToCeiling` already had the concept it
needed (`focusLine`, for the spine's next-hop call site, CG-30); it just wasn't told
about named defs. It now takes a `focusLines` list — spine call site plus every
member at importance ≥ 9, capped at 6 — and:

- tries the **full-ceiling** fill FIRST, holding back 40% only when a focus line is
  actually left uncovered (so a cluster whose head already reaches its focus keeps
  the whole ceiling for source — an improvement on the old unconditional hold-back);
- **splits** the reserve evenly between the uncovered focus lines with carry-forward,
  rather than handing it out greedily in source order. Greedy reproduced the bug one
  level down: on the prose query, four focus lines resolved and the two earliest took
  the entire reserve, dropping `flushQueuedMessages` again.

## The accounting gap — found, measured, deliberately NOT shipped

`shrinkCluster`'s fit test uses the raw source span
(`slice().join('\n').length`) while the render adds `contextPadding` around every
block and a line-number prefix to every line. On the reported file that estimate ran
**~60% under** (16.5K accounted, 26.3K rendered).

An exact projection (prefix-summed line costs, mirroring the merge + padding
`buildSection` performs) was built and measured. **It is worse, and it is not
shipped:**

| | main | exact accounting | exact + spend-the-remainder |
|---|---|---|---|
| django | 20,719 | 20,747 | 20,747 |
| excalidraw | 19,704 | **19,606** | **19,606** |
| okhttp | 18,651 | 18,766 | 18,766 |
| tokio | 21,582 | **21,424** | 21,555 |
| gin | 11,952 | 12,082 | 12,082 |
| alamofire | 11,849 | 11,849 | 11,849 |
| `probe-allocation` | 4 PASS | **payroll-go FAIL** | **payroll-go FAIL** |
... (86 lines truncated)
</file>

<file path="docs/benchmarks/index-drift-cg33.md">
# Index drift: incremental sync vs. full rebuild (CG-33)

Measured 2026-08-06. A live, auto-sync-maintained index **does not converge** to
a clean full rebuild of the identical working tree. On codegraph's own repo,
**4.3% of distinct edges were wrong**, in both directions, overwhelmingly
`calls` edges.

This matters because it is silent: nothing warns, nothing surfaces it, and the
README tells users the index is never stale and there is nothing to re-run.
Retrieval quality decays invisibly, and the user-visible symptom — an agent
falling back to Read — reads as "codegraph isn't very good" rather than "this
index needs rebuilding."

## Result

Subject: codegraph's own `.codegraph/codegraph.db`, long-lived and
incrementally synced, against a full rebuild of the same tree with the same
build. Edges compared as distinct `(source, target, kind)` triples.

| | count |
|---|---|
| distinct edge triples (rebuild) | 28,809 |
| in rebuild but **missing** from live | **751** |
| in live but **absent** from rebuild (stale) | **476** |
| **total divergent** | **1,227 — 4.3%** |

Missing edges by kind: `calls=635`, `contains=38`, `references=34`,
`instantiates=21`, `imports=13`, `extends=10`.

### Raw counts hide it

Raw edge **rows** were 39,845 live vs 40,122 rebuilt — a benign-looking +0.7%.
The divergence is bidirectional, so a net-count check nets it out and reports
almost nothing wrong. **Any drift detector must compare edge sets, not totals.**

### The indexer is deterministic

Control, rebuild vs rebuild on the same tree and build: **0 differing edges**
(28,809 both runs). So the live-vs-rebuild delta is not run-to-run noise.

### It is resolution, not residue

Node sets are identical — `files` 501 = 501, `nodes` 10,110 = 10,110,
heuristic edges 36 = 36 — and every integrity check is 0 on *both* indexes:
no duplicate nodes, no orphan edges, no nodes referencing a missing file row.

Nothing accumulates. Cross-file **resolution** goes stale.

## Mechanism — two causes, both confirmed

`ReferenceResolver` binds a reference to one of the same-named definitions
**project-wide**. Two things follow, and the drift needed both to be fixed.

**1. Scope.** Incremental sync re-resolves only the references *in* the changed
files. Adding or removing a definition of `pct` changes the correct answer for
every `pct(...)` reference in the repo, including references in files the sync
never touches — and those references resolved successfully once, which *deletes*
their `unresolved_refs` row, so nothing existed to revisit them with. (The #1240
retry only revisits refs parked as `status='failed'`.) The index kept an answer
that was correct against an older graph.

**2. Tie-break.** When nothing disambiguated the candidates, `findBestMatch`
kept the first one, and `getNodesByName` had no `ORDER BY` — so the winner was
decided by rowid, i.e. by the order files happened to be **written**. A full
index writes in scan order; a sync appends each file as it changes. The same
tree therefore resolved to different edges depending on how the index was built,
and no amount of re-resolution could converge, because re-resolving against the
identical graph still picked a different candidate.

### The fix

- `getNodesByName` orders by `(file_path, start_line)` — a property of the code,
  not of the write order (`src/db/queries.ts`).
- `sync` returns a `definitionDelta`: the names whose set of definitions the sync
  changed, computed as the symmetric difference of `file\0name` pairs sampled
  before and after the store phase (`ExtractionOrchestrator.sync`).
- For each delta name, `resurrectStaleResolutionEdges` deletes the resolution
  edges targeting a symbol of that name whose source is in an *unchanged* file,
  and re-inserts each as the reference that created it (the `metadata.refName`
  stamp). The existing orphan sweep then resolves them against the post-sync
  graph — the same input a rebuild resolves from. Kill switch:
  `CODEGRAPH_NO_REBIND=1`.

The delta is compared **per file**, not as one name set over the whole batch: a
commit that adds `collect` to a new file while an unrelated changed file already
defines `collect` cancels out of a batch-wide name set, and that miss was the
largest residual class in the first measurement of this fix.

Conservative by construction, because a wrong deletion is a permanent edge loss
while a missed rebind is only residual drift: an edge with no `refName` stamp
(synthesized, or built by an older engine) is never touched, edges whose source
file the sync already re-extracted are skipped, and a per-name ceiling of 500
edges declines the generic names.

### Result

Replaying real commits of this repo through `sync` one at a time, then diffing
against a clean rebuild of the final tree:

| replay | baseline (`main`) | + ORDER BY only | + rebind pass (shipped) |
... (90 lines truncated)
</file>

<file path="docs/benchmarks/regression-audit-2026-09.md">
# Release-to-main correctness repairs (September 2026)

Compared the installed `@colbymchenry/codegraph@1.6.0` npm bundle (release
`dfccdf62547fcd76d343344d823a0e1998d3a89f`) with main
`3ed73bc127323e63153bf6ec8354afa82ce36aaf`. Both ran with the bundle's Node
24.16.0 on Linux x64, identical fixture revisions/settings and separate
indexes. Native and forced-WASM probes were kept separate. Main was fetched
again before this change; the comparison base had not advanced.

## Confirmed losses and repairs

| Loss | Introducing change | Repair |
|---|---|---|
| Typed TSX-to-TS field calls, including Excalidraw's observer registration and mutation-to-render flow | `cece072` (#1792) | Use the same JS/TS language family in cached and uncached method lookup. |
| Destructured Zustand actions lose their callers | `cd4e65b` (#1759) | Trace the actual state binding before rejecting locally bound names. |
| Adding interface signatures makes store accessor calls ambiguous | `ee83636` (#1780) | Find the implementation inside the identified store, not a globally unique name. |
| Direct React Native bridge calls disappear | `de5adba` (#1790) | Retain qualified call sites and let the framework validate the module. |
| Dart extension-type getters disappear in WASM | `ee83636` (#1780) | Apply the bodyless-signature guard only to its intended JS/TS grammars. |

Each introducing commit was checked against its parent with the same minimal
fixture. The lost relationships were checked against source wiring rather
than inferred from edge-count differences. The Excalidraw path is
`Scene.mutateElement → Scene.triggerUpdate → App.triggerRender → App.render
→ StaticCanvas → renderStaticScene`.

## Remaining suite failures

The nine failing Steps assertions had two causes: external member-chain call
sites had been discarded before effect classification, and valid Zustand
selector bindings were blocked as opaque local calls. Qualified external
references now survive without becoming guessed internal call edges. Store
selectors require a Zustand factory import, resolve the selected member in
that store, and respect lexical scope and shadowing. Renamed selections and
closure captures are covered, including negative cases for unrelated
factories, stores, parameters, and local declarations.

The tenth failure was a stale callers-truncation fixture: it counted a filename
as an overload of its exact-named function. The fixture now contains two real
functions and checks that **both** truncated sections carry their markers.
The extraction parity expectations now assert the exact retained qualified
references and all argument calls. No assertion was removed or replaced by a
skip.

## Validation

- All ten formerly failing assertions pass on native and forced WASM.
- The final forced-WASM run passes 148 tests across eleven affected suites.
- Native resolver, framework, graph, context, sync-convergence, and explore
  budget checks pass. The final expanded guard/parity run passes 94 tests.
- All 655 extraction tests pass in seven sequential fresh-process batches;
  the union of passing test names is checked against all 655 original cases.
- Native/WASM TS/JS parity passes for the torture fixtures, CRLF forms, real
  source files, and optional/ordinary member chains. Dart parity also passes.
- The C deep-brace guard, shallow-file checks, worker checks, and built CLI
  stress checks pass. The two all-language 60,000-level cases remain outside
  the completed stress result, as explained below.

The original fresh-index corpus checks cover Express, Gin, Django and
Excalidraw. Source-grounded paths pass 11/12 on release, 9/12 on original main,
and 11/12 after repair. The remaining Django compiler path is absent in both
original versions. Original integrity, foreign-key and orphan checks pass on
all 44 retained corpus indexes; no-op sync preserves all fingerprinted edge
sets. Existing Gin and Django edit/restore drift is not repaired by this
change.

## Runtime limitations

The monolithic extraction suite's worker receives `SIGKILL` as its resident
memory grows to roughly 1.6–1.7 GB; sampled JS heap use is only 70–95 MB. Dense
C++ fixtures and subsequent indexing setup produce substantial native memory
growth. Lowering the JS heap or worker count does not resolve it. Fresh
batches keep peak child RSS below approximately 0.8 GB and run every assertion
successfully. This distinguishes the resource/lifetime sensitivity from the
ten reproducible assertion failures, but does not identify the exact native
allocation-retention cause.

Standalone Scala expressions nested 60,000 levels did not finish within a
45-second diagnostic budget in either native or WASM; equally deep block
expressions did not avoid the parser limitation. The existing stress tests
are unchanged. There is no claim of a full green monolithic suite or a repair
of this extreme-input parsing limit.

These checks do not cover other operating systems, a long-running watcher,
MCP transport latency, or the paid agent A/B harness. Shared-host timing was
noisy, particularly for Excalidraw, and is not used to claim a performance win.

## Independent-review follow-up (September 14–15, 2026)

The user-supplied Claude review of this PR reported 4,636 passing / 3 failing
tests, compared with 4,600 / 18 before the repairs, and confirmed the five
correctness fixes. Those full-suite figures are independent review evidence;
this follow-up did not repeat the completed full audit.

The two `CLAUDE_CONFIG_DIR` failures were path-alias mismatches. The test
fixtures now canonicalize their temporary home and working directories with
`realpathSync`, matching `chdir`'s behavior on macOS `/var` → `/private/var`.
The exact path, file content and idempotency assertions remain in place.
Both failures were reproduced on Linux using a symlinked `TMPDIR` before the
change; all seven override cases pass afterward. macOS was unavailable, so
this is a reproduced path-alias fix, not a claim of a macOS test run.
... (349 lines truncated)
</file>

<file path="docs/benchmarks/residual-context-occupancy.md">
# Residual context occupancy

> One of three feedback metrics the agent-eval harness reports on every run.
> [`agent-eval-feedback-metrics.md`](agent-eval-feedback-metrics.md) is the entry
> point: which metric answers which question, which harness to run, and how to
> read the arm-comparison table.

**What it measures:** how many tokens of the context window a tool's responses
still occupy once the question has been answered — and therefore how much
headroom every following turn has to work in.

This is the metric issue [#1500](https://github.com/colbymchenry/codegraph/issues/1500)
was actually about. The reporter was looking at a live Cursor session: explore's
output was still resident after the answer, so it was charged against everything
that came next. Our A/B harness ran one headless question to completion and
reported cost, tokens, time, and tool calls — none of which can see that. A
single-question run reports *throughput*; occupancy is a *stock*, and it only
starts costing anything on the turns that follow.

The harness now measures it, over multi-turn sessions.

---

## Running it

```bash
# One repo, one three-turn session, both arms:
scripts/agent-eval/run-all.sh /tmp/codegraph-corpus/gin \
  "How does gin route requests through its middleware chain?||\
Where is the 404 / no-route case handled in that same chain?||\
What would I change to add a per-route middleware that runs before the global ones?"

# The 7 README repos (default: 3 turns per session, RUNS=4 per arm):
CORPUS=/tmp/codegraph-corpus RUNS=2 scripts/agent-eval/bench-readme.sh
node scripts/agent-eval/parse-bench-readme.mjs /tmp/ab-readme
```

`||` separates turns. Turn 1 runs normally; each later turn `--resume`s the same
session, so the earlier turns' tool output is still in the window — which is the
entire point. Segments land in `run-<label>.jsonl`, `run-<label>.t2.jsonl`, …
and `parse-run.mjs` stitches them back into one session (`--resume` does not
replay prior messages, so they concatenate cleanly).

`CG_TURNS=1` restores the original single-question A/B. `CG_WINDOW_TOKENS`
overrides the 200k nominal window for the share-of-window column.

Every arm prints:

```
Residual context occupancy at end of run:
  final context       54,950 tok   27.5% of 200k window
  codegraph           13,941 tok   25.4% of ctx    7.0% of 200k win   (31,312 chars, 2 results)
  Read                     0 tok    0.0% of ctx    0.0% of 200k win   (0 chars, 0 results)
  Grep/Glob                0 tok    0.0% of ctx    0.0% of 200k win   (0 chars, 0 results)
  Bash                     0 tok    0.0% of ctx    0.0% of 200k win   (0 chars, 0 results)
  → file-access            0 tok    0.0% of ctx    0.0% of 200k win   (0 chars, 0 results)
  other tools             33 tok    0.1% of ctx    0.0% of 200k win   (73 chars, 1 result)
  base (prompt+prose)  40,976 tok   74.6% of ctx   20.5% of 200k win
    of which fixed    37,726 tok  system + tool schemas + question, before any tool answered
  measure: 2.25 chars/tok measured ±0.9% · turns 6 · compactions 0
```

The comparison is codegraph's residual in the with-arm against **file-access**
(Read + Grep/Glob + Bash) in the without-arm — the two ways an agent gets the
same bytes into its head. Bash matters: on small repos the without-arm often
reaches for `cat`/`grep` through Bash rather than the Read tool, and counting
only Read would score those runs as reading nothing.

---

## How the tokens are measured

**Measured, not estimated.** For each assistant request,

```
ctx_k = usage.input_tokens + cache_read_input_tokens + cache_creation_input_tokens
```

is the exact token count of that request's entire prompt. So `ctx_k − ctx_{k−1}`
is exactly what was appended since the previous request: the previous assistant
output plus the tool results and user text that followed it. Each gap's measured
delta is priced against the characters in it.

The ratio is calibrated on gaps that are **≥80% tool result by characters**, then
every result is priced at that ratio. Calibrating on *all* gaps was wrong: when
the assistant's own output is under-represented in the transcript — redacted or
empty thinking blocks are the common case — a proportional split hands the tool
result the whole delta. One 73-character `ToolSearch` result was charged the
entire 830-token gap, 5.5 tokens per character.

Getting this right matters more than it sounds. Explore output measures around
**2.2–2.3 chars/token** — it is dense, line-numbered source. The usual bytes/4
rule of thumb would under-count it by roughly 40%.

**Error bar.** On a gap that is ≥95% one tool result, the measured delta *is*
that result's token count, so the distance from the run-level ratio is the
attribution error for that result. The median over such gaps is printed after
the ratio: **±1–2%** on real runs.

### Residual is not the same as contributed
... (325 lines truncated)
</file>

<file path="docs/design/adaptive-explore-sizing.md">
# Design + status: adaptive `codegraph_explore` sizing (sibling skeletonization)

**Status:** Implemented & validated, **default-on**, on branch
`feat/adaptive-explore-sizing` (initial commit `d6d059f`; **refined 2026-05-29**
after a real-agent A/B exposed a read-back regression — see
"Refinement" below). Escape hatch: `CODEGRAPH_ADAPTIVE_EXPLORE=0`.
**Motivation:** make `codegraph_explore` size its output to the *answer* rather
than always filling the budget cap — so a "sibling-heavy" flow (many
interchangeable implementations of one interface) stops costing *more* than
plain grep/read, without starving "diffuse" flows that genuinely need broad
source.

> **Refinement (2026-05-29) — the read-back regression.** The first cut gated
> only on *off-spine + polymorphic-sibling*. A real-agent A/B (not the
> deterministic probe) showed that this skeletonized two files the agent then
> **Read back**, defeating the point: OkHttp's `RealCall` (it implements the
> 9-impl `Lockable` *mixin*, so it tripped the sibling signal even though it's
> the orchestrator) and Django's `compiler.py` (it *defines* `SQLCompiler` and
> co-locates its subclasses). Two conditions fixed it — a file skeletonizes only
> if it is **not spared**, where **spared = the agent NAMED a callable in it**
> (`getResponseWithInterceptorChain`, `SQLCompiler.execute_sql` → keep it full)
> **UNLESS the file DEFINES a ≥3-impl supertype** (a base+subclasses "family"
> file is huge and Read-anyway, so skeletonizing it *frees explore budget* for
> the sibling files the agent would otherwise Read). Result: OkHttp **3%
> costlier → ~10% cheaper** (RealCall full, 0 read-backs); Django **10% costlier
> → ~10% cheaper** (compiler.py skeleton frees ~6.5 KB of the 28 KB budget; half
> the runs answer with 0 reads). The supertype signal was initially used as a
> *spare* — that was backwards and regressed Django to 9% costlier by starving
> its budget; it is now an *override* of the named-callable spare. The
> single-condition history below is kept for context.

> **Further refinement (2026-05-29) — per-symbol focused view + named-cluster
> survival.** Whole-file skeleton/spare was still too coarse on a real Django
> A/B: the agent Read back `compiler.py` (collapsed → its `execute_sql`/`as_sql`
> bodies elided) and `query.py` (a non-sibling god-file whose `_fetch_all` cluster
> got trimmed). Four changes took both repos from ~9–10% to **~14–17% cheaper**
> with **median 0 reads**:
> 1. **Uniqueness-aware spare** — only a (near-)UNIQUE named callable spares a
>    file. `as_sql` has **110 defs** across every Compiler/Expression subclass;
>    naming it must not keep every backend variant full (it was flooding Django's
>    budget). `getResponseWithInterceptorChain` (1 def) still spares RealCall.
> 2. **Per-symbol focused view** — a collapsed family file shows the **full body**
>    of on-spine / unique-named / canonical-base-supertype methods and only
>    **signatures** for the rest. So `SQLCompiler.execute_sql`/`as_sql` survive
>    while the 80 other symbols + redundant subclasses collapse → no Read-back.
> 3. **Test-file exclusion on all tiers** — a test file (`custom_lookups/tests.py`)
>    was eating 2.3 KB of Django's 28 KB budget; tests rarely answer an
>    architecture question. (Previously only the <500-file tiers excluded them.)
> 4. **Named-cluster survival in non-sibling files** — inject agent-named method
>    defs into a file's clusters even when the gather missed them, rank them at
>    importance 9, and cap cluster selection at `min(per-file, remaining-total)`
>    so high-importance named clusters survive instead of being source-order
>    trimmed (Django's `_fetch_all`, L2237, the last of four big files emitted).
> Controls held: OkHttp 14% cheaper / 0 RealCall read-backs; Excalidraw 31%
> cheaper / 0 reads (god-file clustering unaffected — its big file is emitted
> first, so the budget cap never binds it). OkHttp's interceptors stay a pure
> signature skeleton (no named callable in them, don't define a supertype).

> **Refinement (2026-09-28) — exact targets.** The per-symbol view above still
> lost the one method the agent asked for by its qualified name. On a fresh django
> index `SQLCompiler.as_sql pre_sql_setup get_select` returned `get_select` and
> `pre_sql_setup` in full and `SQLCompiler.as_sql` — step 1 of the rendered Flow,
> 226 lines — as its signature line, on main and on every branch since. Bodies
> were chosen in SOURCE order within a tier, so the unnamed bridge
> `get_qualify_sql` and `get_select` (both above `as_sql` in the file) took the
> cap. The agents' follow-ups (`SQLCompiler.as_sql full body compiler.py:776`,
> `compiler.py lines 900-1003 as_sql tail`) pinned the file but dropped the line
> numbers, returning `SQLInsertCompiler.as_sql` and friends instead; every run
> Read compiler.py. The fix:
> 1. **Exact targets** — a qualified name that resolves to ≤3 callables
>    (`SQLCompiler.as_sql`: 1 of 110), or the callable enclosing a line anchor
>    (`compiler.py:776`). A bare `as_sql` is NOT exact, so the family rules above
>    still keep the 110 overrides as signatures.
> 2. **Tiers in the focused view:** exact → spine step the agent named → unnamed
>    spine bridge → uniquely-named off-spine → family co-named; the spine in CALL
>    order within its tier.
> 3. **Window, never signature, for tiers 0–1.** A body too big for what is left
>    is cut to its head plus the lines where it calls the question's other
>    symbols, and each hole names the explore query that returns it
>    (`codegraph_explore \`compiler.py:871-1001\``).
> 4. **Line anchors** (`query-paths.ts`): `file:line`, `file:a-b`, `#La-Lb`, and
>    prose `lines a-b` / `L a-L b` next to a path. A range renders as exactly that
>    span (cluster path, ranked first).
> 5. **Priced in rendered chars.** The view counted raw source while it rendered
>    line numbers and ~20 signature lines; once windows fill the cap the
>    undercount became a 19% overshoot that zeroed four excalidraw files below it.
>
> Deterministic replay (54 queries × 8 repos): 43 byte-identical; `as_sql`
> complete in all 5 distinct django queries that single it out (was 1, 0, 175,
> 0 and 226 of 226 lines), the `lines 900-1003` span 104/104 (was 1); named-body
> lines 8,706 → 9,443. The trade: where the file's budget cannot hold everything, a large named
> step now wins over several small off-spine bodies (`pb-compiler`: `as_sql` whole,
> `execute_sql`/`results_iter` to signatures).
>
> Agent A/B (`ab-new-vs-baseline.sh`, django, README question pair, Sonnet /
> `--effort high`, RUNS=3, baseline `e63fe2ec`): **Read 0 in 3/3 new runs vs a
> Read of compiler.py in 2/3 baseline runs** — each right after the agent's own
> `SQLCompiler.as_sql … compiler.py:776` explore, the exact follow-up the report
> described. Tool calls 3 → 4 median, retrieval residual 19.5K vs 22.9K tokens,
> median cost $0.195 vs $0.229 and 30s vs 35s (n=3, the last two within noise).
... (244 lines truncated)
</file>

<file path="docs/design/agent-codegraph-adoption.md">
# Getting agents to actually use codegraph (not Read) — design notes & handoff

> Working doc for a fresh session. Two problems to crack:
> **(P1)** agents still reach for `Read`/`grep` during implementation instead of codegraph;
> **(P2)** on startup the codegraph MCP server can be `pending` when the agent's first turn fires, so the agent runs with *no* codegraph at all.
>
> Read `codegraph/CLAUDE.md` → "Retrieval performance & dynamic-dispatch coverage" first — it's the doctrine these ideas must respect.

---

## Context — what already shipped (so you don't repeat it)

- **#733 (`7175dc4`)** — reframed the agent-facing steering (`src/mcp/server-instructions.ts` + the `codegraph_node`/`codegraph_explore` descriptions in `src/mcp/tools.ts`) to cover *implementation*, not just Q&A; and added **file-view mode**: `codegraph_node` now accepts a bare `file` (no `symbol`) → returns that file's symbol map + its dependents (blast radius) + verbatim bodies (`includeCode`). `handleFileView` in `src/mcp/tools.ts`.
- **Clean A/B result** (new build vs baseline build, both codegraph-connected, same fully-implemented task — `kindExclude` added to `codegraph_search`):
  - **baseline:** 0 codegraph calls, 8 Reads (agent *ignored* available codegraph).
  - **new:** 2 `codegraph_explore` calls, 5 Reads.
  - So the reframe *did* move tool-choice — but the agent used `codegraph_explore`, **never the file-view**, and still Read 5×. n=1/arm.
- **Eval harness fix** (`#735`): nested attach is a *startup-latency* problem, not a hard block. `scripts/agent-eval/ab-new-vs-baseline.sh` now pre-warms a daemon + skips the re-exec; use it (run non-nested for cleanest results).

**Doctrine constraints (from CLAUDE.md — do not relitigate):**
- *Adapt the tool to the agent.* Changing tool descriptions / `server-instructions.ts` is **low-salience** and has *regressed* wall-clock before. Wording alone won't reliably move tool-choice.
- *New tools fare worse than extending an existing one* (the agent under-picks even `trace`; `codegraph_context` was removed).
- The real levers that landed historically: **coverage** (more flows connect statically → `explore` surfaces them) and **sufficiency** (output complete enough that the agent *stops* reading).
- The optimization target is **wall-clock + tool-call count + Read=0**, not token cost (cost is lower as a side effect).

---

## P1 — Agents under-use codegraph during implementation

### STATUS — 2026-06-08 (RESOLVED via Read-parity, not a hook)

**The fix: make `codegraph_node` read a file *exactly like the Read tool*, only
faster — so the agent reaches for it naturally. No forcing.** The owner's steer
settled the direction: *"codegraph should be able to Read just like the Read
tool… make it as good as Read. Read is slow and old; querying the index is fast.
You keep diverging away from using codegraph rather than pursuing the fix."*

**DONE — `handleFileView` (`src/mcp/tools.ts`) is now full Read parity:**
- A `file` with no `symbol` returns the file's current source numbered
  **byte-for-byte the way Read does — `<n>\t<line>`, no padding, trailing empty
  line kept** (verified by reading the same file with both and diffing). The only
  addition is a **one-line blast-radius header** (`used by N files: …`).
- **`offset` / `limit` mean exactly what they do on Read** (1-based start; max
  lines; default whole file capped at 2000 lines like Read). Large files paginate
  honestly (`(lines X–Y of N — pass offset/limit…)`), never the 15k `truncateOutput` chop.
- Content is the **default** (no `includeCode` needed); `symbolsOnly: true` returns
  the cheap structural map instead. Security preserved: `yaml`/`properties`
  summarized by key, never dumped (#383); reads via `validatePathWithinRoot` (#527).
- Tests: `__tests__/node-file-view.test.ts` (9, incl. strict format parity
  `^1000\t  const v998 = 998;` and unpadded `^1\timport …`). Full suite green
  (1270). Descriptions / `server-instructions.ts` / CHANGELOG reframed: "read a
  source file with codegraph_node instead of Read — same bytes, faster."

**The hook (idea 1) — A/B'd and REJECTED. Do not ship.** Kept only as an eval
artifact (`scripts/agent-eval/redirect-read-hook.sh` + `ab-hook.sh`).
- Clean A/B (2 runs/arm, devpit "add `dp ping`, build it"; both arms codegraph-attached):
  - **nohook:** 0 codegraph calls, 1 Read, **5–7 tool calls, 6–8 turns, 55–77s.** (Reproduces P1: agent ignores codegraph — but read-once-and-edit is *efficient* here.)
  - **hook (deny-redirect):** 0 *successful* Reads + 1 file-view call (parity worked, edit compiled), but **8–9 tool calls, 9–10 turns, 200–239s**, and the agent **fought the deny** — `ToolSearch` to find the tool, reflexive re-Read (denied), then **`Bash python3` to read the file around the block.**
  - Verdict: a blanket Read-deny **regresses the target metrics (~2× tool calls, more turns) on a simple edit** and the agent routes around it. Forcing is the wrong lever; making the tool genuinely better than Read is the right one.
- If routing is ever revisited: not a blanket hook. Either a narrow trigger (large
  files only / after-N-reads) **with a clean A/B on a Read-heavy multi-file task**
  (the hook's best case, untested), or just keep widening coverage + sufficiency.

---

**Symptom:** even with codegraph attached + the new steering, the agent reflexively `Read`s/`grep`s mid-implementation, and never reaches for the file-view. Descriptions can't fix this (low-salience wall).

### Ideas, ranked by expected leverage

1. **PreToolUse(Read/Grep) hook that redirects to codegraph** — *highest leverage; the only channel that actually changes behavior.*
   - Claude Code **hooks** can intercept a tool call and inject context or block it — unlike descriptions, this is *not* low-salience. We already have `scripts/agent-eval/block-read-hook.sh` + `hook-settings.json` (used to force Read=0 in evals).
   - Ship a **recommended (opt-in) hook**: on `Read` (or `Grep`) of a path that's *indexed*, inject "this file is indexed — `codegraph_node {file}` returns it + its blast radius for fewer tokens; treat its output as already-Read." Soft nudge (don't hard-block, or it'll frustrate users on configs/docs codegraph doesn't index).
   - The installer (`src/installer/targets/claude.ts`) could offer to add this hook (opt-in, like the auto-allow permissions).
   - **Validate** with `ab-new-vs-baseline.sh` (Read count, with vs without the hook). This is the experiment most likely to move the needle.
   - Open Qs: how to know a path is indexed from inside a hook (query `codegraph files`/`status`, or a fast local check against `.codegraph`); avoiding noise on non-indexed files; per-language false positives.

2. **Sufficiency: make the file-view the obvious Read replacement so the agent *wants* it.**
   - The A/B showed the agent never passed a `file` to `codegraph_node`. Why? It doesn't think "Read this file" → "codegraph_node file=X". Investigate: is the file-view's value (symbols + dependents + bodies) actually *better than Read* for the agent's next step (an `Edit`)? It returns bodies — but does it return enough surrounding context to `Edit` confidently? If not, the agent Reads anyway.
   - Consider: when the agent *does* Read an indexed file, is there a way to make codegraph's prior `explore`/`node` output have *already* given it what it needed? (i.e. fix the upstream sufficiency, not the Read itself.)

3. **Coverage — the durable lever.** Every flow that connects statically is one the agent doesn't Read to reconstruct. Keep closing dynamic-dispatch gaps (`src/resolution/`). Less about "stop Reading," more about "never need to."

4. **Naming / affordance experiments (low confidence, cheap).** The file-view is buried inside `codegraph_node`. A dedicated, obviously-named affordance might get picked more — *but* "new tools fare worse," so this likely loses. If tried, A/B it; don't assume.

**Recommendation:** prototype **idea 1 (the Read-redirect hook)** and A/B it. It's the one lever with a real chance of moving behavior. Everything else is incremental.

---

## P2 — Agent runs without codegraph because the server is `pending` at startup

**Symptom:** `serve --mcp` isn't ready when the agent's first turn fires (the host marks the MCP server `status:"pending"` / 0 tools), so the agent starts Read/grep and never uses codegraph. We saw this hard in nested evals (~2-3s startup vs the agent's turn-1); **real users hit a milder version** — the first query of a session may not have codegraph.

### Root cause
`serve --mcp` does a `--liftoff-only` **re-exec** (for a node memory flag) **and** spawns/binds a detached **daemon** before tools are usable. Under load that exceeds the host's MCP-startup window. (`CODEGRAPH_WASM_RELAUNCHED=1` skips the re-exec; pre-warming a daemon removes the bind latency — both proven in `ab-new-vs-baseline.sh`. But a real user can't pre-warm.)

### Ideas, ranked

1. **CODEGRAPH-SIDE — expose the static tool list INSTANTLY, decoupled from the daemon. *Biggest shippable win; helps every user.***
   - Hypothesis: the host marks codegraph `pending` because `tools/list` (tool exposure) waits on the daemon connect. The local handshake already answers `initialize` fast (~107ms; `runLocalHandshakeProxy` in `src/mcp/proxy.ts`, `getStaticTools` is imported there). **Investigate: does `serve --mcp` answer `tools/list` *locally and instantly* from `getStaticTools`, or does it forward it to the still-connecting daemon?** If the latter, decouple it: advertise the static tools the moment the client asks, mark connected, and resolve the daemon in the background for actual tool *calls*.
   - Verify with: `printf '<initialize>\n<initialized>\n<tools/list>\n' | node dist/bin/codegraph.js serve --mcp --path <repo>` and time the `tools/list` response, daemon-mode vs in-process. In-process answered in ~165ms; daemon-mode is the suspect.
... (37 lines truncated)
</file>

<file path="docs/design/callback-edge-synthesis.md">
# Design + status: general callback / observer edge synthesis

**Status:** SHIPPED (the synthesizer in `callback-synthesizer.ts` is merged and on
`main`). This doc records the original design.
**Motivation:** close the dynamic-dispatch hole that static extraction leaves for
observer / event-emitter / signal patterns, where a *dispatcher* invokes callbacks
registered elsewhere through a shared store — so flows like "how does an update
reach the screen" actually exist in the graph.

> **Update (2026-06-01):** the `codegraph_trace` and `codegraph_context` MCP tools
> were since **removed** — `codegraph_explore` is the single surfacing tool now. Its
> "Flow" section (`buildFlowFromNamedSymbols`) and the `codegraph_node` trail surface
> these synthesized edges; the `trace(a, b)` notation below means "the a→b flow,"
> which you now verify with `codegraph_explore` / `probe-explore.mjs` (the
> `probe-trace.mjs` / `probe-context.mjs` dev probes went away with the tools).

---

## TL;DR for a new session

We synthesize `dispatcher → callback` edges that static parsing misses. It works:

- **Field observer** (excalidraw `Scene.onUpdate`/`triggerUpdate`): synthesizes
  `triggerUpdate → triggerRender`. `trace(mutateElement, triggerRender)` now = 3 hops.
- **EventEmitter** (express `on('mount', …)`/`emit('mount')`): synthesizes `use → onmount`.
- Precision is high: excalidraw got **1** synthesized edge out of 27k (the correct one);
  node count moved +3 after Phase 3 (no explosion).

**Files touched (all uncommitted on `main`):**
- `src/resolution/callback-synthesizer.ts` — the whole-graph synthesis pass (Phase 1 + 2).
- `src/resolution/index.ts` — calls `synthesizeCallbackEdges()` at the end of
  `resolveAndPersistBatched()` (after base edges are persisted) + the import.
- `src/extraction/tree-sitter.ts` — `visitFunctionBody` now extracts **named** nested
  functions (Phase 3), so inline named handlers become linkable nodes.

**How to reproduce / test:**
```bash
npm run build
rm -rf /tmp/codegraph-corpus/excalidraw/.codegraph
( cd /tmp/codegraph-corpus/excalidraw && codegraph init -i )
# synthesized edges (provenance='heuristic', metadata.synthesizedBy in {callback,event-emitter,…,http-client,queue-job,event-bus}):
sqlite3 /tmp/codegraph-corpus/excalidraw/.codegraph/codegraph.db \
  "select s.name||' → '||t.name||'  '||coalesce(e.metadata,'') from edges e \
   join nodes s on e.source=s.id join nodes t on e.target=t.id where e.provenance='heuristic';"
# end-to-end flow (the synthesized edge shows up in explore's Flow section + node trail):
node scripts/agent-eval/probe-explore.mjs /tmp/codegraph-corpus/excalidraw "triggerUpdate triggerRender"
```
Probe scripts (dev-only, in `scripts/agent-eval/`): `probe-node.mjs` (symbol + trail),
`probe-explore.mjs` (relevant source + the flow among named symbols). EventEmitter
fixture lives at `/tmp/cb-fixture/bus.js` (ephemeral — recreate or move into `__tests__/`).

---

## Cross-tier channels (`src/resolution/tier-synthesizer.ts`, 2026-08-28)

The web's RN bridge: one pass, registered before the in-process emitter pass (the more specific edge wins a duplicate
`source>target` pair in the merge), gated on JS-family files, never sourced from a test suite or a generated file.
Three channels, each keyed on a literal on both sides, each edge `kind:'calls'`, `provenance:'heuristic'`, with
`synthesizedBy`, `channel` (`http` | `queue` | `event` | `socket`), `tier` (`client→server` / `server→client`) when the
direction is known, the `event` / `queue` / `method` / `href` it paired on, `line` + `column` of the call, and
`registeredAt` = the other side (route registration, decorator, `.on`):

- **`http-client`** — `fetch` / `$fetch` / `ofetch` / `axios` / `ky` / `got` / `useFetch` / `useSWR`, `<client>.get|post|…(`
  where the receiver is a known client name or a binding made by `axios.create(…)` / `ky.extend(…)` (same file or the file it
  is imported from — `resolveImportPath`, since import mappings carry no resolved path), with a literal / template first
  argument (`new URL('/x', base)` and `{ url, method }` configs read too) → the ONE route `METHOD path` in the index it
  denotes. A hole fills a `:param` / `{id}` / `[id]` / catch-all segment and never a literal one; a hole in front of the path
  (`${API_URL}/users`) matches by the route's tail; a line a framework resolver made a route node on is a registration, not a
  client call; a tie between routes is nothing. No fan-out cap — the match is exact.
- **`queue-job`** — `<queue>.add('job', …)` where the queue is named (`new Queue('email')`, `@InjectQueue('email') x`, in the
  file or its import) or queue-shaped → the `@Process('job')` method of the `@Processor('email')` class (a WorkerHost's
  `process` when there is none), `new Worker('email', handler)` (an inline handler → the enclosing function, else the
  enclosing constant), Bull's `queue.process('job', handler)`. Most specific pairing wins (queue+job > job > the queue's
  default); an unnamed queue pairs only on a unique job name. Fan-out cap 6.
- **`event-bus`** — `.emit|emitAsync('x')` on a bus-shaped receiver (`eventEmitter`, `bus`, `pubsub`, …) → `@OnEvent`
  handlers, `*` / `**` globs honoured; on a socket-shaped receiver (`socket`, `io`, `server`, `client`, `.to(room)`, …) from a
  file without a socket server → `@SubscribeMessage('x')` and server-side `socket.on('x')` (`client→server`); from a file
  with one (`@WebSocketGateway`, `io.on('connection')`, `new Server`) → client-side `socket.on('x', …)`, named or inline
  (→ the enclosing component) (`server→client`). Plain `.on` ↔ `.emit` stays the emitter pass's. Fan-out cap 6.

The Steps view (`ui-server/api/steps.ts`) reads `tier` / `channel` before the languages in `crossing()`, so a hop between
two TS files draws as a bridge (`⇢ POST /api/users`, a boundary like another screen) or an event (`⇠ welcome`); explore's
Flow section labels them (`context/index.ts`, `mcp/tools.ts`). A Next `'use server'` action needs no edge: `steps.ts` marks
the call at request time from the directive. Validated on `bradtraversy/proshop_mern` (30 routes, 23 client→route edges,
all correct on inspection, after Express mounts + chained `router.route()` landed) and `nestjs/nest` (`sample/26-queues`,
`sample/30-event-emitter`); test `__tests__/ui-steps-cross-tier.test.ts`.

## Next.js links (`src/resolution/next-router-synthesizer.ts`, 2026-08-28)

`<Link href="/x">`, `<Link href={`/users/${id}`}>`, `<Link href={{ pathname }}>` and an internal `<a href>` are JSX
attributes — no reference is ever extracted for them — so this pass reads them from the source, attributes each to the
component it is written in, matches the href against the Next page table (`frameworks/nextjs.ts`) and synthesizes a
`navigates` edge (`synthesizedBy:'next-link'`, `href`, `navMethod: 'link' | 'a'`, `registeredAt` = the JSX site). Only files
under a Next app's root, never test files; ≤ 24 links per component (a navigation menu is not a decision); an external `<a>`
is nothing. The Screens view walks back from these edges exactly as from `router.push`; they draw dashed.

## The hole

```ts
class Scene {
... (131 lines truncated)
</file>

<file path="docs/design/ccpp-kernel-port-checklist.md">
# C/C++ kernel port (R7a) — the bug-for-bug checklist

**Status: COMPLETE — walker SHIPPED + gates PASSED, c/cpp DEFAULT-ROUTED
(2026-07-17).** Walker: `codegraph-kernel/src/ccpp/mod.rs` (one dual-language
module, every branch below mirrored; its header comment lists the quirks).
Grammars: tree-sitter-c v0.24.2 (`b780e47`, parser.c `f2883ff9…`) +
tree-sitter-cpp v0.23.4 (`f41e1a0`, parser.c `2a35a43b…`, scanner.c
`cf60387d…`), crates pinned `=exact` in Cargo.toml, wasm vendored from the
same tags, kernel-grammar-parity green. preParse HOISTED to the route point
(`preParsedSource` in src/extraction/kernel/index.ts — both tryKernelExtract
and the raw bulk path), so no blanking ported to Rust.

**Gate results (2026-07-17):**
- Parity sweeps — **0 diffs on every compared file**: redis 592, git 790,
  fmt 42, protobuf 925, ALS-Community (UE spot-check) 40 files byte-parity.
- Full-init dump-diffs — **byte-identical** kernel-arm vs wasm-arm: redis
  (131,921 dump lines), git (160,844), fmt (35,433), protobuf (780,620),
  ALS (3,694).
- Torture fixtures torture.c/.cpp/.hpp + CRLF variants + Metal/CUDA
  hoist-parity + defer tests in `__tests__/kernel-ccpp-parity.test.ts`; new
  preParse blanks unit-tested in extraction.test.ts; full suite green with
  `CODEGRAPH_KERNEL_EXPECT=1`.
- **Deferral-rate guard — CORRECTED BY MEASUREMENT** (the §4f pattern): the
  <10% bar was calibrated on ts/java/py/go (0–0.42% parse-error incidence).
  Macro-heavy C/C++ genuinely parses with errors at double-digit file rates
  (final sweeps: als 9%, git 16.1%, redis 25.3%, protobuf 25.8%, fmt 42% —
  fmt's template metaprogramming + `.operator[]`-in-decltype shapes are
  grammar-inherent), and every erroring file defers BY POLICY. Measured with
  the defer disabled (`CODEGRAPH_KERNEL_CCPP_ERROR_EXTRACT=1`, sweep-only
  hatch): recovery-divergence is real (21/207 redis, 8/382 git, 9/31 fmt
  erroring files extract differently across UTF-8/UTF-16), so the defer
  stays. The sweep harness now takes `--max-deferral` (default 0.1; use 0.5
  for c/cpp — a broken walker still trips it by deferring ~everything).
- **Seven NEW/extended preParse blanks** cut real incidence (from 32%/52%
  starting points; linux `kernel/`+`mm/` subtrees 79% → 58%), each
  offset-preserving, TS-side, shared by both arms, and a graph-quality win
  for the wasm path itself (git 7.1k → 13.3k nodes; the linux subtrees
  2.4k → 7.2k — NOTE these are parity-sweep compared-file totals, NOT
  full-graph counts: round 2 established that full-graph node deltas are
  small because wasm error recovery was already salvaging most SYMBOLS on
  deferred files; the blanks' full-graph win is EDGES + phantom cleanup —
  see the round-2 record below): `#ifdef __cplusplus` guard bodies, lone macro lines
  (`FMT_BEGIN_NAMESPACE`, `Q_OBJECT`), C statement iterator macros
  (`list_for_each_entry(…) { }` and brace-less bodies), C trailing param
  attrs (`int argc UNUSED`), the curated Linux/sparse annotation list
  (`__init`/`__user`/… — structural matching is impossible there: `__u32
  count` is shape-identical; parameterized `__printf(1,2)` guarded out) +
  `container_of`'s type-keyword argument, leading attr macros extended to
  cpp, and directive-line restore (stops the older blanks corrupting
  `#define` lines).
- **Defer-reuse (the linux-economics fix):** a deferred file used to pay the
  pipeline three times — the worker's raw kernel try, extractFromSource's
  kernel RE-try, then wasm with a third preParse. A one-slot defer memo in
  the route point short-circuits the repeat kernel attempt and hands the
  already-blanked source to the wasm fallback (`sourceIsPreParsed`). On
  linux this + the annotation blanks took the kernel-arm parse-loop from
  560s (WORSE than the 426s wasm arm) to **356s vs 435s wasm-arm (−18%)**,
  and the 2c/6GB envelope to **19.1 min kernel-arm vs 22.9 min wasm-arm
  (−17%)** with a RICHER graph (2,048,295 nodes / 6,406,933 edges; two
  independent kernel-arm runs byte-same counts).
- **Linux-scale dump gate:** kernel-arm and wasm-arm full graphs are
  **byte-identical** — `dump-graph.mjs` over both 5.2GB DBs:
  10,444,551 dump lines each, sha256 `cd4182e6…` on both. (Dumping a 2M-node
  DB needs a big-heap host run — `node --max-old-space-size=16000 …
  > file` then hash the FILE; the in-container 6GB heap OOMs and a straight
  pipe at GB scale dies with ENOBUFS, both of which silently hash truncated
  output as the empty stream.)

- **Deferral round 2 (2026-07-18)** — eight new C-only passes + word-list
  extensions took the linux `kernel/`+`mm/` deferral **58.6% → 33.9%**
  (483 → 279 of 824 files; census-driven: `bucket-defers.mjs` clusters each
  deferring file's FIRST post-preParse error-line shape). New passes, all in
  `preParseCSource`: parameterized-annotation whole-blank (`__free(kfree)`,
  `__printf(4,0)`, `__counted_by(n)`, `__bpf_md_ptr(…)` — extends through a
  stranded field `;`, since a lone-`;` field errors but an empty struct body
  doesn't), type-keyword-arg scanner (`kzalloc_obj(struct T)`,
  `list_entry(p, struct T, m)` — a bounded hand scanner, NOT a nested regex
  (backtracking risk on untrusted repos); head exclusions
  sizeof/offsetof/`_Generic`/va_arg + call-vs-declaration guard: an
  identifier or `*` before the head rejects, `return` excepted; blanks
  trailing stars so `DEFINE_PER_CPU(struct T *, x)` leaves two plain
  idents), `static|extern CAPS_MACRO(…);` whole-line blank at ANY scope
  (bare `EXPORT_SYMBOL(x);` parses natively as a K&R decl — probed — and
  stays), the ONE REWRITE in the family — `static CAPS(type, name) = {` →
  `static <type> <name> = {` (name + tail keep exact offsets via d-flag
  indices; blanking would strand the brace block or discard initializer
  fn-refs), `va_arg(ap, const char *)` second-arg blank (single-token
  `va_arg(ap, int)` parses natively — probed), GNU named-variadic
  `#define f(args...)` DOTS-only blank (post-`restoreDirectiveLines` by
  design; whole-tail blanking fails — `#define NAME` + trailing spaces
  errors, measured), storage-sandwiched lowercase markers
  (`static notrace void` — the sandwich is the guard), C23 `auto`
  (`auto x =` only; `auto int x` untouched), and multi-line spans for the
  statement-iterator-macro blank (`hlist_for_each_entry_rcu(…,\n
  lockdep_is_held(&m)) {` — bails on `;`/braces mid-span). Word list +=
  cacheline family (2- AND 4-underscore spellings), `__noclone`,
  `__lockfunc`, `__ref`, `__private`, `__bitwise`, `__nosavedata`,
  `__no_kcsan`, `__cpuidle`, `__ksym`, `__net_initdata`,
  `__initdata_memblock`/`_or_meminfo`. Cross-repo: git 16.1 → 12.2%,
  redis 25.3 → 24.1%, fmt/protobuf unchanged (cpp-dominant — C-only passes,
... (126 lines truncated)
</file>

<file path="docs/design/cg57-highlighting-parity.md">
# Highlighting parity: Shiki → the engine's own tree-sitter parse (CG-57)

The viewer's code block used to be classified by a second highlighter — Shiki with 56 pruned
TextMate grammars shipped in `dist/textmate/` — over source the engine had already parsed with a
real grammar. CG-57 takes the classification off that tree instead. This file records what the swap
changed, measured rather than asserted, so nobody has to re-derive it from a diff.

Screenshots, one per language, before on the left and after on the right, same stylesheet:
[`cg57-highlighting-parity/`](./cg57-highlighting-parity/) — `typescript.png`, `go.png`,
`python.png`, `rust.png`, `swift.png`, `csharp.png`, `ruby.png`, `php.png`.

## What it costs

3 000 lines, cold, dev Mac (M-series), parse + classify + wire:

| | TypeScript | Go | Python | Rust | Swift | C# | Ruby | PHP |
|---|---|---|---|---|---|---|---|---|
| Shiki + TextMate | ~700 ms | 43–57 ms | 35–47 ms | — | — | — | — | — |
| Engine tree-sitter | 24–41 ms | ~30 ms | 25–29 ms | 18–19 ms | 25–27 ms | 20–25 ms | 14–16 ms | 20–22 ms |

The task's budget was **< 100 ms per 3 000-line file warm**; every language clears it *cold*.
TypeScript is the number that mattered: its TextMate grammar was 5–7× every other one and the cost
was regex *execution*, not compilation, so nothing about the old module could have fixed it. The
slice cache still exists — a re-render (resize, theme flip, stepping back through the trail) should
cost nothing at all, and the whole-file view pages the same file repeatedly.

## What it changes on screen

Per-character comparison over ~40 lines of realistic source per language, counting only
non-whitespace characters, and treating `ident` / `other` / `type` as one bucket because all three
paint at plain ink:

| language | painted identically | what moved |
|---|---|---|
| TypeScript | 91.3% | 33 `def`, 40 interpolation chars now code, 2 punctuation |
| Go | 91.5% | 37 built-in type words, 13 `def` |
| Python | 93.2% | 26 `def`, 15 keyword (`is not`, `__future__`) |
| Rust | 96.3% | 21 `def`, 3 keyword |
| Swift | 93.3% | 18 `def`, 14 keyword (`throws`/`rethrows`) |
| C# | 88.3% | 30 built-in type words, 23 `def`, 31 interpolation chars now code |
| Ruby | 83.8% | 23 `def`, 35 interpolation chars now code, 14 symbol literals, 3 keyword |
| PHP | 85.9% | 33 built-in type words, 29 `def`, 15 phpdoc tag chars, 12 keyword |

Every remaining difference is one of five deliberate categories:

1. **`ident` → `def`.** The definition's own name now carries weight 600, everywhere rather than
   only on the line the Symbol view opened at. It comes from the extractors' own definition tables
   (`functionTypes`, `classTypes`, `methodTypes`, …) plus each language's `nameField`, so it cannot
   drift from what indexing considers a definition.
2. **`string` → code, inside an interpolation.** A template literal's `${…}`, an f-string's `{…}`,
   Ruby's `#{…}` and C#'s `$"{…}"` are classified as code. This is the one difference that is not
   cosmetic: the call-site overlay deliberately refuses to claim a token classed `string`, so
   **calls inside interpolated strings now link and did not before.**
3. **`keyword` → `type`, on built-in type words.** `string`, `int`, `u32`, `void`. The grammars
   disagree with each other about what a built-in type is — tree-sitter-go calls `string` a
   `type_identifier`, tree-sitter-typescript wraps it in a `predefined_type` whose child is an
   anonymous token spelled `string` — and TextMate scoped them inconsistently too (plain in
   TypeScript, `storage.type` in Go). They now all paint at plain ink, like a user-defined type
   name, in every language.
4. **Keyword-set corrections.** Python's `is not`, Rust's and Swift's modifiers, and Ruby's `new`
   (which is a method, not a keyword — TextMate's `keyword.operator.new` matched it anyway).
5. **`keyword` → `comment`, on phpdoc tags.** `@var` and friends recede with the comment they are
   in, which is what the near-monochrome ramp asks for.

## What is no longer highlighted

Nine formats have extraction but no tree-sitter grammar. Three of them — `.svelte`, `.vue`,
`.astro` — are classified through their `<script>` blocks with TypeScript or JavaScript, the same
delegation the extractors do, so every symbol the engine indexed in those files is highlighted and
the surrounding markup is not. The other six (Liquid, Razor, YAML, Twig, XML, `.properties`) render
plain, where Shiki had grammars for them.

That is a real, deliberate loss, and it is the alternative to a worse one. `tree-sitter-wasms`
ships an `html` grammar that would cover most of them, but the ABI-13 builds in that package are
the known cause of a shared-WASM-heap corruption that silently drops edges for *every other*
language in the same process (see `VENDORED_WASM_LANGS` in `src/extraction/grammars.ts`), and the
viewer runs in a process someone leaves open all day. Adding unvetted grammars to buy tag colouring
on config files is not a trade worth making. Identifiers are still split out on those files, so the
graph's call-site links land exactly as they do everywhere else — highlighting is the part that
degrades, never the linking.

## Reproducing this

There is no committed harness: the "before" side needs the deleted Shiki module. Rebuild it from
the last commit that had it —

```
git worktree add /tmp/cg48-baseline <ref-with-shiki>
ln -s "$PWD/node_modules" /tmp/cg48-baseline/node_modules   # @shikijs/* must still be installed
( cd /tmp/cg48-baseline && npx tsc && node scripts/prune-grammars.mjs )
```

— then run both `dist/ui-server/highlight/index.js` modules over the same lines and compare
`classes[id]` per character. The screenshots were rendered from the same two token streams through
the viewer's own token CSS at `--force-device-scale-factor=2`.
</file>

<file path="docs/design/chained-call-resolution.md">
# Design + status: chained static-factory / fluent call resolution

**Status:** SHIPPED for **13 languages** (C++, C, PHP, Java, Kotlin, C#, Swift, Rust,
Go, Scala, Dart, Objective-C, Pascal/Delphi) + a conformance pass. **TypeScript and Luau
were evaluated and intentionally skipped** (both gradually typed → the mechanism is +0 /
regresses on real code). See "Full README classification" below. Tracking issue:
**#750** (which began as "the statically-typed README languages" but that enumeration was
incomplete — it missed ObjC / Pascal / Luau).

**Motivation:** a call whose **receiver is itself a call** — a factory / singleton /
builder that returns an object — should produce a `calls` edge to the chained method:

```java
Foo.getInstance().bar();   // bar() should resolve to Foo::bar, never a same-named decoy
```

Before this work, every statically-typed language **dropped the receiver** and
name-matched the bare method (`bar`), so in 7 of 9 languages it silently attached to a
**same-named method on an unrelated type** — a correctness bug, not just missing coverage.

---

## The 3-part mechanism (per language)

1. **Capture the factory's declared return type** — a per-language `getReturnType`
   hook writes `nodes.return_type` (schema v5). `*Foo`→`Foo`, `List<Bar>`→`List`,
   `pkg.Foo`→`Foo`, `-> Self` / `: self` / `this.type` → the declaring type.
2. **Preserve the chained receiver at extraction** — `tree-sitter.ts` (or a bespoke
   extractor) encodes `Foo.getInstance().bar()` as the marker string
   `Foo.getInstance().bar` (the `().` marker never appears in an ordinary ref). A
   per-language gate keeps **instance** chains (`list.map().filter()`) bare so their
   existing resolution is untouched — only capitalized-receiver / factory chains re-encode.
3. **Resolve AND VALIDATE** — at resolution the receiver's type is inferred from what
   the inner call returns, then the outer method is resolved **on that type** and
   validated: the method must exist on the type (or a supertype it conforms to), so a
   wrong inference yields **no edge**, never a wrong one.

Three shared resolvers in `src/resolution/name-matcher.ts`, all calling
`resolveMethodOnType` (which has the conformance supertype-walk):

| Resolver | Receiver style | Languages |
|---|---|---|
| `matchCppCallChain` | `field_expression` (`Foo::instance().bar`) | C++, C |
| `matchScopedCallChain` | `::` (`Cls::for($x)->m`, `Foo::new().bar`) | PHP, Rust |
| `matchDottedCallChain` | `.` (`Foo.create().bar`) | Java, Kotlin, C#, Swift, Go, Scala, Dart |

**Conformance pass (#754).** When the chained method lives on a **supertype** the
return type conforms to (an inherited / default-interface / trait / mixin / embedded
method), the first pass can't see it — `implements`/`extends` edges aren't built yet.
So failed chain refs are deferred (`CHAIN_LANGUAGES` in `resolution/index.ts`) and
re-resolved in a second pass `resolveChainedCallsViaConformance()` after edges exist,
walking `context.getSupertypes(...)`.

**Adding a language:** `getReturnType` in `languages/*.ts`; encode the chained receiver
+ a node-type gate; add the language to the right `matchReference` gate (and
`CONSTRUCTS_VIA_BARE_CALL` if a bare capitalized call constructs the class); add to
`CHAIN_LANGUAGES`; synthetic tests + a real-repo A/B; bump `EXTRACTION_VERSION`.

---

## Coverage (validated — each via synthetic decoy/absent-method tests + a real-repo A/B)

| Language | PR | Receiver | Real-repo A/B (unique `calls` edges) | Notes |
|---|---|---|---|---|
| **C++ / C** | #645 (#742) | `field_expression` | — | The original: singletons / factories / chained getters. |
| **PHP** | #608 (#749) | `::` → `->` | — | `Cls::for($x)->method()` — the Laravel per-tenant client idiom. `: self`/`: static`. |
| **Java** | #751 | `.` | Guava **+1,507 / −0** | Missing-edge → purely additive. |
| **Kotlin** | #752 | `.` | arrow **+49 / −438** | Wrong-edge → precision win (438 removed = test/doc noise + wrong). Needed the capitalized-receiver gate + constructor-receiver handling. |
| **C#** | #753 | `.` | Newtonsoft +3 / NodaTime **+73 / −0** | Additive. Return type is the `returns` field; extension-method chains correctly don't resolve. |
| **conformance** | #754 | (resolver upgrade) | arrow **+22 / −0** | Supertype walk — enables Swift protocol-ext, Rust trait, Go embedded, Dart mixin, Java/Kotlin/C# inherited chains. |
| **Swift** | #755 | `.` | Alamofire / Kingfisher **0 / 0** | Neutral-safe (unique fluent names already bare-resolved). Needed a nested-extension naming fix (`KF.Builder`→`KF::Builder`). |
| **Rust** | #757 | `::` | clap **+937 / −775** | Precision win (622 wrong→right retargets, +162 net). `-> Self`; trait-default methods via conformance. Single-hop. |
| **Go** | #760 | `.` | gin **net-zero** | `New().Method()`; embedded structs via conformance. Variable-inner fallback. **Found + fixed a batched-resolver runaway** (a mutated `original.referenceName` looped the offset-0 batch → 5M edges / 1.4 GB; fixed by tying the fallback to the original ref + a non-progress guard). |
| **Scala** | #761 | `.` | gatling **+14 / −59** | Precision win (−59 = stdlib `Option`/`Iterator` `.map`/`.flatMap` the baseline mis-tied to gatling's `Validation::*`). Companion factories + case-class `apply`. |
| **Dart** | #762 | `.` | localsend hand-written **+17 / −10** | Precision win **+ constructors made first-class** (factory/named ctors `Foo.create()`/`Foo._()` are now indexed; unnamed `Foo()` stays `instantiates`). `dartCtorInfo` validates a ctor against the enclosing class name — handles a tree-sitter misparse where `@override (A,B) m()` makes `m()` look like a ctor. |
| **Objective-C** | #786 | message send | SDWebImage **+35 / −75** | Precision win. Chained message send `[[Foo create] doIt]` over `message_expression`. getReturnType skips nullability qualifiers (`nonnull instancetype`). A class-message factory returns the receiver class by convention, so `[[X alloc] init]` / singleton chains resolve on `X` (validated). The −75 are wrong `init` mis-matches retargeted to the right class. |
| **Pascal/Delphi** | #791 | `.` (`exprDot`) | PascalCoin **+19 / −18** | Precision win. `TFoo.GetInstance().DoIt()` over Pascal's `exprCall`/`exprDot`. getReturnType from the `typeref` (incl. interface returns `IFoo`). Re-encoding gated on the Delphi `TFoo`/`IFoo` type convention so capitalized *variable* chains stay bare. A constructor (no `: TBar`) or typecast `TFoo(x)` resolves on the class. 15 of the −18 are correct class→interface retargets (`GetInstance(): IAsn1OctetString`). |
| **TypeScript** | — | `.` | typeorm +0/−6 · nest **+0/−164** | **Evaluated, NOT shipped** — gradual typing; see below. |
| **Luau** | — | `:` / `.` | Fusion +0/−0 · matter +0/−0 | **Evaluated, NOT shipped** — gradually typed; additive-safe (missing-edge gap, no regression) but real Luau rarely annotates factory returns, so +0 on both benchmarks. Works for `Foo.create(): Bar` then `:doIt()` (synthetic). |

`EXTRACTION_VERSION` is now **18** (C++→…→Pascal chains→paren-less calls→free-routine attribution). Re-index with `codegraph index -f`
to pick up the newer extractor on an existing graph.

## Why TypeScript was skipped

The mechanism resolves a chain from the factory's **declared** return type. TypeScript
leans on **type inference** — e.g. NestJS's `Test.createTestingModule(m) { return new
TestingModuleBuilder(...) }` has no `: TestingModuleBuilder` annotation — so the
factory's type can't be recovered, the re-encoded chain can't resolve, and it **drops
the bare-name edge** the existing resolver found. Real-repo A/B was **+0 added on both
typeorm and nest** with a net recall regression (−164 on nest, mostly the ubiquitous
`Test.createTestingModule({…}).compile()` pattern). The removed edges were mostly
*wrong* (baseline mis-resolved `.compile()` to `ModuleCompiler::compile`), so it's
precision-positive but recall-negative — against the recall-first invariant, and adding
nothing where it doesn't hurt (TS method names are unique enough that bare-name already
lands them). It was fully implemented (5 synthetic tests passed, runaway-safe bare-name
fallback) and consciously not shipped. The only path to a TS win would be reading
**inferred** return types (resolving `return new X()` in the factory body) — a much
larger change. Full write-up on issue #750.

... (47 lines truncated)
</file>

<file path="docs/design/codegraph-ui-design-spec.md">
# codegraph ui — design specification

Authoritative visual + interaction spec for the `codegraph ui` viewer (Kommandr epics CG-39 → CG-48 → CG-56;
Pro layers in docker-app DOCKERAPP-10). Companion to the design proposal ("Reading the graph") and the
interactive prototype; the prototype's stylesheet is appended verbatim at the end and is the source of truth
for every measurement below. Screenshots: `CodeGraph/codegraph-web-prototype/screenshots/` (also attached to
the Kommandr epics).

Design proposal: https://claude.ai/code/artifact/58336c87-9780-4018-8c04-37fe53236e96
Prototype: https://claude.ai/code/artifact/304bffb6-72d6-49c7-8f3a-9e4f244909f8
Prototype sources: `CodeGraph/codegraph-web-prototype/` (`proto.css`, `proto.js`, `extract.mjs`, `build.mjs`)

## 1. Principles (non-negotiable)

1. One symbol at a time — no whole-graph picture, no node-link neighborhood graph (decided).
2. Code order is the coordinate system — layouts by source line or dependency layer; deterministic; never force-directed.
3. Edges grow out of the code — every call edge is drawn from the line that makes the call (gutter port → callee row at that height).
4. Direction is spatial — callers left, callees right, flows read left→right, map dependencies point down.
5. Collapse the tails, show the counts — hubs badge (fan-in ≥ 40), tests fold, confidence < 0.6 folds ("uncertain"), outside-index counts; nothing silently dropped.
6. Honesty in the pixels — confidence = line style; heuristic (synthesized) edges dashed + wiring site; boundaries announced; drift banners; "no test within 3 hops" badge.

## 2. Visual language

The engine's paper/ink editorial system (`site/src/styles/theme.css`): flat, hairline rules, **square corners everywhere**
(`border-radius: 0 !important` globally), no shadows, no gradients, sentence case, **no tiny all-caps tracked labels**,
one oxblood accent used only for focus/selection/edges, one amber used only for the "untested" warning.
Syntax highlighting is deliberately near-monochrome so the graph's edges are the only colour in the code.

### 2.1 Color tokens

| token | light | dark | used for |
|---|---|---|---|
| `--paper` | `#f7f6f2` | `#16150f` | page/body background (always set explicitly) |
| `--paper-2` | `#f1efe8` | `#1c1a14` | trail bar, inputs, hovered code line, figure grounds |
| `--press` | `#e8e6dd` | `#23211a` | hover fills, inline code background, bars |
| `--press-2` | `#dedbd0` | `#2c2a22` | reserved (pressed state) |
| `--ink` | `#16150f` | `#f3f1ea` | primary text, node borders, major rules |
| `--ink-2` | `#56544a` | `#b8b5a8` | secondary text, strings, callers' names when uncertain |
| `--ink-3` | `#87847a` | `#87847a` | tertiary text, comments, glyph borders, edge labels |
| `--ink-4` | `#b4b1a5` | `#5d5b52` | line numbers, resting connectors, dimmed map nodes |
| `--rule` | `#16150f` | `#f3f1ea` | top bar bottom rule, code/blast section rules |
| `--rule-soft` | `#d6d3c8` | `#34322a` | rail dividers, chips, card borders |
| `--rule-faint` | `#e6e3d9` | `#26241d` | row separators, map layer lines |
| `--accent` | `#7a2230` | `#d48b96` | oxblood: call-site links, current trail hop, hot connectors, selected map edges |
| `--accent-ink` | `#5e1a25` | `#e5a5ae` | accent text on accent-soft |
| `--accent-soft` | `#f0e3e5` | `#33201f` | tinted rows ("you came from here"), hot code lines |
| `--accent-line` | `#d9b3b9` | `#6b3a42` | accent borders/underlines at rest |
| `--amber` | `#8a5a0b` | `#d9a94a` | "No test reaches this within 3 caller hops" badge only |
| `--amber-soft` | `#f3e9d2` | `#2e2716` | that badge's fill |

Theme selection: define the light set on bare `:root`; redefine under `@media (prefers-color-scheme: dark)` guarded as
`:root:not([data-theme="light"])`; redefine again under `:root[data-theme="dark"]`. Never define a colour only inside a
media/`[data-theme]` block. `body { background: var(--paper); color: var(--ink) }`.

### 2.2 Type

- UI: **Archivo** 400/500/600/700 (fallback `-apple-system, BlinkMacSystemFont, 'Helvetica Neue', Arial, sans-serif`).
- Code, symbol names, file paths, chips, trail, map labels: **IBM Plex Mono** 400/500/600 (+ italic 400)
  (fallback `ui-monospace, 'SF Mono', Menlo, Consolas, monospace`).
- Scale: body UI `13px/1.45`; code `12.5px/20px`; symbol title `600 20px/1.2` mono, letter-spacing −0.01em;
  section labels (`Called by`, `Calls`, `Blast radius`) `600 13px` sans; rail rows `12.5px` mono name + `11px` sans meta;
  chips `11px` mono; line numbers `11px` mono in `--ink-4`; badges `11.5px`; map node label `13px` mono, count `11px`;
  flow card name `600 13px` mono, window `12px/19px` mono; trail `12px` mono. Headings sentence case, `text-wrap: balance`.
- Code token classes: comment `--code-comment`; string `--ink-2`; keyword weight 500 (same ink); number `--ink-2`; definition
  name on its own line weight 600; **call-site link** = `--accent`, underline `--accent-line`, offset 3px, hover/hot fill
  `--accent-soft`; uncertain link = `--ink-2`, dotted underline `--ink-4`; link to a symbol outside the index = `--ink-2`,
  underline `--rule-soft`, not clickable.
  - *As built (CG-43) — comments are `--code-comment`, not `--ink-3`.* `--ink-3` measures 3.46:1 on `--paper` and 3.00:1 on
    the hot-line tint `--accent-soft`, both under the 4.5:1 that 12.5px body text needs. `--code-comment` is the smallest
    step along the same warm-grey ramp that clears 4.5:1 on every background a code line can have (`#6a675d` light —
    paper 5.23, paper-2 4.92, accent-soft 4.53; `#8e8b81` dark — 5.36 / 5.10 / 4.51) while staying quieter than the
    `--ink-2` strings and numbers use, so the recession order above is unchanged. Everything else in this list passes as
    specified: ink 16.9/16.2, ink-2 7.03/8.89, accent 9.25/6.91 (8.02/5.80 on `--accent-soft`).
  - *Line numbers remain `--ink-4` (1.99:1 light, 2.69:1 dark) — a known contrast gap, left as specified rather than
    changed inside a rendering task. Worth a design call before phase 2.*

### 2.3 Kind glyphs

16×16 hollow square, 1px `--ink-3` border, letter in `500 9.5px` mono: `ƒ` function · `m` method · `C` class · `I`
interface · `S` struct · `T` type alias · `E` enum · `e` enum member · `k` constant · `v` variable · `p` property/field ·
`≡` file (dashed border) · `R` route · `⟨⟩` component · `N` namespace · `M` module · `Tr` trait · `U` union · `P` protocol.
Container/type kinds get a `--press` fill.

## 3. Layout and components

### 3.1 App shell
- Grid rows: **top bar 48px** / **trail bar 34px** / main. Top bar: brand (10px hollow square mark + "CodeGraph" 600 14px +
  "ui" in `--ink-3`), view tabs (`Map · Symbol · Flow`, 5px 10px padding, active = 2px `--ink` bottom border), search input
  (30px tall, `--paper-2` fill, `--rule-soft` border → `--ink` on focus, max-width 720px), project stats in `--ink-2` 12px.
  Bottom rule of the top bar is `--rule` (1px); the trail bar's is `--rule-soft`.
- Focus ring everywhere: `outline: 2px solid var(--accent); outline-offset: 1px`. `prefers-reduced-motion` disables transitions.

### 3.2 Symbol view (`#/s/<id>?t=<trail>&hl=<line>`)
- Grid: **left rail 300px** | stage `minmax(520px, 1fr)`; inside the stage: **center `minmax(480px, 1fr)`** | **right rail 320px**.
  Left rail has its own scroll; center + right rail scroll together in the stage (so callee rows stay aligned to lines).
  ≤ 1100px: 240px | `minmax(360px,1fr)` | 260px.
- Rail headers sticky, `12px 14px 8px` padding, 600 13px, count in `--ink-3`, hint text right-aligned `11.5px` (`← step up`, `step down →`).
- **Center**: padding `18px 22px 40px`. Header row: glyph, name (h1), kind word (`--ink-3` 12.5px, "· async · static · private"),
  location `file:start–end · N lines` (11.5px mono, file is a link). "in ClassName" breadcrumb 11.5px mono `--ink-3`.
  Badges row (gap 6px): `exported` · `hub · N callers` (border `--ink`) · tests badge (`Reached by tests · N files within 3 hops`,
... (1091 lines truncated)
</file>

<file path="docs/design/csharp-kernel-port-checklist.md">
# C# kernel port (R7b) — the bug-for-bug checklist

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/csharp.rs`,
all gates passed (parity sweeps 0-diff on serilog 211/216 / Newtonsoft.Json
914/945 / jellyfin 2104/2105 — every deferral matching §arch-6's predictions;
full-init dump gates byte-identical ×3; kernel-csharp-parity suite + grammar
row; suite ×2 under CODEGRAPH_KERNEL_EXPECT=1; DEFAULT_ROUTED += csharp). This
doc remains the quirk reference for the walker. Survey basis: every
TS-side branch a `.cs` file exercises, with file:line anchors as of **`f1ca991`**
(HEAD at survey time, clean main). Every grammar-shape claim below was **probed
against the vendored tree-sitter-c-sharp 0.23.5 wasm**
(`src/extraction/wasm/tree-sitter-c_sharp.wasm` — note the underscore filename);
probe scripts + raw outputs live in the survey session scratchpad
(`/private/tmp/claude-501/-Users-colby-Development-CodeGraph-codegraph/0c11bda1-0b19-4fec-bcd9-d0cb4b2d6e8a/scratchpad/svy-csharp/`:
`probe1-core.mjs`, `probe2-shapes.mjs`, `probe3-edge.mjs`, `census-wasm.mjs`,
`error-incidence.mjs`, `blank-impl.mjs` + `probe*-out.txt`). Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §5 gates) and the
rust/ccpp checklists (format precedents). **Blocking findings: none** — the
vendored wasm is table-identical to the crates.io 0.23.5 crate (below), so no
grammar bump is needed; grammar prep is a Cargo pin + parity-test entry only.

**Grammar provenance (verified, not assumed):**

- Vendored wasm landed in **PR #717** (commit `80db274e`, 2026-06-07 — the #237
  primary-constructor fix), replacing tree-sitter-wasms' ABI-13 build. The
  commit message says "tree-sitter-c-sharp 0.23.5 (ABI 15)" but does NOT claim a
  parser.c sha-match, so this survey verified compatibility directly against the
  crates.io `tree-sitter-c-sharp-0.23.5` tarball
  (`src/parser.c` sha256 `0a2651e4…`, `src/scanner.c` sha256 `00920daa…`;
  upstream tag `v0.23.5` → commit `cac6d5fb`):
  - wasm ABI **15** == parser.c `LANGUAGE_VERSION 15`;
  - wasm `stateCount` **8053** == parser.c `STATE_COUNT 8053`;
  - wasm `nodeTypeCount` **533** == `SYMBOL_COUNT 530 + ALIAS_COUNT 3`;
  - wasm `fieldCount` **26** with a field-name set identical to the crate's
    node-types.json (accessors…value);
  - named node-kind set: wasm ⊆ crate exactly (the 9 crate-only names are
    node-types.json *supertypes* — `declaration`, `expression`, `pattern`, … —
    which never instantiate; zero real divergence);
  - the crate ships an **external scanner** (`scanner.c`, 12 external tokens)
    and the wasm embeds it — probed: interpolated raw strings
    (`$"""… {Interp(u)} …"""`), raw string literals, and verbatim strings all
    parse clean.
- **Cargo plan:** add `tree-sitter-c-sharp = "=0.23.5"` to
  `codegraph-kernel/Cargo.toml` following the exact-pin comment block (the
  `=0.24.2` c/rust rows); crate symbol is **`tree_sitter_c_sharp::LANGUAGE`**
  (a `LanguageFn`, `.into()` like the other 0.23-era crates); register
  `"csharp" => Some(tree_sitter_c_sharp::LANGUAGE.into())` in
  `codegraph-kernel/src/langs.rs` + add `"csharp"` to `LANGUAGES`. The crate's
  build.rs compiles parser.c **and scanner.c** (both in the tarball) — no extra
  work. `__tests__/kernel-grammar-parity.test.ts` (id-by-id ABI + node-kind +
  field-table compare) is the real gate and needs a csharp row; **no wasm
  change and no TS-side behavior change** — the production wasm stays exactly
  as shipped since #717, so this port has NO grammar-bump-first step.

## Architecture decisions

1. **preParse stays TS-side — already hoisted, port NOTHING.**
   `csharpExtractor.preParse = blankCsharpPreprocessorDirectives`
   (languages/csharp.ts:26, #237) blanks `#if/#elif/#else/#endif` directive
   LINES (both branches of the guarded code are KEPT). The route point already
   applies it for kernel calls — `preParsedSource` (kernel/index.ts:82) names
   csharp explicitly — so both arms parse identical blanked bytes and the
   deferred-file memo reuses them (`takeDeferredPreParse`, kernel/index.ts:120;
   wasm fallback `sourceIsPreParsed`, tree-sitter.ts:499). **Never port the
   regex to Rust**: it is a JS `(?m)^`-anchored replace
   (`/^([ \t]*)#[ \t]*(if|elif|else|endif)\b[^\n]*/gm`) whose `^` matches after
   `\r` (JS multiline semantics) and whose `[^\n]*` EATS the `\r` of a CRLF
   line (probed: `"…\r\n#if X\r\n…"` blanks to `"…\r\n      \n…"` — byte count
   preserved, `\r` becomes a space). Both are JS-semantics traps (the #1329
   class) that the hoist makes moot.
2. **ASP.NET repos take the DECODED path, not raw buffers.** `aspnetResolver`
   (resolution/frameworks/csharp.ts:11, `languages: ['csharp']`, registered in
   frameworks/index.ts:62) has an `extract()` hook (line 133), and
   parse-worker.ts:93-100 forces any language with an applicable framework
   `extract()` onto the decoded `extractFromSource` path. detect()
   (csharp.ts:15) fires on `.csproj` AspNetCore markers, `Program.cs`/
   `Startup.cs` shapes, or controller-source signatures — so web-app repos
   (jellyfin-class) decode per file while pure libraries (serilog,
   Newtonsoft.Json) ride the raw buffers-to-store transport. Don't chase a
   raw-path perf number on an ASP.NET repo and conclude the port is broken.
3. **The framework extractor itself needs NO port** — regex over raw source
   (§Frameworks below), runs in extractFromSource:6736-6758 after either arm.
4. **One walker module** (suggest `codegraph-kernel/src/csharp.rs`), registered
   in langs.rs; per-file `has_error()` → `defer:` like every walker. **java.rs
   is the skeleton** (§java.rs mapping below) — same namespace-node concept,
   same field/constant split, same static-member/value-ref/fn-ref chassis.
5. **`.cs` → `csharp`** at detectLanguage (grammars.ts:87), wasm filename
   `tree-sitter-c_sharp.wasm` (grammars.ts:31), vendored-set membership at
   grammars.ts:292, provenance comment at grammars.ts:252-261. No content
   sniffing, no dialects (`.cshtml`/`.razor` are language `razor`, a T3
   standalone extractor — NOT this port). MAX_FILE_SIZE (1 MiB) and
   generated-file skips are orchestrator/TS-side and shared.
6. **Deferral expectations (measured on the gate repos, post-blank = what the
   kernel sees):** serilog **5/216 = 2.31%** (raw 8.33% — the blanking hoist
   halves it), Newtonsoft.Json **31/945 = 3.28%** (raw 6.88%), jellyfin
   **1/2105 = 0.05%**. Keep the sweep default `--max-deferral 0.1` — C# needs
   NO c/cpp-style 0.5 exemption. The residual error class is grammar-inherent
   both-branches-kept damage (`#if FEATURE_DEFAULT_INTERFACE` around interface
   members in serilog's ILogger.cs; half-expression `#if HAVE_DATE_TIME_OFFSET`
   guards in Newtonsoft's JsonReader.cs) — those files error on BOTH arms and
... (743 lines truncated)
</file>

<file path="docs/design/dart-kernel-port-checklist.md">
# Dart kernel port (R7b batch 4) — the bug-for-bug checklist

**Status: SURVEY COMPLETE (2026-07-20), port not started.** Survey basis: every
TS-side branch a `.dart` file exercises, with file:line anchors as of
**`45a53eb`** (HEAD at survey time, clean main). Every extraction-behavior
claim below was **pinned against the real `dist/` extractor** (the
`extract-*.txt` ground-truth dumps in the session scratchpad `svy-dart/` —
§Probe artifacts), and every grammar-shape claim was **probed against the
production wasm** (tree-sitter-wasms 0.1.13's dart build) via full CST dumps —
not inferred from reading code. Field-presence claims come from
`fieldNameForChild` dumps corroborated by extractor behavior (the swift
lesson: dump labels alone lie — here every field claim is backed by an
extractor-output pin). Read WITH `docs/design/rust-kernel-migration-plan.md`
(§0a recipe, §2 boundary, §4 tracker, §5 gates) and the format precedents
(`kotlin-kernel-port-checklist.md` — the closest structural sibling:
visitNode-hook constants, vendored-grammar-C build; `swift-kernel-port-checklist.md`
— the shared-branch liveness style and high-deferral posture).

**Blocking findings: none — but one mechanism is NOVEL and load-bearing, and
one number is big.** (1) **The sibling-body double-walk (§The double-walk) is
the center of gravity of this port.** Dart's grammar attaches every
function/method BODY as a *next sibling* of its signature node, and the TS
walkers consume the body TWICE — once via `resolveBody` (attributed to the
function/method) and once via the enclosing generic walk (attributed to the
file/class). The result is a deterministic pattern of duplicate nodes
(local functions minted twice under different parents with the SAME id),
duplicate `instantiates`/`calls` refs, and file/class-attributed
`function_ref` twins — all of which the walker must reproduce byte-for-byte,
in exactly the observed interleave. NO previously ported walker has this
surface. (2) **Both-arm parse-error incidence is 3.4–20.7% on the gate
repos** — flutter/flutter sits at 20.73% because the grammar (2025-10) cannot
parse *empty* object patterns (`TimerInitial() =>`, the dominant sealed-class
state-matching idiom) or the unnamed `library;` directive. Run parity sweeps
with **`--max-deferral 0.3`** (swift-style exemption). 0 phantom errors were
found anywhere (3 repos + a 46-snippet battery) — unlike kotlin — but the
defer rule stays trust-the-flag. (3) The "grammar bump" for dart is a
**byte-copy of the ALREADY-SHIPPING wasm** (unpinned-dep de-risking, not a
version change), so the bump gate is trivial — expect byte-identical
everything; the only real grammar gate is kernel-grammar-parity (vendored-C
build ↔ vendored wasm table identity).

## Grammar prep (wasm byte-copy vendor + vendored-C kernel build)

dart is NOT in `VENDORED_WASM_LANGS` (grammars.ts:291-333) — production
resolves `require.resolve('tree-sitter-wasms/out/tree-sitter-dart.wasm')`
(mapping `dart: 'tree-sitter-dart.wasm'` grammars.ts:36; `.dart` → dart at
grammars.ts:108, no content sniffing, no dialects). tree-sitter-wasms 0.1.13's
dart dependency is **UNPINNED `github:UserNobody14/tree-sitter-dart`**, built
at the 0.1.13 publish (2025-10-07) — a tree-sitter-wasms update would silently
change dart's grammar, which is exactly the hazard this vendor kills.

- **Provenance (verified by the batch-4 grammar probe, re-verified here):**
  UserNobody14/tree-sitter-dart **master@`d4d8f3e337d8be23be27ffc35a0aef972343cd54`**
  (2025-10-04, "Fix `set` and `get` contextual keywords…" #89) — parser.c
  tables positionally identical to the shipped wasm (ABI **15**, STATE_COUNT
  3640, SYMBOL_COUNT 524 + ALIAS_COUNT 1, TOKEN_COUNT 161, 22 fields,
  EXTERNAL_TOKEN_COUNT 7).
- **Production wasm** sha256
  `7f5364e4256cf7e55efd01dd52421ef2663caa8061b82659b7e4bf61064545ec`
  (984,666 bytes, `node_modules/tree-sitter-wasms/out/tree-sitter-dart.wasm`).
  **Vendor plan: BYTE-COPY this file** to
  `src/extraction/wasm/tree-sitter-dart.wasm` + `VENDORED_WASM_LANGS +=
  'dart'` (R7b comment: commit sha + "wasm is the byte-copied
  tree-sitter-wasms 0.1.13 artifact; kernel compiles the same-commit vendored
  C — codegraph-kernel/grammars/dart"). No rebuild, no `tree-sitter
  generate` — the shipped bytes ARE the reference. `copy-assets` already
  globs `src/extraction/wasm/*.wasm`. MIT license.
- **External scanner: YES** — `src/scanner.c` PRESENT at the pinned commit.
  It owns 7 external tokens: the 5 string-template char classes
  (`_template_chars_*`), `_block_comment`, and
  `_documentation_block_comment` — i.e. **`/** */` doc comments are
  scanner-produced**; the vendored C must include scanner.c or every
  string/comment shape breaks.
- **Vendor file list + sha256 (recorded at survey time from the commit clone):**
  - `src/parser.c` `5a42b47abb4d494f125dbdee9138979248041689b1aa36355550fa3e28dcb8b8`
  - `src/scanner.c` `07a7b7818b175e9460523e705dd88d20f7b5141bac95c593d4426e6d52284996`
  - `src/tree_sitter/parser.h` `180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2`
  - `src/tree_sitter/alloc.h` `b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea`
  - `src/tree_sitter/array.h` `5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94`
- **crates.io `tree-sitter-dart` 0.2.0 is the nielsenko FORK — REJECTED**
  (different lineage, 480 positional table mismatches per the batch-4 probe).
  This supersedes the plan §4 long-tail row's "crates.io" route for dart. Do
  not revisit unless the TS side migrates grammars.
- **Kernel side — vendored-grammar-C (the kotlin #1382 mechanism, second
  use):** copy the three-file set above (parser.c, scanner.c, tree_sitter/*.h)
  to `codegraph-kernel/grammars/dart/`; extend `codegraph-kernel/build.rs`'s
  cc::Build to compile both C files with the grammar's own flags (its
  checked-in `bindings/rust/build.rs` uses `-Wno-unused-parameter`,
  `-Wno-unused-but-set-variable`, `-Wno-trigraphs`, msvc `-utf-8` — same set
  kotlin vendored). langs.rs:
  ```rust
  extern "C" { fn tree_sitter_dart() -> *const (); }
  // …
  "dart" => Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_dart) }.into()),
  ```
  plus `LANGUAGES` (langs.rs:24; `[&str; 15]` at survey time — sibling
  batch-4 legs are landing concurrently, take whatever count is current)
  += `"dart"`.
  `__tests__/kernel-grammar-parity.test.ts:39` `GRAMMAR_LANGUAGES += 'dart'`
  — the id-by-id ABI/kind/field-table compare against the vendored wasm is
... (983 lines truncated)
</file>

<file path="docs/design/dispatch-synthesizer-backlog.md">
# Dispatch-Synthesizer Backlog — the "dispatch-through-indirection" family

**Audience:** a Claude agent continuing the coverage mission.
**Relationship to the playbook:** this is a *cross-cutting* companion to
[`dynamic-dispatch-coverage-playbook.md`](./dynamic-dispatch-coverage-playbook.md).
The playbook's §6 matrix is organized by **language × framework**. This doc is
organized by **dispatch *shape*** — because a single framework can contain several
distinct indirection shapes (Redux alone is ≥2: hand-written thunks vs RTK Query),
and several shapes recur identically across many frameworks/languages (a name→class
registry is the same problem in trezor `connect`, n8n nodes, and a VS Code command
palette). Redux-thunk (`synthesizedBy:'redux-thunk'`) was the first member shipped;
this is the queue behind it.

Status legend (matches the playbook): ✅ done+validated · 🟡 shipped but under-validated
· 🔬 hole identified · ⬜ not started · ⛔ deliberately not built (silent beats wrong).

---

## The discipline (lessons already paid for — read before building any of these)

1. **Build against ≥2 real repos that *contain the pattern*, from the start.**
   redux-thunk was tuned on **trezor-suite alone (n=1)**. The obvious second repo,
   **shapeshift/web**, fires **0** redux-thunk edges — and that 0 is *correct*:
   shapeshift has **zero** `createAsyncThunk`/`createThunk` (it's an **RTK Query**
   codebase, 14 `createApi` files). So shapeshift could neither confirm nor refute
   generalization — it doesn't contain the shape. **A synthesizer validated on one
   repo is unvalidated.** Pick the validation repos *by grepping for the pattern
   first*, not by reputation.

2. **"One framework" ≠ "one shape."** The trezor→shapeshift split is the proof:
   - `createAsyncThunk` + thunk→thunk `dispatch(Y())` chains → **redux-thunk** ✅ (trezor)
   - `createApi` + `builder.query/mutation` endpoints → hooks/components → **RTK Query** 🔬 (shapeshift) — a *different, unbuilt* synthesizer
   - plain `dispatch(action)` → matching `reducer`/slice `case` → **slice-dispatch** ⬜
   Don't let "we did Redux" hide two-thirds of Redux.

3. **Precision is free recall's price.** redux-thunk's 0-on-shapeshift is the *good*
   kind of zero (no false edges on a non-thunk repo — same bar as the playbook's
   "0 on every non-pattern control"). Every synthesizer below must show **0 on a
   control that lacks the shape** *and* **non-zero + precise on ≥2 that have it**.

4. **Two-part master lever still governs.** An edge only helps if a *realistic
   symbol-named explore seeds a path it lies on*. A synthesizer whose far endpoint
   no normal query names buys nothing (the trezor "11 explores" tail). Prefer shapes
   where both endpoints are names an agent would actually type.

5. **Partial coverage is worse than none** (playbook §7). Close each flow
   *end-to-end* and re-measure; never ship a half-bridged flow.

---

## The backlog (prioritized by frequency × static-resolvability × query-seedability)

### Tier A — high traffic, cleanly static, build next

| Shape | Ecosystem | The static anchor that bridges it | Mechanism | Status |
|---|---|---|---|---|
| **Name→class registry / command bus** | any (TS/JS first) | object-literal registry `{key: Handler}` + computed-key dispatch `(new) reg[var](…)` | S (fan-out, `object-registry`) | ✅ **SHIPPED v1 (2026-06-20)** — `objectRegistryEdges`. Links each dispatcher fn → each registered handler's callable entry (a class's `execute`/run/handle method — preferring the method chained at the dispatch — or the function value). Precise on **xrengine** (CommandManager, 64 edges, class registry → `.execute`), **Prebid.js** (7: builder/consent/message dispatch, fn registry), **warp-drive** (1). **0 false positives** after: minified-file skip (avg line >200), **depth-aware** entry parse (top-level `key: Ident` only — method-shorthand/nested-object bodies don't leak), callable-only targets (no data `constant`), dynamic-dispatch gate. Handles constructor + field-initializer (`this.` normalized) forms. **Deferred (recall, documented):** assign-then-call (`const h=reg[k]; h()` — warp-drive's main `COMMANDS`), augmentation (`reg[k]=H` — Prebid single-entry), method-shorthand entry recall, and the **cross-file barrel-namespace** variant (trezor `getMethod`: `import * as M; M[method]→new` + computed dynamic import + camel↔Pascal — the hard tier, still 🔬). |
| **RTK Query** | TS / Redux Toolkit | `createApi({ endpoints: b => ({ getX: b.query(...) }) })` → generated `useGetXQuery` hook → component; endpoint name ↔ hook name (`getX`↔`useGetXQuery`) is convention | X (extract endpoints) + S (endpoint→hook) | ✅ **SHIPPED (2026-06-20)** — `synthesizedBy:'rtk-query'`. **X:** extraction mints a function node per endpoint (named by its key, spanning the `queryFn`/`query` handler so its calls attribute; both `endpoints: b => ({…})` arrow and `endpoints(b){ return {…} }` method forms; a factory-handler endpoint `queryFn: makeFn(url)` falls back to a bare node spanning the builder call) **and** per generated-hook binding from `export const {…} = api` (carrying the sentinel signature `= RTK Query generated hook`). **S:** `rtkQueryEdges` bridges hook→same-file endpoint by the naming convention (strip `use` + optional `Lazy` + `Query`/`Mutation`, lc head). Component→hook is normal import/call resolution; hook→endpoint surfaces in explore as `dynamic: rtk query`. Validated **100% precision** (hooks == synth edges, **0 cross-file**) on **basetool** (small, 54 edges, both forms + factory fallback), **minusx-metabase** (small, 11), **shapeshift** (large, 13); **0** on the uwave-web control (no `createApi` → a complete no-op, 0 nodes/edges added). Sentinel gate correctly ignores hand-written look-alikes (shapeshift's `useFoxyQuery` is a real custom hook, never bridged). **Deferred:** cross-module `injectEndpoints` where the hook destructuring's RHS isn't the same bare api const (synth requires same-file endpoint). |
| **Vuex / Pinia** | Vue | `store.dispatch('ns/action')` / `commit('mutation')` → action/mutation by string key (namespaced); Pinia `useStore().action()` instance call | **X (extract collections) ✅ + S (dispatch bridge) ⬜** | 🟡 **EXTRACTION FOUNDATION SHIPPED (2026-06-20)** — store actions/mutations/getters are now nodes (`codegraph_node login`/`getSessionList` works). Corpus probe found this is **NOT one clean string-keyed shape** — it's ~5: **(1)** Vuex MODULE non-exported `const actions/mutations = {…}` (element-admin), **(2)** Vuex split-file `export default {…}` + computed-key `commit(CONST)` + `mapActions` (vue2-elm), **(3)** Pinia OPTIONS `defineStore({actions:{…}})` (Geeker), **(4)** Pinia SETUP `defineStore('id',()=>{const f=…;return{f}})` body-locals (MallChat), **(5)** Pinia `useStore().action()` instance dispatch. Extraction covers **1, 3, 4** (`extractObjectLiteralFunctions` on `actions`/`mutations`/`getters` collections + a `findPiniaSetupFn`/`extractPiniaSetupBody` for setup locals; `looksLikeVueStoreFile` ≥2-signal gate + the shape gate make it a **0-node no-op on a Redux control** despite the word "actions"). Validated findable on element-admin (50 fns), Geeker (21), MallChat (68); vue2-elm form-2 + computed-key **deferred** (n=1, needs export-default dispatch + const-string resolution). **The dispatch BRIDGE synth, 2 members — BOTH ✅ SHIPPED (2026-06-20):** **(a)** Vuex string-key `dispatch('ns/action')`/`commit('M')` → action/mutation node — `synthesizedBy:'vuex-dispatch'` (`vuexDispatchEdges`): last `/` segment = action name, preceding = namespace; resolve to a function node IN A STORE FILE (the ≥2-signal `isStoreFile` gate excludes a same-named `api/` helper — `getInfo`/`login` collide), disambiguated by the immediate namespace segment in the path (handles DEEP nesting `d2admin/user/set`) or same-file for a root local `commit('M')`. Also added `export default { namespaced, actions:{…}, mutations:{…} }` extraction (the canonical Vuex module form — `extractStoreCollectionMethods` off the export_statement, store-file gated) since d2-admin needs it. **100% precision: element-admin 55 edges, vue-admin-template 12, d2-admin 63; 0 non-store targets, 0 namespace mismatches (54/54 namespaced edges route to the correct module); 0 on Redux controls (basetool/uwave — non-string `dispatch()` ignored).** `+ vuex-dispatch-synthesizer.test.ts`. **(b)** Pinia `useStore().action()` → action — ✅ **SHIPPED (2026-06-20)** `synthesizedBy:'pinia-store'` (`piniaStoreEdges`): maps each `const useXStore=defineStore(…)` factory → its file, binds `const s=useXStore()` per consumer file, links the enclosing fn (or the `.vue` component, via fallback) → the `s.method()` action node IN THE STORE'S FILE (same-store-file gate ⇒ `$patch`/built-ins/unrelated same-named methods resolve to nothing). Covers options + setup forms uniformly. **100% precision** (Geeker 41 edges, MallChat 64; 0 targets outside a store file), 0 on the Vuex-only element-admin control; surfaces as `dynamic: pinia store`; suite 1612 + `pinia-store-synthesizer.test.ts`. Corpus: `/tmp/cg-vuex-eval/{vue-element-admin,vue2-elm,Geeker-Admin,MallChatWeb}`. |
| **NgRx effects** | Angular | `createEffect(() => actions.pipe(ofType(LoginAction), …))` → effect handler; `Store.dispatch(new LoginAction())` → effect by action type/class | S (type/class-keyed) | ⬜ |

### Tier B — backend command/event/message buses (each needs its own canonical flow + ≥2 repos)

| Shape | Ecosystem | Anchor | Mechanism | Status |
|---|---|---|---|---|
| **MediatR / CQRS** | .NET | `_mediator.Send(x)`/`.Publish(x)` → the `Handle` of `IRequestHandler<X,…>`/`INotificationHandler<X>` by request type | S (type-keyed, 2-pass + arg resolution) | ✅ **SHIPPED (2026-06-20)** — `synthesizedBy:'mediatr-dispatch'` (`mediatrDispatchEdges`). Same 2-pass type-keyed shape as Spring, with a twist: **C# method nodes have NO `signature`** (csharp.ts defines no `getSignature`), so Pass 1 reads the request type from the handler **class base-list source** (`: IRequestHandler<X,…>` — first generic arg), not a param signature, and binds the class's `Handle` method. **The dominant .NET idiom is VARIABLE-passed, not inline** — eShop had **0** genuine inline `Send(new X)` (every send is `mediator.Send(command)`), so Pass 2 RESOLVES the sent type from the argument three ways within the enclosing method: inline `new X(…)`, a local `var v = new X(…)` (backward scan, wins), or a parameter/local declared `X v`. **Two precision gates:** (1) receiver must be mediator-ish (`/mediator|sender|publisher/i` — excludes MAUI `MessagingCenter.Send`, `HttpClient.Send`), (2) resolved type must be in the handler map (so eShop's same-named `CancelOrderCommand` DTO in ClientApp, which has no handler, is never bridged). Handles the `IdentifiedCommand<T,R>` wrapper (sent + handled at that layer) and void single-arg `IRequestHandler<T>`. **100% precision: jasontaylordev/CleanArchitecture (small, 9 edges, inline + param forms) + dotnet/eShop (medium, 9 edges, 0 FP, variable-passed + IdentifiedCommand + DTO-collision avoided); 0 on the Newtonsoft.Json control.** Node-stable (pure edge synth). Surfaces `dynamic: mediatr dispatch`. `+ mediatr-dispatch-synthesizer.test.ts`. **Deferred (recall):** generic `_mediator.Publish(domainEvent)` over a collection (concrete type erased at the publish site — eShop's DDD AddDomainEvent fan-out), `record`-positional or factory-built args whose type isn't a `new X`/param, the `ICommandHandler<T>` facade indirection (modular-monolith). |
| **Celery** | Python | `@shared_task`/`@app.task`/`@<app>.task`/`@task` def + `.delay()`/`.apply_async()` call → task body | S (decorator-gated name) | ✅ **SHIPPED (2026-06-20)** — `synthesizedBy:'celery-dispatch'` (`celeryDispatchEdges`). Link the enclosing fn at each `.delay(`/`.apply_async(` site → the task fn. Precision rests on the DECORATOR gate: the dispatched name must resolve to a Python `function` carrying a task decorator, read from the source lines ABOVE its `def` (the def's own startLine excludes the decorator; no `decorates` edge exists — `@shared_task` is an unresolved external import). `kind==='function'` filter drops the same-named test-method collision (`consume_file`). Canvas forms (`group(t).delay()`, `t.s()`/`.si()`) have no single identifier before `.delay` → skipped, not mis-bridged. Cross-module name collision → same-file preference else bail. **100% precision: paperless-ngx (small, `@shared_task`, 31 edges, 31/31 real), pretix (medium, `@app.task`, 63 edges across 21 tasks, 0/21 FP); 0 on the httpie control (no Celery).** Node-stable (pure edge synth, no extraction change). Surfaces as `dynamic: celery dispatch @site` via the generic fallback. `+ celery-dispatch-synthesizer.test.ts`. **Deferred (recall):** canvas dispatch, class-based `Task` subclasses, `app.send_task('dotted.name')` string dispatch, aliased imports (`import send_email as s; s.delay()`). |
| **Sidekiq** | Ruby | `W.perform_async(...)`/`.perform_in`/`.perform_at` → `W#perform`, gated on `include Sidekiq::Job`/`Worker` | S (name-keyed class→perform) | ✅ **SHIPPED (2026-06-20)** — `synthesizedBy:'sidekiq-dispatch'` (`sidekiqDispatchEdges`). Name-keyed (like Celery): link the enclosing method at each `Worker.perform_async/_in/_at(…)` site → the worker's instance `perform`. The receiver class must be a Sidekiq worker — gated by reading `include Sidekiq::Job|Worker` from the class BODY source (the mixin is an external gem module → no resolvable edge, like Celery's decorator / Spring's annotation). **Namespace disambiguation (the n>1 fix):** loomio's flat workers hid a collision bug forem exposed — 4 `SendEmailNotificationWorker`s across modules; simple-name resolution mis-targeted 7/143 edges to the wrong namespace. Fixed by resolving a namespaced ref (`Comments::SendEmailNotificationWorker`) via EXACT `getNodesByQualifiedName` first, falling back to simple-name only for a unique worker (ambiguous unqualified collision bails). ActiveJob's `perform_later`/`_now` deliberately NOT matched (different shape → ActiveJob-only app yields 0). **100% precision: loomio (medium, `Sidekiq::Worker`, 47 edges) + forem (large, both aliases — 131 `Sidekiq::Job` + 11 `Sidekiq::Worker`, 142 edges, 0 worker-FP, 0 source-FP, 0 namespace-mismatch); 0 on the jekyll control.** Node-stable. Surfaces `dynamic: sidekiq dispatch`. `+ sidekiq-dispatch-synthesizer.test.ts`. **Deferred (recall):** the superclass-chain variant (diaspora: `class Foo < Base` where only `Base` has the include — worker detection must follow `< Base`), the `Jobs.enqueue(:sym)` facade (Discourse), dispatch from non-method contexts (admin DSL blocks → no enclosing method). |
| **Spring events** | Java | `publishEvent(new XEvent(…))` → `@EventListener`/`@TransactionalEventListener`/`ApplicationListener<X>` by event type | S (type-keyed, 2-pass) | ✅ **SHIPPED (2026-06-20)** — `synthesizedBy:'spring-event'` (`springEventEdges`). Pass 1 builds `Map<eventType, listenerMethod[]>` — listeners are `@EventListener`/`@TransactionalEventListener` methods (event type = the first param type off the node `signature`, or the `@EventListener(X.class)` value form) + `class … implements ApplicationListener<X>` `onApplicationEvent` methods (name + file `ApplicationListener<` gate). Pass 2 links each `publishEvent(new XEvent(…))` site's enclosing method → every listener of XEvent. **KEY Java fact:** a method node's range INCLUDES its leading annotations (`startLine` = first `@…` line, NOT the `public void` decl), so the annotation gate scans DOWNWARD from startLine, bounded to consecutive `@`-lines (no bleed into an adjacent method). Keyed by EXACT type name, no name resolution — precision is structural (param type ↔ `new X` type). Multi-line `publishEvent(\n new X(…))` handled (`\s*` spans newlines). **100% precision: halo (medium, 1254 java, 33 edges across 24 events, 0 publisher/listener FP, all 3 listener forms + fan-out) + thombergs/code-examples (4 edges incl. the `@TransactionalEventListener` form halo lacks); 0 on the gson control (no Spring).** Node-stable (pure edge synth). Surfaces `dynamic: spring event @site`. `+ spring-event-synthesizer.test.ts`. **Deferred (recall):** `publishEvent(bareVar)` (needs the var's declared type), Spring's listener-return-value re-publish, `@DomainEvents`/`AbstractAggregateRoot.registerEvent`, generic `PayloadApplicationEvent<X>` params. |
| **Laravel events** | PHP | `event(new XEvent(...))` → each listener's `handle`, via a typed `handle(XEvent $e)` AND the `$listen` map | X+S (two registration sources) | ✅ **SHIPPED (2026-06-21)** — `synthesizedBy:'laravel-event'` (`laravelEventEdges`). Pass 1 builds `Map<eventName, handle[]>` from BOTH mechanisms (both real, both needed): **(A)** a typed listener `handle(EventType $e)` first param (read from the method decl source — PHP has no `signature`, like C#; splits a `handle(A|B $e)` UNION into two events); **(B)** the `protected $listen = [ XEvent::class => [Listener::class, …] ]` map in an EventServiceProvider — parsed from comment-stripped source (so firefly's fully-commented map on auto-discovery contributes nothing), keys/values as `::class` or string literals — which is the ONLY way to link a listener whose `handle()` is UNTYPED (koel's `PruneLibrary`). Pass 2 links each `event(new XEvent(...))` site → every handle of XEvent. **Job exclusion is free:** queued jobs dispatch via `::dispatch()`/`dispatch()` (not matched) and their `handle()` takes an injected service (never an event type) — so matching ONLY `event(new X)` excludes them by construction; no job-vs-event ambiguity. `use Dispatchable` is NOT keyed on (unreliable — koel 1/9, firefly 5/50 events use it). **100% precision: koel (small, populated `$listen` map, 9 edges incl. the untyped-handle case + a fan-out) + firefly-iii (large, pure auto-discovery / empty `$listen`, 141 edges, 0 source/target FP, 0 namespace-mismatch via use-import check, union split verified); 0 on the guzzle control.** Namespace-agnostic (`FireflyIII\` not hardcoded). Node-stable. Surfaces `dynamic: laravel event`. `+ laravel-event-synthesizer.test.ts`. **Deferred (recall):** `XEvent::dispatch()` static-trait dispatch (neither repo uses it for events — would reintroduce job ambiguity), `Event::listen(closure)`, string-literal `$listen` keys for framework events (parsed but never `event(new)`-dispatched), event simple-name collisions across namespaces (none in the corpus — add qualified disambiguation like Sidekiq if a repo needs it). |

### Tier C — frontier, ⛔ do **not** build (no static anchor; would add noise)

| Shape | Why not | 
|---|---|
| **RxJS subscribe** | observable→observer is predominantly *anonymous* closures; no name to seed (playbook ⬜, deferred) |
| **MobX / Vue-reactivity / Solid signals** | Proxy reactive runtime — the edge doesn't exist statically at all; silent beats wrong (matches vue-core deferral) |
| **Redux-Saga** | generator `yield put()` / `takeEvery(ACTION, saga*)` — generator-body dispatch, materially harder; revisit only if a real repo demands it |

### Already shipped (for context)

| Shape | `synthesizedBy` | Validated on |
|---|---|---|
| Redux thunk | `redux-thunk` | ✅ **generalizes (2026-06-20)** — precise on uwave-web (small, 5 edges), session-desktop (medium, 2), trezor (large, 211); control shapeshift (RTK Query, no thunks) = 0. Receiver-agnostic (`api.dispatch`/`thunkApi.dispatch`/`window.…dispatch` all matched). **⚠️ 2 follow-ups below.** |
| Object-literal registry | `object-registry` | ✅ **shipped (2026-06-20)** — xrengine `CommandManager` (64), Prebid.js (7), warp-drive (1); 0 false positives after 4 precision gates. |
| RTK Query | `rtk-query` | ✅ **shipped (2026-06-20)** — 100% precision (hooks == synth edges, 0 cross-file) on basetool (54), minusx-metabase (11), shapeshift (13); 0 on uwave-web control. Extraction mints endpoint + generated-hook nodes; synth bridges hook→endpoint by convention. |
| Pinia store | `pinia-store` | ✅ **shipped (2026-06-20)** — `useStore().action()` instance dispatch → action; 100% precision Geeker (41) / MallChat (64), 0 on element-admin (Vuex) control. |
| Vuex dispatch | `vuex-dispatch` | ✅ **shipped (2026-06-20)** — string `dispatch('ns/action')`/`commit('M')` → handler; 100% precision element-admin (55) / vue-admin-template (12) / d2-admin (63), 0 on Redux controls. |
| Celery | `celery-dispatch` | ✅ **shipped (2026-06-20)** — `.delay()`/`.apply_async()` → `@shared_task`/`@app.task` body; 100% precision paperless-ngx (31) / pretix (63 across 21 tasks), 0 on httpie control. Decorator-gated via source above the `def`. |
| Spring events | `spring-event` | ✅ **shipped (2026-06-20)** — `publishEvent(new XEvent)` → `@EventListener`/`@TransactionalEventListener`/`ApplicationListener<X>` by event type; 100% precision halo (33 across 24 events) / code-examples (4), 0 on gson control. Type-keyed 2-pass, no name resolution. |
| MediatR | `mediatr-dispatch` | ✅ **shipped (2026-06-20)** — `_mediator.Send(x)`/`.Publish(x)` → the `Handle` of `IRequestHandler<X>`/`INotificationHandler<X>` by request type; 100% precision jasontaylor (9) / eShop (9, variable-passed), 0 on Newtonsoft control. Type from class base-list (C# has no signature) + arg resolved inline/local/param; receiver + handler-map gates. |
| Sidekiq | `sidekiq-dispatch` | ✅ **shipped (2026-06-20)** — `W.perform_async/_in/_at(…)` → `W#perform`, gated on `include Sidekiq::Job`/`Worker`; 100% precision loomio (47) / forem (142, both aliases), 0 on jekyll control. Name-keyed; namespaced collisions disambiguated by qualified name; ActiveJob `perform_later` excluded. |
| Laravel events | `laravel-event` | ✅ **shipped (2026-06-21)** — `event(new XEvent)` → each listener's `handle`, via typed `handle(XEvent $e)` (auto-discovery, union-split) AND the `$listen` map (covers untyped handles); 100% precision koel (9, `$listen`) / firefly (141, auto-discovery), 0 on guzzle control. Jobs excluded (they use `::dispatch`). |
| C/C++ fn-pointer dispatch | `fn-pointer-dispatch` | ✅ **shipped (2026-06-22)** — FIRST C / systems-language member (#932). Keyed by **(struct type, fn-pointer field)**: a fn registered to `S.field` (positional init matched by field index, designated `.field=fn`, or `x->field=fn`) ← linked → an indirect dispatch `recv->field(…)` whose receiver resolves to `S` (param/local type, else unique-field fallback). Source-read synth (`c-fnptr-synthesizer.ts`, regex over `ctx.readFile`), NOT extraction — handles the typedef'd field (`hook_func func`) + the **field←field double-hop** (`h->func = found->fn`, the issue's `hook_demo.c` shape). Covers BOTH the command-table idiom (Shape 1) and the ops-struct/vtable idiom (Shape 2) with the same key. Validated: **git 502** (`run_builtin→cmd_*` + 7 real vtables), **redis 357** (`dictType.hashFunction`, conn vtable), **curl 478** (`Curl_cwtype.do_init→{deflate,gzip,brotli,zstd}_do_init`); **0 non-function targets** everywhere, node-stable (pure edge synth), **0 on lua** (its `{name,fn}` tables register into the VM — no C indirect call → correctly nothing to bridge). **⬆️ EXTENDED (2026-06-26, #991) — macro-built command tables (the deferred item below, now shipped):** redis dispatches every command via `c->cmd->proc(c)` but `redisCommand.proc` had **0** registrations because the table is generated into a `#include`-d `.def` that is never indexed, the `proc` arg is buried inside a `MAKE_CMD(…)` macro call, the struct type is itself an object-macro alias (`#define COMMAND_STRUCT redisCommand`), the `proc` field uses a function-TYPE typedef (`typedef void redisCommandProc(client*)` + `redisCommandProc *proc`, not the `(*name)` form), and the receiver is a chained field access. Five composable additions close it: **(1)** function-type typedefs flag `T *f` fields as fn pointers; **(2)** multi-declarator fields (`struct redisCommand *cmd, *last`) each count as a slot/type — needed both for positional alignment and the chain walk; **(3)** `#include "x"` directives are followed (from RAW source) so a non-indexed `.def` is read as a registration unit **with the includer's macros in scope**; **(4)** function-like macro calls are expanded (params→args) and object-like macros resolve the struct-type token, before positional/designated registration; **(5)** a chained/array receiver (`c->cmd->proc`) resolves through field types across structs (a name can be reused — redis has two unrelated `client` structs — so all same-named layouts are searched); a macro that expands to a whole brace-wrapped struct element (sqlite `FUNCTION(…)`) gets one outer brace layer peeled; and a file's effective macro env folds in its #included headers (sqlite's `FUNCTION` is defined in `sqliteInt.h`, the table in `func.c`). Validated on **two independent macro-table lineages**: **redis** — 209 commands via `redisCommand.proc`, 100% `*Command` targets, 0 garbage (`call`→every command, the issue's ask) + `getkeys_proc` as a bonus; **sqlite** — `FUNCTION(name,…,impl)` builtin table, 69 `FuncDef.xSFunc` targets (`valueFromFunction`→`absFunc`/…), header-defined macro + brace-wrapped element. **No regression on the controls** — git (`run_builtin→cmd_*`, 138 builtins, 0 non-`cmd_*`), curl (`Curl_cftype.*` filters), **0 on lua**; **0 non-function targets across all five**. `+` 3 synthetic fixtures (`c-fnptr-synthesizer.test.ts`). **⬆️⬆️ FURTHER EXTENDED (2026-06-26, #991) — conditional-compilation tables (vim, the deferred item below now shipped):** vim's `:ex` and normal-mode command tables are defined INLINE with the struct, behind `#ifdef DO_DECLARE_EXCMD`/`DO_DECLARE_NVCMD` switched on by the includer (`ex_docmd.c`/`normal.c`), built by a macro the same file **conditionally redefines** (`EXCMD`/`NVCMD` = the table element under the switch, the bare enum id otherwise), and dispatched by a parenthesized array subscript through a **file-scope** table (`(cmdnames[i].cmd_func)(&ea)`). Four more composable additions: **(6)** a focused `#ifdef`/`#ifndef`/`#if defined`/`#else`/`#elif`/`#endif` evaluator drops the inactive arms (an unevaluable `#if EXPR` keeps its body) so the active table + the right macro arm survive — and an indexed header is **re-scanned in an includer's context** only when that includer `#define`s a switch the header guards (so the include's conditionals resolve against the includer's defined set, and the include's own macros are re-read from the resolved text — the plain last-wins parse picks the enum arm); **(7)** inline `struct TAG {…} var[] = {…}` tables whose struct never became a node are parsed in place and registered; **(8)** array-subscript receivers (`tbl[i].f`) strip the subscript and resolve the base via a **global-var → struct-type** map; **(9)** an optional `)` before the call covers the parenthesized `(…​.f)(args)` form. Validated **vim** — 273 `:ex` commands (`do_one_cmd`→every command) + 67 normal-mode commands (`nv_cmd.cmd_func`), 0 non-function, **0 cross-table misroute** (registering BOTH tables is what stops `normal_cmd`'s `nv_cmds[i].cmd_func` from falling back to the `cmdname` owner of the shared field name `cmd_func`); controls unchanged at 0 non-function (redis/sqlite/git/curl up in coverage from array/global dispatch, lua still 0); `+` a 4th fixture. **⬆️⬆️⬆️ FURTHER EXTENDED (2026-06-26, #991) — bare arrays of function pointers (the deferred item below now shipped):** a fn-pointer dispatch with NO struct and NO field — an array whose ELEMENT type is a function typedef (`opcode_t *opcodes[256]`, a fn-TYPE typedef element where the `*` makes it an array of pointers; or `zend_rc_dtor_func_t t[]`, a fn-pointer typedef element, **including a calling-convention macro before the `*`** — `typedef void (ZEND_FASTCALL *t)(…)`), initialized with literal fn entries (positional `fn`/`&fn`, designated by index `[IDX]=fn`, or cast-wrapped `(cast)fn`), and dispatched `tbl[i](…)` or the explicit-deref `(*tbl[i])(…)`. **Keyed by the array VARIABLE name** (a new `arrayReg`, separate from the `(struct,field)` `reg`); targets are the literal entries and fan-out is the whole set (a runtime subscript reaches every handler, like a command table). **Same-file table wins on a name collision** — SameBoy declares two file-local `static opcode_t *opcodes[256]` (CPU + disassembler); the same-file gate stops them crossing (0 cross-file leak — the n>1 collision discipline again). Three additions: **(10)** the fn-pointer typedef/field regexes allow a CC/attr macro before the `*` (`(ZEND_FASTCALL *name)`) — also hardens the existing struct-field path; **(11)** `ELEMTYPE [*]name[…]={…}` array-table detection, gated on the element type being in the fn-typedef sets (a data/struct array's element type never is, so it never fires); **(12)** a `tbl[i](…)`/`(*tbl[i])(…)` dispatch regex, fired only when `tbl ∈ arrayReg` (the precision anchor). Validated on **two independent lineages**: **SameBoy** (GB emulator) — 147 edges via `opcodes[]` (`GB_cpu_run`→73 + `GB_cpu_disassemble`→74 opcode handlers, each resolving same-file), 0 non-fn; **php-src** (Zend runtime) — 54 edges across 7 tables (`zend_binary_ops`, `filters`, `zend_rc_dtor_func`, `fn_chain`, …), the designated+cast+CC-macro form, 0 non-fn, precision spot-checked (each is a real `tbl[i](…)`). **Control: lua 0** — its `lua_CFunction searchers[]` is pushed into the VM (`lua_pushcclosure(L, searchers[i], 1)`), never C-dispatched as `searchers[i](…)`, so the call-gate correctly fires nothing (the precision proof: a registered-but-not-called fn-ptr array yields no edge). **No regression** — redis (835) / sqlite (683) struct.field counts byte-identical, git **+3** / curl **+20** legitimate new bare-array edges (curl's `mstate`→`state_enter[state](data,oldstate)` machine, option setters), vim 433 unchanged with all three #991 guards holding (`do_one_cmd→ex_quit` TRUE, `normal_cmd→ex_quit` FALSE, `normal_cmd→nv_addsub` TRUE); **0 non-function targets across all**. `+` 4 fixtures (opcode-table positional, Zend designated+cast+CC-typedef, same-name file-local collision, searchers control). **Deferred (recall):** direct fn-pointer *variables* (`fp=f; fp()` — not field-keyed; mutable by nature → the data-flow frontier, deliberately uncovered), C++ *class* fn-pointer fields (virtual dispatch already covered by `interface-impl`/`cpp-override`), and `##` token-paste handler names (php `zif_##name`, busybox `name##_main` — also blocked upstream by those handlers not being plain extracted nodes). |
| (see playbook §6 / `callback-synthesizer.ts` for the other ~20 channels) | | |

### redux-thunk follow-ups (found by the n>1 validation — this is exactly what it's for)

1. **Precision: name-collision target resolution — ✅ FIXED (2026-06-20).** `reduxThunkEdges`
   resolved the dispatched name via `getNodesByName(name).find(kind ∈ {constant,function,
... (75 lines truncated)
</file>

<file path="docs/design/dynamic-dispatch-coverage-playbook.md">
# Dynamic-Dispatch Coverage Playbook

**Audience:** a Claude agent continuing this work.
**Mission:** systematically close static-extraction coverage holes for **dynamic
dispatch** across **every language and framework codegraph supports**, and validate
each one the same way, so cross-symbol *flows* exist in the graph everywhere.

> This is the top-level playbook. The deep design for one mechanism (the callback
> synthesizer) is in [`callback-edge-synthesis.md`](./callback-edge-synthesis.md).
> The cross-cutting **dispatch-shape** queue (Redux/RTK Query/NgRx/MediatR/registries —
> organized by indirection shape, not language×framework) is in
> [`dispatch-synthesizer-backlog.md`](./dispatch-synthesizer-backlog.md).
> Full investigation context + findings: auto-memory `project_codegraph_read_displacement`.

> **Update (2026-06-01):** the `codegraph_trace` and `codegraph_context` MCP tools were
> **removed** — `codegraph_explore` is the single surfacing tool now. Its "Flow" section
> (`buildFlowFromNamedSymbols`) surfaces the synthesized edges this playbook is about, and
> you validate coverage with `codegraph_explore` / `scripts/agent-eval/probe-explore.mjs`.
> Where the text below writes `trace(a, b)` or lists `trace`/`context` among the tools,
> read it as "the a→b flow, now surfaced and verified via explore." The synthesizers and
> the coverage matrix are unchanged.

---

## 1. The goal (why this matters)

codegraph's value is being **the map** — answering structural/flow questions
(`trace`, `impact`, callers, "how does X reach Y") that grep/Read cannot. Agents
will use codegraph instead of Read **only when it is sufficient**. We proved
empirically (see memory) that the lever for sufficiency is **coverage**, not
prompting/hooks/new-tools: when a flow is missing from the graph, the agent reads
the files to reconstruct it; when the flow *is* in the graph, the agent can answer
completely without reading.

**Validated end-to-end on excalidraw:** after closing the update-flow hole, 2/3
headless agent runs answered the "how does an update reach the screen" question with
**Read 0 and a complete answer** — impossible before, because the key edge wasn't in
the graph. (Caveat: coverage *enables* the no-read path; agent confirm-by-reading
variance means it doesn't *force* it. Completeness improves unconditionally.)

The mission is to make that true for **all** languages/frameworks.

---

## 2. The problem class: dynamic dispatch

Static tree-sitter extraction captures explicit calls (`foo()`, `this.bar()`). It
**misses** any call whose target is computed/indirect. Four recurring shapes, with a
**difficulty gradient** (do the cheap ones first):

| # | Shape | Example | Fix mechanism | Cost |
|---|---|---|---|---|
| 1 | **Named attribute / descriptor** | django `self._iterable_class(self)` | framework resolver (`claimsReference` + `resolve()`) | **cheap** |
| 2 | **Field-backed observer** | `onUpdate(cb)` + `for(cb of cbs)cb()` | callback synthesizer (whole-graph pass) | medium |
| 3 | **String-keyed EventEmitter** | `on('e',fn)` / `emit('e')` | callback synthesizer (event-keyed) | medium |
| 4 | **Inline callback handler** | `on('e', function h(){})` / `() => {}` | extraction (named) + synthesizer link-through-body (anon) | named: cheap · anon: hard |
| 5 | **Closure-collection dispatch** | Swift `validators.write{$0.append(v)}` … `validators.forEach{$0()}` | callback synthesizer (`closureCollectionEdges`, element-invoke gated) | medium |

Key distinction driving the mechanism choice:
- **A named ref exists** to resolve (`_iterable_class` is an attribute name) → **resolver**.
- **No ref exists** (`cb()` is anonymous; needs registrar↔dispatcher correlation) → **synthesizer**.

---

## 3. Worked examples (the two mechanisms, end to end)

### 3a. Django ORM descriptor — the **resolver** pattern (Python)
- **Hole:** `QuerySet._fetch_all` calls `self._iterable_class(self)` (a runtime-chosen
  iterable, default `ModelIterable`), whose `__iter__` runs the SQL compiler. Static
  parsing can't resolve the attribute-as-callable → `_fetch_all`'s only callee was
  `_prefetch_related_objects`; `trace(_fetch_all, execute_sql)` returned no path.
- **Fix:** `djangoResolver` claims the unresolved `_iterable_class` ref through the
  name-exists pre-filter, then resolves it to `ModelIterable.__iter__`.
- **Files:** `src/resolution/types.ts` (`claimsReference?` on `FrameworkResolver`),
  `src/resolution/index.ts` (pre-filter in `resolveOne` consults `claimsReference`),
  `src/resolution/frameworks/python.ts` (`djangoResolver.resolve` + `claimsReference` +
  `resolveModelIterableIter`).
- **Result:** `trace(_fetch_all, execute_sql)` → `_fetch_all → __iter__ → execute_sql` (3 hops).

### 3b. Excalidraw observer + EventEmitter — the **synthesizer** (TS)
- **Hole:** `Scene.triggerUpdate` does `for (cb of this.callbacks) cb()`; `triggerRender`
  is registered via `scene.onUpdate(this.triggerRender)`. The `triggerUpdate →
  triggerRender` edge is dynamic → `trace` returned no path; the whole update flow broke.
- **Fix:** a whole-graph pass that detects registrar/dispatcher channels, correlates
  registration sites, and synthesizes `dispatcher → callback` edges. Plus extraction of
  **named** inline callbacks so handlers like express's `function onmount(){}` are nodes.
- **Files:** `src/resolution/callback-synthesizer.ts` (the pass — field observers +
  EventEmitter), `src/resolution/index.ts` (calls `synthesizeCallbackEdges()` at the end
  of `resolveAndPersistBatched`), `src/extraction/tree-sitter.ts` (`visitFunctionBody`
  extracts named nested functions).
- **Result:** `trace(mutateElement, triggerRender)` → 3 hops; express `use → onmount`.

### 3c. Alamofire deferred validation — closure-collection dispatch (Swift)
- **Hole:** `DataRequest.validate(_:)` builds a closure and `validators.write { $0.append(validator) }`;
  the base `Request.didCompleteTask` runs them via `validators.forEach { $0() }`. Append and
  dispatch live in *different files and classes* (a subclass appends, the base iterates) and the
  field is a Swift `Protected<[@Sendable () -> Void]>` — so neither same-file pairing nor the
  name-based registrar match (`onX`/`subscribe`/…) reaches it. `trace(didCompleteTask, validate)`
  returned no path; the agent grepped `validators` and read three files to reconstruct it.
- **Fix:** `closureCollectionEdges` (callback-synthesizer.ts). A **dispatcher** iterates a collection
... (589 lines truncated)
</file>

<file path="docs/design/explore-budget-allocation.md">
# Explore budget allocation — the instrument and the baseline

`codegraph_explore` has a fixed byte envelope (`getExploreOutputBudget().maxOutputChars`,
hard-capped at 25K so the host never externalizes the result). **How that envelope gets
divided among files** is decided by a long chain of gates, tiers and caps spread across
`handleExplore` — and until CG-4 that chain was unobservable. You could read an explore
response and guess; you could not say "this file took 16% and that one took 20%."

This document covers the diagnostic that makes it measurable, and the baseline it recorded.

## The diagnostic

Set `CODEGRAPH_EXPLORE_DEBUG` and every `codegraph_explore` call (MCP tool or
`codegraph explore` CLI) emits one report:

| value | sink |
|---|---|
| `1` / `true` / `on` / `yes` / `stderr` | human-readable table on stderr |
| `json` | one pretty-printed JSON report on stderr |
| anything else | treated as a path — one JSON report per line, appended (JSONL) |
| unset / `0` / `false` / `off` / `no` / empty | **off** |

Per file it reports: relevance score, graph (RWR) mass, distinct query-term hits, ranking
flags (named / entry / central / spine / low-value / generated), render mode, bytes of
source allocated, bytes actually delivered, both shares, and whether it was clipped. For
files that never rendered it reports why (`max-files`, `budget-90pct`, `budget-whole-file`,
`budget-clusters`, `unreadable`, `no-ranges`). Totals cover the envelope (delivered vs
allocated vs `maxOutputChars` vs hard ceiling), the source/meta split, the file-selection
funnel at each stage, and the thresholds applied (score floor, graph-relevance gate).

**It is off by default and produces byte-identical output when off** — it ships in the
product binary, and a diagnostic that perturbs the response by one byte would invalidate
every A/B measurement taken with it on. `ExploreDiagnostics.start()` returns `null` unless
the env var is set, so every call site is a `diag?.` no-op. Pinned by
`__tests__/explore-diagnostics.test.ts`.

Two envelope numbers, deliberately kept separate:

- **allocated** — what the render loop chose to emit, before the final hard-ceiling cut.
  This is the allocator's own decision, and the number budget work is about.
- **delivered** — what the agent actually received.

They diverge exactly when the ceiling truncates. Conflating them is how a dropped trailing
file goes unnoticed.

## Baseline (2026-08-03, this repo at `main`)

```
codegraph explore "how does explore allocate its output budget across files" --path .
```

469 files indexed → small tier (`maxOutputChars` 18,000, `maxCharsPerFile` 3,800,
`defaultMaxFiles` 5). Envelope: **23,196 delivered / 23,193 allocated against an 18,000
budget — 29% over**, absorbed only because the 25K hard ceiling sits above it.

| # | share | bytes | score | graph | hits | flags | render | file |
|---|---|---|---|---|---|---|---|---|
| 4 | 21.2% | 4,928 | 10 | 0.125 | 1 | entry | whole | `scripts/agent-eval/offload-eval-hook.mjs` |
| 5 | 20.1% | 4,665 | 10 | 0.125 | 1 | entry | whole | `scripts/agent-eval/offload-eval-metrics.mjs` |
| 3 | 19.8% | 4,585 | 22 | 0.125 | 1 | entry central | whole | `scripts/agent-eval/parse-session.mjs` |
| 1 | **15.8%** | 3,659 | **54** | **0.322** | **4** | entry central | clusters* | `src/mcp/tools.ts` |
| 2 | 15.0% | 3,479 | 34 | 0.082 | 2 | entry | clusters* | `src/index.ts` |

\* clipped. Ranked but never rendered: `scripts/agent-eval/offload-eval-cost.mjs` (#6) and
`src/resolution/lru-cache.ts` (#7), both cut by `maxFiles`.

Files: 17 grouped → 10 past the score floor (≥3) → 10 past the low-value filter → 7 past
the relevance gate (graph ≥ 0.0193, 6% of max 0.3215) → 5 in the output.

### What the baseline shows

**Score does not drive allocation.** `src/mcp/tools.ts` — the file that actually answers
the query — carries 5.4× the relevance score, 2.6× the graph mass and 4× the term hits of
any `.mjs` script, and gets a *smaller* share than each of them. The three agent-eval
scripts take **61%** of the envelope between them; the answer file takes 16%.

The mechanism is that the two allocation paths are decided by **file size, not relevance**:
a small file clears `WHOLE_FILE_MAX_LINES`/`WHOLE_FILE_MAX_CHARS` and ships entirely, while
a large file falls through to cluster selection and is clipped at `maxCharsPerFile`. So a
weakly-relevant 130-line script gets 100% of itself; the strongly-relevant 5,000-line file
gets 3,800 chars. Rank ordering is correct (tools.ts sorts #1) and buys nothing, because
rank has no effect on how many bytes a file receives.

**The envelope is over-subscribed.** 23,193 allocated against an 18,000 budget means the
per-file caps do not compose into the total cap; the total is enforced only by the 25K
ceiling silently dropping whole trailing sections. Under a slightly different index state
(one more candidate file) the same query allocated 27,518 chars and the ceiling dropped a
7,678-char section — the single largest allocation in the response — with the only trace
being the truncation notice at the end.

This is the gap the rest of the epic closes: relevance-proportional allocation with a
relative cliff (CG-12), on top of scoring that stops rewarding incidental name collisions
(CG-10 — landed; see below).

## CG-10 — relevance scoring

CG-10 changes **what gets into the response**, ahead of how bytes are split among what's
in. Four levers, all multiplicative so they compose without ordering surprises.

### 1. Kind weighting
... (985 lines truncated)
</file>

<file path="docs/design/explore-session-dedup.md">
# Cross-call explore session state

`codegraph_explore` answers every call as if it were the first one. It has no idea what it
already sent this session, so a 4th call happily re-serves the spine the 1st call already
delivered (the #1500 report: 4 calls on a 2-call tier budget), and the tier's call budget
can only be *asked* for in prose the agent ignores.

This document covers the state layer that fixes the "no idea" part — `src/mcp/explore-session-state.ts`
(CG-17) — and the first thing built on it, cross-call source dedup
(`src/mcp/explore-dedup.ts`, CG-18). Budget decay past the tier budget (CG-19) is the
other consumer.

## What is recorded

One `ExploreSessionState` per MCP session. Inside it, per **resolved project root**:

- `callCount` / `responseBytes` — every explore call served this session for that project;
- `calls[]` — the recent ones in detail: query, per-file emitted **line ranges**, a content
  **fingerprint** for the bytes those ranges were sliced from, source bytes, response bytes,
  and the call's 1-based session index.

Ranges come from the render loop itself — `buildSection` returns the spans it slices
alongside the text, and the whole-file / focused / skeleton paths report theirs at the
point they push source into the response. A separate function mirroring the window and
padding rules would drift, and drift here is not symmetric: see *Which way to be wrong*.

Only files that **survive the final hard-ceiling truncation** are recorded. A section the
ceiling dropped was never delivered. A back-referenced file records its spans at **zero
bytes**: the record means "source the agent HOLDS for this file", not "bytes this call
spent", so re-recording keeps a long session from ageing a pointed-at span out of the
retained window and re-serving it for nothing.

## Four constraints, and what each one rules out

| Constraint | Why | What it rules out |
|---|---|---|
| Per session, never persisted | A new agent has seen nothing | A disk cache keyed by project |
| Per **resolved** project root | One session can query several projects by `projectPath` | Keying on the path the agent typed — `/repo` and `/repo/internal` are one project |
| Bounded memory | Sessions can run for hours | Unbounded `calls[]` growth |
| Daemon-safe | One daemon shares ONE `ToolHandler` and a pool of worker threads across every connected client | State on the handler, in a worker, or in a module-level singleton |

The daemon constraint is the sharp one. State kept on the shared `ToolHandler` would blend
two agents' histories, and a dedup built on that would withhold source from an agent that
never saw it — which costs a Read, the exact failure this area exists to prevent. So the
state lives on `MCPSession`, and the plumbing is:

```
MCPSession (owns the state)
  └─ ToolHandler.execute(tool, args, sessionState)
       ├─ down: session view attached to args    (survives structured clone → worker)
       └─ up:   emission attached to the result  (survives structured clone ← worker)
            └─ recorded on the MAIN thread, then DELETED from the result
```

Both legs travel as plain properties (`_cgExploreSession`, `_cgExploreEmission`) because
either may cross a worker boundary, where a closure or a handler field could not follow.
The emission is stripped in `execute` **unconditionally** — including for callers that
track nothing, like the CLI — so the agent-facing response is byte-identical. A view a
client spells itself is discarded, not trusted: it decides what a later call may withhold.

## The bounds

`EXPLORE_SESSION_LIMITS`: 4 projects (LRU), 8 retained calls per project, 24 files per
call, 24 ranges per file, 4 calls in the view handed to a call.

Every bound caps **detail**. `callCount` and `responseBytes` keep counting past eviction —
decay (CG-19) reads the count, and a bound that reset it would make decay reset itself
every 8 calls.

## Which way to be wrong

Where a bound forces a choice, the record keeps **fewer** ranges than were emitted, never
more:

- under-report → a later call re-serves something the agent already has. Wasteful.
- over-report → a later call withholds source the agent never saw. The agent Reads the
  file, and one Read costs more than every byte the dedup saved.

So `coalesceRanges` drops the smallest spans when it hits the cap (and flags
`rangesTruncated`), invalid spans are discarded rather than clamped, and truncated file
sections are never recorded.

## Inspecting it

The CG-4 diagnostic (`CODEGRAPH_EXPLORE_DEBUG`, see
[explore-budget-allocation.md](./explore-budget-allocation.md)) carries a `session` block
on every report:

```
  session call #2 for this project · 1 prior call · 18,204 chars already served
    already served internal/usecase/payroll_cycle.go · 4,928 chars · L1-159
```

`callIndex` is this call's position in the session; `priorFiles` unions the ranges already
served per file, most-recent call first. The block is **absent** — not zeroed — when the
caller tracks no state, which is how "untracked" and "first call of a tracked session" stay
distinguishable.

---

... (119 lines truncated)
</file>

<file path="docs/design/framework-coverage.md">
# Framework & language coverage — what is done, what is left

**Last verified: 2026-08-29** (Angular row: 2026-09-29) against the build at that date. Re-verify with the
queries in [Checking this file is still true](#checking-this-file-is-still-true)
before trusting a row; this is a snapshot, not a live view.

This file exists to be read cold. It says, for every framework and language the
README claims, **which of the three pictures it can draw today** and what is
missing from the ones it cannot — so a fresh session can pick up the next piece
without re-deriving the map.

---

## The three axes

A framework's support is not one thing. Three separate facts in the graph
unlock three different pictures, and a framework can have any subset:

| Fact in the graph | Unlocks | Produced by |
|---|---|---|
| **`route` nodes** bound to a handler or component | the **Entry points** tab; an endpoint or page can be a Steps anchor | a framework resolver's `extract()` |
| **`navigates` edges** from the code that sends a user somewhere to the route it names | the **Screens** tab — without a single one, `buildScreens` returns `routed: false` and the tab stays hidden | a resolver's `resolve()` (calls) + a synthesizer (markup) |
| **branch-guard rules** for the language | the `WHEN` label on every arrow, in Steps, Screens and `codegraph_explore`'s Flow section | `src/graph/branch-guards.ts` |

The Screens picture is a pure function of the first two: *any* framework that
produces route nodes and `navigates` edges lands on the tab, with no view code
to write. That is why "add a router" is a small, self-contained job.

---

## Routers — routes AND navigation (done)

Seven. Each reads a literal destination and leaves a computed one, a path no
route serves, and a conditional whose arms disagree unresolved rather than
guessed.

| Router | Resolver | Markup synthesizer | Tests | Validated on |
|---|---|---|---|---|
| Expo Router | `frameworks/expo-router.ts` | `expo-router-synthesizer.ts` | `expo-router.test.ts` | — |
| Next.js | `frameworks/nextjs.ts` | `next-router-synthesizer.ts` | `nextjs.test.ts` | next-saas-starter |
| React Router | `frameworks/react-router.ts` | `react-router-synthesizer.ts` | `react-router.test.ts` | proshop (44 edges), proshop-v2 (28), react-redux-realworld (22), react-boilerplate (`styled(Link)`), takenote (v5 `<Redirect>`), bulletproof-react (nested `children`, `lazy` routes, `paths.x.path` constants through an app's own tsconfig alias: 0 → 9 named, linked routes), and its `paths.x.getHref(id)` links and `navigate(paths.x.getHref())` calls (0 → 11 navigates) |
| TanStack Router | `frameworks/tanstack-router.ts` | `tanstack-router-synthesizer.ts` | `tanstack-router.test.ts` | TanStack examples, fastapi-template frontend |
| Vue Router / Nuxt | `frameworks/vue-router.ts` (Nuxt file routes: `nuxtResolver` in `frameworks/vue.ts`) | `vue-router-synthesizer.ts` | `vue-router.test.ts` | vue-realworld (23 edges); vue-element-admin (62 routes), vue-admin-template (14), vben (192), halo console (34) — named tables, module files, `children` + layouts; Nuxt: mealie, elk, nuxt/movies |
| SvelteKit | `frameworks/sveltekit-router.ts` | `sveltekit-synthesizer.ts` | `sveltekit-router.test.ts`, `sveltekit-route-names.test.ts` | sveltekit-realworld (31 edges); shadcn-svelte and skeleton (`(group)` layouts: 13 and 23 edges), svelte.dev (74), kit's test apps (47) |
| Angular | `frameworks/angular-router.ts` | `angular-template-synthesizer.ts` | `angular-router.test.ts` | angular-realworld (31 edges, 18 renders), Ghostfolio (189 edges, 170 renders), ngx-admin (routes and renders; its menus are config), angular-spotify (Nx libs behind barrels: 14 routes), jira-clone (class-constant paths, mount-only redirects), jhipster (60), ionic-conference (18), Angular-JumpStart (18) |

Shared machinery all seven use, in `frameworks/expo-router.ts`: `RouteTable` /
`RootedRouteTable`, `routesForFile`, `addRouteTo`, `matchRoute`, `appRootFor`,
`parseHrefExpression`, `readHrefViaLocal`, `nthArgumentText`, `readStringAt`,
`toHref`. Plus `pageForHref` in `frameworks/nextjs.ts` (framework-agnostic
despite where it lives) and the object-literal walker in
`frameworks/object-literal.ts`.

Angular is the one whose markup is not indexed: a component's template is a
`templateUrl` file (or an inline `template:` string) read at synthesis time,
which also yields the component tree (`<app-foo>` by element selector) — the
edge a navigation in a child component rides to its screen. A `routerLink:`
field written in a component's class (a tab bar's or a menu's config, bound
in a loop elsewhere) counts as a link from that component. An event binding
(`(click)="save()"`) is a `calls` edge from the component to its own method
carrying `metadata.trigger`, which Steps uses in place of reading a trigger
at the edge's line (the binding is in the template, not the source there). A route with
`children` is a layout: its component carries a `references` edge marked
`layout: true` from each screen nested in it, and `routeLayouts` in
`route-roots.ts` gives Screens every screen a layout serves. Known limits: a
route with a custom `matcher` has no static address, a relative navigation
(`relativeTo`) is left unresolved, and an edit to a template file alone is
picked up at the next sync of any source file (templates are not watched).

---

## What is left

Ordered by cost-to-value. Each row says what is missing, not merely that
something is.

### 1. Astro — the last web framework with routes but no navigation

**Has:** `src/pages/` file routes (`.astro` pages + `.ts` endpoints,
`[param]`/`[...rest]`), in `frameworks/astro.ts`.
**Missing:** `navigates` edges. Astro is an MPA — navigation is a plain
`<a href="/about">`, plus `Astro.redirect('/x')` in frontmatter and
`redirect` entries in `astro.config`.
**Size:** smallest job on this list. `sveltekit-synthesizer.ts`'s
`svelteKitLinkEdges` is the same pass over the same tag against a different
table; the resolver half is one `Astro.redirect` reader.
**Validate on:** any `withastro/astro` example, or the Astro docs site.

### 2. Server-rendered frameworks — a redirect is a transition, not just a response

**Fourteen frameworks** have route nodes and no navigation: Django, Flask,
FastAPI, Express, NestJS, Laravel, Drupal, Rails, Spring, Play, Gin/chi/gorilla,
Axum/actix/Rocket, ASP.NET, Vapor.

Be precise about what is missing. `redirect_to`, `HttpResponseRedirect`,
`res.redirect`, PHP's `redirect()` are **already recognised as `response`
effects** (`ui-server/api/effects.ts`), so they draw as a box in the Steps
picture. What is missing is the edge to the page they name — so two pages never
connect on the Screens tab.

... (175 lines truncated)
</file>

<file path="docs/design/function-ref-capture.md">
# Function-as-value capture (#756) — registration-linking for callbacks

**Problem.** A function used as a *value* — passed as an argument, assigned to a
function pointer or field, placed in a struct initializer or handler table —
produced **no edge** in any of the 19 tree-sitter languages (probed 2026-06-11;
0/19). `callers(my_recv_cb)` on a C callback showed nothing but direct calls, so
every registered callback looked dead, and the registration sites — the agent's
actual next question ("where is this wired up?") — were invisible.

**Non-goal, deliberate.** Resolving the *dispatch* (`o->cb(x)` → the concrete
registered function) needs data-flow through struct fields; even an LSP needs
fallbacks there (see the #756 thread). Partial coverage is worse than none and
a wrong edge is worse than silence — dispatch resolution stays uncovered. What
ships is the *registration* side, which is deterministic: the function's name
is literally in the source at the registration site.

## Mechanism

```
capture (tree-sitter.ts walkers, table-driven per language: src/extraction/function-ref.ts)
   → gate (flushFnRefCandidates: same-file fn/method name ∪ imported binding names;
            C-family file-scope initializers skip the gate — see below)
   → unresolved ref, referenceKind 'function_ref' (internal-only kind)
   → resolution (resolveOne branch: resolveViaImport first, then matchFunctionRef —
                 exact name, function/method kinds only, same-family, same-file first,
                 cross-file only when UNIQUE, never fuzzy)
   → edge kind 'references', metadata { fnRef: true, resolvedBy, confidence }
```

`getCallers`/`getCallees`/`getImpactRadius` already traverse `references`, so
registration sites surface with no graph-layer changes. The MCP callers/callees
lists label them "via callback registration".

Capture fires from three walkers (a node is only ever visited by one):
`visitNode` (file/class scope), `visitForCallsAndStructure` (function bodies),
`visitPascalBlock` (Pascal bodies). Subtrees the walkers consume without
descending (top-level variable initializers, class field/property initializers,
custom `visitNode` hooks like Scala's val/var handler) get a candidates-only
`scanFnRefSubtree` that halts at nested function boundaries.

## Per-language value positions (probe-verified)

| Language | arg | assign RHS | keyed init | list/table | wrapper forms |
|---|---|---|---|---|---|
| C / ObjC | `argument_list` | `assignment_expression.right` | `initializer_pair.value` | `initializer_list`, `init_declarator.value` | `&fn` (`pointer_expression`), `@selector(...)` (ObjC) |
| C++ | **`&` forms only** in args/rhs/varinit | (same — explicit `&` only) | bare ids at FILE scope only | bare ids at FILE scope only | `&fn`, `&Cls::method` (resolved scoped to the class) |
| TS / JS (tsx/jsx) | `arguments` | `assignment_expression.right` | `pair.value` | `array`, `variable_declarator.value` | `this.method` (`member_expression`, class-scoped — see rule 3) |
| Python | `argument_list`, `keyword_argument.value`, `return_statement` (#1478 — single expression only; tuple returns not descended) | `assignment.right` | `pair.value` | `list` | `self.method` (`attribute`) |
| Go | `argument_list` | `assignment_statement` / `short_var_declaration` (`expression_list`) | `keyed_element` | `literal_value`, `var_spec.value` | — |
| Rust | `arguments` | `assignment_expression.right` | `field_initializer.value` | `array_expression`, `static_item` / `let_declaration.value` | — |
| Java | `argument_list` | `assignment_expression.right` | — | `variable_declarator.value` | `method_reference` (`Cls::m`, `this::m`) — the only form |
| Kotlin | `value_arguments` | `assignment` (last child) | — | — | `callable_reference` (`::f`), `navigation_expression` `this::m` |
| C# | `argument_list` (`argument`) | `assignment_expression.right` (incl. `+=`) | — | `initializer_expression`, `variable_declarator` | `this.M` (`member_access_expression`; vendored grammar keeps `this` anonymous — handled) |
| Ruby | `argument_list` | — | `pair.value` | — | only `method(:sym)` / `&method(:sym)` — bare ids are calls/locals in Ruby |
| Swift | `value_arguments` (`value_argument.value`) | `assignment.result` | (labeled ctor args = args) | `array_literal`, `property_declaration.value` | `#selector(...)` |
| Scala | `arguments` | `assignment_expression.right` | — | `val_definition.value` (via hook scan) | eta `fn _` (`postfix_expression`) |
| Dart | `arguments` (`argument`) | `assignment_expression.right` | `pair.value` | `list_literal`, `static_final_declaration` | — |
| Lua / Luau | `arguments` | `assignment_statement` (`expression_list.value`) | `field.value` (keyed + positional) | (same) | — |
| Pascal | `exprArgs` (via `visitPascalBlock`) | `assignment.rhs` (`OnFire := Handler`) | — | — | `@Handler` (`exprUnary.operand`) |
| PHP | string callables ONLY as args of known core HOFs (`usort`, `array_map`, `call_user_func*`… — `PHP_CALLABLE_HOFS`), ungated + unique-or-drop (PHP globals aren't imported) | — | — | — | `[$this, 'm']` → class-scoped `this.m`; `[Foo::class, 'm']` → qualified; `'Cls::m'` → qualified; first-class callable `fn(...)` already extracts as `calls` |
| Ruby hooks | `(skip_)?(before\|after\|around)_*` + `validate`/`set_callback`/`helper_method`/`rescue_from(with:)` symbols → class-scoped `this.<sym>` (rides the supertype pass: `before_action :authenticate` → ApplicationController). `validates` (plural) excluded — its symbols are ATTRIBUTES | — | — | — | symbols under any other call yield nothing |

## Precision rules (each one bought by a real-repo false positive)

1. **The gate** (extraction-time): a candidate survives only if its name matches
   a same-file function/method or an **imported binding** (`referenceKind ===
   'imports'` only — scraping type-annotation `references` names let locals that
   shared a type-member's name through; excalidraw).
2. **C-family ungated file scope**: C has no symbol imports and registers
   callbacks cross-file at repo scale (redis `server.c`'s command table names
   handlers from `t_*.c`). File-scope initializer positions (`value`/`list`
   modes) skip the gate — safe because a C file-scope initializer is a
   **constant-expression context**: a bare identifier there can only be a
   function address (enum/macro names get dropped by the kind filter). Local
   initializers and assignments stay gated: `prev = next`, `*str = field`,
   `arena_ind_prev = arena_ind` (redis/jemalloc) each matched a unique
   same-named function somewhere and produced wrong edges when `rhs`/`varinit`
   were ungated.
3. **TS/JS/Python: bare ids resolve to `function` kind only — plus `class`
   for Python (#1478).** A bare identifier can never be a method value in
   these languages (methods need a receiver — `this.m` / `self.m`), so
   allowing method targets soaked up locals passed as arguments
   (`new Set(selectedPointsIndices)`; docopt.py's `name`/`match` params —
   excalidraw/fmt A/B findings). Python bare ids ALSO accept CLASS targets:
   class-as-value is a core Python idiom (`return SomeSerializer`, registry
   dicts, `admin.site.register(Model, Admin)`) with no type-annotation
   recovery path, the gate additionally admits same-file CLASS names for
   Python, and the docopt false-positive mechanism (lowercase locals vs
   same-named methods) doesn't transfer to exact-name class matches. TS/JS
   keep the class exclusion (the KIND FILTER contract).
   TS/JS `this.X` values are captured as `this.`-PREFIXED candidates and
   resolved CLASS-SCOPED (`resolveThisMemberFnRef` in
   `src/resolution/index.ts`): the target must be a function/method whose
   qualified name shares the from-symbol's class prefix, same file, no
   fallback of any kind — `addEventListener(…, this.onResize)` hits the
   enclosing class's method; `this.fonts` (a property, post-#808 field
   classification) and inherited/unknown members yield no edge. Python's
   `self.m` form keeps method targets through its own capture shape.
   C#/Swift/Dart/Java/Kotlin keep method targets (method groups,
   implicit-self, method references are real method values).
... (134 lines truncated)
</file>

<file path="docs/design/generated-file-detection.md">
# Generated-file detection — path convention plus content banner

CG-5, issue #1500. Companion to `explore-budget-allocation.md` (CG-4's instrument) and a
prerequisite for the scoring overhaul (CG-10).

## The problem

`isGeneratedFile` was path-only. It matches the `<basename>.<tool>.<ext>` convention —
`.pb.go`, `_grpc.pb.go`, `.g.dart`, `_pb2.py` — which is where most codegen output lives,
and which was enough for the cosmos-sdk audit that motivated it.

It is not enough for Go. **Go's convention is a content marker, not a filename one:**

```go
// Code generated by <tool>. DO NOT EDIT.
```

codified by `go generate`, honored by gofmt, golangci-lint and GitHub linguist, and emitted
by protoc-gen-go, mockgen, sqlc, ent, wire, stringer — and by in-house generators. #1500 is
exactly this: a Go monorepo with generated FKIT CRUD in ordinarily-named files
(`payroll.go`) sitting beside hand-written workflow use-cases. Nothing in the path gives it
away, so every generated-file down-rank in the codebase was a no-op on it.

### How large the gap is

Measured on a shallow clone of `kubernetes/client-go` (2,453 Go files):

| signal | files flagged |
|---|---|
| ground truth (grep the canonical banner in the first 60 lines) | 2,001 |
| path convention (`isGeneratedFile`) | **0** |
| content banner (`hasGeneratedHeader`) | **2,001** — 0 false positives, 0 misses |

82% of that repository is generated code with ordinary filenames, and the path check saw
none of it. This is not a long-tail case.

## Design

**Decide at index time, store on the file record, read from the DB.** Explore must never
read file headers per request.

- `isGeneratedFile(path)` — unchanged. Path-only, pure, synchronous, free to call in a sort
  comparator. Kept for callers with no database in hand.
- `hasGeneratedHeader(content)` — the content signal (below).
- `detectGeneratedFile(path, content)` — the union, which is what the indexer persists.
- `files.generated INTEGER NOT NULL DEFAULT 0` (schema v9) + a **partial** index
  `idx_files_generated ON files(path) WHERE generated = 1`, so lookups cost the generated
  minority, not the repo.
- `QueryBuilder.generatedPredicateFor(paths)` / `CodeGraph.generatedFilePredicate(paths)` —
  one bounded probe up front, `O(1)` per comparison after, unioned with the path check.

### Why a bounded lookup and not a cached set

Every consumer already holds a short candidate list — a ranked file group, an FTS result
page, a `LIMIT 20` aggregate. Intersecting that list against the partial index needs no
whole-repo set to materialize and, more importantly, **no cache to invalidate**: a ranking
call can never serve a verdict the last sync already replaced. The alternative (a lazily
materialized `Set` of all generated paths) has to be invalidated on every file write and
goes stale on the read-only pool workers, in exchange for saving a sub-millisecond query.

### Precision over recall

A false positive silently demotes hand-written code in every ranking path, so the marker
table is precision-first and the scan is fenced three ways:

1. **Header window only** — first 8,192 chars / 60 lines. Generous enough for build tags
   plus an Apache-2.0 preamble above the banner; tight enough that a generator's own source,
   which holds the banner as a *string constant in its body*, is not flagged.
2. **Comment lines only** — the marker must sit on a line with a comment leader (`//`, `#`,
   `--`, `<!--`, `%`, `;`, `'`, …) or inside an open block comment (`/* */`, `<!-- -->`,
   `"""`, `'''`, `=begin`, `<# #>`), tracked with a small state machine over the window.
   Generators always emit banners as comments; requiring it rules out identifiers and
   string literals that merely contain the words.
3. **Tight markers** — `automatically generated` alone is prose ("the table is automatically
   generated at runtime"); `automatically generated **by**` is a banner. `DO NOT EDIT` alone
   is a style directive; paired with a generation claim it is a banner.

The module deliberately keeps its own quoted banner literals **below** the header window so
it does not classify itself; `generated-detection.test.ts` pins that, so moving the pattern
table upward fails a test rather than silently demoting this file.

### Migration: no backfill, by necessity

v9 is DDL only. The flag derives from file **content**, which the migration cannot see —
`files` stores a hash, not bytes. Migrated rows stay 0 until a re-index, and because every
reader unions the flag with the path check, an un-backfilled database keeps exactly the
pre-#1500 behavior instead of regressing. `sync` heals it file-by-file as files change.
This is why the CHANGELOG entry says a re-index is required.

## Cost

The acceptance bar was "no measurable index-time cost regression."

A single unanchored `/generat/i` test over the header rejects ~every hand-written file
before any line splitting happens. `String.prototype.slice` on a long string yields a V8
sliced view, not a copy, so the fast path allocates nothing.

- **Microbenchmark** (`detectGeneratedFile` over a whole corpus, 5 passes):
  4.6 µs/file on client-go (2,453 files, 14.2 MB, 82% generated — the worst case, where the
  gate passes and the full line scan runs), 7.3 µs/file on this repo's `src`.
... (24 lines truncated)
</file>

<file path="docs/design/kotlin-kernel-port-checklist.md">
# Kotlin kernel port (R7b) — the bug-for-bug checklist

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/kotlin.rs`
+ the vendored-grammar-C build (codegraph-kernel/grammars/kotlin via build.rs
cc — the mechanism's first use), all gates passed (bump dumps byte-identical
old-vs-new ×3 as predicted; parity sweeps 0-diff okio 299/322 / okhttp
531/580 / kotlinx.coroutines 1031/1082 with exactly the predicted 23/49/51
deferrals; kernel-arm dumps byte-identical ×3; KMP expect/actual synthesis
IDENTICAL — 412 edges both arms; kernel-kotlin-parity suite; DEFAULT_ROUTED
+= kotlin — 15 languages). One fixture note: the survey's torture.kt itself
tripped the PHANTOM-error class (one-line class/object bodies) and deferred —
the checked-in parity fixture reflows those to multi-line, and the phantom
shape is pinned in the defer test instead. Survey basis: every
TS-side branch a `.kt`/`.kts` file exercises, with file:line anchors as of
**`a6c62d7`** (HEAD at survey time, clean main). Every grammar-shape claim below
was **probed against both the production tree-sitter-wasms build and a fresh
fwcd 0.3.8 tag build** (probe scripts + dumps in the session scratchpad
`svy-kotlin/` — see §Probe artifacts), and every extraction-behavior claim was
**pinned against the real `dist/` extractor** (`extract-*.txt` ground-truth
dumps), not derived from code reading alone. Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §2 boundary, §4
tracker row "kotlin", §5 gates) and the format precedents
(`rust-lang-kernel-port-checklist.md`, `ruby-kernel-port-checklist.md`,
`php-kernel-port-checklist.md`, `csharp-kernel-port-checklist.md`).

**Blocking findings: none — but two eyes-open items, one of them a NOVEL
mechanism.** (1) The grammar bump is **behavior-neutral** (rust-style gate:
byte-identical CSTs on all 1,984 gate-repo files, 0 error disagreements) —
**but the crates.io crate `tree-sitter-kotlin = 0.3.8` is UNUSABLE by the
kernel** (it pins `tree-sitter >= 0.21, < 0.23`; the kernel links 0.25), and
the successor crate `tree-sitter-kotlin-ng` is a **different grammar** (8
fields vs 0, 289 vs 357 symbols, renamed kinds — would break every kotlin.ts
branch). The port must take the **vendored-grammar-C route**: compile the
sha-matched 0.3.8 `parser.c`+`scanner.c` inside `codegraph-kernel` via
build.rs — the FIRST language to exercise the mechanism the §4 tracker
prescribes for vendored grammars (§Grammar prep). (2) **Both-arm parse-error
incidence is 4.7–8.5%** on the gate repos (fun-interface misparses, phantom
single-line-class-body errors, soft-keyword identifiers, `call().prop = x`
LHS shapes — all grammar-inherent, all identical across arms). The default
`--max-deferral 0.1` HOLDS but with only ~1.2–2× headroom (okhttp 8.45%) —
expect double-digit deferral COUNTS on kotlin sweeps and don't misread them
as walker bugs (§Architecture decisions #6).

## Grammar prep (behavior-neutral re-vendor + the vendored-C kernel build)

kotlin is NOT in `VENDORED_WASM_LANGS` (grammars.ts:291-317) — production
loads `node_modules/tree-sitter-wasms/out/tree-sitter-kotlin.wasm`
(mapping `kotlin: 'tree-sitter-kotlin.wasm'` at grammars.ts:35;
tree-sitter-wasms 0.1.13 builds it from npm `tree-sitter-kotlin` **^0.3.1**,
the fwcd lineage; production wasm sha256 `b5cb00c8…`, 4,052,705 bytes, ABI 14).

- **Lineage decision (investigated, not assumed):** two crates exist.
  - `tree-sitter-kotlin` **0.3.8** (crates.io max_stable, published
    2024-08-03; repo fwcd/tree-sitter-kotlin — OUR wasm's lineage; repo still
    active but no crate release since). Tag `0.3.8` (annotated tag `9e7e624` →
    commit `e1a2d5ad1f61f5740677183cd4125bb071cd2f30`); sha256-verified
    crate-tarball ↔ tag, BOTH generated artifacts (kotlin HAS an external
    scanner):
    - `src/parser.c` `54104a7ef1555c265b746c790e0f8bb953cc17806e9df0c3af82f7f62c06a70a`
    - `src/scanner.c` `27f73337ec357fc341fa57538f34c14277b0346980c3405dc30beab6202ec6d0`
  - `tree-sitter-kotlin-ng` 1.1.0 (tree-sitter-grammars org, 2025-01) —
    **REJECTED**: a different grammar, not a re-publish (STATE_COUNT 11432 vs
    10155, SYMBOL_COUNT 289 vs 357, **FIELD_COUNT 8 vs 0**, kinds renamed —
    `additive_expression`→`binary_expression`, `call_suffix` gone,
    `binding_pattern_kind` gone…). Adopting it is an extractor REWRITE, not a
    port. Do not revisit until/unless the TS side migrates grammars.
- **The 0.3.8 build is behavior-IDENTICAL to the production wasm** (this bump
  is a reproducibility re-vendor, csharp-flavored, not a version change):
  kind/field tables identical (360 node types, 134 named kinds, 0 fields,
  ABI 14 both — `table-compare.cjs`); the 258-line torture file's full CST dump
  is byte-identical OLD↔NEW; and the gate-repo sweep (`error-sweep.cjs
  <repo> --sexp`) found **0 error disagreements and 0 s-expression mismatches
  on every clean file across all three repos**. Expect the standalone bump
  gate's old-vs-new full-init dump diff to be **byte-identical on all three**
  (rust-style "expect zero", NOT php's enumerate+classify).
- **ABI note:** the 0.3.8 tag's checked-in parser.c declares
  `LANGUAGE_VERSION 14` — content parity, ABI stays 14 (ruby precedent).
  kernel-grammar-parity must assert same-revision, not an ABI change.
- **FIELD_COUNT 0 is load-bearing for the whole port**: every
  `childForFieldName`/`getChildByField` lookup in the kotlin path returns
  null, which is what makes several TS hooks dead code (§Extractor config).
  The walker must reproduce the null-field world exactly — do NOT "helpfully"
  use -ng-style fields that don't exist here.
- **Wasm build (from the tag's CHECKED-IN parser.c — never `tree-sitter
  generate`):**
  ```
  git clone --depth 1 --branch 0.3.8 https://github.com/fwcd/tree-sitter-kotlin
  cd tree-sitter-kotlin
  # the 0.3.8 tag predates tree-sitter.json, which cli 0.25.10 requires —
  # add the METADATA-ONLY shim (grammar name/scope; nothing regenerated):
  #   {"grammars":[{"name":"kotlin","scope":"source.kotlin","path":".",
  #     "file-types":["kt","kts"]}],"metadata":{"version":"0.3.8","license":"MIT"}}
  npx -y tree-sitter-cli@0.25.10 build --wasm -o tree-sitter-kotlin.wasm .
  ```
  (brew emcc present; survey artifact sha256
  `c80c88867a589a1a0959bcea89de84b7e9684b3693b2cdb2944812458e62ff48`,
  4,052,313 bytes, at scratchpad `svy-kotlin/tree-sitter-kotlin-NEW.wasm`.
  Do NOT use tree-sitter-cli 0.24 — it drops `\p{...}` classes, the #1164
  vbnet lesson, and this grammar's identifiers use them.)
- **Kernel side — the NOVEL part (crate pin impossible):** the 0.3.8 crate's
... (1042 lines truncated)
</file>

<file path="docs/design/lua-luau-kernel-port-checklist.md">
# Lua + Luau kernel port (R7b batch 4) — the bug-for-bug checklist

**Status: SURVEY COMPLETE (2026-07-20)** — one combined checklist for BOTH
languages: `languages/luau.ts` is 36 lines extending `languages/lua.ts`, the two
grammars share their node-name vocabulary, and the recommendation is ONE walker
module (`codegraph-kernel/src/lua.rs`, ccpp-style language-parameterized —
`"lua" | "luau" => lua::extract(&file_path, &content, &language)` in
lib.rs:214-226). Survey basis: every TS-side branch a `.lua`/`.luau` file
exercises, with file:line anchors as of **`45a53eb`** (HEAD at survey time,
clean main). Every grammar-shape claim was **probed against the production
vendored wasms** (`dist/extraction/wasm/tree-sitter-{lua,luau}.wasm`) via CST
dumps and childForFieldName truth tables, and every extraction-behavior claim
was **pinned against the real `dist/` extractor** (`extract-*.txt` ground-truth
dumps in the session scratchpad `svy-lua/` — §Probe artifacts), not derived
from code reading alone. Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §2 boundary, §4
tracker, §5 gates) and the format precedents
(`kotlin-kernel-port-checklist.md` — the depth bar — plus
`swift-kernel-port-checklist.md`, `ruby-kernel-port-checklist.md`).

**Blocking findings: none.** Three eyes-open items. (1) **No grammar bump at
all** — both languages are already in `VENDORED_WASM_LANGS` (grammars.ts:292)
and the vendored wasms are the exact port-target revisions
(`../scratchpad/batch4-grammar-probe.md`, verified 2026-07-20: lua = the
v0.4.1 tag, table-identical; luau = crate 1.2.0, table-identical). The port is
kernel-side only: lua takes the **vendored-grammar-C route** (kotlin
mechanism, second use) because v0.4.1 is not on crates.io; luau is a plain
**crate pin `tree-sitter-luau = "=1.2.0"`** (csharp-style), and the crate
tarball's parser.c/scanner.c are **sha-identical to the v1.2.0 tag**
(§Grammar prep — the swift tag≠crate divergence does NOT recur here). (2)
**Error incidence is near-zero for lua** (kong 0.08% — a single deliberately
invalid fixture; lazy.nvim and lua-resty-core 0.00%) — ruby-style: **any
deferral on a lua sweep is a walker-bug signal**. Luau real-world incidence is
**1.4–7.1%** (lune 1.36%, Fusion 7.08%), driven by two grammar-inherent
shapes — generic type packs `(A...) -> T` and default type parameters
`<T = D>` — both-arm by construction (same grammar revision on both arms).
(3) The single biggest bug-for-bug surface is the **require/`visitNode`-hook
machinery** and its **asymmetries**: requires at top level (anywhere visitNode
reaches, including inside top-level `if`/`for`/`while` blocks) become `import`
nodes, while the IDENTICAL statement inside a function body emits a
**`calls "require"` ref** (visitFunctionBody never runs the hook); a top-level
`local x = foo()` initializer emits **no** calls ref while a top-level global
assignment `x = foo()` **does** (§extractVariable). Get these exactly wrong
and sweeps light up on file one.

## Grammar prep (kernel-side only — no wasm change, no bump gate)

Both languages already ship vendored wasms (`VENDORED_WASM_LANGS`,
grammars.ts:291-293; file map `lua: 'tree-sitter-lua.wasm'` /
`luau: 'tree-sitter-luau.wasm'` at grammars.ts:39,41; the :255 comment
records WHY lua was vendored — tree-sitter-wasms' ABI-13 build corrupted the
shared WASM heap). Provenance was verified in the batch-4 grammar probe
(`../scratchpad/batch4-grammar-probe.md`) and re-verified in this survey:

- **lua** — vendored wasm ≡ **tree-sitter-grammars/tree-sitter-lua v0.4.1**,
  tag commit `816840c592ab973500ae9750763c707b447e7fef` (release asset
  table-identical, 0 positional mismatches). Tag parser.c declares
  **ABI 15, STATE_COUNT 262, SYMBOL_COUNT 137, FIELD_COUNT 22** (verified in
  the tag clone — matches the wasm's tables). **v0.4.1 is NOT on crates.io**
  (only 0.1/0.2/0.5 exist) → **vendored-grammar-C route**, the kotlin
  mechanism (`codegraph-kernel/grammars/kotlin` + build.rs cc precedent).
  0.5.0 adds Lua-5.5 `global` (+1 field) — a future accuracy bump, NOT this
  batch.
- **luau** — vendored wasm ≡ **tree-sitter-grammars/tree-sitter-luau v1.2.0
  ≡ crates.io crate 1.2.0**. Survey-verified sha match, tag ↔ crate tarball
  (the swift lesson checked and CLEAR):
  - `src/parser.c` `8f25bc1779400fa93d5492310e291fb895363ec051d44753444e724e99a08250` (both)
  - `src/scanner.c` `a157bb5210454add058a08ce53eabcccad41aab6dac7006def2554e5cfebd376` (both)
  Tag commit `a8914d6c1fc5131f8e1c13f769fa704c9f5eb02f`. parser.c declares
  **ABI 14, STATE_COUNT 585, SYMBOL_COUNT 197, FIELD_COUNT 21**. Crate deps:
  `tree-sitter-language = "0.1"` + `cc` build-dep, `tree-sitter` only as a
  dev-dep (0.26.3) → **no pin conflict** with the kernel's tree-sitter 0.25.
  Route: **`tree-sitter-luau = "=1.2.0"`** in codegraph-kernel/Cargo.toml,
  `"luau" => Some(tree_sitter_luau::LANGUAGE.into())` in langs.rs.
- **Lua kernel C vendor** (`codegraph-kernel/grammars/lua/`), from the v0.4.1
  tag's CHECKED-IN generated artifacts (lua HAS an external scanner — comments
  and long strings):
  - `src/parser.c`  `b34a362e43f0311f405721f3089e94f97f31da403b154d456d093e64609a4081`
  - `src/scanner.c` `35bbd630b5a7421d46d2e91185eeea09bf78565d44cb676b63ca20d0f1b54bbd`
  - `src/tree_sitter/alloc.h`  `b29c1c9fb7cc82f58c84b376df1297d6e2737a1d655fd356db0859e3c29c2fea`
  - `src/tree_sitter/array.h`  `5bdf6ed1a78e3409fd443e085ca967a64c188a5d082aaf7f819bccd53a471c94`
  - `src/tree_sitter/parser.h` `180b893c8734778fd32f372dfbc27bd6ad1cd2221f26150b31256ff6716320d2`
  build.rs: extend the kotlin block — `cc::Build` with
  `include("grammars/lua")`, `file(parser.c)`, `file(scanner.c)`; crib the
  tag's own `bindings/rust/build.rs` flags (`.std("c11")`, include src, msvc
  `-utf-8`); `println!("cargo:rerun-if-changed=grammars/lua")`. langs.rs:
  `extern "C" { fn tree_sitter_lua() -> *const (); }` +
  `"lua" => Some(unsafe { tree_sitter_language::LanguageFn::from_raw(tree_sitter_lua) }.into())`
  (kotlin precedent, langs.rs:17-20,57). `LANGUAGES: [&str; 15]` → **17**
  (langs.rs:24).
- **Grammar-parity rows**: `__tests__/kernel-grammar-parity.test.ts:39`
  `GRAMMAR_LANGUAGES += 'lua', 'luau'` — asserts the C build / crate and the
  vendored wasm are the same revision (id-by-id kind+field tables, ABI 15 for
  lua / ABI 14 for luau). This replaces the bump gate entirely: there is no
  old-vs-new dump-diff because nothing wasm-side changes.
- **Error incidence** (current wasm, all files ≤1MiB, `error-sweep.cjs`):

  | Repo | lang | files | hasError | phantoms | first-error classes |
  |---|---|---|---|---|---|
  | Kong/kong | lua | 1,309 | 1 (0.08%) | 0 | `spec/fixtures/invalid-module.lua` — deliberately invalid |
... (645 lines truncated)
</file>

<file path="docs/design/main-thread-stall-followup.md">
# Main-thread stall budget — extraction & resolution follow-up

**Status: IMPLEMENTED** (same branch as the #1212 tail fix — attribution runs
promoted "suspects" to proven culprits fast enough to justify shipping
together). What landed, per suspect:

- **Post-index maintenance — the proven killer, not on the original suspect
  list.** The first full kernel `init` on the FIXED tail completed every
  synthesis pass (cFnPtr alone ran 433s at default heap, yielding throughout)
  and was then SIGKILLed by the default-window watchdog at
  `db.runMaintenance()`: `PRAGMA optimize` + `wal_checkpoint(PASSIVE)` over a
  4.2GB DB with a 593MB WAL is minutes of synchronous IO on 2 cores.
  `runMaintenance` now runs on a worker thread with its own connection
  (checkpointing from a second connection is standard; `PRAGMA optimize`
  persists stats in sqlite_stat tables), with a bounded in-line fallback that
  skips the checkpoint (close() checkpoints after the CLI disarms the
  watchdog).
- **Per-file store commits:** `storeExtractionResult` chunks its node/edge/ref
  inserts (2,000 rows) with time-budgeted yields between; the ordered-commit
  pump serializes async stores on a promise chain (preserving the #1015
  file-order determinism invariant) and its backpressure now also waits on the
  commit chain so the parse buffer stays bounded.
- **Resolver warm-up:** `warmCachesYielding` streams the DISTINCT name set
  with yields (the sync `warmCaches` stays for non-async callers). The 28.2s
  `sync` stall dropped to ≤4s total across the whole sync.
- **Resolution batch-tail:** edge inserts and keyed deletes run in 1,000-row
  sub-transactions with yields between (crash semantics unchanged — the batch
  was already several transactions, and #1187's sweep re-resolves leftovers).
- **Scan:** attributed (phase timings now in the code, `[phase-timing]` on
  `CODEGRAPH_SYNTH_TIMINGS`) — it is the synchronous git enumeration
  (`getGitVisibleFiles`/`collectGitFiles`), NOT a hash loop. See "Accepted
  residuals" below for why it was left synchronous.

**Verification:** full-graph parity (every node id + edge, sorted dump diff)
byte-identical on fresh redis and vim indexes, baseline vs fixed; full test
suite green; kernel `sync` worst stall 28.2s → ~4s; ES synthesis tail worst
stall ≤2.7s.

**Acceptance gate PASSED:** fresh full kernel `init` (70,129 indexed files,
2,048,673 nodes / 6,402,391 edges) completed in **27m 8s** on the 2-core/6GB
container at Node's default heap with the default 60s watchdog — `EXIT 0`,
identical node/edge counts to the pre-fix partial runs, maintenance 48.8s
off-thread with the WAL fully checkpointed (0 bytes). v1.3.0 could not finish
this repo at all (OOM at default heap; watchdog kill at the maintenance step
even with the tail fixed). Post-run, the one genuine synchronous span the run
exposed — the merged synthesized-edge insert (~275k rows, 20.2s in one
transaction) — was chunked (2k rows + yield) like the rest; redis parity
re-verified byte-identical after.

## Accepted residuals (measured, documented, deliberately not fixed)

- **Git enumeration (scan): 2.2–10.5s** single sync span on ~95k-file repos.
  Fixing it means async-ifying `collectGitFiles`' recursive gitlink/submodule
  logic (#1038/#1065) or forking sync/async variants — high regression risk
  for a CPU-bound span ~6× under the watchdog window even on a 2-core
  container (its cost does not get the Windows/Defender per-file-IO
  multiplier; it scales with CPU only).
- **End-of-sync aggregates: ~2.7s** (count recompute / vocab backfill on a
  4.2GB DB).
- **Warm-up first chunk: ~2.6s** — the DISTINCT name scan's initial sort
  chunk before the first cursor row arrives; the rest of the scan yields.
- **Worker-contention timer lag on tiny containers** — with 2 cpuset cores,
  the off-thread checkpoint (and the parse pool early in the run) can delay
  main-loop timers 15–20s even though the main thread executes nothing. The
  stall monitor and the watchdog heartbeat both measure timer latency, so on
  a ~1-core box a long checkpoint could still starve heartbeats; if that ever
  reproduces, the mitigations are a niced worker or heartbeat-side allowance,
  not more yields.

If any of these ever shows up in a real watchdog kill, the async-refactor
shape for the scan is: thread a `MaybeYield` through `collectGitFiles`'
per-line loop and make `getGitVisibleFiles` async, keeping `scanDirectory`
(sync) on the walk fallback only.

---

*Original plan below, kept for the record.*

## Context

The #850 liveness watchdog SIGKILLs the indexer when its event loop stalls past
the window (default 60s). #1091 → #1122/#1137 → #1212 each moved the fix deeper:
per-batch yields, per-ref yields, then (with #1212) yields + streamed queries +
language gates across the entire dynamic-edge synthesis tail, which eliminated
the 14–57s single-pass stalls and the two whole-graph OOMs.

While validating #1212 with an event-loop stall monitor over *full* `init` runs
(Linux kernel, 70k indexed files / 2.05M nodes, 2-core 6GB container; and
llvm-project, 180k tracked files, macOS), the phases **before** the synthesis
tail showed recurring single stalls that nothing currently yields through:

| Run | Phase | Observed single stalls |
|---|---|---|
| kernel (2 cores) | initial scan (t+14s, t+22s) | 5.1s, 10.5s |
| kernel (2 cores) | extraction (t+980–1080s) | 3.0–3.3s |
| kernel (2 cores) | extraction→resolution boundary (t+1354s) | 8.5s |
| llvm (mac, fast) | extraction / early resolution (t+1000–1320s) | 5–14s, recurring |
| kernel (2 cores) | `codegraph sync` on the same DB (110 files) | **28.2s** (single stall) |

None of these approaches 60s on the tested hardware, and none are regressions —
... (89 lines truncated)
</file>

<file path="docs/design/mixed-ios-and-react-native-bridging.md">
# Mixed iOS + React Native Bridging — Coverage Design

**Audience:** a Claude agent (or human) continuing this work after #165 landed
pure-Objective-C support.
**Mission:** make codegraph's `trace` / `callers` / `callees` / `impact` /
flow-context calls connect end-to-end across **cross-language runtime
dispatch boundaries** that today silently break flows: **Swift ↔ Objective-C**
in mixed iOS codebases, and **JavaScript ↔ native** in React Native / Expo
apps.

> This doc is the **plan**, not the implementation. No code lands on this
> branch — only the design, the validation corpus, and the success bar.
> Coding starts on a follow-up branch per phase.

This work is the next item on the
[dynamic-dispatch coverage playbook](./dynamic-dispatch-coverage-playbook.md) §6
matrix: row "Swift × Objective-C bridging" and a new "React Native bridge"
row. Both are **resolver** patterns (named refs exist on both sides — the
bridging rule is deterministic) — not synthesizer patterns. See §3a of the
playbook for the reference Django ORM resolver.

---

## 1. Why this matters (the gap today)

After #165, codegraph indexes Swift, Objective-C, and JavaScript/TypeScript
each correctly **in isolation**. But the value is in cross-language flows —
exactly where iOS apps and React Native apps live:

- **Mixed iOS app:** `MyViewController.swift` calls `imageDownloader.download(url:completion:)`,
  which is `-[ImageDownloader downloadURL:completion:]` in `ImageDownloader.m`.
  Today: a `trace("MyViewController.viewDidLoad", "downloadURL:completion:")`
  call returns no path. The Swift callsite parses as a `call_expression` whose
  selector goes nowhere; the ObjC method exists as a node with no incoming
  edge. The agent reads both files to reconstruct the bridge.
- **React Native app:** `useEffect(() => NativeModules.Geolocation.getCurrentPosition(cb))`
  in `App.js` reaches `RCT_EXPORT_METHOD(getCurrentPosition:(RCTResponseSenderBlock)cb)`
  in `RNCGeolocation.m`. Today: the JS callsite has no outgoing edge to
  the ObjC implementation; the ObjC handler has no incoming edge from JS.
  `impact(getCurrentPosition)` (ObjC side) shows no JS callers.
- **Expo module:** `await ExpoCamera.takePictureAsync(options)` (JS) reaches
  `AsyncFunction("takePictureAsync") { ... }` in `ExpoCamera.swift` (Expo
  Modules API). Same break.

In every case **a name exists on both sides** that an agent or a name-matcher
can correlate — Swift's auto-bridged ObjC selector, `RCT_EXPORT_METHOD`'s
literal first argument, an Expo `Function("name")` literal. The fix is a
**resolver** that knows the bridging rules per channel and emits
`references` edges with `provenance:'heuristic'` and `metadata.synthesizedBy:'<channel>'`.

The playbook's load-bearing warning applies here harder than usual:

> **Partial coverage is WORSE than none.** Bridging one boundary but not the
> next reveals a hop the agent then drills + reads to finish. Always close
> the flow end-to-end and re-measure — never ship a half-bridged flow.

For mixed iOS, this means **both directions** (Swift→ObjC and ObjC→Swift) and
**all bridged kinds** (methods, properties, init/initializers, protocols)
must close before measuring. For React Native, JS→native AND
native→JS (`RCTEventEmitter`, `sendEvent`) must both close, AND on **both
the legacy bridge and TurboModules**, or apps that mix them will half-bridge.

---

## 2. The bridging mechanisms to model

Each row is a separate **dispatch channel** in the playbook's vocabulary —
each gets its own resolver (or synthesizer if no static ref exists), its own
validation, its own row in the §6 matrix.

| # | Direction | Channel | Mapping rule | Where it lives | Difficulty |
|---|---|---|---|---|---|
| 1 | Swift → ObjC | direct call, ObjC class imported via `-Bridging-Header.h` | Swift call `obj.x(y:z:)` ↔ ObjC selector `-x:z:` (literal mapping, see §3a) | resolver in `frameworks/swift-objc.ts` | medium |
| 2 | ObjC → Swift | `@objc` exposure | Swift `@objc func foo(bar:)` ↔ ObjC `-fooWithBar:` (auto-name); `@objc(custom:)` overrides | resolver in `frameworks/swift-objc.ts` | medium |
| 3 | Swift ↔ ObjC | property/getter/setter bridging | Swift `var name: String` ↔ ObjC `-name` / `-setName:` | resolver in `frameworks/swift-objc.ts` | low |
| 4 | Swift ↔ ObjC | initializer bridging | Swift `init(name:age:)` ↔ ObjC `-initWithName:age:` | resolver in `frameworks/swift-objc.ts` | low |
| 5 | Swift ↔ ObjC | protocol bridging (`@objc protocol`) | conformance edges across language | resolver in `frameworks/swift-objc.ts` | medium |
| 6 | JS → ObjC (RN legacy bridge) | `NativeModules.<Mod>.<fn>` ↔ `RCT_EXPORT_METHOD(<fn>:...)` or `RCT_REMAP_METHOD(<jsName>, <selector>:...)` | name match keyed by `RCT_EXPORT_MODULE()` literal on the ObjC side | resolver in `frameworks/react-native.ts` | medium |
| 7 | JS → Java/Kotlin (RN legacy bridge, Android) | `NativeModules.<Mod>.<fn>` ↔ `@ReactMethod` annotated method on a `ReactContextBaseJavaModule` subclass with `getName()` returning `<Mod>` | resolver — same shape as #6, JVM side | medium |
| 8 | JS ↔ native (RN TurboModules / Codegen) | `TurboModuleRegistry.get('Mod')` ↔ generated spec interface (`NativeMod` TS type) ↔ ObjC++/Kotlin impl matching the spec | resolver that reads the spec file as ground truth | hard |
| 9 | Native → JS (events) | ObjC `[self sendEventWithName:@"x" body:b]` (extending `RCTEventEmitter`) ↔ JS `new NativeEventEmitter(NativeModules.Mod).addListener('x', cb)` | EventEmitter-style synthesizer (matches existing `callback-synthesizer.ts` for in-language EventEmitter) | medium |
| 10 | JS → native (Expo modules) | JS `ExpoX.fn(args)` ↔ Swift `Function("fn") { ... }` or `AsyncFunction("fn") { ... }` inside a `Module` subclass with `Name("ExpoX")` | resolver in `frameworks/expo-modules.ts` | medium |
| 11 | JS → native (Fabric view components) | JS `<MyView prop={v}/>` ↔ ObjC/Swift `RCT_EXPORT_VIEW_PROPERTY(prop, ...)` or Codegen view spec | resolver + JSX hop (compose with existing JSX synthesizer) | hard (defer) |

The **Difficulty** column drives phasing — see §6.

### 2a. Why these are resolvers, not synthesizers

In every row, **the bridging rule is deterministic from a name**:
- Swift's `@objc` exposure is a documented automatic mapping; `@objc(custom:)`
  is an explicit override; both are statically extractable.
- `RCT_EXPORT_METHOD` takes a literal selector; `RCT_EXPORT_MODULE()` takes
  an optional literal module name (default: class name minus `RCT` prefix);
  `NativeModules.Mod.fn` is a literal-property access on a known global.
- Expo Modules `Function("name") { ... }` and `Module { Name("ExpoX"); ... }`
  are literal strings inside `Module` definitions.
- TurboModules spec interfaces are literal `Native<Name>` exports with
  `TurboModuleRegistry.get<...>('<Name>')`.

So the work is: **extract the bridging-side names → make the resolver match
... (456 lines truncated)
</file>

<file path="docs/design/native-extraction-kernel.md">
# Native extraction kernel — design + spike results

**Status:** spike validated 2026-07-16; project approved, not yet started.
**Owner context:** the last structural lever for fresh-index wall clock after the
2026-07-16 arc (#1305, #1320, #1321, #1322) exhausted Node-side scheduling.

## Why

Post-arc, the fresh-index profile on dubbo (4,402 Java files) is:
parse-loop ~4.7s, resolution ~5.5s (persist-bound), synthesis ~0.9s, total ~11.1s
vs codebase-memory-mcp v0.9.0 at 7.1s. Two levers were measured dead:

- **RAM-backed DB** (parse-loop 6.9s on a ramdisk vs 4.6–4.8s on SSD, n=2
  interleaved): fast-init `synchronous=OFF` already writes at page-cache speed.
  The parse phase is CPU-bound.
- **TreeCursor rewrite** (earlier arc): web-tree-sitter's traversal is not the
  cost; the floor is per-node JS↔WASM **marshaling** — every `node.kind`,
  `.childForFieldName`, `.text` crosses the boundary.

The only remaining parse lever is doing the walk on the native side and
crossing the boundary **once per file** instead of once per node.

## Spike (2026-07-16)

Minimal Rust binary (`tree-sitter` 0.25 + `tree-sitter-java`, TreeCursor walk
touching every node's kind/range + `name`-field text, emitting flat
`(kind_id, start, end, name_len)` rows — the extraction access pattern).
Dubbo's 4,048 `.java` files, 17MB, 3.59M AST nodes, Apple M3 Pro:

| | wall |
|---|---|
| Current pipeline parse-loop (7 wasm workers, incl. extraction + store dispatch) | 4,700ms |
| Rust parse+walk, rayon | **202ms** |
| Rust parse+walk, single thread | 1,067ms |

One native thread beats the whole 7-worker wasm pool 4.4×; at equal
parallelism the walk is ~14× faster. Even charging the kernel for the
extraction logic it must still perform, parse-loop 4.7s → ~1.0–1.5s is
realistic, putting dubbo ≈ 7.5–8s total (parity with cbm).

## Architecture

- **Crate:** `codegraph-kernel`, napi-rs, links tree-sitter's C library and
  vendored grammars natively. Input: `(filePath, content, language)`. Output:
  flat typed buffers (nodes, edges, unresolved refs) — one boundary crossing
  per file.
- **Per-language logic:** migrate extractors to tree-sitter **query files**
  (`.scm`) executed by a generic Rust emitter; bespoke TS logic that queries
  can't express (macro salvage, dialect sniffing, content-gated `.h`
  detection) stays as TS pre/post passes over the returned buffers.
- **Distribution:** prebuilt `.node` per platform through the existing
  release-bundle pipeline (same per-platform packages as the Node runtime).
  The wasm path remains as the universal fallback — same crate compiled to
  wasm keeps one implementation.
- **Rollout:** per-language, funnel languages first (TS/JS → Java → Python →
  Go). A language ships only when its equivalence gate passes.

## Equivalence gate (per language)

Byte-identity against hand-written extractors is NOT expected (bespoke logic
ports approximately). The gate is:

1. Node/edge/ref **counts** within ±0.5% on 3 real repos (small/medium/large),
   with every diff category eyeballed.
2. The retrieval invariants hold: explore-flow connects the language's
   canonical flows end-to-end (`docs/design/dynamic-dispatch-coverage-playbook.md`),
   agent A/B shows no regression per the standard methodology.
3. Fresh-index wall improves on the language's repos; no regression on a
   control repo of a non-migrated language.

## Non-goals

- Porting resolution, synthesis, frameworks, MCP, or the installer — they are
  pool-parallel and not marshal-bound. The measured native advantage there is
  ~1.4× CPU, not worth the correctness moat (2,444 tests, byte-identical
  determinism, years of invariants).
- A single static binary (distribution polish, orthogonal to speed).

## Risks

- ABI drift between vendored native grammars and the wasm fallback grammars
  (keep both built from the same grammar source revs; CI asserts).
- `.scm` expressiveness ceilings — budget for a per-language "escape hatch"
  callback in the emitter before declaring a language blocked.
- napi-rs threading vs the parse-pool: the kernel replaces the wasm workers'
  parse+extract; the pool orchestration (file-order commit, retry, recycle)
  stays in TS and drives the kernel synchronously per file.
</file>

<file path="docs/design/php-kernel-port-checklist.md">
# PHP kernel port (R7b) — the bug-for-bug checklist

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/php.rs`,
all gates passed (grammar bump validated standalone with the diff enumerated +
classified — see §Grammar-bump deltas incl. the bump-gate-found category 4 and
the ripple-proof note; parity sweeps 0-diff monolog 217/217 /
laravel-framework 3007/3008 / symfony 10726/10737 with only the predicted
broken-fixture deferrals; full-init dump gates byte-identical ×3;
kernel-php-parity suite; DEFAULT_ROUTED += php — 13 languages). Trait-use
implements refs carry filePath via the v2 REF_FLAG_FILE_PATH wire slot
(shipped with the ruby port). Survey basis:
every TS-side branch a php-routed file exercises, with file:line anchors as of
`f1ca991` (HEAD at survey time, clean main). Every grammar-shape claim below
was **probed against both the current production wasm (tree-sitter-wasms
0.1.13 build of tree-sitter-php ^0.22, ABI 14) and a fresh v0.24.2 build**
(probe scripts + dumps in the session scratchpad `svy-php/` — see §Probe
artifacts), not assumed. Read WITH `docs/design/rust-kernel-migration-plan.md`
(§0a recipe, §2 boundary, §5 gates) and the two format precedents
(`rust-lang-kernel-port-checklist.md`, `ccpp-kernel-port-checklist.md`).

**Blocking findings: none.** Two eyes-open notes, neither blocking: (1) the
grammar bump is **NOT graph-neutral** — unlike rust, the old→new wasm diff has
three known behavior-changing deltas (anonymous classes, one grouped-import
clause shape, enum-const files parsing clean), so the bump's standalone gate is
"enumerate + classify the diff", not "expect zero" (§Grammar-bump deltas); (2)
Laravel/Drupal-detected repos force the decoded path via framework `extract()`
hooks, but none of the three gate repos triggers detection, so raw-path sweeps
are representative (§Architecture decisions #2).

## Grammar prep (NOT staged — land FIRST, before any walker exists)

php is **not** in `VENDORED_WASM_LANGS` (grammars.ts:291) — production loads
`require.resolve('tree-sitter-wasms/out/tree-sitter-php.wasm')`
(grammars.ts:307-312; mapping `php: 'tree-sitter-php.wasm'` at grammars.ts:32),
a 2023-era **ABI-14** build of npm tree-sitter-php ^0.22 (sha256 `55bb617b…`,
812,594 bytes).

- **Variant: the full `php` grammar, NOT `php_only`.** Probed: the current
  wasm parses a mixed HTML+PHP file with root-level `text` / `php_tag` /
  `text_interpolation` nodes and no errors — that is the `php/` grammar of the
  two-grammar repo. The bump MUST keep this variant and the kernel walker MUST
  call **`tree_sitter_php::LANGUAGE_PHP`** (the crate also exports
  `LANGUAGE_PHP_ONLY` — wrong one; a php_only build ERRORs on any leading HTML,
  which is a routine Drupal/legacy shape).
- **Version: crate `tree-sitter-php` 0.24.2** (crates.io max_stable) = repo tag
  `v0.24.2` = commit `5b5627faaa290d89eb3d01b9bf47c3bb9e797dea`
  ("fix: publishing, 0.24.2"). sha256-matched tag ↔ crate tarball:
  - `php/src/parser.c` `59ad8e5e4fde3fe60687a488ab8420612840cc966b83739af1b3a4317ed27ec6`
  - `php/src/scanner.c` `58c92cafe4ebda509c3ad3864fa6fc0e9877bbac26e17a03d23ea2101c291ad5`
    — a thin wrapper: **the real external scanner is the SHARED
    `common/scanner.h`** (`de8eb36bc8f517ab9f3eaf82e3825d7b3e11b62e9471545f4c906100cfce0e07`),
    `#include`d by both variants. External scanner: YES (heredoc/nowdoc,
    encapsed strings, `?>`/text interleaving live there) — the crate build
    compiles it automatically; the wasm build picks it up from `src/`.
- **Build (from the tag's CHECKED-IN parser.c — never `tree-sitter generate`):**
  ```
  git clone --depth 1 --branch v0.24.2 https://github.com/tree-sitter/tree-sitter-php
  cd tree-sitter-php/php        # the variant subdir — NOT the repo root
  npx tree-sitter-cli@0.25.10 build --wasm -o tree-sitter-php.wasm .
  ```
  (brew emcc present; survey artifact: ABI 15, 1,058,082 bytes, sha256
  `6545a9a110bc878e26ed329950147e190c83da038bb17e999de646fe6c4d6c82`, left at
  scratchpad `svy-php/tree-sitter-php.wasm`.)
- **Staging plan:** vendor to `src/extraction/wasm/tree-sitter-php.wasm`, add
  `'php'` to `VENDORED_WASM_LANGS` (grammars.ts:291), pin
  `tree-sitter-php = "=0.24.2"` in codegraph-kernel/Cargo.toml (crate + wasm
  move TOGETHER), add `'php'` to `GRAMMAR_LANGUAGES` in
  `__tests__/kernel-grammar-parity.test.ts:39` and to `grammar_for` in
  `codegraph-kernel/src/langs.rs` (+ the `LANGUAGES` const). MIT license, same
  family as the other vendored grammars. `copy-assets` already globs
  `src/extraction/wasm/*.wasm`.
- **Bump lands FIRST with the full suite green and the old-vs-new full-init
  dump diff on the gate repos enumerated + classified** (see §Gates — for php
  this diff is expected NON-empty; every hunk must fall into a §Grammar-bump
  deltas category).

### Error incidence (probed, full php-routed file sets, 1 MiB skip applied)

| Repo | files | OLD (ABI-14 ^0.22) | NEW (v0.24.2) |
|---|---|---|---|
| monolog | 217 | 1 (0.46%) — `Level.php` (enum const) | **0 (0.00%)** |
| laravel/framework | 2,999 | 3 (0.10%) | **1 (0.03%)** — a deliberately-broken test fixture |
| symfony | 10,736 | 40 (0.37%) | **11 (0.10%)** — broken/8.4+ fixtures |

Both arms sit inside the ts/java/py/go norm (0–0.42%). **Deferral guard stays
at the default `--max-deferral 0.1`** — the c/cpp 0.5 exemption does NOT apply;
double-digit deferral on a php sweep means a broken walker. Old-grammar-only
failures (fixed by the bump, probed construct-by-construct): `const` inside an
enum body, property hooks (8.4), asymmetric visibility (8.4). Everything else
(8.0–8.3: enums, readonly, promotion, DNF/intersection types, first-class
callables, nullsafe, match, attributes, named args, typed class consts) parses
clean on BOTH.

## Grammar-bump deltas (old → v0.24.2), every one classified

Full-tree diff on a clean-parsing torture file = 278 lines, all accounted for:

**Behavior-changing (the bump gate must show exactly these, nothing else):**

1. **Anonymous classes get a wrapper node.** OLD: `new class … { }` puts
... (879 lines truncated)
</file>

<file path="docs/design/r-kernel-port-checklist.md">
# R kernel port (R7b batch 4) — the bug-for-bug checklist

**Status: SURVEY COMPLETE (2026-07-20)** — no walker exists yet. Survey basis:
every TS-side branch a `.R`/`.r` file exercises, with file:line anchors as of
**`45a53eb`** (HEAD at survey time, clean main). Every grammar-shape claim was
probed against the production vendored wasm
(`src/extraction/wasm/tree-sitter-r.wasm`, r-lib v1.2.0), and every
extraction-behavior claim was pinned against the real `dist/` extractor
(`extract-*.txt` ground-truth dumps in the session scratchpad `svy-r/` —
see §Probe artifacts) — not derived from code reading alone. Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §2 boundary, §4
tracker row "r", §5 gates) and the format precedents
(`kotlin-kernel-port-checklist.md`, `swift-kernel-port-checklist.md`,
`ruby-kernel-port-checklist.md`).

**Blocking findings: none — and this is the LIGHTEST-shared-surface port so
far, but the HEAVIEST hook port.** Three structural facts shape everything:

1. **R has no declaration syntax** — `languages/r.ts` (310 lines) works
   ENTIRELY through the `visitNode` hook. Every type list except
   `callTypes: ['call']` is EMPTY, so the generic dispatch ladder, extract-
   Function/Method/Class/Enum/Interface/Variable/Field/Property/Import/
   TypeAlias, `visitFunctionBody`, docstrings, decorators, inheritance,
   instantiation — the entire shared extraction machine — **never runs**.
   The walker is: file node + a faithful transcription of the hook + the
   generic `extractCall` + pre-order recursion. Nothing else.
2. **R is in NONE of the cross-cutting language sets**: not in
   `VALUE_REF_LANGS` (tree-sitter.ts:401), not in `STATIC_MEMBER_LANGS`
   (:345-347), not in `TYPE_ANNOTATION_LANGUAGES` (:5752-5754), not in
   `FN_REF_SPECS` (function-ref.ts:376-398 — no `r` key). Four whole
   machineries (value-reference edges + the shadow prune, static-member
   reads, type-annotation refs, function-as-value capture) are **dead** and
   must STAY dead — the walker needs cheap early-outs that emit exactly
   nothing.
3. **Grammar prep is csharp-style: crate pin, zero grammar change.** The
   vendored wasm IS r-lib v1.2.0 and the crates.io `tree-sitter-r = "=1.2.0"`
   tarball is sha-identical on BOTH generated artifacts (§Grammar prep). No
   bump gate, no wasm re-vendor, no C vendoring.

Error incidence on the gate repos is **~0%** (ruby-class): any deferral on an
R sweep is a walker-bug signal, not grammar reality (§Error incidence).

## Grammar prep (crate pin — NO grammar change)

r IS already in `VENDORED_WASM_LANGS` (grammars.ts:292) and maps
`r: 'tree-sitter-r.wasm'` (grammars.ts:40). `.r` → `r` at EXTENSION_MAP
(grammars.ts:113); `detectLanguage` lowercases the extension (grammars.ts:473)
so **`.R` (the dominant real-world casing) resolves identically** — probed:
`extract.cjs smoke.R` → `language=r`. No content sniffing, no dialect.
(`.Rmd`/`.qmd`/`.Rprofile` are not in EXTENSION_MAP → `unknown` → never
extracted; out of scope.)

- **Provenance (verified, batch-4 grammar probe + this survey):** the
  production wasm is **r-lib/tree-sitter-r v1.2.0** — ABI 14, 2,072 states,
  135 node types (134 symbols + 1 alias), **20 fields** — positionally
  identical to the tag's `src/parser.c`. The crates.io **`tree-sitter-r`
  1.2.0** tarball ships BOTH generated artifacts sha-identical to the tag
  (R has an external scanner):
  - `src/parser.c` `622165734714c6e81f70d99d522d78cf98915fdf2b1032f8bb33e775a0b971c0`
  - `src/scanner.c` `1209d1107616b470a4292c18d57b56b44990c39792acf7af6ccada0af563dbff`
  Crate file list: `bindings/rust/{build.rs,lib.rs}`, `grammar.js`,
  `queries/{highlights,locals,tags}.scm`, `src/{parser.c,scanner.c,
  grammar.json,node-types.json}`, `src/tree_sitter/{alloc,array,parser}.h`,
  `tree-sitter.json`, Cargo metadata.
- **Crate usability (kotlin-lesson check): USABLE.** `[dependencies]` is
  `tree-sitter-language = "0.1"` only (`tree-sitter` 0.24.7 is a DEV-dep,
  `cc` 1.1.22 a build-dep) — no pin conflict with the kernel's tree-sitter
  0.25. Port route: **`tree-sitter-r = "=1.2.0"` in codegraph-kernel's
  Cargo.toml** (csharp-style), `langs.rs` `"r" => tree_sitter_r::LANGUAGE`,
  `LANGUAGES` 15→16.
- **v1.3.0 exists and is NOT this batch** (future accuracy PR only):
  return-as-identifier (changes the `return` callee quirk's CST shape —
  §extractCall), raw-string lexing split, and the **CRLF comment-node fix**
  (v1.2.0 comment nodes INCLUDE the trailing `\r` — probed:
  `"#' roxy for cf\r"` spans cols 0-15 on a CRLF file, `cst.cjs
  crlf-crlf.R`). Extraction-invisible today (R reads no comments — §Docstrings)
  but a bump would be a behavior change on three axes; treat it like any
  grammar bump with its own gate, never fold it into the walker PR.
- **Field table (1-based, all 20):** alternative, argument, arguments, body,
  close, condition, consequence, content, default, function, lhs, name, open,
  operator, parameter, parameters, rhs, sequence, value, variable
  (`table-dump.out`). **r.ts reads 9 of them**: `function`, `arguments`,
  `value`, `name`, `operator`, `lhs`, `rhs`, `parameters`, `body` — all via
  `childForFieldName` semantics (getChildByField, tree-sitter-helpers).
  Unlike kotlin's zero-field world, R's field lookups are LIVE — the walker
  uses real field IDs.
- **Named kinds that matter** (135 total, `table-dump.out`): `program`,
  `binary_operator`, `unary_operator`, `call`, `subset` (`x[i]`), `subset2`
  (`x[[i]]`), `arguments` (three positional kind ids 97/98/99, aliased to one
  name — call/`[`/`[[` argument lists), `argument`, `function_definition`
  (covers BOTH `function(x)` and the `\(x)` lambda — probed), `parameters`,
  `parameter`, `identifier`, `string`, `string_content`, `escape_sequence`,
  `namespace_operator` (`pkg::fn`, `pkg:::fn`), `extract_operator` (`x$y`
  AND `x@y`), `braced_expression`, `parenthesized_expression`,
  `if_statement`, `for_statement`, `while_statement`, `repeat_statement`,
  `comment`, `comma`, literals (`integer`, `float`, `complex`, `true`,
  `false`, `null`, `inf`, `nan`, `na`, `dots`, `dot_dot_i`), and **`return`,
  `next`, `break` as NAMED nodes** (v1.2.0 — the source of the `calls
  "return"` quirk below).
- `__tests__/kernel-grammar-parity.test.ts:39` `GRAMMAR_LANGUAGES += 'r'` —
... (532 lines truncated)
</file>

<file path="docs/design/ruby-kernel-port-checklist.md">
# Ruby kernel port (R7b) — the bug-for-bug checklist

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/ruby.rs`,
all gates passed (grammar bump validated standalone — sinatra/jekyll dumps
byte-identical old-vs-new, rails exactly the one classified `&.!=` hunk;
parity sweeps 0-diff sinatra 147/147 / jekyll 164/164 / rails 3452/3452 with
0 deferrals; full-init dump gates byte-identical ×3; kernel-ruby-parity suite;
DEFAULT_ROUTED += ruby). **One correction to this doc found during gating
(§Misc said "refs carry NO filePath"): the visitNode hook's mixin
`implements` refs DO carry `filePath: ctx.filePath` (languages/ruby.ts:45) —
the port added a v2 ref-flag wire slot (REF_FLAG_FILE_PATH, buffers.rs /
layout.ts, KERNEL_ABI_VERSION 1→2) and decode re-attaches its filePath
parameter; php's trait-use refs need the same bit.** Survey basis:
every TS-side branch a `.rb`/`.rake` file exercises, with file:line anchors as
of `f1ca991` (HEAD at survey time, clean main). Every grammar-shape claim below
was **probed against both the old tree-sitter-wasms build and a fresh v0.23.1
build** (probe scripts + outputs in the session scratchpad, `svy-ruby/` — see
§Grammar prep), not assumed. Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §5 gates) and the two
format precedents (`rust-lang-kernel-port-checklist.md`,
`ccpp-kernel-port-checklist.md`). **Blocking findings: none** — grammar bump is
shape-neutral on all extractor-relevant constructs (two classified deltas, one
inert, one precision-positive), error incidence 0.00% both arms on all three
gate repos, and `python.rs` is a close walker skeleton.

## Grammar prep (do FIRST, land standalone — the rust recipe)

Ruby is NOT in `VENDORED_WASM_LANGS` (grammars.ts:291-304) — production loads
`node_modules/tree-sitter-wasms/out/tree-sitter-ruby.wasm`, built from
tree-sitter-ruby **^0.20.1** (tree-sitter-wasms 0.1.13 devDependency; 2024-02
era). The bump:

- **Crate: `tree-sitter-ruby = "=0.23.1"`** (crates.io max, published
  2024-11-11) = git tag **`v0.23.1`** = commit
  `71bd32fb7607035768799732addba884a37a6210` (also current master).
  sha256-verified crate-tarball ↔ tag, BOTH generated artifacts (ruby has an
  external scanner):
  - `src/parser.c` `4ce468358b6f4e25a35c8cf6bc0eaf60665bc22d602f8c939323c2347255cd15`
  - `src/scanner.c` `e7a6196d6e78bf4c6728502e924c867dee5d851c6253e43fcdb8ba169009bc58`
- **ABI note (differs from the rust precedent):** v0.23.1's checked-in
  parser.c declares `LANGUAGE_VERSION 14` — the tag predates the ABI-15
  generator, so this is a grammar-CONTENT bump, **ABI stays 14** (accepted by
  both web-tree-sitter and native tree-sitter 0.25, min-compatible 13). Don't
  expect an ABI change in kernel-grammar-parity; DO assert same-revision.
- **Build (from the CHECKED-IN parser.c — never run `tree-sitter generate`):**
  ```
  git clone https://github.com/tree-sitter/tree-sitter-ruby && cd tree-sitter-ruby
  git checkout v0.23.1
  npx -y tree-sitter-cli@0.25.10 build --wasm -o tree-sitter-ruby.wasm .
  ```
  (brew emcc present; survey artifact sha256
  `4cb5a4b12870876ca864c1e92fe1f5cd47036b2adc083e9306488af88867dbb4`, 2,106,097
  bytes, at scratchpad `svy-ruby/tree-sitter-ruby.wasm`.)
- **Staging plan (grammar-bump PR, before any walker exists):** vendor the
  wasm to `src/extraction/wasm/tree-sitter-ruby.wasm`; add `'ruby'` to
  `VENDORED_WASM_LANGS` (grammars.ts:291) with an R7b comment following the
  rust pattern (tag + sha-matched note); pin `tree-sitter-ruby = "=0.23.1"` in
  codegraph-kernel/Cargo.toml under the exact-pin comment block (`=` like
  c/cpp/rust — crate + wasm move together or kernel-grammar-parity fails);
  kernel symbol `tree_sitter_ruby::LANGUAGE` in langs.rs when the walker
  lands. Full suite green + the standalone bump gate (§Gates) before walker
  work starts.
- **Shape delta OLD→NEW — probed, complete classification (two deltas
  total):**
  1. **`__END__` data trailer — INERT.** OLD has a separate `__END__` anon
     token + the `uninterpreted` node starting after the newline; NEW drops
     the `__END__` kind-table entries (353 → 351 kinds; kind ids renumber)
     and `uninterpreted` starts right after `__END__` including the leading
     `\n` in its text. No extractor branch touches `uninterpreted` (not in
     any ruby type list; recursed with nothing matching; file endLine comes
     from `source.split('\n')`), so no emission changes. Field table (32
     fields) identical.
  2. **Safe-nav operator-method calls — BEHAVIOR-CHANGING,
     precision-positive.** `recv&.!= arg` (rails
     `activerecord/lib/active_record/relation/where_clause.rb:62`, the only
     hit in 3,763 real files): OLD misparses as `assignment` (`recv&.!`
     method `!`, then `= arg`) → wasm emitted `recv.!` calls ref; NEW parses
     correctly as `call` with `operator`-typed method `!=` → `recv.!=` calls
     ref, args walked as arguments. Wasm-path-only churn at bump time (both
     arms agree after); classify+accept in the bump gate's dump diff exactly
     like rust's "small precision-positive edge churn".
  Everything else probed byte-identical between OLD and NEW: full torture
  probe (modules/mixins/visibility/inline-def/calls/blocks/heredocs/hooks —
  848-line CST dump identical), modern-syntax probe (endless methods `def f(x)
  = …`, `...`/`&`/`*`/`**` forwarding, case/in pattern matching, rightward
  assignment, hash shorthand, %-literals, operator method defs — identical
  incl. identical error behavior), CRLF variant (no errors either arm,
  identical shapes, node-type sequence == LF).
- **Error incidence (both arms, all `.rb`/`.rake` ≤1MiB):** sinatra 0/147
  (0.00%/0.00%), jekyll 0/164, rails 0/3452 — zero disagreements. Ruby is a
  ts/java/py/go-class language: expect ~0% deferral, default `--max-deferral
  0.1` with huge margin; double-digit deferral on a ruby sweep = broken
  walker (NO c/cpp 0.5 exemption).
- Probe scripts + outputs live in the survey scratchpad
  (`…/scratchpad/svy-ruby/`): `shape-probe-ruby.cjs` (CST dumper, OLD vs
  NEW), `table-compare.cjs` (kind/field tables + error locator),
  `error-sweep.cjs` (per-repo has_error + full-CST sexp compare),
  `extract-probe.cjs` (runs the REAL dist extractor — its
  `extract-{dblcap,vis,req,vref,misc,reqedge}.txt` dumps are the pinned
  ground truth cited throughout this doc, and double as walker test
... (643 lines truncated)
</file>

<file path="docs/design/rust-kernel-migration-plan.md">
# Rust extraction-kernel migration plan + post-kernel roadmap

**Audience:** the agent/engineer executing the native-kernel project. Self-contained handoff:
context, current state, per-language tracker, gates, and the follow-on roadmap.
**Companion:** `docs/design/native-extraction-kernel.md` (architecture + spike detail).
**Written:** 2026-06-12 planning → executed 2026-07-16/17. **R1–R6 ARE DONE.** The shipped
records live in §3a and §4a–§4f; the per-language tracker is current; §0a is the
cold-start handoff for the next session. Read §0 + §0a first — parts of §1/§6 below
them are the ORIGINAL plan and carry expectations that measurement later corrected
(each is annotated where superseded).

---

## 0. Status checklist (R1–R6 done; what remains)

- [x] **R1. Scaffold the napi-rs crate** — done 2026-07-16, §3a. Buffer contract v1,
      routing + per-file wasm fallback, kill switch, build/release wiring,
      grammar-source-parity CI.
- [x] **R2. Port TypeScript/JavaScript (tsx/jsx)** — done 2026-07-16, §4a. The generic
      `.scm` emitter was SUPERSEDED by bespoke per-language walkers (queries can't
      express extraction parity); byte-parity from day one of the harness.
- [x] **R3. TS/JS equivalence gate → DEFAULT-ON** — done 2026-07-16, §4b. Dumps
      byte-identical (express/excalidraw/vscode + flask control). Found + fixed:
      encoding-dependent error recovery → per-file `defer:` policy.
- [x] **R4. Java (incl. Lombok synthesis) → DEFAULT-ON** — done 2026-07-16, §4c.
      dubbo 441k-row dump byte-identical. Found + fixed: node-ID-collision dedupe
      (cross-language). Found: many-core parse-loop wall is NOT extraction (→ §4d).
- [x] **Direct-to-store decode** — done 2026-07-16, §4d. Main thread never
      materializes nodes; measured: the many-core fresh-index wall is single-writer
      SQLite ingest (94% of dubbo's parse-loop) — a store-architecture arc, out of
      scope here.
- [x] **R5. Python + Go → DEFAULT-ON** — done 2026-07-16, §4e. django 360.8k /
      prometheus 213.8k row dumps byte-identical; 2-CPU envelope 1.32× / 1.46×.
- [x] **R6. Kernel-scale re-validation (cg1212)** — done 2026-07-17, §4f. No
      regression (26.4min vs ~27min, identical 2.05M-node graph). The "parse 6m→2m"
      premise was wrong for THIS repo: the Linux tree is ~99% C (unported T2) —
      the expectation transfers to the C/C++ port.

**Open, in recommended order (rationale in §0a):**

- [x] **O1. Merge the `rust-kernel` branch** — DONE 2026-07-17: PR #1326, **merge
      commit** (the integration-branch exception — 9 milestone commits preserved),
      main tip `c1dc78d`. Suite green pre-merge (2,472 passed / 4 skipped,
      `CODEGRAPH_KERNEL_EXPECT=1`).
- [x] **O2. Windows VM validation** — DONE 2026-07-17. Guest (ARM64 Win11):
      rustc 1.97.1 aarch64-pc-windows-msvc + MSVC Build Tools (VCTools workload +
      VC.Tools.ARM64 + Win11 SDK; installed via **scheduled task** — Windows sshd
      kills detached children on session close, `schtasks` is the survival
      pattern). `build-kernel.sh --target aarch64-pc-windows-msvc` builds native
      win32-arm64 in ~2min; **all three kernel suites green with
      `CODEGRAPH_KERNEL_EXPECT=1` (33/33)**. The leg EARNED ITS KEEP: the guest's
      autocrlf checkout exposed a real CRLF parity bug (docstring cleaning; JS
      multiline `^` anchors after `\r` — §0a traps) — fixed + CRLF fixtures pinned
      cross-platform in #1329. Every prebuild target platform is now validated.
- [ ] **P1. Kernel-scale resolution speed** (§7a) — measurement round RUN 2026-07-17
      and it RESHAPED the arc (full record §7a.1); items (1) WAL containment and
      (2) memory-aware/cgroup-honest sizing **SHIPPED same day (#1332–#1335,
      §7a.2)** after an implementation arc whose three failed/diagnostic
      kernel-scale runs each corrected the design (WAL file ≠ WAL backlog;
      cgroup cache credit; pool net-negative at 2 cores; parse floor). The
      2c/6GB envelope already improved 26.4 → 21.6min with counts byte-exact.
      Record runs DONE (§7a.2): 2c/6GB 20.4min, 8c/7GB 18.3min NO-OOM — byte-exact.
      Batch-loop profile round DONE (§7a.3, #1339): countGuard quadratic killed,
      19.3min. cFnPtr round DONE (§7a.4, #1341): 2.07× standalone, edge set
      hash-identical, envelope **17.6min (R6 −33%)**. R7a landed 2026-07-17:
      envelope now **19.1min on a substantially RICHER graph** (the new
      preParse blanks recover previously-error-swallowed code; wasm-arm on
      the same graph is 22.9min — the 17.6 record was the old smaller graph
      and isn't directly comparable). 8c re-run DONE post-R7a (§7a.5):
      **16.4min** (pre-R7a record 18.3min), EXIT 0, counts == both 2c arms,
      WAL 1.34GB. The <10min-on-8c target remains open, and the re-run
      re-ranked the levers honestly: at 8c the parse-loop (202.6s) is
      already AT the single-writer floor, so **the target gap is ~entirely
      the core-invariant resolution superphase (715s ≈ 12 of the 16.4min)
      — the per-ref path is THE 8c lever**. C/C++ deferral round 2 DONE
      2026-07-18 (full record: checklist doc): eight new C-only preParse
      passes + word-list extensions took kernel/+mm/ deferral
      **58.6% → 33.9%** (git 16.1 → 12.2%, redis 25.3 → 24.1%,
      fmt/protobuf unchanged — cpp-dominant, correct no-op), five-repo
      sweeps 0-diff, linux full-tree both arms **2,049,153 / 6,413,518**
      with **byte-identical dumps** (10,446,478 lines, sha `6dd1185b…`);
      kernel-arm parse-loop **356 → 306s** at 2c, envelope ~17.1min
      (host-contaminated, indicative). Honesty note: full-graph node
      deltas are small (+858) — wasm error recovery was already salvaging
      most SYMBOLS on deferred files; the real win is EDGES (+6,585),
      phantom cleanup, and native-path coverage. Remaining deferral is
      policy-skips (CONFIG interleaves, TP_PROTO DSL, module_init-no-semi)
      + small buckets — this lever is largely SPENT. Per-ref measurement
      round DONE 2026-07-18 (§7a.6): fresh 2c/8c stage tables; the pool
      double-buffer WORKS (8c settle 3.6s — "core-invariant" superseded);
      2c record now 16.5min, 8c range 15.0–16.4 (n=2). Two cache
      experiments killed by measurement same-day (nameCache scaling, lazy
      candidates — §7a.6 has the numbers; code reverted).
      Writes-under-readers PROBED + FIXED 2026-07-18 (§7a.7): mechanism =
      WAL read-through depth under reader pins (proven by pool-off/dose/
      valve discrimination); fix = worker connection recycling at the
      pool-idle boundary (cadence 8); superphase **715 → 633.6s (−11.4%)**,
      8c envelope best **14.8min**, byte-neutral at every gate. Queue now:
      **cFnPtr native site extraction** (synthesis ~230s) >
      continuous-shallow WAL (the remaining ~45s to the valve floor) >
... (1133 lines truncated)
</file>

<file path="docs/design/rust-lang-kernel-port-checklist.md">
# Rust-language kernel port (R7b) — the bug-for-bug checklist

("rust-lang" in the filename to avoid confusion with the kernel's own
implementation language.)

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/rustlang.rs`,
all gates below passed (parity sweeps 0-diff on ripgrep/tokio/rust-analyzer,
dump gates byte-identical ×3, DEFAULT_ROUTED += rust). This doc remains the
quirk reference for the walker. Survey basis: every TS-side branch a
`.rs` file exercises, with file:line anchors as of `ce0ae30` (HEAD at survey
time). Every grammar-shape claim below was **probed against the vendored
tree-sitter-rust v0.24.2 wasm** (probe scripts in the session scratchpad), not
assumed. Read WITH `docs/design/rust-kernel-migration-plan.md` (§0a recipe, §5
gates) and `docs/design/ccpp-kernel-port-checklist.md` (format precedent).

**Grammar prep is ALREADY STAGED (uncommitted at survey time):** Cargo.toml
pins `tree-sitter-rust = "=0.24.2"`, `src/extraction/wasm/tree-sitter-rust.wasm`
is vendored from tag `77a3747` (parser.c/scanner.c sha-matched against the
crates.io tarball), and `rust` is in `VENDORED_WASM_LANGS` (grammars.ts:291) —
replacing the 2023-era tree-sitter-wasms build (ABI 14 → 15). Per the recipe:
land the grammar bump FIRST and get the full suite green before the walker
exists. Probing showed the 0.24.2 shapes match the old build on every branch
below (function_modifiers nesting, token trees, impl fields, use shapes), so no
TS-side behavior change is expected from the bump — but the suite run is the
proof.

## Architecture decisions

1. **No preParse.** `rustExtractor` has no `preParse` hook, so the route
   point's `preParsedSource` (kernel/index.ts:76) is a no-op for rust — both
   arms parse raw bytes. Nothing to hoist, nothing to port.
2. **Cargo repos take the DECODED path, not raw buffers.** `rustResolver`
   (resolution/frameworks/rust.ts:22, `languages: ['rust']`, detect =
   `Cargo.toml` exists) has an `extract()` hook, and parse-worker.ts:93 forces
   any language with an applicable framework `extract()` onto the decoded
   `extractFromSource` path (framework nodes/refs merge into the decoded
   result). So on real Rust repos the kernel win is parse+walk+decode, never
   the buffers-to-store transport. Don't chase a raw-path number on
   ripgrep/tokio and conclude the port is broken.
3. **The framework extractor itself needs NO port.** It is regex-over-raw-source
   TS (see §Frameworks below) and runs identically after either arm inside
   `extractFromSource` (tree-sitter.ts:6736-6758). Only the tree-sitter-walk
   emissions below move to Rust.
4. **One walker module** (suggest `codegraph-kernel/src/rustlang.rs` — "rust"
   alone collides with the crate language), registered in `langs.rs`; per-file
   `has_error()` → `defer:` like every walker.
5. **`.rs` → `rust`** at detectLanguage (grammars.ts:78), no content sniffing,
   no dialect. MAX_FILE_SIZE (1 MiB, extraction/index.ts:132) and generated-file
   skips are orchestrator/TS-side and shared.

## Extractor config (languages/rust.ts — 151 lines, read it whole)

Types: functionTypes=[`function_item`, **`function_signature_item`**] (the
latter = a trait method DECLARATION `fn render(&self);` — extracted so a
trait's method set is first-class); classTypes=[] (impl blocks instead);
methodTypes = same two; interfaceTypes=[`trait_item`] with
**interfaceKind:'trait'**; structTypes=[`struct_item`];
unionTypes=[`union_item`] (same body walk, distinct `union` node kind);
enumTypes=[`enum_item`];
enumMemberTypes=[`enum_variant`]; typeAliasTypes=[`type_item`];
importTypes=[`use_declaration`]; callTypes=[`call_expression`];
variableTypes=[`let_declaration`, `const_item`, `static_item`].
nameField=`name`, bodyField=`body`, paramsField=`parameters`,
returnField=`return_type`.

Hooks PRESENT (port each exactly):

- **getReturnType = extractRustReturnType (rust.ts:14)** — reads the
  `return_type` field; if `reference_type`, unwrap to the first namedChild of
  type `type_identifier`/`scoped_type_identifier`/`generic_type` (`?? rt` —
  falls back to the reference_type itself); then if type ∈
  {`primitive_type`,`unit_type`,`tuple_type`} → undefined. Else:
  `text.trim().replace(/<[^>]*>/g, '')`, take last `::` segment, trim; must
  match `/^[A-Za-z_]\w*$/` else undefined; `'Self'` → the marker **`'self'`**
  (resolved to the impl's own type at resolution time). QUIRKS: the
  non-greedy-ish `/<[^>]*>/g` strip breaks on NESTED generics —
  `Result<Vec<Foo>, E>` → `"Result, E>"` → regex fails → **undefined** (only
  single-level generics like `Vec<Foo>` → `Vec` survive). `-> &Foo` unwraps to
  `Foo`; `-> fmt::Result` → `Result`.
- **getSignature (rust.ts:57)** — `undefined` if no `parameters` field; else
  raw text of params, plus `' -> ' + <return_type raw text>` when present.
  Raw `getNodeText` — multi-line params keep their newlines.
- **isAsync (rust.ts:67) — DEAD CODE BUG, PRESERVE:** scans DIRECT children for
  `child.type === 'async'`. Probed on v0.24.2: `async` nests inside a
  `function_modifiers` child (`pub async fn` children:
  `visibility_modifier, function_modifiers, fn, identifier, parameters, ->,
  <ret>, block`), so **isAsync always returns false** — no rust node ever gets
  `isAsync: true`. The walker must reproduce false.
- **getVisibility (rust.ts:74)** — direct child of type `visibility_modifier`:
  text `.includes('pub')` → `'public'` else `'private'`; no modifier →
  `'private'` (so `pub(crate)`/`pub(super)` are all `'public'`).
- **getReceiverType (rust.ts)** — walk PARENT chain to the nearest
  `impl_item`; there, read the grammar's `type` field through
  `rustImplTypeName` (kernel: `impl_type_name`): `type_identifier`/`identifier`
  → text; `generic_type` → its `type` field (bare name, never the args);
  `scoped_type_identifier`/`scoped_identifier` → its `name` field (last
  segment); `reference_type` → its `type` field; anything else (tuple, `dyn`,
  pointer, primitive, fn type) → undefined. Never an impl parent → undefined.
  **Changed in #1588 on both sides together**: the original rule took the LAST
  direct `type_identifier` child, so for `impl Trait for Generic<T>` /
... (437 lines truncated)
</file>

<file path="docs/design/scala-kernel-port-checklist.md">
# Scala kernel port (R7b) — the bug-for-bug checklist

**Status: SURVEY COMPLETE (2026-07-20), port not started.** Survey basis: every
TS-side branch a `.scala`/`.sc` file exercises, with file:line anchors as of
**`45a53eb`** (HEAD at survey time, clean main; a6c62d7..45a53eb touched only
grammars.ts/kernel/index.ts/wasm inside src/extraction — tree-sitter.ts,
languages/scala.ts, function-ref.ts, and tree-sitter-helpers.ts are
byte-unchanged, so kotlin/swift-checklist anchors into shared code remain
valid). Every grammar-shape claim below was **probed against the
production vendored wasm** (`dist/extraction/wasm/tree-sitter-scala.wasm`,
sha256 `7945b13e…`, identical to `src/…`), and every extraction-behavior claim
was **pinned against the real `dist/` extractor** (`extract-*.txt` ground-truth
dumps) — not derived from code reading. childForFieldName truth tables were
probed directly (`brace-field.out`, the FIELDS sections of `cst-snippets.txt`)
because **this grammar attaches field names to ANONYMOUS tokens** — CST dump
labels alone mislead (the swift lesson, §Extension). Probe scripts + dumps in
the session scratchpad `svy-scala/` (§Probe artifacts). Read WITH
`docs/design/rust-kernel-migration-plan.md` (§0a recipe, §2 boundary, §4
tracker row "scala", §5 gates) and the format precedents
(`kotlin-kernel-port-checklist.md` — the closest sibling: JVM family, hook
property branch, re-encode gate — and `swift-kernel-port-checklist.md`).

**Blocking findings: none — but three eyes-open items.** (1) The wasm is
**already vendored and needs NO bump**: `VENDORED_WASM_LANGS` has contained
`scala` since 2026-05-07 (#91), and the vendored wasm is table-identical to
tree-sitter/tree-sitter-scala **master@`0aca5d0a6f`** (verified twice: the
batch-4 positional table compare, and this survey's clone-sha match). The port
is vendored-grammar-C only (kotlin mechanism) — there is no behavior-delta
gate to run. (2) **Error incidence is bimodal**: mainstream Scala-2-style
repos are clean (os-lib 0.00%, cats 1.80%) but bleeding-edge Scala-3 code is
not (scala3 compiler/src 9.88%, library/src **17.79%** — capture-checking `^`
types), and **~40–60% of erroring files are PHANTOMS** (hasError=true, zero
ERROR/missing nodes — trust the flag). Sweep guidance in §Architecture #6.
(3) **scala has 32 real fields but three load-bearing places where
`childForFieldName` returns the FIRST of SEVERAL same-named fields — or an
anonymous `{` token** (import `path`, curried `parameters`, extension `body`).
The walker must reproduce first-match-wins over the full (named+anonymous)
child list, not "the" field (§Extractor config, §Extension).

## Grammar prep (NO wasm bump — vendored-C kernel build only)

> **Superseded (2026-09-23, #1823):** both copies were bumped to the
> tree-sitter-scala **v0.26.2** release (tag commit `b931fcc338`). The
> `0aca5d0a6f` pin parsed `class A(x: X)(implicit y: Y) extends B(x)(y) with C
> with D` with an ERROR and cut the `extends` clause after `B(x)(y)`, so `C`
> and `D` never became inheritance edges. v0.26.2 is additive over the pin (no
> node type or field removed; new ones: capture checking, XML literals,
> `uses_clause`, `early_defs`, …). Wasm = the release asset, sha256
> `37d7fe5a91ca98941dc05493b0c05a0df0f36df5035890fa00b02497c68aaac3`; C sources
> from the tag's `src/` (shas in `codegraph-kernel/build.rs`). The record below
> describes the original port.

- **Production wasm**: `src/extraction/wasm/tree-sitter-scala.wasm`, sha256
  `7945b13e6f9b15b578c5e5e4e60253c049fec07c531518163f3415a76c0621aa`
  (src == dist byte-identical), ABI **15**, STATE_COUNT 26650, 357+5 symbols,
  **FIELD_COUNT 32**. In `VENDORED_WASM_LANGS` (grammars.ts:292) since #91
  (2026-05-07). Mapping `scala: 'tree-sitter-scala.wasm'` (grammars.ts:38).
- **Provenance (verified)**: tree-sitter/tree-sitter-scala
  **master@`0aca5d0a6fe115b16d55cb100e1bb05e7fb11385`** (2026-04-22 "chore:
  generate and sync from ec71cd9d51" — the post-v0.26.0 fix batch:
  scala2-compiler-100%, lambda-body restrict, wildcard self-type). The clone's
  `src/parser.c` sha256 equals the batch-4 probe's positional-table-verified
  copy (`bc3c3c79…`), and that probe found the wasm's kind/field tables
  positionally identical to it. The v0.26.0 tag == crate 0.26.0 is 26620
  states — **30 states BEHIND our wasm** — so a crate pin would be a silent
  downgrade; later master (`fc99b1bd`, Apr-27) is a 23959-state restructure —
  a future-bump candidate, NOT this port. Full record:
  `../scratchpad/batch4-grammar-probe.md`.
- **Vendored-C route (kotlin mechanism, second use)** — copy from the
  `0aca5d0a6f` clone into `codegraph-kernel/grammars/scala/` (shas recorded in
  a comment; survey record `grammar-shas.txt`):
  - `src/parser.c`  `bc3c3c794f19461d99d04de6c31d57fa3e41243509b9ab023a9b88ed3273d102` (34,970,232 bytes — 35 MB, the biggest grammar in the tree; expect a slow `cc` step)
  - `src/scanner.c` `e4ba242568ee3493015598997bf60f613802616eade62717c21109287ef64752` (17,731 bytes — a REAL external scanner: significant-indentation + interpolation; it handles `\r` explicitly, scanner.c:476)
  - `src/tree_sitter/alloc.h` `b29c1c9f…`, `array.h` `31e60a1b…`, `parser.h` `180b893c…`
  - build.rs: crib the upstream `bindings/rust/build.rs` flag set — `cc::Build`
    `.std("c11").include(grammars/scala).flag_if_supported("-Wno-unused")`,
    msvc `-utf-8`; compile parser.c + scanner.c; symbol `tree_sitter_scala`
    (parser.c:1199034). Same shape as the kotlin block (build.rs:14-22).
  - Cargo: `tree-sitter-language` shim already present (kotlin). langs.rs:
    `extern "C" { fn tree_sitter_scala() -> *const (); }` +
    `"scala" => LanguageFn::from_raw(...)` + `LANGUAGES` 15 → **16**.
  - `__tests__/kernel-grammar-parity.test.ts:39` `GRAMMAR_LANGUAGES += 'scala'`
    — the id-by-id table compare against the vendored wasm proves the C build
    is the same revision (ABI 15 / 26650 states / 32 fields must match).
  - License: MIT (tree-sitter org). No metadata shim needed (repo has
    tree-sitter.json-era layout; we never run `tree-sitter generate`).
- **NO grammar-bump gate.** Unlike every other R7b language there is no
  old-vs-new wasm diff to run — production already parses with this exact
  revision. The kernel-grammar-parity row IS the alignment proof.
- **Scanner-state parity risks — probed clean:** the indentation scanner
  handles CRLF: LF-vs-CRLF parses are **s-expression-identical on every
  fixture including Scala-3 indentation syntax** (`crlf-cst.cjs`: indent/
  torture/docs/vref/misc/ext/script all `sexpEqual=true`, no error flips).
  Extraction under CRLF is byte-identical except the multi-line-block-comment
  docstring `\r` retention (§Docstrings — a shared `js_multiline_strip`
  concern, not a scanner one). The kernel parses UTF-8 while wasm parses
  UTF-16 — error-recovery differences are exactly what per-file
  `has_error() → defer:` guards; nothing scala-specific beyond the elevated
  incidence below.

... (870 lines truncated)
</file>

<file path="docs/design/swift-kernel-port-checklist.md">
# Swift kernel port (R7b) — the bug-for-bug checklist

**Status: PORT COMPLETE (2026-07-20)** — walker `codegraph-kernel/src/swift.rs`,
all gates passed (bump validated standalone with the diff classified per the
error-union rule + ripple pairing + two gate-found categories 7/8 below;
parity sweeps 0-diff Alamofire 89/98 / vapor 224/247 / swift-nio 407/554 at
--max-deferral 0.3 with exactly the predicted deferral counts; dump gates
byte-identical ×3; the Alamofire census reproduced property=348 on the kernel
arm; kernel-swift-parity suite; DEFAULT_ROUTED += swift). **One survey
correction found by the swift-nio sweep: §Shadow prune understated the case
list — the shared `assignment` prune case (tree-sitter.ts:829) is ALSO
swift-live** (a declared-then-assigned `let X: T` + `X = …` branches bumps
per assignment via the directly_assignable_expression's simple_identifier,
pruning X — swift-nio's main.swift files pin it). Survey basis: every
TS-side branch a `.swift` file exercises, with file:line anchors as of
**`a6c62d7`** (HEAD at survey time, clean main). Every grammar-shape and
emission claim below was **probed against both the current production wasm
(tree-sitter-wasms 0.1.13 build of npm tree-sitter-swift ^0.4.0, ABI 13) and a
fresh crate-0.7.3 build (ABI 15)** — CST probes for shapes, **plus the built
`dist/` extractor run end-to-end on a 106-line torture file and on all 98
Alamofire files** (emissions, order, counts pinned from real output, not
inference). Probe scripts + raw outputs: session scratchpad `svy-swift/`
(§Probe artifacts). Read WITH `docs/design/rust-kernel-migration-plan.md`
(§0a recipe, §2 boundary, §5 gates) and the format precedents
(`rust-lang-`, `csharp-`, `ruby-`, `php-kernel-port-checklist.md` — php's
non-neutral-bump "enumerate + classify" gate is the template here).

**Blocking findings: none.** Three eyes-open findings that shape the port:
(1) the grammar bump is **NOT graph-neutral** — the old→new delta is confined
to *error-set membership* (65 files across the three gate repos parse
differently-erroneously per arm; three NEW-only regression construct classes
enumerated in §Grammar-bump deltas) while every clean-parse extractor-relevant
shape probed **byte-identical** (53-line CST diff across the whole battery,
all classified inert); the bump gate is php-style enumerate+classify, not
expect-zero. (2) **Swift error incidence is structurally high — 9.2–26.5% on
the NEW arm (both-arm reality, not a bump artifact)** — the parity-sweep
deferral guard MUST be raised for swift (§Deferral policy); a 0.1 guard fails
the sweep on all three gate repos. (3) The port's center of gravity is the
**dedicated in-class property branch in tree-sitter.ts (#1020)** — it is NOT
in languages/swift.ts, it attributes its refs to the *enclosing type* rather
than the property node, and Alamofire's 348 computed-property nodes (re-counted
at survey time: exactly 348) ride it (§Dedicated property branch).

## Grammar prep (NOT staged — land FIRST, before any walker exists)

swift is **not** in `VENDORED_WASM_LANGS` (grammars.ts:291) — production loads
`require.resolve('tree-sitter-wasms/out/tree-sitter-swift.wasm')` (mapping
`swift: 'tree-sitter-swift.wasm'` at grammars.ts:34; `.swift` → swift at
grammars.ts:105), a 2023/24-era **ABI-13** build of npm tree-sitter-swift
^0.4.0 (sha256 `41c4fdb2…`, 3,147,876 bytes; 540 node types / 45 fields).

- **Version: crate `tree-sitter-swift = "=0.7.3"`** (crates.io max_stable,
  published 2026-06-01; repo alex-pinkus/tree-sitter-swift).
- **PROVENANCE TWIST — the crate tarball is the canonical generated-file
  source, NOT the git tag.** alex-pinkus keeps generated files off `main`;
  tag `0.7.3-with-generated-files` (commit
  `31d17fe7e818a2048c808b5c6fdc2dc792f4f5b5`) ships an **ABI-14**
  parser.c (LANGUAGE_VERSION 14, SYMBOL_COUNT 565 — an *older-generator* run,
  plus `parser_abi13.c`/`parser_abi14.c` variants), while the crates.io
  tarball ships an **ABI-15** regeneration (LANGUAGE_VERSION 15, SYMBOL_COUNT
  558, STATE_COUNT 10321). The two are the SAME grammar — `grammar.json`
  `rules` and `externals` are JSON-equal between tag and crate (probed) — but
  the parser.c bytes differ, so a tag-side sha-match is impossible.
  **Build the wasm from the CRATE TARBALL's `src/`** (that is literally what
  the kernel's cargo build compiles → table-identity by construction, the
  csharp-precedent verification posture). Never touch the tag's parser.c and
  never run `tree-sitter generate`.
  - crate `src/parser.c` sha256
    `d3edff6effe31b9a507f496577407987343b101b23eb7bee7a9b050e8ab5d27a` (20,642,243 bytes — expect slow builds)
  - crate `src/scanner.c` sha256
    `f3d6271d64f58c39eed544104a70ca2cf9ecbf80c5d900620f1afd38836542cb`
    (== the tag's scanner.c byte-for-byte). **External scanner: YES** — the
    crate build compiles it automatically; the wasm build picks it up from `src/`.
- **Build (survey-verified commands):**
  ```
  curl -sL https://crates.io/api/v1/crates/tree-sitter-swift/0.7.3/download -o ts-swift-0.7.3.crate
  tar xzf ts-swift-0.7.3.crate && cd tree-sitter-swift-0.7.3
  # crate tarball lacks tree-sitter.json (metadata only — no effect on tables);
  # copy it from the 0.7.3-with-generated-files tag clone:
  cp ../tag-clone/tree-sitter.json .
  npx -y tree-sitter-cli@0.25.10 build --wasm -o tree-sitter-swift.wasm .
  ```
  (brew emcc present; one benign scanner warning. Survey artifact: ABI 15,
  3,726,622 bytes, sha256
  `cc77a63b8487956270e2f385e29a03ba0773ba532a3c8a8844a26b4c98793843`, 563 node
  types / 46 fields, at scratchpad `svy-swift/tree-sitter-swift.wasm`.)
- **Version-choice rationale (evaluated, not defaulted):** the feared
  alex-pinkus shape churn did NOT materialize for extraction — the full
  OLD-vs-NEW CST battery (types/funcs/props/calls/imports/statics/docs) diffs
  in only 53 lines, all inert (§deltas). An older crate (0.5.0/0.6.0) was
  considered as a closer-match alternative and REJECTED: clean-parse shapes are
  already identical on 0.7.3, so an older pin buys no shape proximity and
  loses the error-set wins that dominate the delta — swift-testing `#expect`
  (Alamofire's whole test suite), `#Preview`/`#GET`-style freestanding macros
  (vapor 57→23 error files), `package` access, and typed `throws(E)` all parse
  ONLY on 0.7.x. 0.7.3's three regression construct classes (§deltas) are
  net-smaller (21 files) than its fixes (63 files) on the gate repos.
- **Staging plan:** vendor to `src/extraction/wasm/tree-sitter-swift.wasm`;
  add `'swift'` to `VENDORED_WASM_LANGS` (grammars.ts:291) with an R7b
  comment noting the crate-tarball provenance (NOT tag-sha-matched — state
... (985 lines truncated)
</file>

<file path="docs/design/telemetry.md">
# Anonymous usage telemetry

Status: implemented — client (`src/telemetry/`), `codegraph telemetry` CLI, MCP + installer
wiring, `TELEMETRY.md`, ingest Worker (`telemetry-worker/`) storing to its own Cloudflare D1
database, nightly rollup + retention cron, and the admin dashboard Worker
(`telemetry-dashboard/`).
Scope: public `codegraph` engine (CLI + MCP server + installer)

CodeGraph is a local-first tool whose whole pitch is "your code never leaves your machine."
Telemetry has to be designed so that sentence stays true and provable: a short, auditable list
of anonymous counters, documented field-by-field, easy to turn off, and impossible to grow
quietly. This doc is the contract; `TELEMETRY.md` (repo root, user-facing) restates it and the
implementation must never collect anything not listed there.

## Goals

Answer, in aggregate and anonymously:

- How many machines actively use codegraph (daily/weekly), and how does that change?
- Which agents drive usage (Claude Code, Cursor, Codex, opencode, …) — via MCP `clientInfo`.
- Which install targets people pick, local vs global, fresh vs upgrade.
- Which MCP tools and CLI commands get used, how often, and how often they error.
- Which languages people index (prioritize extractor/framework work by real usage).
- Version adoption speed, OS/arch/Node mix. (The SQLite backend is always the built-in `node:sqlite` now — there is no native-vs-wasm split left to measure.)

## Non-goals / never collected

- **No source code, ever.** No file paths, file names, repo names, symbol names, query
  strings, search terms, or anything derived from the contents of an indexed project.
- No IP addresses — never read at the edge, and there is no downstream backend that could
  see one.
- No third-party analytics vendor. Events are stored only in our own database; the ingest
  Worker makes no outbound requests at all.
- No hardware fingerprinting — the machine ID is a random UUID, not derived from anything.
- No per-keystroke / per-call event stream — usage is aggregated locally into daily rollups
  before anything is sent.
- No telemetry from the `codegraph-pro` fork (see "codegraph-pro rule" below).

## Principles

1. **The schema is the allowlist.** Client sends only the events below; the ingest Worker
   validates against the same allowlist and drops anything else. Adding a field = PR that
   edits this doc + `TELEMETRY.md` + the Worker allowlist together.
2. **Telemetry may never cost the user anything**: no network requests or queue writes on the MCP tool-call
   hot path (only a small local consent-file read), zero new npm dependencies (global `fetch`, Node ≥18),
   zero bytes on stdout (stdio is the MCP protocol channel), zero retries, zero error noise.
   Every failure mode is silence.
3. **Off is off.** When disabled, no process opens a socket to the telemetry endpoint — not
   even an "opted out" ping.
4. **First-party endpoint.** Clients only ever talk to `telemetry.getcodegraph.com`. The URL
   baked into a published npm version POSTs there forever, so the domain must be ours; the
   backend behind it can change without a client release.

## Events

Common envelope on every batch (identity revalidated before each request):

| field | example | notes |
|---|---|---|
| `machine_id` | `b3a8…` (UUIDv4) | random, minted at first run, stored in global config |
| `codegraph_version` | `0.9.12` | from package.json |
| `os` / `arch` | `darwin` / `arm64` | `process.platform` / `process.arch` |
| `node_major` | `22` | major only |
| `ci` | `false` | `CI` env var present |
| `schema_version` | `2` | bump when the schema changes (v2 dropped `index.sqlite_backend`) |

Event types:

- **`install`** — one per installer run. Props: `targets` (e.g. `["claude","cursor"]`),
  `scope` (`local`/`global`), `kind` (`fresh`/`upgrade`/`reinstall`).
- **`index`** — one per full index (`init`/`index`, not per `sync`). Props: `languages`
  (names only, e.g. `["typescript","go"]`), `file_count_bucket` (`<100`, `100-1k`, `1k-10k`,
  `10k+`), `duration_bucket` (`<10s`, `10-60s`, `1-5m`, `5m+`).
- **`usage_rollup`** — the workhorse. One event per `(day, kind, name)` per machine,
  aggregated locally. Props: `kind` (`mcp_tool`/`cli_command`), `name`
  (e.g. `codegraph_explore`, `affected`), `count`, `error_count`, and for MCP:
  `client_name`/`client_version` captured from the `initialize` handshake
  (`src/mcp/session.ts`) and passed through on every `recordUsage` call.
  The prompt hook additionally rolls up its gate DECISION as `cli_command`
  counters named `prompt-hook-gate-<outcome>`, outcome ∈ `high-keyword` /
  `high-token` / `medium-segment` / `nudge-projects` / `noop-shape` /
  `noop-no-index` / `noop-unverified` / `noop-explore-keyword` /
  `noop-explore-token` / `noop-vocab-empty` — decision names only, never
  prompt content. This is the gate's measured recall/precision funnel: a
  rising `noop-*` share against the `high`/`medium` tiers is the signal that
  the gate (keyword table or segment matching) is missing real questions.
  A `high-*` outcome means context was actually injected — a gate decision
  whose `codegraph_explore` errored or returned nothing records
  `noop-explore-<trigger>` instead (#1143), and a MEDIUM-eligible prompt
  hitting a not-yet-backfilled segment vocabulary records `noop-vocab-empty`
  rather than polluting `noop-unverified` (#1142).
- **`uninstall`** — one per `uninstall`/`uninit` run (churn signal). Props: `targets`.

One legacy field is still *accepted* and belongs in the mirror even though nothing sends
it: `sqlite_backend` (`native`/`wasm`) on `install` and `index`. Pre-schema-v2 clients
(≤ June 2026) sent it; `node:sqlite` is the only backend now, so current clients omit it.
It is never `required`, and it is safe to drop from the Worker once those clients'
share is negligible.

Volume math: rollups mean monthly events ≈ active machines × active days × distinct tools
... (173 lines truncated)
</file>

<file path="docs/design/template-markup-parser.md">
# Scope: Template-markup parser (Razor / Blazor / Thymeleaf)

Status: **P1+P2+@code IMPLEMENTED** (commits 59b8de2 directives/tags, 90c5f39 @code
delegation) on `feat/cross-language-impact-coverage`. Razor/Blazor markup is parsed
(`src/extraction/razor-extractor.ts`). Remaining: `@using` namespace disambiguation
for DTO-vs-entity name collisions (the residual ASP.NET gap), and Thymeleaf/Django
(P4, deferred — weak code links). Authored 2026-06-04.

## Problem

The impact graph is built from code the engine parses. **Template markup is not
parsed**, so any code-behind, component, view-model, or DTO that is referenced
*only* from markup looks like it has no in-repo dependent. On convention-heavy
frameworks this is the dominant residual gap after framework-entry exclusions:

| Framework | App | FAIR coverage (entries excluded) | Residual cause |
|---|---|---|---|
| ASP.NET | eShopOnWeb | **77.2%** (115/149) | Razor `.cshtml` + Blazor `.razor` reference `.cs` we don't parse |
| Spring | petclinic | 65.2% | mostly Spring Data proxies + JPA, **not** templates (Thymeleaf links are weak) |
| Django | django-realworld | 74.1% | signals / DRF / string-config, **not** templates |

**This feature is primarily an ASP.NET (Razor + Blazor) win.** Thymeleaf and Django
templates link to code only weakly (template→template fragments + fuzzy
model-attribute strings), and those frameworks' real gaps are elsewhere — so they
are explicitly lower priority here.

### Quantified target (eShopOnWeb, the 34 residual zeros after entry-exclusion)

- **~20 markup-coverable** by this feature:
  - 5 MVC `ViewModels/*` ← Razor `@model X`
  - 7 `BlazorShared/Models/*` (DTOs) ← Blazor `@bind` / component params
  - 6 `BlazorAdmin/*` C# components ← Blazor `<Component/>` tags
  - 1 `BasketComponent` ViewComponent ← `<vc:basket>` / `Component.InvokeAsync`
  - 1 Razor page helper
- **~13 NOT covered** (separate frontier — reflection/proxy + value-reads): AutoMapper
  `MappingProfile`, Swagger `CustomSchemaFilters`/`ImageValidators`, `ExceptionMiddleware`,
  health checks, `Constants` (static-member reads), `Buyer` entity.

**Honest ceiling: ASP.NET ~77% → ~90%**, not 95%. The last ~10% is reflection/proxy
(AutoMapper, Swagger, DI/middleware registration) + C# static-const reads — a
*separate* feature (reflection modeling + extending the static-member pass to C#).

## Reference patterns to extract (prioritized)

| Pri | Format | Markup construct | Edge to emit | Resolves to |
|---|---|---|---|---|
| P1 | Razor `.cshtml`/`.razor` | `@model Foo` / `@inherits X<Foo>` | `references` | the model/VM class `Foo` |
| P1 | Razor/Blazor | `@inject IBar bar` | `references` | the service type `IBar` |
| P2 | Blazor `.razor` | `<MyComponent .../>` (PascalCase element) | `references` | component class (`.razor` or `.cs : ComponentBase`) |
| P2 | Blazor `.razor` | `@typeof(MainLayout)`, `@inherits LayoutBase` | `references` | the type |
| P3 | Razor `.cshtml` | `<partial name="_X"/>`, `<vc:basket>`, `Component.InvokeAsync("X")` | `references` | the partial view / `XViewComponent` |
| P3 | Razor `.cshtml` | `asp-page="./Register"`, `asp-controller`/`asp-action` | `references` | the page / controller action |
| P4 (defer) | Thymeleaf `.html` | `th:replace="~{frag :: x}"` | `references` | template fragment (template→template only) |
| P4 (defer) | Django `.html` | `{% extends %}` / `{% include %}` / `{% url 'n' %}` | `references` | template / named route |

`asp-for="Prop"`, `th:field="*{prop}"` (property-string bindings) are the data-flow
frontier — **out of scope** (would need model-type inference; low value, high noise).

## Architecture — follow the existing standalone-extractor pattern

The engine already has non-tree-sitter extractors (`svelte-extractor.ts`,
`vue-extractor.ts`, `liquid-extractor.ts`): a class taking `(filePath, source)`,
returning `{ nodes, references }`, wired in two places. Mirror exactly:

1. **`src/extraction/grammars.ts`** — map extensions to a synthetic language:
   `.cshtml`/`.razor` → `'razor'`, (later) `.html` under `templates/` → `'thymeleaf'`.
   (Django `.html` is ambiguous with plain HTML — gate on a `templates/` path or a
   `{% %}`/`{{ }}` content sniff, like the framework resolvers do.)
2. **`src/extraction/tree-sitter.ts`** — dispatch by extension to a new
   `RazorExtractor` (and `ThymeleafExtractor`), exactly as `SvelteExtractor` is
   dispatched (~line 4025).
3. **`src/extraction/razor-extractor.ts`** (new) — regex/line scan (markup is
   highly stylized; no grammar needed, same as Liquid/Svelte template scanning):
   - Emit ONE `component` node for the file (so `.razor` components are linkable as
     `<X/>` targets and the file is a graph citizen).
   - Emit `references` per the P1–P3 patterns above, `fromNodeId` = the file/component
     node, `referenceKind: 'references'`, `language: 'razor'`.
   - **Code-behind link:** a `Foo.razor` + `Foo.razor.cs` (partial class) — emit a
     `references` (or rely on same-basename) so the markup's refs also credit the
     code-behind. (eShop's Blazor components are plain `.cs : ComponentBase`, named
     `<ToastComponent/>` → resolves by class name; the `.razor.cs` partial case is
     the other shape.)

**Resolution: no new resolver needed.** The emitted refs are ordinary `references`
to a class/component by name; the existing name-matcher resolves them (`@model
RegisterModel` → class `RegisterModel`; `<ToastComponent/>` → class `ToastComponent`).
Apply the **same cross-family language gate** already in place — a `razor` ref must
resolve to a `csharp` symbol, so add `razor` to the `web`/dotnet family or treat
`razor`↔`csharp` as same-family (otherwise the gate from commit 082353e drops it).
**This is the one resolver-side change** and must be done or every edge is gated away.

## Node/edge shape & invariants

- +1 `component` node per template file (real new symbol — like `.svelte`/`.vue`).
  Node count grows by the template-file count only; **no per-tag node explosion**
  (component tags become `references` edges, not nodes).
- All edges are `references` (counted by impact / `affected` / `getFileDependents`,
  not by `callers`/`callees` — matches how `route`/`component` edges already behave).
- Idempotent re-index; node count stable across re-runs.

... (56 lines truncated)
</file>

<file path="docs/design/value-reference-edges-playbook.md">
# Playbook: extend value-reference edges to a new language

**Purpose.** This is the operational runbook for adding + validating value-reference-edge
coverage for one more language. Point a fresh session at this file and say **"Start on
language X"** — it has everything: how the feature works, where the code is, the exact
validation recipe (with scripts), the per-language checklist, and the traps already hit.

Design rationale + the validation matrix already done live in the companion doc:
[`value-reference-edges.md`](./value-reference-edges.md). This file is the *how-to*.

---

## 0. "Start on language X" — do this in order

1. Read §1 (how it works) and §2 (current state) so you know the mechanism and what's done.
2. Do the **per-language wiring check** (§5 step A–C) — this is where languages differ and
   where most of the real work/decisions are. Do NOT skip: a wrong declarator node type or a
   class-scope-vs-file-scope mismatch makes the feature silently emit nothing (or wrong edges).
3. Run the **validation sweep** (§4) on small/medium/large **public OSS** repos for that
   language. Hunt FPs. **Fix FP clusters; record singletons.** (See §3 for what a real FP
   looks like vs an acceptable one.)
4. Add a **row to the matrix** in `value-reference-edges.md` and a **test case** in
   `__tests__/value-reference-edges.test.ts`.
5. Commit on a branch, open a PR. (§6 has the git workflow + how the prior PRs were done.)

Scope rule (hard): **never eval on the maintainer's own repos** — clone a real public OSS
repo for the language. (Memory: `agent-eval-targets-public-oss-only`.)

---

## 1. How value-reference edges work

**What:** a `references` edge with `metadata: { valueRef: true }` from a *reader symbol* to
the **file-scope `const`/`var` it reads**, same-file only. It exists so impact analysis
catches "change this constant / config object / lookup table → affect its readers" — a class
of change calls/imports/inheritance edges never captured (a const's consumers used to look
like "nothing depends on this").

**Where it flows:** straight into `getImpactRadius` → `codegraph impact` and the impact trail
in `codegraph_explore` / `codegraph_node`. No agent-behaviour change required. **The win is
impact-radius correctness** (a const 90 symbols read going from "1 affected" to "90"), *not*
agent read-reduction (see §4.3).

**Code — all in `src/extraction/tree-sitter.ts`:**

| Symbol | Role |
|---|---|
| `VALUE_REF_LANGS` (static Set) | languages the feature runs for. Currently `typescript`, `javascript`, `tsx`, `go`, `python`, `rust`, `ruby`, `c`, `java`, `csharp`, `php`, `scala`, `kotlin`, `swift`, `dart`, `pascal`. **Add the new language here.** |
| `valueRefsEnabled` | `process.env.CODEGRAPH_VALUE_REFS !== '0'` — default ON, env opts out. |
| `MAX_VALUE_REF_NODES` (20_000) | per-scope traversal cap (and the shadow-scan cap). |
| `captureValueRefScope(kind, name, id, node)` | called from `createNode` on every node. Records **targets** (file-scope `const`/`var`) and **reader scopes** (`function`/`method`/`const`/`var`). |
| `flushValueRefs()` | called once at end of `extract()`. Prunes shadowed targets, then for each reader scope walks its subtree for identifiers matching a target name and emits the edges. |

**The two gates inside `captureValueRefScope`** (what you may need to adjust per language):

- **Target gate:** `kind ∈ {constant, variable}` **and** `name.length >= 3` **and**
  `/[A-Z_]/.test(name)` (distinctive name — dodges single-letter / all-lowercase shadowing)
  **and** the node's parent id starts with `file:`, `class:`, or `module:` (file/class/module scope).
- **Reader gate:** `kind ∈ {function, method, constant, variable}`.

**The emit loop in `flushValueRefs`:** same-file only (targets + scopes are per-file, reset
each flush); deduped per `(reader, target)`; skips `isGeneratedFile(path)`; **prunes shadowed
targets** (see §3).

---

## 2. Current state (what's shipped + validated)

- **Default ON** for TS/JS/tsx + Go + Python + Rust + Ruby + C + Java + C# (`CODEGRAPH_VALUE_REFS=0` disables). Shipped in **PR #895**
  (flip-on + the shadow prune); Go added in a later PR (the shadow-prune declarator switch +
  `VALUE_REF_LANGS`); C added later still (extractor change to emit the nodes + the bare-identifier
  misparse guard); Java + C# after that (field→constant kind switch for the const subset).
- **Validated S/M/L** in **TS, JS, tsx, Go, Python, Rust, Ruby, C, Java, and C#** — see the matrix in the
  design doc. All clean: node count identical on/off, precision guards held, impact win
  reproduced. Go required extending the shadow prune (per-grammar declarators) — the worked
  example of "step B is load-bearing." **C required the Ruby treatment** (the extractor didn't emit
  C file-scope const/var nodes at all) **plus** a C-specific FP guard (a macro-prefixed-prototype
  misparse mints a bare-identifier "variable" named after the return type — skip bare-`identifier`
  declarators). It was the worked example of "the §2b coverage table's *easy-path* guess can be
  wrong — always do §5 step C (confirm the nodes exist) before trusting it."
- **Java + C# were the cleanest class-scope ("Ruby treatment") languages.** The constants already
  extract — but as `field` kind, which the gate rejects. The whole change was emitting the const
  *subset* as `constant`: an `isConst` predicate on each extractor (Java `static final`; C# `const`
  / `static readonly`) + a kind switch in `extractField`. **No new shadow-prune wiring** (method
  locals are `variable_declarator`, already in the switch) and **no FP guards** (UPPER_SNAKE /
  PascalCase fit the distinctive-name gate). Instance `final`/`readonly` fields correctly stay
  `field`. Validated S/M/L: gson/commons-lang/guava, automapper/newtonsoft/efcore — 0 leaks, node
  parity, big impact wins (`INDEX_NOT_FOUND` 4→165, `_resourceManager` 22→1664).
- **PHP was the cleanest of all — one reader-scan line.** Constants already extract as `constant`
  (top-level + class), so the only change was teaching the reader-scan that a PHP constant
  *reference* is a `name` node (bare `X`, or the const half of `self::X` / `Foo::X`). **No extractor
  change, no prune wiring** (a `$var` local can't shadow a bare constant — different namespace).
  Validated S/M/L (guzzle/monolog/laravel), all clean, 0 class/const collisions. The honest caveat:
  **lower yield** — PHP reads constants cross-file far more than same-file (laravel 2,956 files → 86
  edges), and value-refs is same-file only; still correct, just a smaller contribution.
- **Scala — an `object` is the constant scope.** Scala has no `static`; a singleton `object`'s `val`s
  are the shared-constant idiom (`object Config { val Timeout = 30 }`). Top-level `val` already
  extracted as `constant`, but object/class vals both came out as `field`. The fix: in the Scala
  `val_definition` handler, walk to the enclosing definition — `object_definition` (or top-level) →
  `constant`/`variable`; `class`/`trait`/`enum` → `field` (per-instance, like Java instance `final`).
... (445 lines truncated)
</file>

<file path="docs/design/value-reference-edges.md">
# Design + status: same-file value-reference edges

**Status:** SHIPPED (default-on for TS/JS/tsx + Go + Python + Rust + Ruby + C + Java + C# + PHP + Scala + Kotlin + Swift + Dart + Pascal; `CODEGRAPH_VALUE_REFS=0` disables). The
emitter lives in `TreeSitterExtractor.flushValueRefs` (`src/extraction/tree-sitter.ts`).
**Motivation:** close the impact-analysis hole for *value consumers*. Static
extraction edges calls, imports, and inheritance, but never edges a constant to the
symbols that read it — so changing a config object / lookup table / shared constant
looked like "nothing depends on this." This is the "change this table, break its
readers" class of change (the ReScript-PR false positive that motivated the work).

---

## TL;DR for a new session

We emit a `references` edge (`metadata: { valueRef: true }`) from a reader symbol to
the **file/package-scope `const`/`var` it reads**, same-file only, for TS/JS/tsx + Go + Python + Rust + Ruby + C + Java + C# + PHP + Scala + Kotlin + Swift + Dart + Pascal. Those edges
flow straight into `getImpactRadius` / `codegraph impact` and the impact trail in
`codegraph_explore` / `codegraph_node` — no agent-behaviour change required.

The win is **impact-radius correctness**, not agent read-reduction (see "Agent A/B").

## Edge semantics

- **Target:** a file-scope `const`/`var` whose name is "distinctive" (≥3 chars and
  contains an uppercase letter or `_`) — dodges the local-shadowing precision trap
  that single-letter / all-lowercase names invite.
- **Reader (source):** any `function` / `method` / `const` / `var` symbol whose body
  references the target name.
- **Same-file only** — resolution is unambiguous without import/scope analysis.
- **Deduped** per `(reader, target)`. **Additive** — adds edges, never nodes.

## Precision guards (in emission order)

1. **`isGeneratedFile(path)`** — skip suffix-recognised generated files (`.pb.ts`,
   `.min.js`, …). Path-only; it cannot catch content-minified bundles.
2. **Shadow prune** — drop a target when its **declarator count exceeds its file-scope node
   count**, i.e. it's also bound in an *inner* (local) scope. A bundled/Emscripten `const
   Module` re-declared as an inner `var Module`, a Go package const shadowed by a local `:=`,
   or a Python module const shadowed by a local `=` all resolve to the inner binding for nested
   readers — a file-scope edge would be a false positive. Inner re-bindings aren't graph nodes,
   so declarators are counted at the syntax level (per-grammar node types: `variable_declarator`
   for TS/JS, `const_spec`/`var_spec`/`short_var_declaration` for Go, `assignment` for Python,
   `const_item`/`static_item`/`let_declaration` for Rust).
   Comparing against file-scope node count (not a flat ">1") keeps **conditional module defs**
   (`try: X=…; except: X=…`), which legitimately bind a name twice at file scope. This catches
   the content-minified bundles guard #1 misses.
3. **Distinctive-name + same-file** as above.

## Validation matrix — TS / JS / Go / Python / Rust / Ruby / C / Java / C# / PHP / Scala / Kotlin / Swift / Dart / Pascal

Method per repo: index the same tree twice (value-refs on vs `CODEGRAPH_VALUE_REFS=0`),
diff node/edge counts, spot-check precision, and measure `codegraph impact` on a few
file-scope consts. Node count must be **identical** on/off (edges-only feature).

**TypeScript**

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| sindresorhus/ky | small | 54 | 562 (stable) | +29 (0.8%) | all sampled TP | — |
| excalidraw/excalidraw | medium | 645 | 10,301 (stable) | +717 (1.6%) | TP after shadow prune (#895 removed 23 woff2-bundle FPs) | `tablerIconProps` 1→**170** |
| microsoft/vscode | large | 11,548 | 333,999 (stable) | +10,605 (0.69%) | all sampled TP; no param-shadow / bundle FPs in top 200 | `LayoutStateKeys` 1→**85**, `CORE_WEIGHT` 1→52 |

**JavaScript** (same extractor; CommonJS, `var`, IIFE/UMD)

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| expressjs/express | small | 147 | 1,082 (stable) | +27 (0.75%) | all sampled TP | — |
| eslint/eslint | medium | 1,420 | 7,167 (stable) | +1,192 (4.2%) | all sampled TP; guard holds; no minified-file FPs | `internalSlotsMap` 1→**32**, `INDEX_MAP` 1→27 |
| webpack/webpack | large | 9,371 | 28,922 (stable) | +3,521 (4.8%) | all sampled TP; guard holds; no minified-file FPs | `LogType` 1→**89**, `LOG_SYMBOL` 1→90, `UsageState` 2→52 |

**Go** (package-level `const`/`var`; required extending the shadow prune — see below)

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| gin-gonic/gin | small | 110 | 2,599 (stable) | +166 (1.9%) | all sampled TP; guard holds | `abortIndex` 1→**24**, `jsonContentType` 1→8 |
| gohugoio/hugo | medium | 952 | 19,160 (stable) | +1,616 (2.5%) | all sampled TP; guard holds | `filepathSeparator` 2→**26** |
| prometheus/prometheus | large | 1,329 | 23,322 (stable) | +3,466 (3.3%) | all sampled TP; guard holds | `rdsLabelInstance` 1→**82**, `ec2Label` 1→24 |
| kubernetes/kubernetes | very large | 19,160 | 251,086 (stable) | +20,574 (1.9%) | all sampled TP; guard holds on 250 targets | `KubeletSubsystem` 3→**138**, `LEVEL_0` 1→102 |

**Python** (module-level `NAME = …`; required extending the prune *and* refining its rule — see below)

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| psf/requests | small | 49 | 1,299 (stable) | +85 (2.9%) | all sampled TP; guard holds | `ITER_CHUNK_SIZE` 1→4, `DEFAULT_POOLBLOCK` 1→4 |
| sqlalchemy/sqlalchemy | medium | 679 | 59,963 (stable) | +1,929 (0.8%) | all sampled TP; guard holds | `COMPARE_FAILED` 1→**26**, `DB_LINK_PLACEHOLDER` 1→19 |
| django/django | large | 3,005 | 61,748 (stable) | +1,328 (0.7%) | all sampled TP; guard holds | `_trans` 1→**138**, `SEARCH_VAR` 4→8 |

**Rust** (module-level `const`/`static`; declarators added, no rule change needed)

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| BurntSushi/ripgrep | small | 107 | 3,731 (stable) | +144 (0.9%) | all sampled TP; guard holds | `SHERLOCK` 7→**113** |
| tokio-rs/tokio | medium | 795 | 13,281 (stable) | +476 (1.1%) | all sampled TP; `#[cfg]`-conditional consts kept | `PERMIT_SHIFT` 1→**97**, `LOCAL_QUEUE_CAPACITY` 2→46 |
| rust-lang/rust-analyzer | large | 1,530 | 38,780 (stable) | +475 (0.25%) | all sampled TP; 0 real shadow leaks | `INLINE_CAP` 2→**183**, `SPAN_PARTS_BIT` 2→18 |

**Ruby** (`CONST = …`, almost always **inside a class/module** — needed the class-scope extension)

| Repo | size | files | nodes (on=off) | +value-ref edges | precision | `impact` on→off example |
|---|---|---|---|---|---|---|
| sinatra/sinatra | small | 96 | 1,800 (stable) | +73 (2.1%) | ~100% TP (flags are valid nested reads) | `HEADER_PARAM` 1→**5** |
... (370 lines truncated)
</file>

<file path="docs/from-chat/no-it-s-the-opposite.md">
# No — it's the opposite.

No — it's the opposite. CG-72 exists to *prevent* the scenario you're describing, and nothing in this epic puts any plugin on a slow path. Let me untangle the two things the card compresses.

**What's shipping in this epic (CG-64–71) has nothing to do with the kernel.** v1 plugins are framework/semantic plugins — route resolvers and synthesis passes, the same `FrameworkResolver` contract the ~35 built-ins (Express, Next.js, Django, Drupal…) use. They don't parse files; they run in the resolution layer after extraction. An external Acme-routes plugin executes on *exactly* the same path, at exactly the same speed, as the in-tree Drupal resolver. There is no legacy piping anywhere in v1. (The one real cost, which built-ins pay identically: any resolver with an `extract()` hook makes its languages' files take the decoded path instead of the kernel's raw-buffer shortcut — that's the price of framework extraction itself, in-tree or plugin, and CG-71's perf gate measures it.)

**CG-72 is about a different, not-yet-existing thing: plugins that add a whole new *language*.** For language support there are two implementations today — the Rust kernel (hot path for migrated languages) and the TS/tree-sitter extractor (the fallback, which plenty of in-tree languages still use). If we published a language-plugin API *today*, the only interface we could hand authors is the TS `LanguageExtractor` — and then yes, your worry becomes real, twice over:

1. Third-party languages would run the fallback path while first-party ones go native — permanently second-class, because
2. a published API is frozen. Semver obligations would fossilize the legacy interface as the public contract, and every future kernel change would have to tiptoe around it. We'd have built the slow lane *into the spec*.

So the deferral isn't "language plugins will be slow" — it's "we refuse to ship an API whose only possible implementation is the slow lane." CG-72's job is to design a backend-neutral `LanguageProvider` centered on the kernel's batch/buffer contract, so tree-sitter and the Rust walker become two implementations *behind* the same boundary and a third-party provider (likely WASM) plugs into the fast contract, not the legacy one. Until that spike lands, the honest position — stated in the doc — is that a new language is still a core contribution: nobody can write a language plugin at all yet, fast or slow, and that's deliberate.

One calibration on "way slower": the fallback path is just tree-sitter — it's what every language used before the kernel existed and what several still use. The kernel is a big win, not the difference between usable and unusable. The real stake in CG-72 is API-freezing, with performance as the visible symptom.
</file>

<file path="docs/grammars/tree-sitter-cobol.md">
# tree-sitter-cobol.wasm — provenance & rebuild

`src/extraction/wasm/tree-sitter-cobol.wasm` is built from
[yutaro-sakamoto/tree-sitter-cobol](https://github.com/yutaro-sakamoto/tree-sitter-cobol)
at commit `e99dbdc3d800d5fa2796476efd60af91f6b43d93` with the patch in
`tree-sitter-cobol.patch` applied (grammar.js + src/scanner.c; everything else
is regenerated by `tree-sitter generate`).

## What the patch adds

The upstream grammar (COBOL85, derived from opensource-cobol, NIST-tested)
parses batch COBOL well but chokes on the constructs that dominate real
mainframe and GnuCOBOL code:

1. **`EXEC ... END-EXEC` blocks** (CICS / SQL / DLI). Upstream has no EXEC
   support at all — the tokens get absorbed into the preceding statement until
   one breaks the parse, cascading hundreds of lines into one ERROR. The patch
   adds an `EXEC_BLOCK` external-scanner token that consumes the whole block,
   surfaced as a single `exec_statement` node (valid as a procedure statement
   and as a data-division entry, for `EXEC SQL INCLUDE`/`DECLARE`).
2. **`NOT=`** without a space (IBM COBOL accepts it).
3. **`FD <name>.` followed by `COPY`** for the record layout — upstream
   required a literal record description after every FD (also fixed for
   LINKAGE SECTION).
4. **`COPY ... REPLACING ==pseudo-text== BY ==pseudo-text==`** with multiple
   replacement pairs. (Upstream's `replacing_clause` never consumed the
   REPLACING keyword and allowed only one WORD/string pair.)
5. **Single-quote string continuation lines** (hyphen in the indicator
   column). Upstream's scanner handled continuation only for double-quoted
   strings; the patch generalizes the quote character and handles doubled-
   quote escapes (`'DON''T'`).
6. **`FUNCTION <intrinsic>(refmod)`** — upstream's generic FUNCTION fallback
   took arguments but not a reference-modification suffix
   (`FUNCTION CURRENT-DATE(1:4)`; the dedicated intrinsic tokens like
   `CURRENT-DATE-FUNC` only match opensource-cobol's *preprocessed* names).
7. **Standalone copybook entry point** — a `copybook_fragment` start
   alternative so `.cpy` files (data records or procedure paragraphs, no
   IDENTIFICATION DIVISION) parse without a wrapper. A file is either
   programs or one fragment, keeping program suffixes unambiguous.
8. **Wide mode for free-format source** — the extractor converts free-format
   COBOL to fixed by left-padding 7 columns and plants a `CGWIDE` sentinel in
   the first line's sequence area; the scanner then relaxes the column-72
   right margin (free-format lines routinely exceed it). One byte of scanner
   state, carried through serialize/deserialize. Fixed-format files are
   untouched.
9. **COBOL-2002 / GnuCOBOL surface**: `BINARY-LONG-LONG`, `FLOAT-LONG`,
   `FLOAT-SHORT` usages; `PROGRAM-ID. X IS RECURSIVE.`; relational `WHEN`
   objects (`WHEN > 0`); abbreviated combined relations
   (`WHEN X < 0 OR > Y`); bitwise operators (`B-AND`, `B-OR`, `B-XOR`,
   `B-NOT`, `B-SHIFT-L/-LC`, `B-SHIFT-R/-RC`); the `FREE` statement;
   `VALUE <constant-name>`; `PIC X(CONSTANT-NAME)`; `>>` compiler
   directives as comments; `ENTRY 'literal' USING ...` (IMS batch
   alternate entry points); empty `DATE-COMPILED.` / `DATE-WRITTEN.` /
   `SECURITY.` headers.
10. **`CALL ... GIVING`** — upstream *intended* to support it but a misnested
    `field()` call swallowed the GIVING alternative entirely.

## Measured parse health (at vendoring time)

| Corpus | Clean parses |
|---|---|
| AWS CardDemo, all programs incl. DB2/IMS/MQ variants (44 `.cbl`) | 43/44 — upstream: 9/31 on the base set alone. The one residual (a period-less `EXEC SQL INCLUDE` between paragraphs) is repaired by the extractor's preParse, which terminates the single-line form with a period. |
| AWS CardDemo copybooks (29 `.cpy`) | 28/29 — upstream: 0/29 (the failure is a `COPY REPLACING` template containing `(TESTVAR1)` placeholders, not valid COBOL pre-substitution) |
| NIST COBOL85 suite (382 programs) | 373/382 — unchanged from upstream |
| CobolCraft (17 free-format GnuCOBOL programs, via wide mode) | 17/17 — upstream: unparseable (free format) |
| Upstream corpus tests | 1 pre-existing failure (`comment`), no new failures |


## Rebuild

```bash
git clone https://github.com/yutaro-sakamoto/tree-sitter-cobol
cd tree-sitter-cobol
git checkout e99dbdc3d800d5fa2796476efd60af91f6b43d93
git apply path/to/tree-sitter-cobol.patch
# tree-sitter 0.24.x needs a tree-sitter.json; grammar name must stay COBOL
# (the C symbols are tree_sitter_COBOL*):
cat > tree-sitter.json <<'JSON'
{
  "grammars": [
    { "name": "COBOL", "camelcase": "COBOL", "scope": "source.cobol",
      "path": ".", "file-types": ["cbl", "cob", "cpy"] }
  ],
  "metadata": { "version": "0.1.1", "license": "MIT",
    "description": "COBOL grammar for tree-sitter",
    "links": { "repository": "https://github.com/yutaro-sakamoto/tree-sitter-cobol" } }
}
JSON
npm install tree-sitter-cli@0.24.5
npx tree-sitter generate
npx tree-sitter build --wasm -o tree-sitter-cobol.wasm   # needs emscripten or Docker
```

The patches are written to be upstreamable — each is independent and comes
with the failing construct documented above.

## Upstreaming

Sent as [yutaro-sakamoto/tree-sitter-cobol#41](https://github.com/yutaro-sakamoto/tree-sitter-cobol/pull/41)
(branch `real-world-cobol-sources` on the colbymchenry fork). If upstream
... (28 lines truncated)
</file>

<file path="docs/grammars/tree-sitter-kotlin.md">
# tree-sitter-kotlin.wasm — provenance & rebuild

`src/extraction/wasm/tree-sitter-kotlin.wasm` and the kernel's vendored C
(`codegraph-kernel/grammars/kotlin/`) are both built from
[fwcd/tree-sitter-kotlin](https://github.com/fwcd/tree-sitter-kotlin) (MIT)
tag `0.3.8` (commit `e1a2d5ad1f61f5740677183cd4125bb071cd2f30`), from the
tag's checked-in `src/parser.c` — never `tree-sitter generate` — with the
patch in `tree-sitter-kotlin.patch` applied to `src/scanner.c`.

| file | upstream sha256 | patched sha256 |
|---|---|---|
| `src/parser.c` | `54104a7ef1555c265b746c790e0f8bb953cc17806e9df0c3af82f7f62c06a70a` | unchanged |
| `src/scanner.c` | `27f73337ec357fc341fa57538f34c14277b0346980c3405dc30beab6202ec6d0` | `2ca842dd04b60b0a6df59a03e9ad01209d8c5641f079a79a84d65708669b6cb6` |
| `tree-sitter-kotlin.wasm` | `c80c88867a589a1a0959bcea89de84b7e9684b3693b2cdb2944812458e62ff48` | `e2ef7c0c83e5fd4bece547d2acd41b9f89da2fed5644d74be139b9765d4c74af` |

## What the patch fixes

The external scanner decides where to insert an automatic semicolon. On the
same line as the end of an expression it inserted one before any word
starting with `e` that was not `else` — so an infix call with such a name
(Exposed's `Users.id eq id1`, used in nearly every Exposed query) ended the
statement early and the rest became a parse error. On a file with many of
them, error recovery could swallow the whole class: Exposed's r2dbc
`UpsertTests` came out as one loose function nesting every test.

On the same line nothing but `;` or `import` starts a new statement, so the
patched scanner inserts no semicolon before any `e` word. Measured on
Exposed, files with a parse error went from 229 to 71 of 1,004; koin,
nowinandroid, moshi, okio, okhttp and kotlinx.coroutines parsed exactly as
before (one okhttp file fixed, none broken).

## Rebuild

```
git clone --depth 1 --branch 0.3.8 https://github.com/fwcd/tree-sitter-kotlin
cd tree-sitter-kotlin
git apply /path/to/codegraph/docs/grammars/tree-sitter-kotlin.patch
# the 0.3.8 tag predates tree-sitter.json, which cli 0.25.10 requires —
# add the METADATA-ONLY shim (grammar name/scope; nothing regenerated):
#   {"grammars":[{"name":"kotlin","scope":"source.kotlin","path":".",
#     "file-types":["kt","kts"]}],"metadata":{"version":"0.3.8","license":"MIT"}}
npx -y tree-sitter-cli@0.25.10 build --wasm -o tree-sitter-kotlin.wasm .
cp src/scanner.c /path/to/codegraph/codegraph-kernel/grammars/kotlin/scanner.c
```

Built without the patch, the same command reproduces the upstream wasm above
byte for byte. After updating either side, rebuild the kernel
(`npm run build:kernel`) and check `scripts/kernel-parity.mjs` on a Kotlin
repo: the wasm and the kernel must parse the same.
</file>

<file path="docs/grammars/tree-sitter-vbnet.md">
# tree-sitter-vbnet.wasm — provenance & rebuild

`src/extraction/wasm/tree-sitter-vbnet.wasm` is built from
[govindbanura/tree-sitter-vbnet](https://github.com/govindbanura/tree-sitter-vbnet)
(MIT) at commit `538b7087bf80e86004531b392fe1186379c0a2b5` with the patch in
`tree-sitter-vbnet.patch` applied. The patch carries two files: `grammar.js`
(edits) and `src/scanner.c` (a new external scanner; upstream has none). The
upstream repo checks in no generated `src/`, so everything else is produced by
`tree-sitter generate`.

Alternatives considered: `CodeAnt-AI/tree-sitter-vb-dotnet` (22★) has **no
license file** and its git history stopped in July 2025 — unusable for
vendoring; `gabriel-gubert/tree-sitter-vbnet` is a 470-line VBScript-flavored
toy. The Roslyn-based approach (PR #627) was withdrawn by its author in favor
of tree-sitter — a Roslyn sidecar would add a .NET runtime dependency to a
local-first npm tool.

## What the patch adds

Upstream parses textbook VB.NET but fails on the constructs that dominate real
codebases (measured: 3–18% of files parsed clean across PolicyPlus, CompactGUI,
and staxrip before patching). Each item below was found by parse-error census
on those repos plus SCrawler and PCL:

1. **Generic type arguments in dotted names** — `System.Collections.Generic.
   Dictionary(Of K, V)`, `Implements IRepository(Of Invoice)`, and
   method-level `Implements I(Of T).Member` (generic segments were only
   accepted unqualified). Open generic types (`GetType(LoaderTask(Of ,))`)
   parse too.
2. **Interpolated strings** `$"… {expr[,align][:fmt]} …"` with `""`/`{{`/`}}`
   escapes — including multi-line bodies and content pieces that begin with an
   apostrophe: the pieces carry lexical precedence 101 (above `comment`'s 100)
   because the comment **extra** otherwise fires *inside* the string rule and
   eats the rest of the line, closing quote included.
3. **Date/time literals** `#1/15/2020#` — previously lexed as a preprocessor
   directive that swallowed to end-of-line. Directives are now constrained to
   `#` + letter (`#If`, `#Region`, …), which real directives always satisfy.
4. **VB 14 multi-line string literals** (a `"…"` literal may span lines since
   VS 2015) and single-token `string_literal`/`character_literal` (`"["c`) —
   the old multi-token form let extras interleave mid-string.
5. **Numeric literal forms** — hex/octal/binary (`&HFF`, `&O777`, `&B1010`),
   digit separators (`1_000`), type characters (`6.0!`, `50.0#`, `1.5@`,
   `123&`, `7%`), and lowercase `f/r/d` suffixes. WinForms `.Designer.vb`
   files are full of `6.0!`.
6. **Identifier type characters and Unicode identifiers** — `Dim i% = 0`,
   `Dim r$ = …` (classic VB style, pervasive in SCrawler) and full Unicode
   identifiers (`CrashReason.Java虚拟机参数有误` — PCL is written in Chinese).
   The identifier token is now `[\p{L}\p{Nl}_][\p{L}\p{Nl}\p{Nd}\p{Mn}\p{Pc}]*
   [%$&!#@]?` with the `u` regex flag. **The `u` flag requires
   tree-sitter-cli ≥ 0.25** — 0.24.x silently drops the `\p{…}` classes.
7. **`As New T(args)` initializer clauses** — `as_clause` embeds a full
   `object_creation_expression` for the `As New` form, so `Dim x As New
   StringBuilder` / `Property P As New List(Of String)` produce instantiation
   nodes. `Dim x? = expr` nullable declarators parse as well.
8. **Statement separators and single-line forms** — `:` as a statement
   terminator and block opener (`Class X : Inherits Y`, `Case 1 : Return "X"`),
   single-line `If … Then stmt Else stmt` (via terminator-less inline statement
   variants, aliased to the normal statement node names), inline `RaiseEvent`,
   and optional `Then` on block `If` and `ElseIf` (legal VB, used in staxrip).
9. **Multi-line lambdas** — `Sub(…) … End Sub` / `Function(…) … End Function`
   bodies (upstream had a statement-block body with no `End` closer, so every
   block lambda broke its surrounding argument list), `Async`/`Iterator`
   lambda modifiers, `ByVal`/`ByRef` lambda parameters, and single-line
   `Sub() If cond Then …` statement bodies.
10. **Member declarations** — `Declare [Auto|Ansi|Unicode] Sub/Function … Lib
    "dll" [Alias "…"]` P/Invoke declarations, `Custom Event … AddHandler/
    RemoveHandler/RaiseEvent … End Event`, stacked attribute lines above one
    member, property `= initializer` before `Implements`, type-less
    auto-properties, and **`MustOverride` body-less methods and properties**:
    `MustOverride` lexes as a dedicated token (removed from the
    `member_modifier` alternation) that only `abstract_method_declaration` /
    `abstract_property_declaration` accept, making the body-less parse
    deterministic. (A GLR body-less alternative on `method_declaration` was
    tried first and measurably poisoned error recovery — 100%→60% clean on
    PolicyPlus — before being replaced with the token split.)
11. **Expressions** — VB 15 tuple literals `(a, b)`, array literals
    `{1, 2, 3}` (plus nested `{{k, v}, …}` dictionary groups, replacing the
    ambiguous upstream `dictionary_initializer`), omitted argument slots
    (`f(a,, b)` — Optional parameters passed positionally), `TypeOf x IsNot T`,
    generic method calls without parens (`items.OfType(Of Panel)`),
    null-conditional indexing `x?(0)`, and `Global.`-qualified type names.
12. **LINQ queries** — query expressions no longer require a trailing
    `Select`/`Group` clause, `Aggregate`-led queries, and
    `Distinct`/`Skip`/`Take` clauses.

### External scanner (`src/scanner.c`, new)

Two constructs are not LR(1)-parseable with tree-sitter's newline-as-extra
treatment; both get external tokens:

- **`QUERY_CLAUSE_CONTINUATION`** — multi-line LINQ (`From x In xs` ↵
  `Where …`). At a clause boundary the newline alone cannot distinguish
  "query continues on the next line" from "statement ends here". The scanner
  looks past the newline run at the next word and emits the continuation
  token only when it is a query-clause keyword (with a `Select Case`
  guard), so the decision is made by the lexer instead of the LR table.
- **`XML_LITERAL`** — whole VB XML literals (`<Tags><Tag/></Tags>`) consumed
  as one opaque token: element nesting, attributes, comments, CDATA,
  processing instructions, and **nested** `<%= … %>` embedded expressions
  (the staxrip `WriteTagfile` shape). Valid only where a literal can begin an
... (72 lines truncated)
</file>

<file path="docs/plans/2026-04-24-framework-resolver-extract.md">
# Framework Resolver `extract()` Wiring Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Wire up the dead `FrameworkResolver.extractNodes` hook so every framework resolver can contribute route nodes AND route-to-handler edges to the graph, and update all 13 existing framework resolvers to use it correctly.

**Architecture:** Replace the unused `extractNodes?(filePath, content): Node[]` hook with a single `extract?(filePath, content): { nodes, references }` method. Call it once per file during the extraction phase (after tree-sitter parses the file) for any framework whose language matches the file. Extracted nodes go into the DB alongside tree-sitter nodes; extracted references flow into the existing unresolved-references pipeline so the existing name-matcher / import-resolver / framework `resolve()` machinery creates the final edges. Net effect: `path('/users', UserListView.as_view())` produces a `route` node linked by a `references` edge to the `UserListView` class node — and the equivalent holds for Flask, FastAPI, Express, Rails, Laravel, Spring, Gin, Axum, ASP.NET, Vapor, React Router, and SvelteKit.

**Tech Stack:** TypeScript, vitest, tree-sitter (existing), better-sqlite3 (existing). No new dependencies.

---

## Background

Today, every `FrameworkResolver` ships with an `extractNodes?(filePath, content)` method (express, laravel, python/django, python/flask, python/fastapi, ruby/rails, java/spring, go, rust, csharp, swift × 3, react, svelte). None of them are ever called. Empirical proof: grep across `src/` finds exactly one reference to `extractNodes` — the interface definition at `src/resolution/types.ts:99`. As a result the graph has zero `route` kind nodes in practice, and the link between a URL entry in a routing file and its view/controller/handler doesn't exist.

Separately, the Django extractor's regex captures the view name in group 2 but the destructure in `src/resolution/frameworks/python.ts` discards it, so even if the hook were alive it wouldn't link the route to the view. Similar shape bugs exist across most frameworks.

This plan fixes both problems in one coherent change.

## File Structure

- `src/resolution/types.ts` — add `extract?()` to `FrameworkResolver`; remove `extractNodes?()`.
- `src/resolution/frameworks/index.ts` — keep `detectFrameworks` signature; add `getApplicableFrameworks(language)` helper.
- `src/resolution/frameworks/python.ts` — rewrite Django/Flask/FastAPI extractors.
- `src/resolution/frameworks/express.ts` / `laravel.ts` / `ruby.ts` / `java.ts` / `go.ts` / `rust.ts` / `csharp.ts` / `swift.ts` / `react.ts` / `svelte.ts` — migrate to new interface.
- `src/extraction/index.ts` — plug framework extraction into `ExtractionOrchestrator.indexAll` after per-file tree-sitter parse.
- `src/extraction/parse-worker.ts` — pass detected-framework names into the worker so the worker can invoke framework extractors itself (needed because main-thread `extractFromSource` and worker-thread parse path both have to cover this).
- `__tests__/frameworks.test.ts` — NEW. One `describe` per framework, checking that representative fixtures produce the expected `{nodes, references}`.
- `__tests__/frameworks-integration.test.ts` — NEW. End-to-end test: index a tiny Django project fixture, assert a `route -> class` edge with kind `references` exists from `urlpatterns` entry to `UserListView`.

Rationale for splitting the two test files: the unit tests are deterministic string-in / array-out and run in milliseconds; the integration test boots a CodeGraph DB and is slower but gives the strongest behavioral guarantee.

## Scope Note

This plan does NOT move Django extraction from regex to AST. The regex approach is fine for the shapes this PR targets (`path(...)`, `url(...)`, `re_path(...)`, `include(...)`, DRF `router.register(...)`, CBV `.as_view()`, dotted module paths). A follow-up PR can swap the regex for AST walking using tree-sitter's existing Python parser. That's a larger change and doesn't block this one.

---

## Task 1: Update the `FrameworkResolver` interface

**Files:**
- Modify: `src/resolution/types.ts:88-100`

- [ ] **Step 1: Write the failing test**

Create `__tests__/frameworks.test.ts`:

```typescript
import { describe, it, expect } from 'vitest';
import type { FrameworkResolver, UnresolvedRef } from '../src/resolution/types';
import type { Node } from '../src/types';

describe('FrameworkResolver.extract interface', () => {
  it('extract() returns { nodes, references }', () => {
    const resolver: FrameworkResolver = {
      name: 'fake',
      detect: () => true,
      resolve: () => null,
      languages: ['python'],
      extract: (_filePath: string, _content: string) => ({
        nodes: [] as Node[],
        references: [] as UnresolvedRef[],
      }),
    };
    const result = resolver.extract!('foo.py', '');
    expect(result).toEqual({ nodes: [], references: [] });
  });
});
```

- [ ] **Step 2: Run test to verify it fails**

Run: `npx vitest run __tests__/frameworks.test.ts`
Expected: FAIL — `extract` is not a property of `FrameworkResolver`; `languages` is not a property of `FrameworkResolver`.

- [ ] **Step 3: Update the interface**

Replace `src/resolution/types.ts:88-100` with:

```typescript
/**
 * Result of framework-specific file extraction.
 */
export interface FrameworkExtractionResult {
  /** Framework-specific nodes (e.g. routes) */
  nodes: Node[];
  /** Framework-specific unresolved references (e.g. route -> handler) */
  references: UnresolvedRef[];
}

/**
 * Framework-specific resolver
 */
export interface FrameworkResolver {
  /** Framework name */
  name: string;
  /** Languages this framework applies to. If omitted, applies to all languages. */
  languages?: Language[];
  /** Detect if project uses this framework (project-level, called once at startup) */
... (1018 lines truncated)
</file>

<file path="docs/plans/2026-08-28-steps-and-screens-for-apis-and-web.md">
# Steps & Screens for APIs and web apps — handoff

**Status:** plan, written 2026-08-28 at the end of the session that built the Steps view and the
readings it rests on (Expo + React Native app, `amniservices-mobile-app`). **Updated the same day, later
sessions: P0–P6 are built** (see the per-item notes marked *Built*); P7 has its first agent A/B (proshop, small) and
the medium / large rows are open.
**Next: BUILT (2026-08-29).** `docs/plans/2026-08-29-steps-in-code-order.md` — the Steps tab reading a handler in the
code's order (a rail with forks) instead of the tree by distance; a derivation from this walk, no new walk. P0–P6 are
in (`src/ui-server/api/program.ts`, `ui/src/lib/program-model.ts`, spec §3.13.1); validating it against four real
servers also fixed three defects in THIS walk — a hop's span read from the wrong call, a name-match the call as
written disproves, and a value with one `references` edge going unlent the file's calls. Every claim about what a
resolver emits *today* was verified against the source on this date — re-verify before building on it,
the resolvers move. What was learned building it, beyond the plan: the index keeps only the LAST
segment of a deep member call (`create` for `prisma.user.create`) and name-matches it — often to the
wrong `create` at confidence 0.4 — so the Steps walk reads every call **as written** from the tree at
request time (`callSitesForFile`) and classifies on the chain; and the declared types of a class's
members (`private readonly usersService: UsersService`, `OwnerRepository owners`) are read from the
class body (`memberTypesInTree`) to send `this.usersService.findByEmail(…)` where the type says and to
call `owners.save` the database. Validation pictures: `gothinkster/node-express-realworld-example-app`,
`brocoders/nestjs-boilerplate`, `nestjs/nest/sample`, `fastapi/full-stack-fastapi-template`,
`Netflix/dispatch`, `spring-projects/spring-petclinic`, `spring-petclinic/spring-petclinic-kotlin`,
`dotnet-architecture/eShopOnWeb`, `jqlang/jq`, `redis/redis`, `android/nowinandroid`,
`Dimillian/IceCubesApp`, `TryGhost/Ghost` — each shot headlessly (`codegraph ui --no-open` + Playwright)
and read against the mobile app's picture.

**Goal.** The two pictures — **Screens** (`#/screens`, design spec §3.12) and **Steps**
(`#/steps`, §3.13) — must be as good on an Express / NestJS / Fastify API, a Next.js / React Router /
SvelteKit web app, and a monorepo that has both, as they are on the mobile app today. "As good" is
defined precisely in §1 below; it is not "draws something".

Companion reading, in this order: `docs/design/codegraph-ui-design-spec.md` §1 (principles), §3.12,
§3.13, §3.14; `CHANGELOG.md` `[Unreleased]` (the user-facing description of what shipped);
`docs/design/dynamic-dispatch-coverage-playbook.md` (the coverage rules and the validation method —
**"partial coverage is worse than none"** governs everything here); `CLAUDE.md` (tests, kernel, docs).

---

## 1. The bar: what "up to par" means

On the mobile app, selecting `/capture/review` and walking to the upload gives the reader, per link:

| Reading | Example | Where it comes from |
|---|---|---|
| **The step itself, typed** | `⇢ finalizeCaptureSession` (native call), `⇠ onZipComplete` (native event), `setZipUri` (store action), `axios.post(\`…/oauth/token\`, {…})` (leaves the index) | `src/ui-server/api/steps.ts` classification |
| **FIRES FROM** — what triggers it | `onSubmit · useFormik(…) in LoginButton`, `onPress · <Button>`, `addListener('onZipComplete')` | `graph/branch-guards.ts` `triggersForFile` — read at request time from the cached tree |
| **via** — the plumbing folded into the arrow | `via LoginButton → handleLogin`, `via uploadARCapture` | the walk's fold (`steps.ts`) |
| **WHEN** — the conditions, as words, one row per scenario | `WHEN NOT (busy \|\| late)` once, then `AND NOT user?.organization_id` · site, `AND user?.organization_id AND (…)` · site … | `guardsForFile` + `ui/src/lib/conditions.ts` (`scenarios`, `whenTokens`) |
| **with what** — the arguments as written | `SecureStore.setItemAsync('userEmail', values.email)`, `client.post('/frames', { uri })` | `callArgumentsForFile` |
| **Honesty** | other screens are boundaries (`…`), caps announced on the step they hit, synthesized hops dashed, a crossing needs evidence | `steps.ts` caps + `evidenced` rule |

An API or web project reaches the bar when its canonical flow — **request → guard/middleware →
handler → service → database → queue/email/other service → response** for an API, **page → data
fetch → user action → server action/route → database → redirect** for a web app — shows every one of
those readings on every link, on a real mid-size repo, with the caps and the boundaries behaving as
they do on the mobile app. Numbers to record per framework are in §7.

---

## 2. How the pictures work today — the facts they rest on

Read this before touching anything. Each picture is a pure function of a small set of graph facts;
extending the pictures to a new framework is almost entirely a matter of making the **same facts
exist** for it, plus wording.

### 2.1 Screens (`src/ui-server/api/screens.ts`, `ui/src/lib/screens-model.ts`)

| Needs | Today comes from |
|---|---|
| `route` nodes named by path (`/capture/review`) | `resolution/frameworks/expo-router.ts` (file-path routing); React Router / Next.js *pages* routes from `frameworks/react.ts` also exist but carry no navigation |
| route → the component that renders it (`calls` / `instantiates` edge out of the route) | expo-router resolver (default export of the screen file) |
| `navigates` edges from the function that pushes a path to the route it names, with `metadata.href` / `navMethod` | expo-router resolver (literal / template / pathname-object hrefs) + `resolution/expo-router-synthesizer.ts` (helper return values → `provenance: 'heuristic'`) |
| the attribution walk BACK from the navigation call to a screen's component, folding the chain into `via` | `screens.ts` (`attribute`, caps: 7 hops / 30 callers / 800 visited) |
| `when` per site | `createSiteReader(...).when` in `api/when.ts` → `guardsForFile` |

If there are no `navigates` edges the endpoint answers `routed: false` and the view says "No screen
navigation in this graph". **That is what every API and every non-Expo web app gets today.**

### 2.2 Steps (`src/ui-server/api/steps.ts`, `ui/src/lib/steps-model.ts`, `ui/src/views/StepsView.svelte`)

The walk: from the anchor, breadth-first over `calls` / `instantiates` / `navigates` /
function-as-value `references` (`metadata.fnRef`) / function→function `contains`, folding every node
that is not a step into `via`. A node **is** a step when it is one of:

| Kind | Evidence today | Server rule |
|---|---|---|
| `screen` | target is a `route` node | any edge into a route (a `navigates` edge in practice) |
| `trigger` (handler) | a function passed as a value (`fnRef`), **or** called from under an event binding — JSX prop, `on*` option, runs-later callback (`triggerInTree`) — and not a component, not a store action | `steps.ts` classification, `looksLikeComponent` |
| `bridge` ⇢ | language family changes JS→native **and** the edge is evidenced: `metadata.bridge === 'react-native'`, `resolvedBy === 'framework'`, or `provenance: 'heuristic'` | `crossing()` + `evidenced`; a plain name-matched cross-family call is dropped |
| `event` ⇠ | native→JS, evidenced (`synthesizedBy: 'rn-event-channel'`) | same |
| `store` | function in a store **file** (`STORE_FILE` regex: `stores?/`, `storage/`, `.store.ts`, `.slice.ts`…) — file-name evidence, the legend says so | `isStoreFile` |
| `effect` | an unresolved call, or a call that resolved to a `constant`/`variable`, whose text matches the curated `EFFECTS` table: `network`, `storage`, `device`, `telemetry` | `effectCategory`; one box per (function, category), `apis[]` listed |

Boundaries and caps (all announced on the step, `cut`): another **screen** (`through=1` enters it), a
native event landing in a **component** of another screen, depth (8 default, ≤14), fan-out per node
(80), folded nodes per step (300), steps per picture (120 default, ≤400); hubs (fan-in ≥ 40) and shared
chrome (a component rendered by ≥ 5 parents) are dead ends counted in `truncated`. HOC wrappers
(`memo(X)`) are seen through via the file-scope function reference within the wrapper's lines.

**Where the anchor's root comes from:** for a `route` anchor the walk starts at the component the
route renders — found as the first `calls`/`instantiates` edge OUT of the route node (`componentOf`
... (405 lines truncated)
</file>

<file path="docs/plans/2026-08-29-steps-in-code-order.md">
# Steps, in the code's order — plan

**Status: BUILT** 2026-08-29 on `feature/steps-servers`, P0–P6. Written the same day (at tip `5797d7e`) as a plan for a
fresh session; what follows is that plan, kept as written, with the notes below on where the build differs from it.
The reading is `&view=order` on the Steps tab, `src/ui-server/api/program.ts` + `ui/src/lib/program-model.ts`, and
spec §3.13.1 is the description of what was built.

**Where the build differs from the plan:**
- **A guard carries the decision it belongs to** (`BranchGuard.branch`), not just its text and line — §4.1's
  "same `line`, same `text`" pairing does not tell one `switch` case from another, nor two `try`/`catch` blocks apart.
  It also carries how the arm it is in leaves (`armExit`) and, for an early exit, how the arm not taken leaves (`exit`),
  which is where `WireArm.ends` comes from.
- **A function is read ONCE per rail** (`again` on the item), not redrawn at every call: expanding per path turned an
  87-step screen into 3,849 items and 618 KB. Once-only is 476 items and 94 KB (+3% wall clock on that picture).
- **A step the walk entered reads on into its own body** under its box, so the rail holds the same steps the tree does
  (§4.1.7 only said this for boundaries under `through`).
- **`WireItem`'s blocks are one kind with a discriminator** (`block: 'inline' | 'loop' | 'later' | 'together'`) rather
  than four item kinds, and they carry facts (`by`, `via`, `loop`) rather than words — the viewer says them.
- **The reading is drawn on the CANVAS, not as a nested document.** §4.2's rail — a column of boxes with forks as rows
  of arm columns — was built first and rejected on sight by the maintainer: *"this is very hard to read… go back to the
  way it looked, but since the 200 and 401 come after the signing of the jwt those should branch out of it."* The right
  picture is the same Svelte Flow canvas with the same boxes, laid out by WHEN things happen: a line means **and then**,
  a row down is one more thing already done, and the fork's condition rides on the line (drawn at rest — on this
  picture the conditions are the content). `ui/src/lib/program-model.ts` turns the block tree into that graph;
  `StepsRail`/`RailBlock` are gone.
- **Loops needed their own reading** (`loopsForFile`), and loops and forks nest by which construct BEGINS first, since
  neither reading knows about the other.
- The open questions of §7 were answered: order for functions/endpoints and the tree for screens (1); read each
  function once rather than capping the fold depth (2); a loop's body once, marked (3); the fork carries its condition
  and the arms say WHEN / WHEN NOT (4).

The Steps tab as it stood (spec §3.13, `src/ui-server/api/steps.ts`, `ui/src/views/StepsView.svelte`) is the base;
everything here is a second *reading* of the same walk, not a new walk.

**The ask, in the maintainer's words:** on proshop's `POST /api/users/login` the picture draws `User.findOne · jwt.sign ·
200 · 401` in one row under the handler. That is true — all four are one step from `authUser` — and it is not what a
person wants from a handler. They want *the flow of the code*: first the lookup, then **if** the password matches, sign a
token and answer 200, **else** answer 401. "I think this should show the flow/order of the code. That would be way more
useful to me." Build that.

Read first, in this order: spec §3.13 and §3.14 (`docs/design/codegraph-ui-design-spec.md`), then
`docs/plans/2026-08-28-steps-and-screens-for-apis-and-web.md` §2 and §6 (how the pictures work and the gotchas), then the
auto-memory note `steps-for-apis-2026-08-28` (the two facts that made Steps work, the screenshot harness), then the files in
§3 below. `CLAUDE.md` for tests, docs and the no-kernel-work rule (this plan is all request-time: no extractor changes).

---

## 1. The reading to build

For `authUser` in `bradtraversy/proshop_mern` (`backend/controllers/userController.js`):

```js
const user = await User.findOne({ email })
if (user && (await user.matchPassword(password))) {
  res.json({ _id: user._id, …, token: generateToken(user._id) })
} else {
  res.status(401)
  throw new Error('Invalid email or password')
}
```

the picture reads top to bottom, as a rail that forks where the code forks:

```
● POST /api/users/login · authUser          FIRES FROM POST /api/users/login
│
├─ User.findOne({ email })                  database · User · read
│
╞═ user && (await user.matchPassword(password))
│    ┌─ WHEN ──────────────────────────┐   ┌─ WHEN NOT ─────────────────────────┐
│    │ jwt.sign({ id }, …)  auth        │   │ 401 · res.status(401)   response    │
│    │   via generateToken · inside     │   │   then throw new Error('Invalid …') │
│    │   res.json(…)                    │   └─────────────────────────────────────┘
│    │ 200 · res.json({ _id, …, token })│
│    └─────────────────────────────────┘
```

Every reading the Steps tab has today survives on each box — kind, `FIRES FROM`, `via`, `WHEN`, what it passes, the status,
`inside res.json(…)` — but the *arrangement* is the code's: **sequence down the rail, branches as forks, an arm that
replies (or returns / throws) ends there, arms that fall through rejoin.** A helper the walk folded (`generateToken`) is
drawn *in place*: its own steps appear where it is called, marked `via generateToken`. A boundary (another endpoint the
handler calls, another screen) sits in the sequence where the call is, still not entered unless `through` asks.

The reading is the **outline of a function**, not a control-flow graph: statements in source order, `if` / `else` /
`switch` / `try` / early exits as forks, loops as a marked block (the body once, "for each …"), callbacks that run later
(`.then`, `setTimeout`, `useEffect`) as a marked block ("later"), `Promise.all([a(), b()])` as siblings marked "together".
Source order is execution order for straight-line code and for arguments before their call; where it is not (callbacks,
concurrency) the block says so rather than pretending.

**What stays:** the existing tree ("what it sets in motion", rows = distance) remains as the other reading, one toggle
away — it is the right picture for a screen, where handlers fire on events and have no order. **Default:** in order when
the anchor's root is a function / method (a handler, an endpoint, any symbol); the tree when the anchor is a screen.
Both read the same URL (`&view=order` / `&view=tree`), the same panel, the same double-click and `Start here →`.

---

## 2. Why the current picture cannot say it

`buildSteps` is breadth-first from the anchor's root: a node is a *step* when it is a screen, a handler, a bridge, an
event, a store action or an effect; everything else folds into the link's `via`. Rows are distance from the anchor.
... (242 lines truncated)
</file>

<file path="docs/AGENTS.md">
# AGENTS.md (docs/)

Nested Codex guidance under `docs/`. Loaded with the repo-root `AGENTS.md` when cwd is under `docs/` (Codex walks root to cwd; shared `project_doc_max_bytes` budget).

Root `AGENTS.md` already carries the non-negotiable retrieval principles (adapt-the-tool, explore budgets, end-to-end synthesis). This file holds the longer validation methodology and Excalidraw worked example that were moved out of root to fit the budget.

### Validation methodology (REQUIRED for every new language/framework)

For each **language × framework**, validate on **small, medium, and large** real repos with **≥3 different flow prompts** each:

1. **Pick the canonical flow** for the framework ("how does X reach Y": state→render, request→handler→view, query→SQL, action→reducer→store…).
2. **Deterministic probes** (`scripts/agent-eval/probe-{node,explore}.mjs` against the built `dist/`): `codegraph_explore` with the flow's symbol names connects from→to end-to-end with no break (its Flow section shows the path); **no node explosion** (`select count(*) from nodes` stable before/after re-index); synthesized-edge **precision** spot-check (`select … where provenance='heuristic'`).
3. **Agent A/B** (`scripts/agent-eval/run-all.sh <repo> "<Q>"`): with vs without codegraph, **≥2 runs/arm** (run-to-run variance is large — never conclude from n=1). Record **duration, total tool calls, Read, Grep**. Optional forced-Read-0 sufficiency proof via the block-read hook (`scripts/agent-eval/hook-settings.json`).
   - **Every run also reports three feedback metrics** — residual context occupancy, explore sufficiency (what the agent did NEXT after each explore), and allocation efficiency (share of returned bytes the answer cited) — under each run, plus a side-by-side arm table (`compare-arms.mjs`). Entry point: `docs/benchmarks/agent-eval-feedback-metrics.md`. Reading them: `Read a file we returned` is an allocation miss, `Read a file we did NOT return`/`Grep` is recall; allocation efficiency is **relative** (attribution is by citation) so it is only valid between builds on the same question; occupancy *shares* are Claude Code / 200k and don't transfer to another host — the arm ratio does.
   - **The `codegraph` CLI is blocked in every arm** (`no-cli-shim.sh`: sanitized PATH + a PreToolUse hook, shared by both harnesses). Without it 14 of 15 without-arm runs in one 7-repo pass reached codegraph through Bash. Check the contamination row before believing any number: `CLI calls that RETURNED output` > 0 invalidates the run (in a new-vs-baseline A/B it silently drops calls from all three metrics, since a CLI explore is not a tool call).
   - **Model policy — every A/B arm runs Claude with `--model sonnet --effort high`. Always. Never Opus/Fable.** All `scripts/agent-eval/*.sh` default to this (`MODEL`/`EFFORT` env override exists — don't raise it without an explicit reason from the maintainer). Two reasons, and the second matters more than cost: (a) Sonnet doesn't burn tokens; (b) **Sonnet is the deliberate floor model** — codegraph's real users attach it to whatever agent they already run (Cursor Composer, Gemini, etc.), so we validate on a "dumber" model on purpose: a stronger model's tool-use covers up the salience/sufficiency problems a weaker one exposes. An affordance that lands on Sonnet generalizes up to every host; one that only works on Opus/Fable doesn't generalize down to the agents most users actually have. Both arms always use the same model.
   - **MCP attach is a startup-latency issue, not a hard block.** On a multi-step task the agent dives into Read/grep before codegraph finishes its ~2-3s startup (worse when the eval is itself run nested inside a Claude session, under CPU contention), so it runs with no codegraph. Fix: **pre-warm a persistent daemon** for the target (`CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS` high; spawn `serve --mcp --path <target> </dev/null &`; wait for `.codegraph/daemon.sock`) **and skip the startup re-exec** (`CODEGRAPH_WASM_RELAUNCHED=1`) so claude connects before the agent's first turn. Don't trust claude's `init` snapshot — it can read `status:"pending"` / 0 tools even when it then connects; judge by actual codegraph usage in `parse-run.mjs`'s `by type`. To isolate a change — **new-build vs baseline-build, both codegraph-on** (vs run-all.sh's with-vs-without) — use `scripts/agent-eval/ab-new-vs-baseline.sh <indexed-repo> "<task>" [baseline-ref]` (it bakes in the pre-warm).
4. **Pass bar:** a normal flow question reaches **~0 Read/Grep within the repo's explore-call budget**, runs **faster** than without-codegraph, and shows **no regression on a control repo**. Record the numbers in `docs/design/dynamic-dispatch-coverage-playbook.md` (the coverage matrix).

Full playbook + per-mechanism design: `docs/design/dynamic-dispatch-coverage-playbook.md` and `docs/design/callback-edge-synthesis.md`.

### Worked example — Excalidraw (TS/React, medium, 643 files)

The template to replicate per language/framework. Question: *"how does updating an element re-render the canvas on screen?"* (the full flow crosses three React boundaries: observer callback, `setState`→`render`, and JSX child).

| Stage | duration | Read | Grep | codegraph |
|---|---|---|---|---|
| Without codegraph | 115–139s | 9–10 | 10–11 | 0 |
| Broken (explore-budget regression) | 131–139s | 5–10 | 3–5 | 6–14 |
| Fixed (budget + msgs + synthesis) | 64–112s | 0–2 | 2–4 | 3–**10** |
| + trace-first steering | **51–74s** | **0–2** | 0–4 | **3–4** |

n=4 unhooked runs/stage, same prompt. After steering flow questions to `codegraph_trace` first: **best run 0 Read / 0 Grep / 3 codegraph / 51s**; **2 of 4 fully clean** (0 Read, 0 Grep). Steering eliminated the over-drill variance — call count tightened from 3–10 to 3–4, trace adoption went 3/4 → 4/4, and the `search`+`callers` path-reconstruction floundering dropped to 0. Run-to-run variance is still real; report the range, never a single run. **Residual reads/greps are all the nonce data-flow** (`canvasNonce` — a local prop with no graph edges); that's the def-use/data-flow frontier, left deliberately uncovered (tracking every local would explode the graph). Validated: `trace(mutateElement, renderStaticScene)` connects in **6 hops** across all three boundaries (`mutateElement → triggerUpdate → [callback] triggerRender → [react-render] render → [jsx] StaticCanvas → renderStaticScene`), each hop showing inline source + the wiring site; node count stable at 9,289; 1 callback + 46 react-render + 280 jsx-render synthesized edges (no explosion, precision-checked).


Also see: `docs/design/dynamic-dispatch-coverage-playbook.md`, `docs/design/callback-edge-synthesis.md`, `docs/benchmarks/call-sequence-analysis.md`, `docs/benchmarks/agent-eval-feedback-metrics.md`.
</file>

<file path="docs/SEARCH_QUALITY_LOOP.md">
# CodeGraph Language Verification Guide

You are verifying that CodeGraph fully supports a specific programming language. The user will give you a path to a real-world, popular open-source codebase cloned locally. Your job is to run a battery of realistic prompts against it using CodeGraph's API and verify the results are good enough to say that language is **covered and supported**.

A language is NOT verified until an LLM can reliably use CodeGraph's MCP tools to navigate that codebase — finding the right symbols, understanding call chains, exploring subsystems, and getting useful context for real tasks.

## Setup

### 1. Build and index

```bash
npm run build
rm -rf <codebase_path>/.codegraph
node dist/bin/codegraph.js init -iv <codebase_path>
```

The `-iv` flag gives verbose output showing extraction progress, node/edge counts, and timing.

### 2. Quick sanity check

```bash
# Verify nodes were extracted with proper qualified names
sqlite3 <codebase_path>/.codegraph/codegraph.db \
  "SELECT name, kind, qualified_name FROM nodes WHERE kind = 'method' LIMIT 10;"

# GOOD: file.go::StructName::method_name  (owner type present)
# BAD:  file.go::file.go::method_name     (owner type missing — needs getReceiverType)

# Check edge counts
sqlite3 <codebase_path>/.codegraph/codegraph.db \
  "SELECT kind, COUNT(*) FROM edges GROUP BY kind ORDER BY COUNT(*) DESC;"

# Check node kind distribution
sqlite3 <codebase_path>/.codegraph/codegraph.db \
  "SELECT kind, COUNT(*) FROM nodes GROUP BY kind ORDER BY COUNT(*) DESC;"
```

If methods are missing their owner type in `qualified_name`, fix that first (see [Adding getReceiverType](#adding-getreceivertype)) before proceeding with the full test battery.

## The Test Battery

Run **all** of the following test categories against the codebase. Use the Node.js API directly — the test scripts below are templates. Adapt the queries to match real types, methods, and subsystems in the codebase you're testing.

**Pass criteria for each test:** Does the result give an LLM enough correct information to answer the question or complete the task? Would you trust these results if you were the LLM?

---

### Test 1: `codegraph_explore` — Deep Exploration (MOST IMPORTANT)

This is the primary tool LLMs use. It must return relevant source code grouped by file, with correct relationships, for a natural language query. Test it with **at least 5 different query types**:

```bash
node -e "
const { CodeGraph } = require('./dist/index.js');
async function test() {
  const cg = await CodeGraph.open('<codebase_path>');

  const queries = [
    // A. Subsystem exploration — broad topic, should find the right files and key classes
    'How does the caching system work?',

    // B. Specific class/type deep dive — should return that class, its methods, and related types
    'CacheBuilder configuration and build process',

    // C. Cross-cutting concern — should find implementations across multiple files
    'How are errors handled and propagated?',

    // D. Data flow question — should trace through multiple layers
    'How does data flow from input to storage?',

    // E. Implementation detail — specific method behavior
    'How does eviction decide which entries to remove?',
  ];

  for (const query of queries) {
    console.log(\`\n========================================\`);
    console.log(\`QUERY: \${query}\`);
    console.log(\`========================================\`);

    const subgraph = await cg.findRelevantContext(query, {
      searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2,
    });

    // Show entry points — these are what the LLM sees first
    console.log(\`\nEntry points (\${subgraph.roots.length}):\`);
    for (const rootId of subgraph.roots.slice(0, 8)) {
      const node = subgraph.nodes.get(rootId);
      if (node) console.log(\`  \${node.name} (\${node.kind}) — \${node.filePath}:\${node.startLine}\`);
    }

    // Show file distribution — are the right files surfacing?
    const fileGroups = new Map();
    for (const node of subgraph.nodes.values()) {
      if (!fileGroups.has(node.filePath)) fileGroups.set(node.filePath, []);
      fileGroups.get(node.filePath).push(node.name);
    }
    console.log(\`\nFiles (\${fileGroups.size}):\`);
    for (const [file, nodes] of [...fileGroups.entries()].sort((a,b) => b[1].length - a[1].length).slice(0, 8)) {
      console.log(\`  \${file} (\${nodes.length} symbols): \${nodes.slice(0, 6).join(', ')}\`);
    }
... (459 lines truncated)
</file>

<file path="docs/viewer-launch-changelog.md">
# Changelog entries held for the viewer launch

These describe `codegraph ui` and its screens. They were taken out of `## [Unreleased]` when a fixes release shipped with the viewer withheld behind `CODEGRAPH_UI=1` (`src/bin/viewer-gate.ts`). At launch, move them back under `## [Unreleased]` in `CHANGELOG.md`, bring back the Highlights below, and delete this file.

## Highlights, as written for the viewer launch

- **`codegraph ui` — your graph in a browser.** A local, read-only viewer for the project you already indexed: your code with its callers and callees in the margin, a map of the whole repository, and a strip that shows how one symbol reaches another.
- **See your app the way its users meet it.** A Screens tab draws every screen and the navigation between them, for Expo Router, React Router, Next.js, TanStack Router, Vue Router / Nuxt, SvelteKit and Angular apps.
- **See what happens from a screen or an endpoint.** A Steps tab draws what one action sets in motion — the handlers it fires, the state it writes, the calls that leave your code, and every way it can answer — with the condition on each arrow.
- **APIs too, and across tiers.** Endpoints in Express, NestJS, Fastify, Koa, Hono, FastAPI, Flask, Django, Spring, ASP.NET, Vapor and Gin, with a page's `fetch` following through to the route that serves it, a queued job to its consumer, an event to its handler.
- **Read a handler in the order its code runs.** The same picture laid out by when things happen rather than by distance, so a reply sits below the token it carries. Where the code chooses, the condition is said once and each arrow answers it.
- **Find what nothing reaches, and where everything starts.** Dead code and entry points as screens of their own, a type hierarchy showing what is built on what, and trails you can name, save and come back to after the code has changed.
- **Conditions and arguments for more languages.** What a call passes, and the `if` / `switch` / `try` it runs under, are now read for Python, Java, Kotlin, C#, Go and C as well as JavaScript, TypeScript and Swift.
- **Upgrading:** re-index your projects after this release — several of the new readings rest on edges that are written while indexing.

## New Features

- **The Steps tab draws what an Angular screen does.** Each handler a template binds is drawn with the event that fires it, like `submitForm` on the form's `(ngSubmit)` or `toggleFavorite` on a button's `(click)`, followed by the requests it sends and the screen it opens. That includes handlers in child components the screen renders. Re-index Angular projects after upgrading.

- **The Screens tab draws Angular apps.** Every screen in an Angular app's routes, with the navigation between them: `router.navigate(…)`, a guard's redirect and each template's `routerLink`, under the condition the code checks first. A button in a child component, like an article's favorite button, is drawn from the screen that renders it. A layout's tabs and buttons are drawn from every screen inside that layout. Re-index Angular projects after upgrading.

- **A big screen's picture stops wrapping into a column.** How wide a screen's lines run before they wrap was worked out with a formula, and the formula was wrong for the way these pictures are actually drawn: a part of a screen spends lines on its own structure — a step that fires things gets a line to itself, and what it fires starts another — so estimating the lines from the boxes alone badly undercounted them, and one screen's 98 boxes wrapped into a 4,356px column. Laying a picture out is cheap and exact, so the widths are now simply tried and the one that comes out closest to the shape of a window is kept. Across one app's 51 screens the tallest picture went from 4,356px to 3,796px, total height fell 8%, and — because a shorter picture is also a picture whose lines have less far to go — lines running over other boxes fell by a third and lines crossing each other went from 13 to 5.

- **A screen's picture stops being mostly empty.** The parts of a screen were tiled a row at a time, each row as tall as its tallest member — so one short region beside a tall one left the whole rest of that row blank. Measured across one app: the median screen's canvas was only 55% picture and 45% nothing, and its busiest screen was 44% — 4,860px tall to hold about 2,160px of content, all of which a reader has to scroll through. Each part now goes as high as it can and then as far left as it can, so a short one tucks under another short one instead of waiting for the tall one beside it. Reading order is unchanged: parts are still placed in the screen's own source order, and an earlier one is never pushed below a later one. That screen is now 3,584px instead of 4,860px, and close to square rather than a ribbon.

- **The screen's own line into each part of itself stops sweeping across the picture.** A screen's picture holds back the screen's whole fan-out and draws one line into each region instead — but on a screen with ten regions those regions tile into bands, so the line into a region two bands down had to travel the height of the whole picture to get there. Measured across one app's 51 screens: those lines were 17% of everything drawn and caused **79% of every remaining crossing**. Two fixes. The line now lands on the box nearest the region's top-left that the screen actually leads to, rather than on whichever box the walk happened to meet first — which, once a screen is drawn in clusters, could be lines down inside the region. And when the region is still too far for a line to be followed, the link is said in words like any other, with no exception for the screen itself. Across those 51 screens, lines crossing each other went from 47 to **10**, with no screen above 10; the busiest screen went from 19 to 2.

- **A busy screen's picture no longer draws itself as a web.** On a screen whose whole body is one component, the region grouping had nothing to divide — 98 of 100 boxes landed in a single column — and the picture came back as a 5,600px ribbon whose 113 lines crossed each other 652 times, each one running over five other boxes' names. Three things are fixed. A screen is now laid out in **clusters**: a step, then the steps it sets in motion on the line under it, stepped in — so a box and the thing it fires are one line apart instead of seven, which is what the crossings were made of. A region's lines run to a width its size earns rather than a fixed one, so a big screen comes out about as wide as it is tall instead of a narrow ribbon. And a link whose two boxes end up too far apart to follow is now **said in words at both ends** — `→ resumeInference` under the box that leads there, `← CaptureView` under the box it arrives at — rather than drawn as a line across the whole picture; select either box and every one of its real lines draws, exactly as before. On the screen that prompted this, the lines drawn at rest cross each other **once**, down from 652, with half of them still drawn as real lines. Steps that fire nothing still share a line, so a flat screen is unchanged. Nothing needs a re-index.

- **A region that holds a cycle no longer stretches the picture.** Rows inside a region were settled by relaxation, which never converges on a graph that has a loop in it: one real screen's 65 boxes were pushed to rows 294-301 while the rest sat at rows 0-2, and the order they were drawn in had nothing to do with what leads to what. Cycle-closing links are now set aside before the rows are settled, as the in-order reading already did — the loop is still drawn, it just cannot stretch the picture.

- **A busy screen's picture is laid out by the parts of the screen.** A screen is a set of handlers with no order between them, so on a hub screen the old rows-by-distance collapsed into one enormous row — the main screen of one app put 89 boxes side by side on a canvas over 28,000px wide, every line a near-horizontal sweep across all of it. The Steps tab now groups a screen's picture by region — the component that owns each handler, named in a small caption over its boxes — with each region a column where a step sits above what it sets in motion, tiled in the screen's own source order. At rest the picture hides only two things: the screen's own fan-out — one line into each region stands in for it — and lines that point back up; every other line draws where it leads, between two regions included, and selecting a step brings out its whole story in the side panel, link by link. A box nothing points at is the screen's own doing — run on render or mount, or from a binding written inline — the key says so, and selecting it lights its line from the screen with what fires it. The same app's widest screen now lays out under 3,500px with every line local, and the whole picture fits on screen when it opens. Endpoints, handlers and the in-order reading are untouched, and nothing needs a re-index: the regions come from the same walk that draws the steps.

- **Where the code chooses, the picture says so once.** A helper that ends `return (await hasSeenWelcome(id)) ? '/home/' : '/welcome/'` sends the app to one of two screens, but the Steps picture drew that as two separate arrows, each carrying the whole condition with one of them negated and both cut off at the same forty characters — and before you clicked anything, neither arrow was labelled at all, so nothing said it was a choice. Now sibling arrows out of one box that are the arms of one `if`, `switch` or ternary are drawn as the choice they are: the condition is written once under the box that decides it, and each arrow out says only which way it is — `yes`, `no`, or a case's own value. They are the only arrows labelled before you select anything, so the picture reads at a glance without becoming a wall of text. A one-sided guard — an early exit, an `if` with only one side drawn — still carries its condition on the arrow, and an arrow that is reached whether or not the condition holds never claims a side. Nothing needs a re-index: the decision is read from the source at request time.

- **A dialog's buttons fire what they run.** `Alert.prompt('Add Folder', …, [{ onPress: (name) => createBackgroundFolder(name) }])` is two facts: the prompt is a call that leaves the index, and its button fires the handler. The handler's line now arrives from the dialog's own box — with the condition on it — instead of from the screen, so the confirm-then-act chains a mobile app is full of read as chains: the delete alert leads to the delete, which leads to the request it sends. The same holds for anything bound inside the arguments of a call that leaves the index. Nothing needs a re-index: it is read from the source at request time.

- **The Steps tab draws a handler in the order its code runs.** The picture of what an endpoint sets in motion put the lookup, the token signing, the 200 and the 401 side by side, because each is one step from the anchor — true, and not how the code reads. Now a handler, an endpoint or any function opens as the same picture laid out by *when* things happen: a line means **and then**, so the 200 sits below the token signing it is built from and the 401 branches off the check that chose it. Where the code forks both ways, a small box asks the condition once and each line out of it answers — `yes`, `no`, a case's value — so the two arms of one `if` read as one decision instead of two lines that each carry the whole predicate, one of them negated; selecting a step next to the decision lights the whole fork through it. A lone guard — an early exit, an `if` with one drawn side — keeps its condition on the line, and an arm that answers the request, returns or throws simply has nothing leaving it. A call written inside another call's arguments happens first, so the token is signed before the reply that carries it. A helper is drawn where it is called (`via generateToken`), a body that repeats says so (`for each item of items`), and work registered to run later (`later · then`) or started at once (`together · Promise.all`) says that rather than pretending to be a sequence. A screen still opens as before — its handlers fire on events and have no order between them — and either reading is one click, or one `&view=order` / `&view=tree` in the link, away. Nothing to re-index: it is read from the source at request time, and where the conditions cannot be read the picture is a plain sequence rather than an invented structure.

- **Double-click a box to go there.** On the Steps tab a double-click on any step starts the picture from it — the same as the panel's *Start here* — so an endpoint the page calls, or another screen drawn as a boundary, opens as its own chapter in one gesture; on the Screens tab a double-click on a screen opens what happens from it. A boundary's panel now says it is not entered rather than that nothing leaves it.

- **The Steps tab now draws an API as well as an app.** Anchor on an endpoint — `POST /users` in Express, NestJS, Fastify, FastAPI, Flask, Django, Spring (Java or Kotlin), ASP.NET, Vapor or Gin — and the viewer starts at the handler the route runs (or at the route itself when the handler is an inline arrow), says what fires it (`FIRES FROM POST /users · after authenticate, validate(…)` — the middleware arguments at the registration, or the guard decorators on the method and its class, or a FastAPI `dependencies=[…]`), and draws what the request sets in motion: the database calls with the model and whether they read or write (`prisma.user.create({ data })` · `database · user · write`), jobs put on a queue, emails, payments, cache reads, token checks, calls to other services, files and processes — and the **responses**, one box per status a handler can send (`201`, `404`) whose panel rows are the endpoint's contract as the code has it: `WHEN NOT user → 404 · NotFoundException('no such user')`, `always → 201 · res.status(201).json(user)`. A queue consumer or a scheduled job anchored by name says the decorator that fires it (`@Process('email')`). The legend, the panel and the chooser use the project's own words — endpoint, data call, another tier — and the bare Steps tab lists an API's endpoints by router file when there are no screens. Re-index is not needed: everything new is read from the source at request time.

- **Calls are read as written, so the database is the database.** The index keeps only the last segment of a deep member call (`create` for `prisma.user.create`), and a bare name matches by name alone — often to the wrong `create`. The Steps walk now reads each call from the source as written, classifies `prisma.user.create`, `this.usersRepository.save`, `session.commit`, `owners.save` and `_context.TodoItems.Add` by the whole chain and by the receiver's declared type (`OwnerRepository owners`, `private readonly usersService: UsersService`, `val owners: OwnerRepository`, read from the class body), and follows `this.usersService.findByEmail(…)` into the class the type names instead of the name-only guess. A hop resolved this way says so in the panel.

- **A Steps tab in `codegraph ui` — what happens from here.** Pick a screen (or search any symbol and choose *What happens from here*) and the viewer draws everything it sets in motion as typed steps: the handlers wired to its taps and listeners, the calls that cross into native code, the native events that come back, the store actions it writes, and the calls that leave the app into the network, storage, the device or telemetry — one box per step, an arrow for every way one leads to the next, and on each arrow the condition under which it happens. The plumbing between two steps (hooks, helpers, the components in between) is folded into the arrow and listed in the side panel, exactly as the Screens tab folds a tap's chain into one transition — and every call the panel lists says what it passes, read from the source as written (`SecureStore.setItemAsync('userEmail', values.email)`, `axios.post('/auth/login', { email, password })`), so a step is not just *that* something was stored or sent but *what*. And each handler says what fires it — the JSX prop and its element (`onPress · <Button>`), the option it is written under (`onSubmit · useFormik(…)`), the listener or effect it runs from — read from the source at the call site, so `onPress={() => handleLogin(values)}` and Formik's `onSubmit` make `handleLogin` a step of its own with the event on the arrow into it. Any step is the next anchor, any link opens as a Flow strip, a cap the walk hit is announced on the step it hit it at, and the picture travels in the URL. React Native + Expo apps get the full picture today; any project gets handlers, stores and calls that leave the index.

- **A Screens tab in `codegraph ui` — the app the way its user meets it.** One box per screen, an arrow for every way of getting from one to another, and on each arrow the condition under which it happens. Click a screen and each of its transitions is labelled beside the screen at the other end of the line with the last condition checked before it happens — `→ isCollected` above `/object-detail` — laid out so that no two labels overlap and none sits under a line; hover a label, a line, or its row in the side panel for the whole condition and the chain the tap travels through (`HomeSearchResults → ItemCard → openObjectDetail`), with a link to each navigation call. A screen that returns to where it came from is drawn around the boxes rather than through them, shared chrome (a top bar rendered on ten screens) is one node a row above what it opens rather than the same arrows from every box, a screen that opens many others is wide enough to follow each line back to it and its lines take separate paths through the gap so they fan out instead of stacking, hovering picks the line nearest the pointer, and a helper that chooses the destination after login shows its fork. Projects whose graph holds screen navigation land on this tab. Expo Router apps today.

- **Read your graph in a browser: `codegraph ui`.** Point it at a project you've already indexed and it opens a viewer for it on your own machine. Pick a symbol and you see who calls it on the left, its real source in the middle with a marker on every line that calls something, and what it calls on the right, each one drawn level with the line that calls it. Hover either end and both light up; click anything to step into it. Test callers fold into a single line so real callers stay in view, edges CodeGraph isn't confident about are folded away as "uncertain" rather than shown as fact, and a symbol no test reaches within three caller hops says so on a badge. A blast-radius strip counts what a change would reach. Search with `/` or Cmd-K across every symbol and file, start from suggested entry points (routes, hubs, files that run code when imported), and follow a trail of the path you walked that lives in the URL, so you can send someone the exact route you took. Click any file path for that file's outline in source order between everything it depends on and everything that depends on it.

  Run `codegraph ui` in an indexed project, or `codegraph ui /path/to/project` for one indexed elsewhere (`codegraph web` is an alias). It takes port 4747, or the next free one; `--port <n>` pins a specific port and `--no-open` just prints the URL for a headless box or an SSH session. Set `CODEGRAPH_BROWSER=<command>` to choose the browser, or `CODEGRAPH_BROWSER=none` to never open one.

  The viewer listens on `127.0.0.1` only, so nothing on your network can reach it, and requests claiming to come from any other host are refused. It opens an index that already exists, never creates one, and never changes your graph or a line of your code — the one thing it writes is a trail you asked it to save (see below), and `--read-only` turns even that off. It sends nothing anywhere.

- **A map of the whole project, in `codegraph ui`.** The Map tab draws your repository at module granularity — one box per directory — with dependencies pointing down, so the top of the picture is what runs first and the bottom is what everything else stands on. Nothing is placed by hand and nothing floats: a module sits one layer above whatever it depends on, line weight is how many calls, imports and type references cross the link, and the same project always draws the same picture. Hover a link for what crosses it, including the busiest symbol pairs behind the weight; click a module to isolate its links, list its dependencies and dependents with counts, and jump straight into one of its files.

  It says what it leaves out. Links carrying only a handful of references stay hidden until you select a module they touch, references CodeGraph isn't confident about are excluded from every count on the screen and the number is printed, and mutual dependencies, module loops and circular imports between files are listed rather than straightened away. The vertical order rests on the dependencies your code actually writes down — imports, qualified names, inheritance, typed receivers — because a method name shared by two unrelated folders should not be able to move a box.

  It opens on your project's source directory; a picker switches to any other top-level folder or the whole repository, a checkbox brings tests in, and `depth` splits a large folder into its sub-folders — useful on a monorepo. What you're looking at lives in the address, so the view is shareable.

- **Ask how one symbol reaches another, in `codegraph ui`.** Type "how does execute reach getFile" into the search box — or `execute -> getFile` — and the Flow strip draws the call path between them, left to right, one card per hop. Each card is opened at the exact line that makes the next call rather than at the top of the function, so reading the strip is reading the handful of lines that actually carry the work; the identifier being called is a link, and clicking a card opens it in the symbol screen with the trail already set to the path you've read so far.

  A dashed link is a hop nobody can see in the source — a callback, an interface dispatch, a React re-render, a JSX child — and it names the mechanism and, where CodeGraph knows it, the exact line the handler was wired at. When a name means several definitions, the strip says so and names the one the path runs through, offers the alternatives in a picker, and can draw them together as one branching diagram.

  The **"Read as flow"** button on the trail turns a walk you did by hand into the same strip. It is the same path finder `codegraph_explore` leads its answers with, so the picture and what your agent tells you can't disagree.

- **When a path runs out, the Flow strip says where — and why.** A flow that doesn't reach what you asked about now ends in a small block: *"Where the graph stops."* It names the kind of dispatch that ended it — a computed member call, a `getattr`, a reflective invoke, a typed message bus — and the line it's on, and the card beside it opens at that exact line so you can read the code the block is talking about. Where the key is written in the source (`handlers['save']`) it shows the key and shortlists the symbols that could be on the other side, marking any you already named; where the key is a runtime value it says so rather than guessing.

  It also lists what CodeGraph chose not to follow: name-only matches it wasn't confident enough about, with their confidence, and a count of the other calls the symbol makes that this path didn't need. Nothing is invented — no edge is guessed and none is added to your graph — and a flow that does reach what you asked for never shows the block at all. It's the same finding `codegraph_explore` announces to your agent when a flow breaks, so the screen and the answer agree.

- **Read a whole file, with its call graph in the margin, in `codegraph ui`.** The file screen gained a **Source** tab: the file itself, top to bottom, with the same gutter markers as the symbol view and the same right-hand list of what each line calls, positioned level with the line that calls it. A 6,800-line file scrolls at full speed — only the lines on screen are ever drawn, and the text pages in behind you while the markers are there from the first frame.

  In the left margin is an arc for every call that stays inside the file, drawn from the calling line to the line the callee is defined on. Nothing is laid out by an algorithm — the author already put the symbols in order, so source order does the work, and this is the one place a file's internal call structure is legible at a glance. Hover a line to light the arcs the function under your cursor takes part in, and click an arc to jump to the other end. On a file with more than forty of them the picture narrows to the symbol you're reading instead of drawing a wash of overlapping sweeps, with the total in the header. A rail on the far left lists the file's symbols and follows you as you scroll, when the window is wide enough for it.

- **The viewer keeps up with your project while it's open.** Save a file and `codegraph ui` says so within about a third of a second: a banner on the file's screen explaining that the index hasn't caught up yet, and the file's **current** source in place of a body sliced at line numbers it no longer has — the call arcs, gutter markers and call list go away with the old numbering rather than pointing at the wrong lines. It's the same answer `codegraph_node` gives your agent about a file that changed after its last sync.

  When anything re-indexes the project — your agent's background sync, `codegraph sync`, a git hook — whatever is on screen re-reads the graph and a small "Index updated · reloaded" note appears. A symbol that moved because you added a line above it is followed to its new place, with your trail intact, instead of turning into a dead link.

  Nothing polls: the viewer watches for these two things and is told about them. If it loses touch with the server it retries a few times with a growing delay, then stops and says "Not live" in the top bar rather than hammering a port that isn't answering.

- **Take a flow or a map with you: copy it as an image, or save it as an SVG.** The Flow strip and the Map both gained **Copy image** and **Download SVG**. Copy image puts a PNG on your clipboard, ready to paste into a pull-request comment or a chat — the fastest way to say "here is what your change actually touches" without asking anyone to install anything. Download SVG saves a file for a README: it is real text rather than a bitmap, so it stays sharp at any size and the symbol names in it are selectable.

  Both render the light theme whichever one you are reading in, because the image is going to be read on somebody else's screen, and both carry a caption saying what the picture is. What comes out is exactly what is on screen — the same hops, the same dashed dynamic-dispatch links with their wiring sites, the same "where the graph stops" block, the same modules dimmed or brought forward by your selection — because the image is drawn from the same measurements the screen is, not photographed off it. An eight-hop strip comes out around half a megabyte, well inside what GitHub takes inline.

- **"Where does anything start?" has a screen now.** The **Entry points** tab in `codegraph ui` (or press `e`) is the first thing worth opening on a codebase you have never seen. Every route with the symbol that serves it and the `file:line` you will find it at, grouped by the file the URL is registered in — your router, not your handlers — and headed with the framework CodeGraph detected it from. Under that, the files that actually *do* something when they load (a CLI, a worker entry, a build script), the tests ranked by how much of the project each one exercises, and the symbols the most code depends on.

  None of it is guessed from a filename: a file "runs something" because the graph recorded a call from the file itself, and a project with fewer than three routes simply has no Routes section rather than an empty one. Every list says how much of itself it is showing, and says "at least" wherever the real total can only be a floor.

  Any row that names a symbol can start a **flow**: press `Flow ›`, then type a second symbol or press `→ here` on another row, and you get the path between them — so "how does `POST /v1/payroll/cycles/{cycleID}/run` reach the database" is two clicks. Typing into the search box now finds entry points too, under their own heading below the symbol matches, so a URL comes back with its handler attached instead of on its own.

- **Syntax colouring in `codegraph ui` now comes from CodeGraph's own reading of your code.** The viewer used to run a second syntax highlighter over source CodeGraph had already parsed, with its own separate set of grammars. It doesn't any more: the colouring is taken straight from the parse that built your graph, so a file is coloured by exactly the grammar that decided what its symbols are. Three things you will notice — the name a definition declares now stands out on the line that declares it, wherever it appears; calls written inside a string (`${user.name()}`, `#{...}`, `$"{...}"`) are read as code and are now clickable links like every other call site; and built-in type words such as `string`, `int` and `void` look the same in every language instead of one way in Go and another in TypeScript. A big file paints far faster, most visibly in TypeScript, which was by a wide margin the slowest before.

  Two formats change for the worse and it is worth saying so: Liquid, Razor, YAML, Twig, XML and `.properties` files are shown without colouring now, and in `.svelte`, `.vue` and `.astro` files the `<script>` block is coloured but the surrounding markup is not. Nothing about navigation changes there — call sites in those files still link, exactly as before.

  This also takes about 3 MB of grammar files and two dependencies out of the install.

- **The viewer's screens are now a component library other tools can render.** The Symbol view, the Flow strip and the Map are packaged as `@colbymchenry/codegraph-ui` — the same components `codegraph ui` draws, not a copy of them — so another application can show you a symbol's callers, a call path or your architecture over its own copy of the graph. Everything a screen knows arrives through one small interface it is handed, so the tool doing the rendering decides where the data comes from and where a click goes; a design-token stylesheet ships with it so the screens can be themed to match whatever they are embedded in. It is versioned with the engine, so the reader and the graph it reads always match.

  Nothing changes for `codegraph ui` itself — it is the same viewer, now the library's first user. The package is prepared, not yet on npm.
... (121 lines truncated)
</file>

<file path="site/src/components/GraphDiagram.astro">
---
// Flat technical node-link diagram for the hero. Hand-placed so it reads as a
// deliberate blueprint, not a physics blob: thin ink lines, hollow nodes, mono
// labels. Hovering a node inks it in. No glow, no gradients, no motion.
---

<svg
	class="cg-graph"
	viewBox="0 0 780 600"
	role="img"
	aria-label="A code knowledge graph: index.ts links to auth.ts, router.ts and api/users.ts, which branch to middleware.ts, types/index.ts, createRouter and listUsers."
>
	<g class="edges">
		<line x1="430" y1="64" x2="250" y2="210" />
		<line x1="430" y1="64" x2="450" y2="250" />
		<line x1="430" y1="64" x2="650" y2="200" />
		<line x1="250" y1="210" x2="180" y2="380" />
		<line x1="250" y1="210" x2="340" y2="380" />
		<line x1="450" y1="250" x2="560" y2="380" />
		<line x1="560" y1="380" x2="560" y2="500" />
	</g>

	<g class="nodes">
		<g class="node">
			<circle cx="430" cy="64" r="9" />
			<text x="448" y="69" text-anchor="start">index.ts</text>
		</g>
		<g class="node">
			<circle cx="250" cy="210" r="9" />
			<text x="232" y="215" text-anchor="end">auth.ts</text>
		</g>
		<g class="node">
			<circle cx="450" cy="250" r="9" />
			<text x="468" y="255" text-anchor="start">router.ts</text>
		</g>
		<g class="node">
			<circle cx="650" cy="200" r="9" />
			<text x="668" y="205" text-anchor="start">api/users.ts</text>
		</g>
		<g class="node">
			<circle cx="180" cy="380" r="9" />
			<text x="180" y="410" text-anchor="middle">middleware.ts</text>
		</g>
		<g class="node">
			<circle cx="340" cy="380" r="9" />
			<text x="340" y="410" text-anchor="middle">types/index.ts</text>
		</g>
		<g class="node">
			<circle cx="560" cy="380" r="9" />
			<text x="578" y="385" text-anchor="start">createRouter</text>
		</g>
		<g class="node">
			<circle cx="560" cy="500" r="9" />
			<text x="560" y="530" text-anchor="middle">listUsers</text>
		</g>
	</g>
</svg>

<style>
	.cg-graph {
		width: 100%;
		height: auto;
		max-width: 560px;
		min-width: 0; /* flex item: allow shrinking below intrinsic SVG width */
		display: block;
	}
	.cg-graph .edges line {
		stroke: var(--cg-ink);
		stroke-width: 1.25;
	}
	.cg-graph .node circle {
		fill: var(--cg-paper);
		stroke: var(--cg-ink);
		stroke-width: 1.5;
		transition: fill 0.12s ease;
	}
	.cg-graph .node text {
		font-family: var(--sl-font-mono);
		font-size: 15px;
		fill: var(--cg-ink);
		dominant-baseline: middle;
	}
	.cg-graph .node:hover circle {
		fill: var(--cg-ink);
	}
</style>
</file>

<file path="site/src/components/SiteTitle.astro">
---
// Starlight 0.39 exposes route data on Astro.locals.starlightRoute (not props).
// Link the wordmark to the landing page at the site root.
const { siteTitle } = Astro.locals.starlightRoute;
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
---

<a href={`${base}/`} class="cg-site-title" translate="no">{siteTitle}</a>

<style>
	.cg-site-title {
		font-family: var(--sl-font);
		font-weight: 800;
		font-size: 1.25rem;
		letter-spacing: -0.025em;
		line-height: 1;
		color: var(--cg-ink);
		text-decoration: none;
		white-space: nowrap;
	}
	.cg-site-title:hover {
		color: var(--cg-ink);
	}
</style>
</file>

<file path="site/src/components/SocialIcons.astro">
---
// Docs-header right cluster: Docs + Languages text links, Starlight's default
// social icons (the GitHub link), and a live star-count pill — same order as
// the landing nav (Docs · Languages · GitHub · Star). Done here, in the slot we
// already own, to avoid a full header rebuild that could break search/mobile.
import Default from '@astrojs/starlight/components/SocialIcons.astro';
import { getStarsLabel } from '../lib/github';

const stars = await getStarsLabel();
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const repo = 'https://github.com/colbymchenry/codegraph';
---

<a class="cg-navlink" href={`${base}/getting-started/introduction/`}>Docs</a>
<a class="cg-navlink" href={`${base}/reference/languages/`}>Languages</a>
<Default {...Astro.props} />
<a
	class="cg-star"
	href={`${repo}/stargazers`}
	target="_blank"
	rel="noopener noreferrer"
	aria-label={`${stars} GitHub stars`}
>
	<span class="cg-star-glyph" aria-hidden="true">★</span>{stars}
</a>

<style>
	.cg-navlink {
		font-family: var(--sl-font);
		font-size: 0.9rem;
		font-weight: 500;
		line-height: 1;
		color: var(--cg-ink);
		text-decoration: none;
		white-space: nowrap;
	}
	.cg-navlink:hover {
		text-decoration: underline;
		text-underline-offset: 4px;
	}
	.cg-star {
		display: inline-flex;
		align-items: center;
		gap: 0.35rem;
		border: 1px solid var(--cg-rule);
		padding: 0.32rem 0.6rem;
		font-family: var(--sl-font);
		font-size: 0.85rem;
		font-weight: 600;
		line-height: 1;
		color: var(--cg-ink);
		text-decoration: none;
		white-space: nowrap;
		font-variant-numeric: tabular-nums;
	}
	.cg-star:hover {
		background: var(--cg-paper-press);
		color: var(--cg-ink);
	}
	.cg-star-glyph {
		font-size: 0.85em;
	}
	/* Keep the compact mobile header clean — the sidebar covers navigation there. */
	@media (max-width: 50rem) {
		.cg-navlink,
		.cg-star {
			display: none;
		}
	}
</style>
</file>

<file path="site/src/content/docs/core-concepts/how-it-works.md">
---
title: How It Works
description: The extraction, storage, resolution, and auto-sync pipeline.
---

CodeGraph turns source code into a queryable graph in four stages.

```
files → Extraction (tree-sitter) → DB (nodes/edges/files)
            ↓
      Resolution (imports, name-matching, framework patterns)
            ↓
      Graph queries (callers, callees, impact)
            ↓
      Context building (markdown / JSON for AI consumption)
```

## 1. Extraction

[tree-sitter](https://tree-sitter.github.io/) parses source into ASTs. Language-specific queries extract **nodes** (functions, classes, methods, types…) and **edges** (calls, imports, extends, implements). Heavy parsing runs off the main thread.

## 2. Storage

Everything goes into a local SQLite database (`.codegraph/codegraph.db`) with FTS5 full-text search, using Node's built-in `node:sqlite` in WAL mode from the bundled runtime.

## 3. Resolution

After extraction, references are resolved: function calls → definitions, imports → source files, class inheritance, and framework-specific patterns. Some dynamic-dispatch boundaries (callbacks, observers, React re-render, JSX children) are bridged by synthesizers so flows connect end-to-end. See [Resolution & Frameworks](/codegraph/core-concepts/resolution/).

## 4. Auto-sync

The MCP server watches your project using native OS file events (FSEvents / inotify / ReadDirectoryChangesW). Changes are debounced, filtered to source files, and incrementally synced — the graph stays fresh as you code, with no configuration.
</file>

<file path="site/src/content/docs/core-concepts/knowledge-graph.md">
---
title: The Knowledge Graph
description: The node and edge kinds the graph is built from.
---

CodeGraph stores three things: **nodes** (symbols and files), **edges** (relationships between them), and **files**. Every node and edge carries an exact `kind`, drawn from a fixed vocabulary so queries are consistent across languages.

## Node kinds

`file`, `module`, `class`, `struct`, `interface`, `trait`, `protocol`, `function`, `method`, `property`, `field`, `variable`, `constant`, `enum`, `enum_member`, `type_alias`, `namespace`, `parameter`, `import`, `export`, `route`, `component`.

## Edge kinds

`contains`, `calls`, `imports`, `exports`, `extends`, `implements`, `references`, `type_of`, `returns`, `instantiates`, `overrides`, `decorates`.

## Provenance

Most edges come straight from the AST. A few — at dynamic-dispatch boundaries that static parsing can't follow — are **synthesized** and marked with `provenance: 'heuristic'` plus the wiring site that created them. These are surfaced inline in `explore` and the `node` trail, so an agent can see exactly where a connection came from.

## Querying it

- **Search** symbols by name (FTS5).
- **Callers / callees** walk the call graph one hop at a time.
- **Impact** computes the transitive radius affected by a change.
- **Explore** returns source for several related symbols grouped by file, plus the call path among them, in one call.

See the [CLI](/codegraph/reference/cli/) and [MCP Server](/codegraph/reference/mcp-server/) references for how to run these.
</file>

<file path="site/src/content/docs/core-concepts/resolution.md">
---
title: Resolution & Frameworks
description: How CodeGraph connects references and links routes to handlers.
---

Extraction produces nodes and raw edges; **resolution** turns names into real connections.

## Reference resolution

After parsing, CodeGraph resolves:

- **Imports** → the source files they point at (including tsconfig path aliases and cargo workspace members).
- **Calls** → their definitions, by import resolution and name matching.
- **Inheritance** → `extends` / `implements` between types.

## Framework awareness

CodeGraph recognizes web-framework routing files and emits `route` nodes linked by `references` edges to their handler classes or functions — so querying the callers of a view or controller surfaces the URL pattern that binds it. See [Framework Routes](/codegraph/guides/framework-routes/) for the full list of recognized frameworks.

## Dynamic-dispatch coverage

Static parsing misses computed and indirect calls, so flows can break at dynamic dispatch. CodeGraph bridges several of these boundaries with synthesizers so a flow connects end-to-end:

- Callback / observer registration
- `EventEmitter` channels
- React re-render (`setState` → `render`)
- JSX child (`render` → child component)
- Interface → implementation dispatch

Every synthesized edge is marked `provenance: 'heuristic'` with the site that wired it, and is shown inline wherever a path crosses it.
</file>

<file path="site/src/content/docs/getting-started/configuration.md">
---
title: Configuration
description: CodeGraph is zero-config by default, with one optional codegraph.json for custom extensions, excluding tracked directories, indexing gitignored source, and indexing nested git repositories.
---

Next to none — CodeGraph is **zero-config by default**, with nothing to write or keep in sync to get started. Language support is automatic from the file extension; there's nothing to wire up per language. The one optional file, `codegraph.json`, covers [custom file extensions](#custom-file-extensions), [excluding tracked directories](#excluding-a-tracked-directory), [indexing gitignored source](#indexing-gitignored-source-a-second-vcs), and [indexing nested git repositories](#indexing-nested-git-repositories).

## What it skips out of the box

- **Dependency, build, and cache directories** — `node_modules`, `vendor`, `dist`, `build`, `target`, `.venv`, `Pods`, `.next`, and the like across every [supported stack](/codegraph/reference/languages/) — so the graph is your code, not third-party noise. This holds even with no `.gitignore`.
- **Anything in your `.gitignore`** — honored in git repos via git, and in non-git projects by reading `.gitignore` directly (root and nested).
- **Files larger than 1 MB** — generated bundles, minified JS, vendored blobs.

## Excluding or including more

To keep something else out, add it to `.gitignore`. To pull a default-excluded directory back **in** (e.g. you really want a vendored dependency indexed), add a negation — `!vendor/`.

The defaults apply uniformly, so committing a dependency or build directory doesn't force it into the graph — the `.gitignore` negation is the explicit opt-in.

## Excluding a tracked directory

`.gitignore` only affects files git **doesn't already track** — it can't drop a directory you've committed. So a vendored theme, SDK, or asset bundle that's checked into the repo (say a Metronic admin theme under `static/`, with hundreds of `.js` files) can't be excluded that way. For those, list them under `exclude` in `codegraph.json`:

```json
{
  "exclude": ["static/", "**/vendor/**"]
}
```

Each entry is a gitignore-style pattern, matched against project-root-relative paths, and honored everywhere CodeGraph looks at files — the full index, incremental `sync`, and file-watching. It applies even to tracked files (that's the whole point) and takes precedence over everything else, so it's the right tool for a large committed dependency that bloats the graph but isn't really your code. (This is the opposite of [`includeIgnored`](#indexing-nested-git-repositories), which pulls gitignored directories back *in*.)

Re-index (`codegraph index`) after adding or changing `exclude`.

## Indexing gitignored source (a second VCS)

`.gitignore` keeps files out of the index — which is usually what you want, but not when the gitignored files are real first-party source. The case this exists for: a project tracked by **SVN, Perforce, or another VCS alongside Git**, where some source is committed to that VCS and deliberately listed in `.gitignore` so it never lands in Git. That source is still yours and you want it in the graph, but git never lists it, so CodeGraph never sees it. (`includeIgnored` doesn't help — it only revives *embedded git repositories* inside a gitignored directory, not plain source.)

List those paths under `include` in `codegraph.json` to force them in:

```json
{
  "include": ["Tools/", "Local/typescript/"]
}
```

Each entry is a gitignore-style pattern, matched against project-root-relative paths (a directory like `"Tools/"`, a recursive `"Tools/**"` glob, or a single file all work). CodeGraph discovers the matching files directly off disk — overriding `.gitignore` — and indexes them everywhere it looks at files: the full index, incremental `sync`, and file-watching.

A few things to know:

- An explicit [`exclude`](#excluding-a-tracked-directory) still wins — listing the same path in both keeps it out.
- Built-in skips like `node_modules`, `dist`, and `.git` are never re-included, even when an `include` pattern would match inside them.
- This is the opposite of `exclude` (which keeps tracked files *out*); it's for source git itself never tracks.

Re-index (`codegraph index`) after adding or changing `include`.

## Custom file extensions

If your project uses a non-standard extension for a [supported language](/codegraph/reference/languages/) — say `.dota_lua` for Lua, or `.tpl` for PHP — those files are skipped by default, because the extension isn't one CodeGraph recognizes. Map them with an optional `codegraph.json` at your project root:

```json
{
  "extensions": {
    ".dota_lua": "lua",
    ".tpl": "php"
  }
}
```

Each value is a supported language id. The mappings merge on top of the built-in defaults and win on conflict, so you can also re-point a built-in (e.g. `".h": "cpp"`). Commit the file to share the mapping with your team.

A typo'd language or a malformed file is warned about and skipped — it never breaks indexing — and a project with no `codegraph.json` behaves exactly as before. Re-index (`codegraph index`) after adding or changing mappings.

## Indexing nested git repositories

CodeGraph respects your `.gitignore`, so a directory you've gitignored stays out of the graph — **including any git repositories nested inside it.** If you keep cloned reference projects, vendored copies, or a folder of unrelated repos in a gitignored directory (a `resource/`, `.repos/`, or `examples/` dir), CodeGraph leaves it untouched: it won't walk in, discover the embedded repos, or index them.

If instead you run a **"super-repo" of independent clones** — a workspace whose own `.gitignore` lists its child repos to keep `git status` quiet, where you genuinely want every child indexed into one graph — opt those directories back in with `includeIgnored`:

```json
{
  "includeIgnored": ["packages/", "services/"]
}
```

Each entry is a gitignore-style pattern naming a gitignored directory whose nested git repositories should be indexed anyway. CodeGraph descends into the directories you list and indexes each embedded repo by its own `git ls-files`, so every child repo's own `.gitignore` is still honored. Directories you don't list stay excluded.

A few things to know:

- **Untracked** nested repositories (ones you haven't gitignored) are indexed automatically — `includeIgnored` is only for the ones your `.gitignore` excludes.
- Built-in skips like `node_modules` are never re-included, even inside an opted-in directory.
- A project without this layout needs no `codegraph.json` at all.

Re-index (`codegraph index`) after adding or changing `includeIgnored`.

## Where data lives

Per-project data lives in a `.codegraph/` directory at your project root, containing the SQLite database (`codegraph.db`). Nothing leaves your machine.
</file>

<file path="site/src/content/docs/getting-started/installation.md">
---
title: Installation
description: Install CodeGraph and configure your AI coding agents.
---

## 1. Run the installer

```bash
npx @colbymchenry/codegraph
```

The installer will:

- Ask which agent(s) to configure — auto-detecting installed ones from **Claude Code**, **Cursor**, **Codex CLI**, **opencode**, **Hermes Agent**, **Gemini CLI**, **Antigravity IDE**, and **Kiro**.
- Prompt to install `codegraph` on your `PATH` (so agents can launch the MCP server).
- Ask whether configs apply to all your projects or just this one.
- Write each chosen agent's MCP server config, plus a small marker-fenced CodeGraph section in the agent's instructions file (`CLAUDE.md` / `AGENTS.md` / `GEMINI.md`). Cursor and Kiro get the MCP config only. Removed cleanly by `codegraph uninstall`.
- Set up auto-allow permissions when Claude Code is one of the targets.

The installer **wires up your agents only — it does not index your code.** After it finishes, build each project's graph yourself with `codegraph init` (step 3 below).

## Non-interactive (scripting / CI)

```bash
codegraph install --yes                              # auto-detect agents, install global
codegraph install --target=cursor,claude --yes       # explicit target list
codegraph install --target=auto --location=local     # detected agents, project-local
codegraph install --print-config codex               # print snippet, no file writes
```

| Flag | Values | Default |
|---|---|---|
| `--target` | `auto`, `all`, `none`, or csv (`claude,cursor,…`) | prompt |
| `--location` | `global`, `local` | prompt |
| `--yes` | (boolean) | prompt every step |
| `--no-permissions` | (boolean) skip Claude auto-allow list | permissions on |
| `--print-config <id>` | dump snippet for one agent and exit | — |

## 2. Restart your agent

Restart your agent (Claude Code / Cursor / Codex CLI / opencode / Hermes Agent / Gemini CLI / Antigravity IDE / Kiro) for the MCP server to load.

## 3. Initialize projects

```bash
cd your-project
codegraph init
```

`codegraph init` creates the local `.codegraph/` directory and builds the full graph in the same step — one command. A single global `codegraph install` covers every project; you run `codegraph init` once per project.

## Supported platforms

Every release ships a self-contained build (bundled Node runtime — nothing to compile) for all three desktop OSes, on both x64 and arm64:

| Platform | Architectures | Install |
|---|---|---|
| Windows | x64, arm64 | PowerShell installer or npm |
| macOS | x64, arm64 | shell installer or npm |
| Linux | x64, arm64 | shell installer or npm |

## Uninstall

Changed your mind? One command removes CodeGraph from every agent it configured:

```bash
codegraph uninstall
```

This reverses the installer — stripping CodeGraph's MCP server config, instructions, and permissions from each configured agent. Your project indexes (`.codegraph/`) are left untouched; remove those per-project with `codegraph uninit`. Use `--target` to remove from specific agents, or `--yes` to run non-interactively.
</file>

<file path="site/src/content/docs/getting-started/introduction.md">
---
title: Introduction
description: What CodeGraph is, and why it makes AI coding agents faster and more precise.
---

CodeGraph is a **local-first code-intelligence tool**. It parses your codebase with [tree-sitter](https://tree-sitter.github.io/), stores every symbol, edge, and file in a local SQLite database, and exposes the result as a queryable **knowledge graph** — over the [Model Context Protocol (MCP)](/codegraph/reference/mcp-server/), a CLI, and a TypeScript library.

It exists to make AI coding agents — Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro — **answer structural questions without scanning files**. Instead of fanning out across `grep`, `glob`, and `Read` to reconstruct how code fits together, an agent queries a pre-built index and gets the answer in a handful of calls.

## Why it matters

When an agent explores a codebase, it spends most of its budget on *discovery* — finding the right files before it can read them. CodeGraph removes that step: it hands the agent the exact code it needs in one call, so symbol relationships, call graphs, and structure don't have to be rebuilt file by file.

The universal win is **surgical context and speed** — fewer tool calls, faster answers, on every codebase. Tested across 7 real-world open-source codebases (median of 4 runs per arm), giving an agent CodeGraph meant, regardless of repo size:

- **58% fewer tool calls**
- **22% faster**
- **file reads cut to ~zero**

Token and dollar savings are real too, but they're the **scale-dependent bonus** that shows up on large, tangled codebases run at volume — small and noisy on a modest repo, material only once the codebase (and the team) gets big.

## What's in the graph

- **Symbols** — functions, classes, methods, types, routes, components, and more.
- **Edges** — calls, imports, inheritance, references, and framework-specific relationships.
- **Files** — structure plus full-text search (FTS5).

Extraction is **deterministic** — derived from the AST, never LLM-summarized.

## 100% local

No data leaves your machine. No API keys, no external services — just a SQLite database in `.codegraph/`.

Ready to try it? Head to the [Quickstart](/codegraph/getting-started/quickstart/).
</file>

<file path="site/src/content/docs/getting-started/next-steps.md">
---
title: Next Steps
description: Where to go once CodeGraph is installed and indexing.
---

You've got CodeGraph installed and a graph built. Here's where to go next.

## Understand the model

- [How It Works](/codegraph/core-concepts/how-it-works/) — the extraction → storage → resolution → sync pipeline.
- [The Knowledge Graph](/codegraph/core-concepts/knowledge-graph/) — the node and edge kinds the graph is built from.
- [Resolution & Frameworks](/codegraph/core-concepts/resolution/) — how references and framework routes get connected.

## Put it to work

- [Indexing a Project](/codegraph/guides/indexing/) — full index, incremental sync, and the file watcher.
- [Reading Your Graph in the Browser](/codegraph/guides/viewer/) — `codegraph ui`: callers, source and callees on one screen (coming in an upcoming release).
- [Framework Routes](/codegraph/guides/framework-routes/) — link URL patterns to their handlers.
- [Affected Tests in CI](/codegraph/guides/affected-tests/) — run only the tests a change touches.

## Reference

- [MCP Server](/codegraph/reference/mcp-server/) — the tools agents call.
- [CLI](/codegraph/reference/cli/) — every command and flag.
- [API](/codegraph/reference/api/) — use CodeGraph as a TypeScript library.
- [Integrations](/codegraph/reference/integrations/) — supported agents and manual setup.
</file>

<file path="site/src/content/docs/getting-started/quickstart.md">
---
title: Get Started
description: Get up and running with CodeGraph in seconds.
---

Get up and running with CodeGraph in seconds.

## 1. Install the CLI

No Node.js required — one command grabs the right build for your OS:

```bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh

# Windows (PowerShell)
irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex
```

Already have Node? `npm i -g @colbymchenry/codegraph` works on any version. CodeGraph bundles its own runtime — nothing to compile, no native build, works the same everywhere. The installer puts `codegraph` on your `PATH` but doesn't change your current shell — open a new terminal before the next step.

## 2. Wire up your agent(s)

```bash
codegraph install
```

Auto-detects and configures Claude Code, Cursor, Codex CLI, opencode, Hermes Agent, Gemini CLI, Antigravity IDE, and Kiro — wiring the CodeGraph MCP server into each. This step connects your agents only; it does **not** index any code. (Shortcut: `npx @colbymchenry/codegraph` downloads and runs the installer in one go.)

## 3. Initialize each project

```bash
cd your-project
codegraph init
```

`codegraph init` creates the local `.codegraph/` directory and builds the full graph in the same step — one command, done. Your agent will use CodeGraph tools automatically when a `.codegraph/` directory exists.

Next: build [Your First Graph](/codegraph/getting-started/your-first-graph/), or see the full [Installation](/codegraph/getting-started/installation/) options.
</file>

<file path="site/src/content/docs/getting-started/your-first-graph.md">
---
title: Your First Graph
description: Build an index and run your first queries against it.
---

Once CodeGraph is installed, building and exploring a graph takes a few commands.

## Index a project

```bash
cd your-project
codegraph init
```

`codegraph init` creates the `.codegraph/` directory and builds the full graph in the same step — one command, done. From there a native file watcher keeps the index in sync on every change, so you rarely need to rebuild by hand. When you do want to:

```bash
codegraph index          # full re-index
codegraph sync           # incremental update of changed files
```

## Check it worked

```bash
codegraph status
```

This reports the node/edge/file counts, the active SQLite backend, and the journal mode — a quick health check that the index is ready.

## Run a query

Reach for `codegraph explore` first — a natural-language question or a bag of symbol names returns the relevant source plus the call paths between those symbols in a single shot (the same output the `codegraph_explore` tool gives your agent):

```bash
codegraph explore "how does login work"
```

For narrower, scriptable lookups there are focused commands:

```bash
codegraph query UserService          # find symbols by name
codegraph callers handleRequest      # what calls a function
codegraph callees handleRequest      # what a function calls
codegraph impact AuthMiddleware      # what a change would affect
```

These four each accept `--json` for machine-readable output. See the full [CLI reference](/codegraph/reference/cli/).

## Hand it to your agent

With a `.codegraph/` directory present and an agent configured (see [Installation](/codegraph/getting-started/installation/)), your agent uses the [MCP tools](/codegraph/reference/mcp-server/) automatically — no extra step.
</file>

<file path="site/src/content/docs/guides/affected-tests.md">
---
title: Affected Tests in CI
description: Run only the tests a change actually touches.
---

`codegraph affected` traces import dependencies transitively to find which test files are affected by a set of changed source files — so CI can run only the relevant tests.

```bash
codegraph affected src/utils.ts src/api.ts          # pass files as arguments
git diff --name-only | codegraph affected --stdin    # pipe from git diff
codegraph affected src/auth.ts --filter "e2e/*"      # custom test-file pattern
```

## Options

| Option | Description | Default |
|---|---|---|
| `--stdin` | Read the file list from stdin | `false` |
| `-d, --depth <n>` | Max dependency traversal depth | `5` |
| `-f, --filter <glob>` | Custom glob to identify test files | auto-detect |
| `-j, --json` | Output as JSON | `false` |
| `-q, --quiet` | Output file paths only | `false` |

## CI / hook example

```bash
#!/usr/bin/env bash
AFFECTED=$(git diff --name-only HEAD | codegraph affected --stdin --quiet)
if [ -n "$AFFECTED" ]; then
  npx vitest run $AFFECTED
fi
```
</file>

<file path="site/src/content/docs/guides/framework-routes.md">
---
title: Framework Routes
description: CodeGraph links URL patterns to the handlers that serve them.
---

CodeGraph detects web-framework routing files and emits `route` nodes linked by `references` edges to their handler classes or functions. Querying the callers of a view or controller then surfaces the URL pattern that binds it.

| Framework | Shapes recognized |
|---|---|
| **Django** | `path()`, `re_path()`, `url()`, `include()` in `urls.py` (CBV `.as_view()`, dotted paths) |
| **Flask** | `@app.route('/path', methods=[...])`, blueprint routes |
| **FastAPI** | `@app.get(...)`, `@router.post(...)`, all standard methods |
| **Express** | `app.get(...)`, `router.post(...)` with middleware chains |
| **NestJS** | `@Controller` + `@Get/@Post/...`, GraphQL `@Resolver` + `@Query/@Mutation`, `@MessagePattern`/`@EventPattern`, `@SubscribeMessage` |
| **Laravel** | `Route::get()`, `Route::resource()`, `Controller@action`, tuple syntax |
| **Drupal** | `*.routing.yml` routes (`_controller`, `_form`, entity handlers); `hook_*` implementations in `.module`/`.theme`/`.install`/`.inc` |
| **Rails** | `get '/x', to: 'users#index'`, hash-rocket `=>` syntax |
| **Spring** | `@GetMapping`, `@PostMapping`, `@RequestMapping` on methods |
| **Play** | `GET`/`POST`/… verb routes in `conf/routes` → `Controller.method` actions (Scala + Java) |
| **Gin / chi / gorilla / mux** | `r.GET(...)`, `router.HandleFunc(...)` |
| **Axum / actix / Rocket** | `.route("/x", get(handler))` |
| **ASP.NET** | `[HttpGet("/x")]` attributes on action methods |
| **Vapor** | `app.get("x", use: handler)` |
| **React Router** / **SvelteKit** | Route component nodes |
| **Vue Router** / **Nuxt** | `pages/` file-based routes, `server/api/` endpoints, route middleware |
| **Astro** | `src/pages/` file-based routes (`.astro` pages + `.ts` endpoints, `[param]`/`[...rest]` syntax) |

Route resolution is automatic — there's nothing to configure. If a framework file is recognized, its routes appear in the graph after the next index or sync.
</file>

<file path="site/src/content/docs/guides/indexing.md">
---
title: Indexing a Project
description: Full index, incremental sync, and the file watcher.
---

## Initialize and index

```bash
cd your-project
codegraph init      # creates .codegraph/ and builds the full graph — one step
```

`codegraph init` creates the local `.codegraph/` directory and builds the full graph in the same step — one command, done. There's no separate index step to run afterward, and from here the graph [stays fresh automatically](#stay-fresh-automatically).

## Full vs. incremental

```bash
codegraph index           # full index of the whole project
codegraph index --force   # re-index from scratch
codegraph sync            # incremental — only changed files
```

`sync` is fast because it only reparses what changed — it's what the file watcher runs for you on every edit (see [Stay fresh automatically](#stay-fresh-automatically)). You rarely need to run it by hand.

## Stay fresh automatically

**You don't need to run `codegraph sync` by hand during an agent session.** When your agent (Claude Code, Cursor, Codex, opencode, Hermes, Gemini, Antigravity, Kiro) launches `codegraph serve --mcp`, three layers cooperate to keep the index in step with your code — and to never give the agent a quiet wrong answer in the small window between an edit and the next sync.

### 1. File watcher with debounced auto-sync (always on)

`serve --mcp` spins up a native file watcher (FSEvents on macOS, inotify on Linux, ReadDirectoryChangesW on Windows) over the project root. Every source-file create / modify / delete is captured. A debounce timer collapses bursts of edits into a single sync.

```
agent writes src/Widget.ts
  → watcher fires (event delivery: typically <100ms)
  → 2000ms debounce
  → sync runs; Widget.ts's nodes + edges are in the index
  → next agent query sees it
```

**Tunable**: `CODEGRAPH_WATCH_DEBOUNCE_MS` overrides the default 2000ms, clamped to `[100ms, 60s]`. Useful when a build step or formatter writes many files in a tight burst — bump it to `5000` or `10000` so the watcher coalesces them into one sync.

### 2. Per-file staleness banner — covers the debounce window

The watcher debounce introduces a small window (typically 2s) where a freshly-edited file is on disk but not yet in the index. CodeGraph closes that window with a per-file staleness banner: if any MCP tool response would reference a file that's currently pending re-index, the response prepends a `⚠️` banner naming the stale file:

```
⚠️ Some files referenced below were edited since the last index sync —
their codegraph entries may be stale:
  - src/Widget.ts (edited 800ms ago, pending sync)
For accurate content of those specific files, Read them directly.
The rest of this response is fresh.

## Code Context
…
```

Agents read this and follow up with a direct `Read` on the named file — validated end-to-end with Claude Code, where the agent literally says "Reading the file directly for the live content" before opening it. So even during the 2-second debounce window, the agent never gets a silent wrong answer.

Pending files **not** referenced by the response surface as a small footer instead (`(Note: N file(s) elsewhere in this project are pending index sync but were not referenced above: …)`). Either way, the signal is explicit.

### 3. Connect-time catch-up — covers gaps when the MCP server wasn't running

When your editor / agent (re)connects to the MCP server, codegraph runs a fast filesystem-based reconciliation (a `(size, mtime)` stat pre-filter, then a content hash on the rest) before answering the first query. So files changed while no MCP server was running — a `git pull` from the terminal, an edit from another editor, an agent that finished and exited — are caught up automatically on the next session's first tool call.

### Verify what the watcher sees

`codegraph_status` exposes the pending set first-class — useful for an agent asking "is the index caught up?" in one call:

```
codegraph_status →
  ## CodeGraph Status
  …
  ### Pending sync:
  - src/Widget.ts (edited 1200ms ago)
```

If `### Pending sync:` isn't in the response, nothing is in flight.

### When manual `codegraph sync` makes sense

Almost never. The edge cases:

- **The watcher is disabled.** Sandboxes that block local fs watchers, or you've set `CODEGRAPH_NO_DAEMON=1` to opt out of the shared daemon. In those cases `codegraph sync` is the manual fallback.
- **Pre-flight before a CI run.** If you're scripting against the index outside an agent session, a single `codegraph sync` at the start of the script guarantees the index reflects the current working tree.

Otherwise: just use it. The watcher + banner + connect-sync covers the AI-assisted workflow end-to-end. If you're seeing files genuinely missed after the debounce window has passed, that's a bug — please file an issue with a reproduction.

> See the v0.9.5 release notes for the [staleness banner (#403)](https://github.com/colbymchenry/codegraph/releases/tag/v0.9.5) and the connect-time catch-up (#414); both shipped together.

## Check status

```bash
codegraph status
```

Reports node/edge/file counts, the active SQLite backend, and the journal mode. In an agent session, the MCP-side `codegraph_status` additionally surfaces the `### Pending sync:` block described above.

## What gets indexed

... (2 lines truncated)
</file>

<file path="site/src/content/docs/guides/viewer.md">
---
title: Reading Your Graph in the Browser
description: codegraph ui opens a local viewer for an indexed project — callers, source, and callees on one screen.
---

:::note[Not released yet]
The viewer isn't in a CodeGraph release yet: `codegraph ui` arrives in an upcoming release. This page describes it ahead of that.
:::

`codegraph ui` opens a viewer for a project you have already indexed. It is the same graph your agent reads, on screen.

```bash
codegraph init          # once per project, if you haven't already
codegraph ui            # opens http://127.0.0.1:4747 in your browser
```

![The CodeGraph viewer: callers on the left, the symbol's source in the middle with a marker on every calling line, and the symbols it calls on the right, each level with its call site](https://raw.githubusercontent.com/colbymchenry/codegraph/main/assets/codegraph-ui-symbol-view.png?v=1)

## The symbol screen

Pick a symbol and you get three columns that all describe the same thing:

- **Called by**, on the left, grouped by file, each caller carrying the exact line it calls from. Click a line number to open that caller scrolled to the call. Test callers fold into a single line so real callers stay in view.
- **The source**, in the middle, verbatim from disk and syntax-highlighted, with a marker in the gutter on every line that calls something and a link on every call CodeGraph resolved. A long body shows its opening plus a window around every call site, with the skipped runs counted rather than hidden.
- **Calls**, on the right, one row per symbol this one calls, drawn level with the line that calls it and joined to that line by a hairline. Hover either end and the line, the gutter marker and the connector all light up. A symbol called from several lines says so; `creates` marks a constructor.

A class, interface, struct or enum shows its members in source order instead of a body, each with how many things call it and how many things it calls.

Under the source, a **blast radius** strip counts what a change here would reach: direct dependents, everything within three hops, and how many files, test files and routes that touches.

## Honesty on screen

The viewer never presents a guess as a fact:

- Edges CodeGraph resolved by name alone, below its confidence threshold, fold into an "uncertain" line rather than sitting among the resolved ones. Nothing is silently dropped — the count is always there.
- A symbol that no test reaches within three caller hops wears a badge saying exactly that.
- Calls into symbols that aren't in the index are counted and marked, not omitted.
- A file that changed on disk since it was indexed wears a banner and switches to the file's **current** source, with everything the graph anchors to a line number — the gutter markers, the call arcs, the right-hand list — switched off. The bytes on disk are right by construction; the line numbers the index recorded are the part that stopped being true.

## It keeps up with your project

The viewer follows the project while it is open, and it does it by watching, never by asking on a timer.

- **Save a file and the banner appears** — about a third of a second later, before any sync has run. That is the honest state: the file on disk and the index have parted company, and the screen says so rather than showing you a body sliced at the wrong lines.
- **When something re-indexes** — your agent's background sync, `codegraph sync`, a git hook — whatever is on screen refetches itself and a small "Index updated · reloaded" note appears at the bottom. The symbol, the file, the map and the flow are all answers about the graph as a whole, so all of them re-read it.
- **A symbol that moved is followed, not lost.** Adding two lines above a function changes its identity in the graph; the viewer finds it again in its file and carries your trail across, rather than telling you the thing you were reading no longer exists.

If the viewer ever loses touch with the server, it retries a handful of times with a growing delay and then stops and says **"Not live"** in the top bar — it never falls back to polling. Focus the tab to reconnect.

## Getting around

- **Search** with `/` or Cmd-K: every symbol and file, grouped by kind, with signature and `file:line`. Arrow keys and Enter, no mouse needed.
- **Entry points** on the opening screen, and in full on the **Entry points** tab (`e`) — see below.
- **Typing a name also finds entry points.** They come back under their own heading below the symbol matches, so searching `payroll` returns the URL *with* the symbol that serves it, not just the URL.
- **A trail** records the path you walked, with an arrow per hop showing whether you stepped into a call or up to a caller. Click any hop to jump back to it. The trail lives in the URL, so you can send someone the exact route you took — or press **Save trail** to keep it (see below).
- **Keyboard:** arrow keys move within a column, left/right switch columns, Enter follows, Backspace steps back.

Clicking any file path opens the **file view**: everything that file depends on, its outline in source order, and everything that depends on it.

## Saved trails

A trail you want to come back to is worth a name. Press **Save trail** on the trail bar, type one, and it is kept — listed on the opening screen and on the **Entry points** tab, above the derived suggestions. Opening one puts you back at the symbol you left with the whole walk restored in the bar. Explaining "how a request is served" to a new teammate becomes a name and a link.

**A saved trail survives your project changing.** Each step is remembered by what it *is* — its qualified name, its kind, the file it was in — rather than by where it sat, so editing the file above a function does not lose it. When something does move, the row says so rather than quietly showing you something else:

- a step that moved to another file still opens, and the row names both files;
- a step that was renamed or deleted is called out by name, and the row says how much of the walk still opens (`Opens hops 2–4 of 6`);
- a name now carried by several symbols is marked as a guess.

A gap is never stitched over. The trail is a *path*, so a row opens the longest run of consecutive steps that still resolve — joining step 2 to step 4 would draw a call that does not exist.

**Where they live.** One JSON file per trail under `.codegraph/ui/trails/`, which git already ignores, so trails are yours by default. **Export** on any row hands you the same file if you would rather commit one for the team; drop it back into that directory in another checkout and it re-resolves against *that* index.

This is the only thing the viewer writes. Start it with `codegraph ui --read-only` and it will not write even this — saved trails can still be opened, just not saved or deleted.

## Entry points

The first screen worth opening on a codebase you have never seen. Four lists, all read out of the graph rather than guessed from filenames:

- **Routes** — every URL with the symbol that serves it and the `file:line` you will find it at, grouped by the file the route is *registered* in (your router, not your handlers) and headed with the framework CodeGraph detected. A project with fewer than three routes is not a routed app, so this section is simply absent rather than empty.
- **Top-level files with calls** — the files that *do* something when they load: a CLI, a worker entry, a build script. That is a fact about the graph (a statement outside every definition is recorded as a call from the file itself), not a guess about a filename, which is why a library module correctly shows nothing.
- **Tests** — the other direction: what already exercises this code, widest reach first.
- **Most depended on** — not where the project starts, but where a change radiates furthest.

Every row opens the code. Every row that names a symbol also carries a **Flow ›** chip: press it, then name a second symbol — type it, or press **→ here** on another row — and you get the path between them. "How does `POST /v1/payroll/cycles/{cycleID}/run` reach the database" is two clicks once both ends are on the screen.

## The whole file

The **Source** tab on that screen replaces the outline with the file itself, top to bottom, with the same gutter markers and the same right-hand list of what each line calls — a 6,800-line file scrolls as smoothly as a 60-line one, and the text pages in behind you.

The margin on the left is the part you cannot get anywhere else: **an arc for every call that stays inside the file**, drawn from the calling line to the line the callee is defined on. Source order is the only layout — nothing is placed by an algorithm, because the author already placed it — so the shape of a file's internal call structure is legible at a glance. Hover a line to light the arcs the function under your cursor takes part in; click an arc to jump to the other end. On a file with more than forty of them the diagram narrows to the symbol you are reading rather than drawing a wash of overlapping sweeps, and the count stays in the header.

A rail on the far left lists the file's symbols and follows you as you scroll, when the window is wide enough for it.

## The flow

Type **"how does execute reach getFile"** into the search box — or `execute -> getFile` — and the first result opens the **Flow** strip: the call path between the two symbols, left to right, one card per hop.

Each card is opened at the line that makes the next call, not at the top of the function, so reading the strip is reading the six or eight lines that actually carry the request. The identifier being called is a link; click a card's header to open it in the symbol screen with the trail already set to the path you have read so far.

... (61 lines truncated)
</file>

<file path="site/src/content/docs/reference/api.md">
---
title: API
description: Use CodeGraph as a TypeScript library.
---

CodeGraph ships a TypeScript API. The public surface is the `CodeGraph` class.

```typescript
import CodeGraph from '@colbymchenry/codegraph';

const cg = await CodeGraph.init('/path/to/project');
// Or open an existing index:
// const cg = await CodeGraph.open('/path/to/project');

await cg.indexAll({
  onProgress: (p) => console.log(`${p.phase}: ${p.current}/${p.total}`),
});

const results = cg.searchNodes('UserService');
const callers = cg.getCallers(results[0].node.id);
const context = await cg.buildContext('fix login bug', {
  maxNodes: 20,
  includeCode: true,
  format: 'markdown',
});
const impact = cg.getImpactRadius(results[0].node.id, 2);

cg.watch();   // auto-sync on file changes
cg.unwatch(); // stop watching
cg.close();
```

## Key methods

| Method | Purpose |
|---|---|
| `CodeGraph.init(path)` / `CodeGraph.open(path)` | Create or open a project index |
| `indexAll(opts)` | Full index, with progress callback |
| `sync()` | Incremental update |
| `searchNodes(query)` | Full-text symbol search |
| `getCallers(id)` / `getCallees(id)` | Walk the call graph |
| `getImpactRadius(id, depth)` | Transitive impact of a change |
| `buildContext(task, opts)` | Markdown / JSON context for AI |
| `watch()` / `unwatch()` | Start / stop the file watcher |
| `close()` | Close the database connection |

CommonJS works too — `const { CodeGraph } = require('@colbymchenry/codegraph');`.

## Lower-level building blocks

The same entry point exports primitives for callers that drive the graph directly rather than through the `CodeGraph` facade: `DatabaseConnection`, `QueryBuilder`, `getDatabasePath`, `initGrammars` / `loadGrammarsForLanguages`, and `FileLock`.

```typescript
import {
  CodeGraph,
  DatabaseConnection,
  QueryBuilder,
  getDatabasePath,
  initGrammars,
  loadGrammarsForLanguages,
  FileLock,
} from '@colbymchenry/codegraph';
```

## Embedding requirements

- **Install from npm** (`npm i @colbymchenry/codegraph`) so the matching per-platform package — which carries the compiled library — is fetched alongside the shim.
- The API runs on **your** runtime, so it needs **Node 22.5+** for the built-in `node:sqlite` module (an Electron main process qualifies when its bundled Node is 22.5+). The CLI and MCP server are unaffected — they ship with a self-contained bundled runtime and need no Node at all.
- TypeScript types ship with the package. Keep `@types/node` available and `skipLibCheck: true` (the common default).
</file>

<file path="site/src/content/docs/reference/cli.md">
---
title: CLI
description: Every CodeGraph command and the flags it accepts.
---

```bash
codegraph                         # Run interactive installer
codegraph install                 # Run installer (explicit)
codegraph uninstall               # Remove CodeGraph from your agents (inverse of install)
codegraph init [path]             # Initialize a project + build its graph (one step)
codegraph uninit [path]           # Remove CodeGraph from a project (--force to skip prompt)
codegraph index [path]            # Full re-index from scratch (--force, --quiet, --verbose)
codegraph sync [path]             # Incremental update (--quiet)
codegraph status [path]           # Show statistics (--json)
codegraph ui [path]               # Open the browser viewer (not released yet — see below)
codegraph unlock [path]           # Remove a stale lock file that's blocking indexing
codegraph query <search>          # Search symbols (--kind, --limit, --json)
codegraph explore <query>         # Relevant symbols' source + call paths in one shot (same output as the codegraph_explore MCP tool)
codegraph node <symbol|file>      # One symbol's source + callers, or read a file with line numbers (same output as codegraph_node)
codegraph files [path]            # Show file structure (--format, --filter, --pattern, --max-depth, --json)
codegraph callers <symbol>        # Find what calls a function/method (--limit, --json)
codegraph callees <symbol>        # Find what a function/method calls (--limit, --json)
codegraph impact <symbol>         # Analyze what code is affected by changing a symbol (--depth, --json)
codegraph affected [files...]     # Find test files affected by changes (see below)
codegraph daemon                  # Manage background daemons — pick one to stop (alias: daemons)
codegraph telemetry [on|off]      # Show or change anonymous usage telemetry
codegraph upgrade [version]       # Update to the latest release (--check, --force)
codegraph version                 # Print the installed version (also -v, --version)
codegraph help [command]          # Show help, optionally for one command
```

The MCP server (`codegraph serve --mcp`) is launched automatically by your agent — you don't run it by hand. See [MCP Server](/codegraph/reference/mcp-server/).

## init, index, and sync

`codegraph init` creates the local `.codegraph/` directory **and** builds the full graph in one step. (The old `-i`/`--index` flag is now a no-op, accepted only so existing scripts don't break.) After that the file watcher keeps the graph current automatically — `index` (a full rebuild from scratch) and `sync` (an incremental update) are only needed when the watcher is disabled or you're scripting against the index outside an agent session.

## Query commands

`query`, `callers`, `callees`, and `impact` all accept `--json` for machine-readable output.

```bash
codegraph query UserService --kind class --limit 10
codegraph callers handleRequest --json
codegraph impact AuthMiddleware --depth 3
```

`explore` and `node` are the CLI faces of the `codegraph_explore` and `codegraph_node` MCP tools — same output — so subagents and non-MCP harnesses can reach the graph from a shell.

## affected

Traces import dependencies transitively to find which test files are affected by changed source files. See [Affected Tests in CI](/codegraph/guides/affected-tests/) for options and a CI example.

## ui

:::note[Not released yet]
The viewer isn't in a CodeGraph release yet: `codegraph ui` arrives in an upcoming release. This page describes it ahead of that.
:::

`codegraph ui` opens the [browser viewer](/codegraph/guides/viewer/) for a project you have already indexed: callers on the left, the symbol's source in the middle, and what it calls on the right at the height of the line that calls it.

```bash
codegraph ui                     # the project you're standing in
codegraph ui ~/code/my-app       # a project indexed elsewhere
codegraph ui --port 8080         # pin a port (fails if it's taken)
codegraph ui --no-open           # just print the URL (headless boxes, SSH)
codegraph ui --read-only         # refuse every write, including saved trails
```

Without `--port` it takes 4747, or the next free port. `CODEGRAPH_BROWSER=<command>` chooses which browser opens; `CODEGRAPH_BROWSER=none` never opens one. `codegraph web` is an alias.

The viewer listens on `127.0.0.1` only: it opens an index that already exists, never creates one, never changes your graph or a line of your code, and sends nothing anywhere. The one thing it writes is a trail you asked it to save, under `.codegraph/ui/trails/`; `--read-only` refuses even that.
</file>

<file path="site/src/content/docs/reference/integrations.md">
---
title: Integrations
description: Supported agents, and manual MCP setup.
---

The interactive installer auto-detects and configures each supported agent — wiring the CodeGraph MCP server into each. For the agents that use an instructions file, it also writes a short marker-fenced CodeGraph section (`CLAUDE.md`, `AGENTS.md`, or `GEMINI.md`) so subagents and non-MCP harnesses learn the `codegraph explore` command; `codegraph uninstall` removes it.

## Supported agents

- **Claude Code**
- **Cursor**
- **Codex CLI**
- **opencode**
- **Hermes Agent**
- **Gemini CLI**
- **Antigravity IDE**
- **Kiro**

Run `npx @colbymchenry/codegraph` and pick your agent(s); see [Installation](/codegraph/getting-started/installation/) for the non-interactive flags.

## Manual setup

If you'd rather wire it up yourself, install globally:

```bash
npm install -g @colbymchenry/codegraph
```

Add the MCP server to `~/.claude.json`:

```json
{
  "mcpServers": {
    "codegraph": {
      "type": "stdio",
      "command": "codegraph",
      "args": ["serve", "--mcp"]
    }
  }
}
```

Optionally auto-allow CodeGraph's tools in `~/.claude/settings.json`:

```json
{
  "permissions": {
    "allow": [
      "mcp__codegraph__*"
    ]
  }
}
```

One wildcard auto-approves every CodeGraph tool. The server lists a single tool by default — `codegraph_explore` — but if you re-enable others via the `CODEGRAPH_MCP_TOOLS` environment variable, they're already permitted with no prompt.

:::tip
Cursor launches MCP subprocesses with the wrong working directory. The installer handles this for you by injecting a `--path` argument; if you wire Cursor up by hand, pass the project path explicitly.
:::
</file>

<file path="site/src/content/docs/reference/languages.md">
---
title: Languages
description: Every language CodeGraph parses, and the extensions it recognizes.
---

Language support is automatic from the file extension — there's nothing to configure.

| Language | Extensions | Status |
|---|---|---|
| TypeScript | `.ts`, `.tsx` | Full support |
| JavaScript | `.js`, `.jsx`, `.mjs` | Full support |
| Python | `.py` | Full support |
| Go | `.go` | Full support |
| Rust | `.rs` | Full support |
| Java | `.java` | Full support |
| C# | `.cs` | Full support |
| PHP | `.php` | Full support |
| Ruby | `.rb` | Full support |
| C | `.c`, `.h` | Full support |
| C++ | `.cpp`, `.hpp`, `.cc` | Full support |
| Objective-C | `.m`, `.mm`, `.h` | Partial support (classes, protocols, methods, `@property`, `#import`, message sends; `.mm` ObjC++ may parse incompletely) |
| Swift | `.swift` | Full support |
| Kotlin | `.kt`, `.kts` | Full support |
| Scala | `.scala`, `.sc` | Full support (classes, traits, methods, type aliases, Scala 3 enums) |
| Dart | `.dart` | Full support |
| Svelte | `.svelte` | Full support (script extraction, Svelte 5 runes, SvelteKit routes) |
| Vue | `.vue` | Full support (script + script-setup, Nuxt page/API/middleware routes) |
| Astro | `.astro` | Full support (frontmatter + script extraction, template component/call references, `src/pages/` routes) |
| Liquid | `.liquid` | Full support |
| Pascal / Delphi | `.pas`, `.dpr`, `.dpk`, `.lpr` | Full support (classes, records, interfaces, enums, DFM/FMX forms) |
| Lua | `.lua` | Full support (functions, methods, locals, `require` imports, call edges) |
| R | `.R`, `.r` | Full support (functions, S4/R5/R6 classes with methods, `library`/`require` imports, `source()` file references, call edges) |
| Luau | `.luau` | Full support (Lua, plus typed signatures, `type` aliases, Roblox `require`) |
</file>

<file path="site/src/content/docs/reference/mcp-server.md">
---
title: MCP Server
description: The tools CodeGraph exposes to AI agents over MCP.
---

CodeGraph runs as a [Model Context Protocol](https://modelcontextprotocol.io/) server. Agents configured by the installer launch it automatically — you don't start it by hand:

```bash
codegraph serve --mcp
```

When a `.codegraph/` index exists, the agent gets the tool below. In a workspace with **no** index, the server announces itself inactive and lists **no** tools — the agent works normally with its built-in tools, and indexing stays your decision.

## One tool by default: `codegraph_explore`

By default the server exposes a **single tool**, `codegraph_explore`. It's Read-equivalent: give it a natural-language question or a bag of symbol and file names, and it returns the **verbatim, line-numbered source** of the relevant symbols grouped by file — the same shape the `Read` tool gives you — plus the call paths between them (including dynamic-dispatch hops like callbacks, React re-render, and JSX children that grep can't follow) and a blast-radius summary of what depends on them. One call usually answers the whole question.

Exposing a single strong tool is deliberate. Measured agent behavior showed that one well-aimed tool steers agents to a direct answer better than a menu of narrower ones — fewer mis-picks — and agents reach for it both when answering questions and while editing code.

## The other tools

Seven more tools exist and stay fully functional, but are **unlisted by default** — everything they return already arrives inline on a `codegraph_explore` response (its blast-radius section, the relationship map, a symbol's body and its callee list):

| Tool | Purpose |
|---|---|
| `codegraph_node` | One symbol's source + caller/callee trail, or a whole file read with line numbers (Read-parity). Returns every overload's body for an ambiguous name. |
| `codegraph_search` | Find symbols by name across the codebase (locations only) |
| `codegraph_callers` | Find what calls a function |
| `codegraph_callees` | Find what a function calls |
| `codegraph_impact` | Analyze what code is affected by changing a symbol |
| `codegraph_files` | Get the indexed file structure (faster than filesystem scanning) |
| `codegraph_status` | Check index health and statistics |

Re-enable any of them with the `CODEGRAPH_MCP_TOOLS` environment variable — a comma-separated allowlist of short names that replaces the default:

```bash
CODEGRAPH_MCP_TOOLS=explore,node,search,callers
```

Each also has a CLI equivalent (`codegraph node` / `query` / `callers` / `callees` / `impact` / `files` / `status`) for scripts and non-MCP harnesses.

## How agents should use it

CodeGraph *is* the pre-built search index. For "how does X work?", architecture, a flow ("how does X reach Y"), or where-is-X questions — and while editing code — an agent should answer with `codegraph_explore` and stop, typically with **zero file reads**, rather than re-deriving the answer with `grep` + `Read`. A direct CodeGraph answer is one to a few calls; a grep/read exploration is dozens.

The MCP server delivers this guidance to the main agent automatically, in the MCP `initialize` response. Because subagents and non-MCP harnesses never see that response, the installer also writes a short marker-fenced section into each agent's instructions file pointing at the `codegraph explore` CLI equivalent.
</file>

<file path="site/src/content/docs/troubleshooting.md">
---
title: Troubleshooting
description: Fixes for the most common CodeGraph issues.
---

## "CodeGraph not initialized"

Run `codegraph init` in your project directory first.

## Indexing is slow

Check that `node_modules` and other large directories are excluded (they are, if gitignored). Use `--quiet` to reduce output overhead.

## MCP hits `database is locked`

Current builds shouldn't: CodeGraph bundles its own Node runtime and uses Node's built-in `node:sqlite` in WAL mode, where concurrent reads never block on a writer. If you still see it:

- **You're on an old (pre-0.9) install.** Reinstall to get the bundled runtime — `curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh` (macOS/Linux), `irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex` (Windows), or `npm i -g @colbymchenry/codegraph@latest`.
- **`codegraph status` shows `Journal:` other than `wal`** — WAL couldn't be enabled on this filesystem (common on network shares and WSL2 `/mnt`), so reads can block on writes. Move the project (with its `.codegraph/` folder) onto a local disk.

## MCP server not connecting

Your agent starts the server itself, so you don't launch it by hand. Make sure the project is initialized and indexed (`codegraph status`) and that the path in your MCP config is correct. If it still won't connect, re-run `codegraph install` to rewrite the config.

## Missing symbols

The MCP server auto-syncs on save (wait a couple of seconds). Run `codegraph sync` manually if needed. Check that the file's language is [supported](/codegraph/reference/languages/) and isn't inside a `.gitignore`d or default-excluded directory (e.g. `node_modules`, `dist`).

## Sharing one checkout between Windows and WSL

Don't point both at the same `.codegraph/`: the background-server lock and the SQLite index are tied to the OS that wrote them, and SQLite locking across the WSL2/Windows filesystem boundary is unreliable (WSL reports it as a `disk I/O error`). For a project on a Windows drive (a `/mnt/c/…` path), WSL keeps its own index automatically: an index first built from WSL goes in `.codegraph-wsl/`, leaving `.codegraph/` to Windows. An index already in `.codegraph/` stays where it is, so if Windows built that one, give WSL its own by setting `CODEGRAPH_DIR=.codegraph-wsl` in WSL and running `codegraph init` there. `CODEGRAPH_DIR` always picks the name when set, on either side. CodeGraph skips any sibling `.codegraph-*` directory when indexing and watching, so the two never trip over each other.
</file>

<file path="site/src/pages/index.astro">
---
import '@fontsource-variable/archivo';
import '@fontsource/ibm-plex-mono/400.css';
import '@fontsource/ibm-plex-mono/500.css';
import '@fontsource/ibm-plex-mono/600.css';
import '../styles/theme.css';
import GraphDiagram from '../components/GraphDiagram.astro';
import { getStarsLabel } from '../lib/github';

const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const repo = 'https://github.com/colbymchenry/codegraph';
const npm = 'https://www.npmjs.com/package/@colbymchenry/codegraph';
const stars = await getStarsLabel();
const install = 'npx @colbymchenry/codegraph';
---

<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<link rel="icon" href={`${base}/favicon.svg`} type="image/svg+xml" />
		<title>codegraph — Understand any codebase as a graph</title>
		<meta
			name="description"
			content="A local-first code-intelligence tool that turns any codebase into a queryable knowledge graph for AI coding agents."
		/>
		<meta property="og:title" content="codegraph" />
		<meta property="og:description" content="Understand any codebase as a graph." />
		<meta property="og:type" content="website" />
		<meta name="theme-color" content="#f7f6f2" />
	</head>
	<body>
		<div class="frame">
			<header class="nav">
				<a class="wordmark" href={`${base}/`}>codegraph</a>
				<nav class="nav-links">
					<a href={`${base}/getting-started/introduction`}>Docs</a>
					<a class="opt" href={`${base}/reference/languages`}>Languages</a>
					<a href={repo}>GitHub</a>
					<a class="star" href={`${repo}/stargazers`}>
						<span class="star-glyph" aria-hidden="true">★</span>{stars}
					</a>
				</nav>
			</header>

			<main>
				<section class="hero">
					<div class="hero-left">
						<h1>Understand any codebase as a graph</h1>
						<p class="lede">
							A local-first code-intelligence tool that turns any codebase into a
							queryable knowledge graph for AI coding agents.
						</p>
						<div class="cta">
							<a class="btn btn-primary" href={`${base}/getting-started/quickstart`}>Get started</a>
							<a class="btn btn-ghost" href={`${base}/getting-started/introduction`}>View documentation</a>
						</div>
						<div class="install" data-install={install}>
							<code>{install}</code>
							<button class="copy" type="button" aria-label="Copy install command">
								<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="1.6">
									<rect x="9" y="9" width="11" height="11" />
									<path d="M5 15V5a1 1 0 0 1 1-1h9" />
								</svg>
							</button>
						</div>
					</div>
					<div class="hero-right">
						<GraphDiagram />
					</div>
				</section>

				<section class="features">
					<article class="feature">
						<svg class="ficon" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.5">
							<rect x="19" y="4" width="10" height="10" />
							<rect x="4" y="34" width="10" height="10" />
							<rect x="19" y="34" width="10" height="10" />
							<rect x="34" y="34" width="10" height="10" />
							<path d="M24 14v10M9 34v-10h30v10M24 24v10" />
						</svg>
						<h2>Tree-sitter parsing</h2>
						<p>
							Fast, incremental parsing across 20+ languages — accurate symbols and
							edges drawn from real ASTs, not guesses.
						</p>
					</article>
					<article class="feature">
						<svg class="ficon" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="1.5">
							<rect x="5" y="10" width="38" height="28" />
							<path d="M13 20l6 4-6 4M26 28h9" />
						</svg>
						<h2>MCP server</h2>
						<p>
							Expose the graph to Claude Code, Cursor, Codex, opencode, Hermes,
							Gemini, Antigravity, and Kiro over MCP — agents answer in a handful of calls.
						</p>
					</article>
					<article class="feature">
... (358 lines truncated)
</file>

<file path="site/src/content.config.ts">
import { defineCollection } from 'astro:content';
import { docsLoader } from '@astrojs/starlight/loaders';
import { docsSchema } from '@astrojs/starlight/schema';
</file>

<file path="site/astro.config.mjs">
// @ts-check
⋮----
// Project page on GitHub Pages: https://colbymchenry.github.io/codegraph/
// `site` + `base` make every internal link resolve under the /codegraph/ prefix.
⋮----
// Default to the light / paper theme on first visit; the toggle still
// lets a visitor switch to (and persist) the dark / ink theme.
⋮----
// Wordmark in the docs header.
⋮----
// Default GitHub icon + a live star-count pill (matches the landing nav).
</file>

<file path="site/package.json">
{
  "name": "site",
  "type": "module",
  "version": "0.0.1",
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/starlight": "^0.39.2",
    "@fontsource-variable/archivo": "^5.2.8",
    "@fontsource/ibm-plex-mono": "^5.2.7",
    "astro": "^6.3.1",
    "sharp": "^0.34.5"
  }
}
</file>

<file path="site/README.md">
# Starlight Starter Kit: Basics

[![Built with Starlight](https://astro.badg.es/v2/built-with-starlight/tiny.svg)](https://starlight.astro.build)

```
npm create astro@latest -- --template starlight
```

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

## 🚀 Project Structure

Inside of your Astro + Starlight project, you'll see the following folders and files:

```
.
├── public/
├── src/
│   ├── assets/
│   ├── content/
│   │   └── docs/
│   └── content.config.ts
├── astro.config.mjs
├── package.json
└── tsconfig.json
```

Starlight looks for `.md` or `.mdx` files in the `src/content/docs/` directory. Each file is exposed as a route based on its file name.

Images can be added to `src/assets/` and embedded in Markdown with a relative link.

Static assets, like favicons, can be placed in the `public/` directory.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command                   | Action                                           |
| :------------------------ | :----------------------------------------------- |
| `npm install`             | Installs dependencies                            |
| `npm run dev`             | Starts local dev server at `localhost:4321`      |
| `npm run build`           | Build your production site to `./dist/`          |
| `npm run preview`         | Preview your build locally, before deploying     |
| `npm run astro ...`       | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI                     |

## 👀 Want to learn more?

Check out [Starlight’s docs](https://starlight.astro.build/), read [the Astro documentation](https://docs.astro.build), or jump into the [Astro Discord server](https://astro.build/chat).
</file>

<file path="site/tsconfig.json">
{
  "extends": "astro/tsconfigs/strict",
  "include": [".astro/types.d.ts", "**/*"],
  "exclude": ["dist"]
}
</file>

<file path="src/context/formatter.ts">
import { Node, Edge, TaskContext, Subgraph } from '../types';
import { isGeneratedFile } from '../extraction/generated-detection';
⋮----
export function formatContextAsMarkdown(
  context: TaskContext,
  isGenerated: (filePath: string) => boolean = isGeneratedFile
): string
⋮----
// Related symbols - compact list (skip verbose structure tree). Drop nodes
// in generated source files (`.pb.go` / `.pulsar.go` / mocks / …) — agents
// chasing a flow never want to land on protobuf scaffolding (cosmos-Q3 used
// to list `gov.pulsar.go::GetExpeditedThreshold` and `1.pulsar.go::Get` in
// Related Symbols, pure noise that displaced real-flow entries).
⋮----
.slice(0, 10); // Limit to 10 related symbols
⋮----
// Code blocks - only for key entry points. Re-sort so non-generated blocks
// show first (consistent with Entry Points reordering above).
⋮----
export function formatContextAsJson(context: TaskContext): string
⋮----
export function formatSubgraphTree(subgraph: Subgraph, entryPoints: Node[]): string
⋮----
lines.push(''); // Blank line between trees
⋮----
// Print any remaining nodes not reached from entry points
⋮----
function formatNodeTree(
  node: Node,
  subgraph: Subgraph,
  outgoing: Map<string, Edge[]>,
  printed: Set<string>,
  lines: string[],
  depth: number,
  prefix: string
): void
⋮----
// Outgoing edges
⋮----
function serializeNode(node: Node): Record<string, unknown>
⋮----
function serializeEdge(edge: Edge): Record<string, unknown>
⋮----
function truncate(str: string, maxLength: number): string
⋮----
export function formatBytes(bytes: number): string
</file>

<file path="src/context/index.ts">
import {
  Node,
  Edge,
  NodeKind,
  EdgeKind,
  Subgraph,
  CodeBlock,
  TaskContext,
  TaskInput,
  BuildContextOptions,
  FindRelevantContextOptions,
  SearchResult,
} from '../types';
import { QueryBuilder } from '../db/queries';
import { GraphTraverser } from '../graph';
import { formatContextAsMarkdown, formatContextAsJson } from './formatter';
import { logDebug } from '../errors';
import { validatePathWithinRoot, isConfigLeafNode } from '../utils';
import { isTestFile, extractSearchTerms, scorePathRelevance, getStemVariants, isDistinctiveIdentifier } from '../search/query-utils';
import { LOW_CONFIDENCE_MARKER } from './markers';
⋮----
function extractSymbolsFromQuery(query: string): string[]
⋮----
export class ContextBuilder
⋮----
constructor(
    projectRoot: string,
    queries: QueryBuilder,
    traverser: GraphTraverser
)
⋮----
private isDeprioritized(filePath: string): boolean
⋮----
async buildContext(
    input: TaskInput,
    options: BuildContextOptions = {}
): Promise<TaskContext | string>
⋮----
private buildLowConfidenceNote(entryPoints: Node[]): string
⋮----
private buildCallPathsSection(subgraph: Subgraph): string
⋮----
let budget = 2000; // bound DFS work on dense subgraphs
const dfs = (id: string, path: string[], seen: Set<string>): void =>
⋮----
if (path.length >= 3) chains.push([...path]); // >=3 nodes = a real flow, not a single call
⋮----
// Keep only chains that connect TWO OR MORE query-relevant symbols (roots).
// A chain from a root into an arbitrary callee (render → onMagicFrameGenerate)
// is structurally valid but tangential to the question; requiring ≥2 roots
// keeps the chain anchored to what the user actually asked about. Rank by
// #roots then length, and drop any that are a sub-path of a longer kept chain.
⋮----
const rootCount = (c: string[]): number
⋮----
const name = (id: string): string
⋮----
// Synthesized (dynamic-dispatch) hops are real `calls` edges but invisible to
// static parsing — mark them inline so the agent sees WHERE the callback was
// wired up (`registered @file:line`) instead of grepping for it. Keyed by
// "source>target".
⋮----
const renderChain = (c: string[]): string =>
⋮----
async findRelevantContext(
    query: string,
    options: FindRelevantContextOptions = {}
): Promise<Subgraph>
⋮----
async getCode(nodeId: string): Promise<string | null>
⋮----
private async extractNodeCode(node: Node): Promise<string | null>
⋮----
private getEntryPoints(subgraph: Subgraph): Node[]
⋮----
private async extractCodeBlocks(
    subgraph: Subgraph,
    maxBlocks: number,
    maxBlockSize: number
): Promise<CodeBlock[]>
⋮----
private getRelatedFiles(subgraph: Subgraph): string[]
⋮----
private generateSummary(_query: string, subgraph: Subgraph, entryPoints: Node[]): string
⋮----
/**
   * Resolve import/export nodes to their actual definitions
   *
   * When search returns `import { TerminalPanel }`, users want the TerminalPanel
   * class definition, not the import statement. This follows the `imports` edge
   * to find and return the actual definition instead.
   *
   * @param results - Search results that may include import/export nodes
   * @returns Results with imports resolved to definitions where possible
   */
private resolveImportsToDefinitions(results: SearchResult[]): SearchResult[]
⋮----
// If it's not an import/export, keep it as-is
⋮----
export function createContextBuilder(
... (5 lines truncated)
</file>

<file path="src/context/markers.ts">

</file>

<file path="src/db/index.ts">
import { SqliteDatabase, SqliteBackend, createDatabase } from './sqlite-adapter';
⋮----
import { SchemaVersion } from '../types';
import { runMigrations, getCurrentVersion, CURRENT_SCHEMA_VERSION } from './migrations';
import { getCodeGraphDir, statInode } from '../directory';
⋮----
function configureConnection(db: SqliteDatabase, readOnly = false): void
⋮----
export function resolveWalHealBytes(envVal: string | undefined): number
⋮----
/**
 * Database connection wrapper with lifecycle management
 */
export class DatabaseConnection
⋮----
/**
   * `dev:ino` of the DB file at the moment we opened it (or null when the
   * platform/filesystem reports no usable inode). Lets us notice when the file
   * we hold open has been unlinked and REPLACED by a new file at the same path
   * — a git worktree removed and re-added, or `.codegraph/` deleted and
   * re-`init`ed under a long-lived server — at which point our fd reads a now
   * dead inode forever (#925). See `isReplacedOnDisk`.
   */
⋮----
/**
   * Whether FTS5 is available in this Node.js build. When false, search
   * falls back to LIKE + fuzzy matching (#1532).
   */
⋮----
private constructor(db: SqliteDatabase, dbPath: string, backend: SqliteBackend, fts5Available: boolean, readonly readOnly = false)
⋮----
/**
   * Initialize a new database at the given path
   */
static initialize(dbPath: string): DatabaseConnection
⋮----
// Ensure parent directory exists
⋮----
// Create and configure database
⋮----
// Run schema initialization, splitting FTS5 from the rest so
// codegraph still works when Node.js was built without FTS5 (#1532).
⋮----
static open(dbPath: string, options:
⋮----
beginBulkNodeLoad(): void
⋮----
endBulkNodeLoad(): void
⋮----
beginBulkParseLoad(): void
⋮----
async endBulkParseLoad(): Promise<void>
⋮----
beginBulkRefLoad(): void
⋮----
async endBulkRefLoad(): Promise<void>
⋮----
beginBulkEdgeLoad(): void
⋮----
async endBulkEdgeLoad(options:
⋮----
createSynthesisSiteIndex(): void
⋮----
private healBulkNodeLoad(): void
⋮----
private healBulkSecondaryIndexes(): void
⋮----
private recreateFtsTriggers(): void
⋮----
getDb(): SqliteDatabase
⋮----
getBackend(): SqliteBackend
⋮----
getPath(): string
⋮----
getJournalMode(): string
⋮----
/**
   * Get current schema version
   */
getSchemaVersion(): SchemaVersion | null
⋮----
transaction<T>(fn: () => T): T
⋮----
getSize(): number
⋮----
getWalSizeBytes(): number
⋮----
getDbFileSizeBytes(): number
⋮----
getWalAutocheckpoint(): number
⋮----
setWalAutocheckpoint(pages: number): void
⋮----
async checkpointWalPassive(): Promise<
⋮----
async checkpointWalTruncate(): Promise<
⋮----
async healOversizedWal(): Promise<
⋮----
... (22 lines truncated)
</file>

<file path="src/db/migrations.ts">
import { SqliteDatabase } from './sqlite-adapter';
⋮----
interface Migration {
  version: number;
  description: string;
  up: (db: SqliteDatabase) => void;
}
⋮----
const hasColumn = (name: string)
⋮----
export function getCurrentVersion(db: SqliteDatabase): number
⋮----
function recordMigration(db: SqliteDatabase, version: number, description: string): void
⋮----
export function runMigrations(db: SqliteDatabase, fromVersion: number): void
⋮----
export function needsMigration(db: SqliteDatabase): boolean
⋮----
export function getPendingMigrations(db: SqliteDatabase): Migration[]
⋮----
export function getMigrationHistory(
  db: SqliteDatabase
): Array<
</file>

<file path="src/db/queries.ts">
import { SqliteDatabase, SqliteStatement } from './sqlite-adapter';
import {
  Node,
  Edge,
  FileRecord,
  UnresolvedReference,
  NodeKind,
  EdgeKind,
  Language,
  GraphStats,
  SearchOptions,
  SearchResult,
} from '../types';
import { safeJsonParse } from '../utils';
import { kindBonus, nameMatchBonus, scorePathRelevance } from '../search/query-utils';
import { parseQuery, boundedEditDistance } from '../search/query-parser';
import { isGeneratedFile } from '../extraction/generated-detection';
import { splitIdentifierSegments } from '../search/identifier-segments';
⋮----
function isLowValueFile(filePath: string, generated?: ReadonlySet<string>): boolean
⋮----
const IS_INTERFACE_MEMBER = (alias: string): string => `EXISTS (
  SELECT 1 FROM edges ce JOIN nodes owner ON owner.id = ce.source
   WHERE ce.target = ${alias}.id AND ce.kind = 'contains' AND owner.kind = 'interface'
)`;
⋮----
interface NodeRow {
  id: string;
  kind: string;
  name: string;
  qualified_name: string;
  file_path: string;
  language: string;
  start_line: number;
  end_line: number;
  start_column: number;
  end_column: number;
  docstring: string | null;
  signature: string | null;
  visibility: string | null;
  is_exported: number;
  is_async: number;
  is_static: number;
  is_abstract: number;
  decorators: string | null;
  type_parameters: string | null;
  return_type: string | null;
  updated_at: number;
}
⋮----
interface EdgeRow {
  id: number;
  source: string;
  target: string;
  kind: string;
  metadata: string | null;
  line: number | null;
  col: number | null;
  provenance: string | null;
}
⋮----
interface FileRow {
  path: string;
  content_hash: string;
  language: string;
  size: number;
  modified_at: number;
  indexed_at: number;
  node_count: number;
  errors: string | null;
  generated?: number | null;
}
⋮----
interface UnresolvedRefRow {
  id: number;
  from_node_id: string;
  reference_name: string;
  reference_kind: string;
  line: number;
  col: number;
  candidates: string | null;
  file_path: string;
  language: string;
  status: string;
  name_tail: string;
}
⋮----
function referenceNameTail(referenceName: string): string
⋮----
/**
 * Convert database row to Node object
 */
function rowToNode(row: NodeRow): Node
⋮----
function rowToEdge(row: EdgeRow): Edge
⋮----
function rowToFileRecord(row: FileRow): FileRecord
⋮----
export class QueryBuilder
⋮----
... (403 lines truncated)
</file>

<file path="src/db/schema.sql">
CREATE TABLE IF NOT EXISTS schema_versions (
    version INTEGER PRIMARY KEY,
    applied_at INTEGER NOT NULL,
    description TEXT
);
INSERT INTO schema_versions (version, applied_at, description)
VALUES (1, strftime('%s', 'now') * 1000, 'Initial schema');
CREATE TABLE IF NOT EXISTS nodes (
    id TEXT PRIMARY KEY,
    kind TEXT NOT NULL,
    name TEXT NOT NULL,
    qualified_name TEXT NOT NULL,
    file_path TEXT NOT NULL,
    language TEXT NOT NULL,
    start_line INTEGER NOT NULL,
    end_line INTEGER NOT NULL,
    start_column INTEGER NOT NULL,
    end_column INTEGER NOT NULL,
    docstring TEXT,
    signature TEXT,
    visibility TEXT,
    is_exported INTEGER DEFAULT 0,
    is_async INTEGER DEFAULT 0,
    is_static INTEGER DEFAULT 0,
    is_abstract INTEGER DEFAULT 0,
    decorators TEXT,
    type_parameters TEXT,
    return_type TEXT,
    updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS edges (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    source TEXT NOT NULL,
    target TEXT NOT NULL,
    kind TEXT NOT NULL,
    metadata TEXT,
    line INTEGER,
    col INTEGER,
    provenance TEXT DEFAULT NULL,
    FOREIGN KEY (source) REFERENCES nodes(id) ON DELETE CASCADE,
    FOREIGN KEY (target) REFERENCES nodes(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS files (
    path TEXT PRIMARY KEY,
    content_hash TEXT NOT NULL,
    language TEXT NOT NULL,
    size INTEGER NOT NULL,
    modified_at INTEGER NOT NULL,
    indexed_at INTEGER NOT NULL,
    node_count INTEGER DEFAULT 0,
    errors TEXT,
    generated INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS unresolved_refs (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    from_node_id TEXT NOT NULL,
    reference_name TEXT NOT NULL,
    reference_kind TEXT NOT NULL,
    line INTEGER NOT NULL,
    col INTEGER NOT NULL,
    candidates TEXT,
    file_path TEXT NOT NULL DEFAULT '',
    language TEXT NOT NULL DEFAULT 'unknown',
    status TEXT NOT NULL DEFAULT 'pending',
    name_tail TEXT NOT NULL DEFAULT '',
    FOREIGN KEY (from_node_id) REFERENCES nodes(id) ON DELETE CASCADE
);
-- =============================================================================
-- Indexes for Query Performance
-- =============================================================================
-- Node indexes
CREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind, file_path, start_line, id);
CREATE INDEX IF NOT EXISTS idx_nodes_name ON nodes(name);
CREATE INDEX IF NOT EXISTS idx_nodes_qualified_name ON nodes(qualified_name);
CREATE INDEX IF NOT EXISTS idx_nodes_file_path ON nodes(file_path);
CREATE INDEX IF NOT EXISTS idx_nodes_language ON nodes(language);
CREATE INDEX IF NOT EXISTS idx_nodes_file_line ON nodes(file_path, start_line);
CREATE INDEX IF NOT EXISTS idx_nodes_lower_name ON nodes(lower(name));
-- Full-text search index on node names, docstrings, and signatures
CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
    id,
    name,
    qualified_name,
    docstring,
    signature,
    content='nodes',
    content_rowid='rowid'
);
CREATE TRIGGER IF NOT EXISTS nodes_ai AFTER INSERT ON nodes BEGIN
    INSERT INTO nodes_fts(rowid, id, name, qualified_name, docstring, signature)
    VALUES (NEW.rowid, NEW.id, NEW.name, NEW.qualified_name, NEW.docstring, NEW.signature);
END;
CREATE TRIGGER IF NOT EXISTS nodes_ad AFTER DELETE ON nodes BEGIN
    INSERT INTO nodes_fts(nodes_fts, rowid, id, name, qualified_name, docstring, signature)
    VALUES ('delete', OLD.rowid, OLD.id, OLD.name, OLD.qualified_name, OLD.docstring, OLD.signature);
END;
CREATE TRIGGER IF NOT EXISTS nodes_au AFTER UPDATE ON nodes BEGIN
    INSERT INTO nodes_fts(nodes_fts, rowid, id, name, qualified_name, docstring, signature)
    VALUES ('delete', OLD.rowid, OLD.id, OLD.name, OLD.qualified_name, OLD.docstring, OLD.signature);
    INSERT INTO nodes_fts(rowid, id, name, qualified_name, docstring, signature)
... (33 lines truncated)
</file>

<file path="src/db/sqlite-adapter.ts">
import { toWslSharedIndexError } from './wsl-shared-index';
⋮----
export interface SqliteStatement {
  run(...params: any[]): { changes: number; lastInsertRowid: number | bigint };
  get(...params: any[]): any;
  all(...params: any[]): any[];
  iterate(...params: any[]): IterableIterator<any>;
}
⋮----
run(...params: any[]):
get(...params: any[]): any;
all(...params: any[]): any[];
⋮----
iterate(...params: any[]): IterableIterator<any>;
⋮----
export interface SqliteDatabase {
  prepare(sql: string): SqliteStatement;
  exec(sql: string): void;
  pragma(str: string, options?: { simple?: boolean }): any;
  transaction<T>(fn: (...args: any[]) => T): (...args: any[]) => T;
  close(): void;
  readonly open: boolean;
  readonly inTransaction?: boolean;
}
⋮----
prepare(sql: string): SqliteStatement;
exec(sql: string): void;
pragma(str: string, options?:
transaction<T>(fn: (...args: any[])
close(): void;
⋮----
export type SqliteBackend = 'node-sqlite';
⋮----
class NodeSqliteAdapter implements SqliteDatabase
⋮----
constructor(dbPath: string, opts?:
⋮----
private failure(err: unknown): unknown
⋮----
get inTransaction(): boolean | undefined
⋮----
get open(): boolean
⋮----
prepare(sql: string): SqliteStatement
⋮----
const failure = (err: unknown): unknown
⋮----
run(...params: any[])
get(...params: any[])
all(...params: any[])
iterate(...params: any[])
⋮----
exec(sql: string): void
⋮----
transaction<T>(fn: (...args: any[]) => T): (...args: any[]) => T
⋮----
close(): void
⋮----
export function createDatabase(dbPath: string, opts?:
</file>

<file path="src/db/synthesis-stage.ts">
import { createDatabase, type SqliteDatabase } from './sqlite-adapter';
import { QueryBuilder } from './queries';
import { createYielder } from '../resolution/cooperative-yield';
⋮----
export class SynthesisStage
⋮----
constructor(dbPath: string)
⋮----
async publish(backpressure?: () => Promise<void> | null): Promise<void>
⋮----
close(): void
</file>

<file path="src/db/wal-valve.ts">
import type { DatabaseConnection } from './index';
⋮----
export class WalValveAbortError extends Error
⋮----
constructor(message: string, sizes:
⋮----
export function resolveWalValveMb(envVal: string | undefined, dbSizeBytes?: number): number
⋮----
// Scale with the project when the caller knows the DB size: every fold
// re-writes hot B-tree pages into the main file (the #1231 pathology in
// bounded form — 111s of a kernel-scale batch loop at the flat 256MB cap,
// §7a.2), so a big project affords a proportionally bigger transient WAL
// (~dbSize/4 soft ⇒ file cap ≈ dbSize) in exchange for ~4× fewer folds.
⋮----
export class WalCheckpointValve
⋮----
/** Writer pause in progress (hard cap breached): passes loop until a full backfill. */
⋮----
/**
   * WAL file size observed when a checkpoint last reported the ENTIRE WAL
   * backfilled. Growth is measured against this baseline — see the header
   * comment for why absolute size cannot be used.
   */
⋮----
/**
   * Consecutive parked-backfill give-ups. Used only for diagnostics in the
   * abort message — parking is never disabled (#1539 fail-closed).
   */
⋮----
constructor(
    private readonly db: DatabaseConnection,
    softMb: number = resolveWalValveMb(process.env.CODEGRAPH_WAL_VALVE_MB),
    private readonly intervalMs: number = CHECK_INTERVAL_MS,
    log: (msg: string) => void = () => {}
)
⋮----
// CODEGRAPH_WAL_VALVE_DEBUG=1 surfaces valve decisions to stderr without
// needing the caller's verbose plumbing — the observability gap that let
⋮----
private mb(n: number): string
⋮----
private growthBytes(): number
⋮----
start(): void
⋮----
stop(): void
⋮----
check(): void
⋮----
backpressure(): Promise<void> | null
⋮----
async drain(): Promise<void>
⋮----
async foldNow(): Promise<void>
⋮----
private async backfillFully(): Promise<void>
⋮----
private fire(): void
</file>

<file path="src/db/wsl-shared-index.ts">
import { DEFAULT_CODEGRAPH_DIR, WSL_CODEGRAPH_DIR } from '../directory';
import { isWindowsDriveMount, isWslWindowsDrive } from '../sync/watch-policy';
⋮----
export function isSqliteIoError(err: unknown): boolean
⋮----
export class WslSharedIndexError extends Error
⋮----
constructor(original: Error, dataDir: string)
⋮----
export interface WslSharedIndexProbe {
  isWsl?: boolean;
}
⋮----
export function toWslSharedIndexError(
  err: unknown,
  dbPath: string,
  probe: WslSharedIndexProbe = {}
): WslSharedIndexError | null
</file>

<file path="src/extraction/kernel/decode.ts">
import type {
  Edge,
  EdgeKind,
  ExtractionError,
  ExtractionResult,
  Language,
  Node,
  NodeKind,
  ReferenceKind,
  UnresolvedReference,
} from '../../types';
import { NODE_KINDS, EDGE_KINDS } from '../../types';
import type { KernelBuffers } from './loader';
import {
  EDGE,
  EDGE_ROW_SIZE,
  FLAG,
  FUNCTION_REF_CODE,
  KERNEL_ABI_VERSION,
  META,
  META_SIZE,
  NODE,
  NODE_ROW_SIZE,
  NONE,
  PROVENANCES,
  REF,
  REF_FLAG_FILE_PATH,
  REF_ROW_SIZE,
  VISIBILITIES,
} from './layout';
⋮----
function str(arena: Buffer, row: Buffer, at: number): string | undefined
⋮----
function strList(arena: Buffer, row: Buffer, at: number): string[] | undefined
⋮----
function flag(flags: number, pair: number): boolean | undefined
⋮----
function u32opt(row: Buffer, at: number): number | undefined
⋮----
export function decodeExtractBuffers(
  buffers: KernelBuffers,
  filePath: string,
  language: Language
): ExtractionResult
</file>

<file path="src/extraction/kernel/index.ts">
import type { ExtractionResult, Language } from '../../types';
import { EXTRACTORS } from '../languages';
import { getKernel, kernelSupports } from './loader';
import { decodeExtractBuffers } from './decode';
import {
  KERNEL_ABI_VERSION as LAYOUT_ABI,
  META as LAYOUT_META,
  NONE as LAYOUT_NONE,
} from './layout';
⋮----
export type KernelPostPass = (result: ExtractionResult, source: string) => void;
⋮----
function preParsedSource(filePath: string, source: string, language: Language): string
⋮----
function isRouted(language: Language): boolean
⋮----
export function kernelRoutes(language: Language): boolean
⋮----
export function takeDeferredPreParse(
  filePath: string,
  source: string,
  language: Language
): string | null
⋮----
export interface KernelRawResult {
  buffers: NonNullable<ExtractionResult['kernelBuffers']>;
  counts: { nodes: number; edges: number; refs: number };
  errors: ExtractionResult['errors'];
}
⋮----
export function tryKernelExtractRaw(
  filePath: string,
  source: string,
  language: Language
): KernelRawResult | null
⋮----
export function materializeKernelResult(
  result: ExtractionResult,
  filePath: string,
  language: Language
): ExtractionResult
⋮----
const asBuf = (u: Uint8Array)
⋮----
export function tryKernelExtract(
  filePath: string,
  source: string,
  language: Language
): ExtractionResult | null
</file>

<file path="src/extraction/kernel/layout.ts">

</file>

<file path="src/extraction/kernel/loader.ts">
import { createRequire } from 'module';
import { NODE_KINDS, EDGE_KINDS } from '../../types';
import { KERNEL_ABI_VERSION } from './layout';
⋮----
export interface KernelBuffers {
  meta: Buffer;
  nodes: Buffer;
  edges: Buffer;
  refs: Buffer;
  arena: Buffer;
}
⋮----
export interface KernelContractInfo {
  abiVersion: number;
  kernelVersion: string;
  nodeKinds: string[];
  edgeKinds: string[];
  languages: string[];
}
⋮----
export interface KernelGrammarInfo {
  abiVersion: number;
  nodeKindCount: number;
  fieldCount: number;
  nodeKinds: string[];
  fieldNames: string[];
}
⋮----
export interface CfnptrFileIn {
  text: string;
  structs: { id: string; startLine: number; endLine: number }[];
}
⋮----
export interface CfnptrFactsOut {
  fnPtrTypedefs: string[];
  fnTypeTypedefs: string[];
  structs: { id: string; parsed: boolean; fields: { name: string; index: number; ptr: boolean; type: string }[] }[];
  inlinePtr: boolean;
  inlineTypes: string[];
  inlineTags: string[];
  initTokens: string[];
  arrayElems: string[];
  aliasNames: string[];
  dPairs: string[];
  dispatchFields: string[];
  arrayDispatchNames: string[];
  includes: string[];
}
⋮----
export interface KernelModule {
  extractFile(filePath: string, content: string, language: string): KernelBuffers;
  contractInfo(): KernelContractInfo;
  grammarInfo(language: string): KernelGrammarInfo | null;
  cfnptrScanFiles?(files: CfnptrFileIn[]): CfnptrFactsOut[];
  cfnptrStripC?(text: string): string;
}
⋮----
extractFile(filePath: string, content: string, language: string): KernelBuffers;
contractInfo(): KernelContractInfo;
grammarInfo(language: string): KernelGrammarInfo | null;
⋮----
cfnptrScanFiles?(files: CfnptrFileIn[]): CfnptrFactsOut[];
⋮----
cfnptrStripC?(text: string): string;
⋮----
const debugEnabled = ()
function debug(msg: string): void
⋮----
function candidatePaths(): string[]
⋮----
function verifyContract(mod: KernelModule, from: string): boolean
⋮----
const sameTable = (a: readonly string[], b: readonly string[])
⋮----
export function getKernel(): KernelModule | null
⋮----
export function kernelSupports(language: string): boolean
⋮----
export function resetKernelForTests(): void
</file>

<file path="src/extraction/languages/arkts.ts">
import type { LanguageExtractor } from '../tree-sitter-types';
import { typescriptExtractor } from './typescript';
import type { Node as SyntaxNode } from 'web-tree-sitter';
⋮----
function collectDecoratorNames(node: SyntaxNode): string[] | undefined
⋮----
const nameOf = (dec: SyntaxNode): string | undefined =>
</file>

<file path="src/extraction/languages/c-cpp.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getChildByField, getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function findDeclaratorQualifiedId(declarator: SyntaxNode): SyntaxNode | undefined
⋮----
function recoverSingleArgMacroDefinedName(node: SyntaxNode, source: string): string | undefined
⋮----
function recoverCppMacroDefinedName(node: SyntaxNode, source: string): string | undefined
⋮----
const loneIdentText = (p: SyntaxNode): string | null
⋮----
function extractCppQualifiedMethodName(node: SyntaxNode, source: string): string | undefined
⋮----
function extractCppReceiverType(node: SyntaxNode, source: string): string | undefined
⋮----
export function normalizeCppReturnType(raw: string): string | undefined
⋮----
export function stripCppTemplateArgs(name: string): string
⋮----
/**
 * Is this C++ `field_declaration` a pure-virtual method (`virtual int read(int key) = 0;`)?
 * tree-sitter-cpp shapes those as a field_declaration whose declarator unwraps to a
 * `function_declarator`, with the pure-virtual `= 0` as a DIRECT `number_literal` "0"
 * child of the field_declaration (default-arg `= 0` lives inside parameter_declaration
 * and must not match). Bodiless method prototypes (`int foo();`) and data members
 * (`int x = 0;`) are excluded — prototypes usually have an out-of-line definition that
 * already mints the method node; pure virtuals never do (#1727).
 */
export function isCppPureVirtualMethodDecl(node: SyntaxNode): boolean
⋮----
function extractCppReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
function isMacroMisparsedTypeDecl(node: SyntaxNode): boolean
⋮----
export function blankCppExportMacros(source: string): string
⋮----
export function blankCppInlineMacros(source: string): string
⋮----
export function recoverMangledCppName(name: string): string
⋮----
export function blankMetalAttributes(source: string): string
⋮----
export function maskCppRawStrings(source: string):
⋮----
// An unterminated raw literal owns the rest of the file too.
⋮----
restore(blanked): string
⋮----
// A length-changing rewrite cannot be restored at the original offsets.
⋮----
/**
 * Blank annotation-style macro invocations that decorate a declaration but carry
 * NO terminating semicolon — the pervasive Unreal-Engine reflection markup
 * (`UPROPERTY(...)`, `UFUNCTION(...)`, `UCLASS(...)`, `GENERATED_BODY()`,
 * `UE_DEPRECATED_FORGAME(...)`, `DECLARE_DELEGATE_*(...)`, …) that sits on its
 * own line right before a member/type. tree-sitter's C++ grammar doesn't know
 * these are macros, so each one drops into error recovery; in a big reflected
 * class (`CharacterMovementComponent.h` has ~240 of them) the errors accumulate
 * until the enclosing `class_specifier` can't close and collapses into an ERROR
 * node — the whole class definition, its members, and its `extends` edges vanish
 * from the graph. Neither `blankCppExportMacros` (class-header export macros) nor
 * `blankCppInlineMacros` (return-type inline specifiers) touches these in-body
 * markup macros. Replacing each with equal-length spaces preserves every byte
 * offset (so line/column stay exact) and the class then parses normally.
 *
 * Deliberately name-list-FREE — UE alone has hundreds of such macros and projects
 * add their own — so it keys on structure, not a curated list, matched tightly to
 * avoid touching legitimate C++:
 *  - the macro must be the FIRST non-whitespace token on its line (`^[ \t]*`),
 *    which is where declaration markup lives — so a macro used inside an
 *    expression or condition (`if (CHECK(x))`, `x = MACRO(a) + b`) is never
 *    matched (it isn't line-leading);
 *  - the name must be ALL-CAPS (`[A-Z][A-Z0-9_]{2,}`), since ordinary
 *    function/type names called at line start are lower/mixed case;
 *  - the char after the balanced `(...)` must START A DECLARATION — a letter,
 *    `_`, `~` (destructor), or `#` (a following directive). Declaration markup is
 *    always followed by the thing it decorates (`UPROPERTY(...)\n float X;`,
 *    `UE_DEPRECATED(...) UPROPERTY(...)`), whereas a statement call is followed by
 *    `;` (`FOO(x);`), an init-list item by `,`/`{`, and an expression fragment by
 *    an operator (`MAKE(a) + 1`) — all rejected. String/char literals inside the
 *    args are skipped so an embedded `)` can't mis-close the balance.
 *
 * C++-only (wired into cppExtractor). A blanked macro inside a block comment is
 * harmless (comments don't parse), and the rare line-leading no-semicolon
 * ALL-CAPS call that isn't markup only loses that one annotation, never a whole
 * class.
 */
export function blankCppAnnotationMacroCalls(source: string): string
⋮----
const macroStart = m.index + (m[1] ?? '').length; // skip leading indent
let i = m.index + m[0].length - 1; // index of the opening '('
⋮----
// Only markup is followed by the declaration it decorates; a statement call
// (`;`), init-list item (`,`/`{`), or expression fragment (operator) is not.
⋮----
/**
 * Blank a macro that is the ONLY token on its line — no parens, no semicolon:
 * namespace-management macros (`FMT_BEGIN_NAMESPACE`, `FMT_END_EXPORT`,
 * `JEMALLOC_DIAGNOSTIC_DISABLE_SPURIOUS`), Qt's `Q_OBJECT`, and friends. A
... (276 lines truncated)
</file>

<file path="src/extraction/languages/cfquery.ts">
import type { LanguageExtractor } from '../tree-sitter-types';
</file>

<file path="src/extraction/languages/cfscript.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function cfmlVisibility(node: SyntaxNode): 'public' | 'private' | 'protected' | 'internal' | undefined
⋮----
// `import com.foo.Bar;` (dotted path) or `import "java:java.util.ArrayList";` (string form)
</file>

<file path="src/extraction/languages/cobol.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types';
⋮----
/** EXEC CICS RETURN/START — next transaction, quoted literal or data name. */
⋮----
/** EXEC SQL INCLUDE <member> — the SQL flavor of COPY. */
⋮----
/** The VALUE literal in a data item's signature ("PIC X(04) VALUE 'CB00'"). */
⋮----
function line(node: SyntaxNode): number
⋮----
function endLineOf(node: SyntaxNode): number
⋮----
/** Collapse whitespace runs so multi-line clauses read as one signature. */
function collapse(text: string, cap = 120): string
⋮----
function currentScope(ctx: ExtractorContext): string | undefined
⋮----
/**
 * DB2 convention writes `EXEC SQL INCLUDE member END-EXEC` with no sentence
 * period, sitting between paragraphs like a COPY — which derails the
 * grammar's sentence machinery. Terminate the single-line form by writing a
 * period into the character right after END-EXEC (a space), or appending one
 * at end of line. Both are offset-preserving for every other character.
 */
function terminateSqlIncludes(source: string): string
⋮----
function addRef(
  ctx: ExtractorContext,
  fromNodeId: string | undefined,
  referenceName: string,
  referenceKind: 'calls' | 'imports' | 'references',
  at: SyntaxNode
): void
⋮----
/** COPY <book> [IN/OF lib] — import node + imports reference. */
function handleCopy(node: SyntaxNode, ctx: ExtractorContext): void
⋮----
function derefSameFileValue(name: string, ctx: ExtractorContext): string | undefined
⋮----
function handleExec(
  node: SyntaxNode,
  ctx: ExtractorContext,
  fromNodeId: string | undefined
): void
⋮----
function walkDataEntries(entries: SyntaxNode[], ctx: ExtractorContext): void
⋮----
interface Item {
    node: SyntaxNode;
    level: number;
    name: string | null;
  }
⋮----
const isTopLevel = (level: number): boolean
⋮----
const groupEnd = (i: number): number =>
⋮----
const closeTo = (level: number) =>
⋮----
function targetBaseName(target: SyntaxNode, source: string): SyntaxNode | null
⋮----
function emitWriteRefs(
  statement: SyntaxNode,
  fields: string[],
  fromNodeId: string | undefined,
  ctx: ExtractorContext
): void
⋮----
function collectRefs(
  node: SyntaxNode,
  fromNodeId: string | undefined,
  ctx: ExtractorContext
): void
⋮----
/** "PARA-NAME." → "PARA-NAME"; "SEC-NAME SECTION." → "SEC-NAME". */
function headerName(header: SyntaxNode, source: string): string
⋮----
/**
 * Walk the flat PROCEDURE DIVISION (or a procedure copybook fragment):
 * reconstruct section/paragraph extents from header positions and attribute
 * the sibling statements between headers to the open paragraph.
 */
function walkProcedureChildren(
  children: SyntaxNode[],
  divisionEndLine: number,
  ctx: ExtractorContext
): void
⋮----
/** 1-based last line of the region started at children[i]. */
const regionEnd = (i: number, sectionsOnly: boolean): number =>
⋮----
function programName(programNode: SyntaxNode, source: string): string | null
⋮----
// All extraction flows through the visitNode hook — COBOL's flat,
// column-oriented AST doesn't fit the generic type-list dispatch.
⋮----
// The grammar implements fixed-format column rules (sequence area 1-6,
// indicator 7, code 8-72). A free-format file — where real code starts
... (11 lines truncated)
</file>

<file path="src/extraction/languages/csharp.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
export function blankCsharpPreprocessorDirectives(source: string): string
⋮----
function extractCsharpReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
t = t.replace(/\?+$/, ''); // nullable `Foo?`
t = t.replace(/<[^>]*>/g, ''); // generics `List<Foo>` → `List`
const last = t.split('.').pop()?.trim(); // namespace `Ns.Foo` → `Foo`
⋮----
/** Where a C# declaration with no access modifier defaults to `internal`. */
</file>

<file path="src/extraction/languages/dart.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function dartInnerSignature(node: SyntaxNode): SyntaxNode
⋮----
function dartConstructorSignature(node: SyntaxNode): SyntaxNode | undefined
⋮----
function dartEnclosingTypeName(node: SyntaxNode): string | undefined
⋮----
function dartCtorInfo(node: SyntaxNode):
⋮----
function extractDartReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
const last = text.split('.').pop(); // prefixed `p.Bar` → `Bar`
⋮----
/**
 * The callee name of the Dart call whose `argument_part` selector is `argPart`
 * — mirrors the main extractBareCall accessor logic so a chained receiver
 * (`Foo.create()` in `Foo.create().bar()`) can be reconstructed. Returns
 * `Foo.create`, a bare `create`, or `Foo` (constructor) — or undefined.
 */
function dartCalleeOfArgPart(argPart: SyntaxNode): string | undefined
⋮----
// Dart convention: _ prefix means private, otherwise public
⋮----
// Dart imports: import 'dart:async'; import 'package:foo/bar.dart' as bar;
⋮----
// Also handle exports: export 'src/foo.dart';
⋮----
// Dart calls are: identifier + selector(argument_part), not a dedicated call node.
// Match on selector nodes that contain argument_part.
</file>

<file path="src/extraction/languages/erlang.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField, getPrecedingDocstring } from '../tree-sitter-helpers';
import type { LanguageExtractor, ExtractorContext } from '../tree-sitter-types';
⋮----
function atomText(node: SyntaxNode, source: string): string
⋮----
function collapseWs(text: string): string
⋮----
function moduleExports(node: SyntaxNode, source: string, filePath: string): Set<string> | 'all'
⋮----
function nodeArity(withArgs: SyntaxNode): number
⋮----
function precedingSpec(node: SyntaxNode, name: string, arity: number, source: string): SyntaxNode | null
⋮----
function clauseHeader(clause: SyntaxNode, source: string): string | undefined
⋮----
function handleFunDecl(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
function handleRecordDecl(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
function handleTypeAlias(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
function handlePpDefine(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
function handleBehaviour(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
function handleAppResourceTuple(node: SyntaxNode, ctx: ExtractorContext): boolean
⋮----
const ref = (nameNode: SyntaxNode, kind: 'references' | 'imports'): void =>
</file>

<file path="src/extraction/languages/go.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function extractGoReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
.replace(/\[[^\]]*\]/g, ''); // strip generic args `Foo[T]`
const last = text.split('.').pop()?.trim(); // qualified `pkg.Foo` → `Foo`
</file>

<file path="src/extraction/languages/index.ts">
import { Language } from '../../types';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
import { typescriptExtractor } from './typescript';
import { javascriptExtractor } from './javascript';
import { pythonExtractor } from './python';
import { goExtractor } from './go';
import { rustExtractor } from './rust';
import { javaExtractor } from './java';
import { cExtractor, cppExtractor } from './c-cpp';
import { csharpExtractor } from './csharp';
import { phpExtractor } from './php';
import { rubyExtractor } from './ruby';
import { swiftExtractor } from './swift';
import { kotlinExtractor } from './kotlin';
import { dartExtractor } from './dart';
import { pascalExtractor } from './pascal';
import { scalaExtractor } from './scala';
import { luaExtractor } from './lua';
import { rExtractor } from './r';
import { luauExtractor } from './luau';
import { objcExtractor } from './objc';
import { cfscriptExtractor } from './cfscript';
import { cfqueryExtractor } from './cfquery';
import { cobolExtractor } from './cobol';
import { vbnetExtractor } from './vbnet';
import { erlangExtractor } from './erlang';
import { solidityExtractor } from './solidity';
import { terraformExtractor } from './terraform';
import { arktsExtractor } from './arkts';
import { nixExtractor } from './nix';
</file>

<file path="src/extraction/languages/java.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types';
⋮----
function normalizeJavaType(typeNode: SyntaxNode | null, source: string): string | undefined
⋮----
// Strip a dotted package / outer-class qualifier (`java.util.List` → `List`).
⋮----
/**
 * A Java method's declared return type. Reads the `type` field; constructors
 * (no `type` field) → undefined.
 */
function extractJavaReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
function lombokAnnotationNames(node: SyntaxNode): Set<string>
⋮----
function modifierTextOf(node: SyntaxNode): string
⋮----
function capitalizeJava(name: string): string
⋮----
/** Lombok getter name: `getX`, or `isX` for a primitive boolean (keeping an existing `isFoo` field name). */
function lombokGetterName(fieldName: string, isBooleanPrimitive: boolean): string
⋮----
function lombokSetterName(fieldName: string, isBooleanPrimitive: boolean): string
⋮----
function synthesizeLombokMembers(classNode: SyntaxNode, ctx: ExtractorContext): void
⋮----
const emitMethod = (
    name: string,
    anchor: SyntaxNode,
    signature: string,
    fromAnnotation: string,
    extra: { returnType?: string; isStatic?: boolean } = {}
): void =>
</file>

<file path="src/extraction/languages/javascript.ts">
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
import { classifyTsClassMember } from './typescript';
</file>

<file path="src/extraction/languages/kotlin.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function extractKotlinReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
function kotlinPropertyInitializers(node: SyntaxNode): SyntaxNode[]
⋮----
function kotlinPropertyKind(
  node: SyntaxNode,
  source: string
): 'field' | 'constant' | 'variable' | null
⋮----
function kotlinAccessorOwner(node: SyntaxNode): SyntaxNode | null
⋮----
function kotlinFollowingAccessors(node: SyntaxNode): SyntaxNode[]
⋮----
function isFunInterfaceNode(node: SyntaxNode): boolean
⋮----
export function blankKotlinQualifiedReceivers(source: string): string
⋮----
export function joinKotlinSplitConstructors(source: string): string
⋮----
export function rewriteNewerKotlinSyntax(source: string): string
⋮----
function preParseKotlin(source: string): string
⋮----
// A local — no node is minted, but the initializer is still code. Walk
// it at the ENCLOSING scope: an `init { }` block's `val q = load()` is
</file>

<file path="src/extraction/languages/lua.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function findDescendant(node: SyntaxNode, type: string): SyntaxNode | null
⋮----
function requireModule(callNode: SyntaxNode, source: string): string | null
⋮----
// Roblox/Luau instance-path require: `require(script.Parent.Signal)` → "Signal".
⋮----
const emit = (callNode: SyntaxNode): void =>
</file>

<file path="src/extraction/languages/luau.ts">
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
import { luaExtractor } from './lua';
</file>

<file path="src/extraction/languages/nix.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types';
⋮----
function unwrapVariableExpression(node: SyntaxNode): SyntaxNode
⋮----
function getCalleeName(node: SyntaxNode, source: string): string | null
⋮----
function getDirectCalleeName(node: SyntaxNode, source: string): string | null
⋮----
function isStaticProjectPath(value: string): boolean
⋮----
function getStaticImportPath(argNode: SyntaxNode, source: string): string | null
⋮----
function isReturnedAttrsetMember(node: SyntaxNode): boolean
⋮----
function getCurriedParamsAndBody(node: SyntaxNode, source: string):
⋮----
function formatFunctionSignature(params: string[]): string
⋮----
function inheritedAttrs(node: SyntaxNode): SyntaxNode | null
⋮----
function isCallPackageName(name: string): boolean
⋮----
function getFirstApplyArgument(node: SyntaxNode): SyntaxNode | null
⋮----
function emitFileImport(ctx: ExtractorContext, importPath: string, anchorNode: SyntaxNode, source: string): void
</file>

<file path="src/extraction/languages/objc.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getChildByField, getNodeText } from '../tree-sitter-helpers';
import type { ExtractorContext, LanguageExtractor } from '../tree-sitter-types';
⋮----
function findCompoundStatement(node: SyntaxNode): SyntaxNode | null
⋮----
function extractObjcMethodName(node: SyntaxNode, source: string): string | undefined
⋮----
/** Nullability / ARC qualifiers that sit where a return type's first type
 *  identifier does (`(nonnull instancetype)`, `(nullable Bar *)`) — never the type. */
⋮----
function collectTypeIdentifiers(node: SyntaxNode, source: string, out: string[]): void
⋮----
function extractObjcReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
function extractObjcPropertyName(node: SyntaxNode, source: string): string | null
</file>

<file path="src/extraction/languages/pascal.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
</file>

<file path="src/extraction/languages/php.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function phpStaticIncludePath(node: SyntaxNode, source: string): string | null
⋮----
function extractPhpReturnType(node: SyntaxNode, source: string): string | undefined
</file>

<file path="src/extraction/languages/python.ts">
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function dedentDocstring(raw: string): string
</file>

<file path="src/extraction/languages/r.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor, ExtractorContext } from '../tree-sitter-types';
⋮----
function calleeName(call: SyntaxNode, source: string): string | null
⋮----
function firstArgValue(call: SyntaxNode): SyntaxNode | null
⋮----
function literalOrIdentifier(node: SyntaxNode | null, source: string): string | null
⋮----
return ''; // empty string literal
⋮----
/** Emit one `name = function(…)` argument entry as a method in the current scope. */
function emitMethodArg(entry: SyntaxNode, ctx: ExtractorContext): void
⋮----
function extractClassMembers(classCall: SyntaxNode, classId: string, ctx: ExtractorContext): void
</file>

<file path="src/extraction/languages/ruby.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
</file>

<file path="src/extraction/languages/rust.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function extractRustReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
export function rustImplTypeName(typeNode: SyntaxNode | null, source: string): string | undefined
⋮----
const getRootModule = (scopedNode: SyntaxNode): string =>
</file>

<file path="src/extraction/languages/scala.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function getValVarName(node: SyntaxNode, source: string): string | null
⋮----
function emitScalaTypeRefs(typeNode: SyntaxNode, fromId: string, ctx:
⋮----
function extractScalaReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
.replace(/\[[^\]]*\]/g, '') // strip generic args: List[Bar] → List
⋮----
const last = base.split('.').pop(); // qualified pkg.Bar → Bar
⋮----
function extractVisibility(node: SyntaxNode): 'public' | 'private' | 'protected'
</file>

<file path="src/extraction/languages/solidity.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function getInheritanceAncestors(node: SyntaxNode, source: string): string[]
⋮----
function fallbackReceiveName(node: SyntaxNode): string
</file>

<file path="src/extraction/languages/swift.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function extractSwiftReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
export function joinSwiftCompositionContinuations(source: string): string
⋮----
// The previous line must end on a type; a trailing comment would swallow the `&`.
</file>

<file path="src/extraction/languages/terraform.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
function stringLitValue(node: SyntaxNode, source: string): string
⋮----
/** Block "type" and its label values. Returns null if the block is malformed. */
function readBlockHeader(block: SyntaxNode, source: string):
⋮----
function getBlockBody(block: SyntaxNode): SyntaxNode | null
⋮----
function collectReferences(
  expr: SyntaxNode,
  source: string,
  onRef: (qualifiedName: string, line: number, column: number) => void
): void
⋮----
function emitRefFromVariableExpr(
  varExpr: SyntaxNode,
  source: string,
  onRef: (qualifiedName: string, line: number, column: number) => void
): void
⋮----
function qualifyReference(head: string, attrs: string[]): string[]
⋮----
function emitModuleWiring(
  moduleName: string,
  block: SyntaxNode,
  body: SyntaxNode,
  ctx: Parameters<NonNullable<LanguageExtractor['visitNode']>>[1],
  fromNodeId: string
): void
⋮----
function findStringLit(expr: SyntaxNode): SyntaxNode | null
⋮----
interface BlockDecl {
  kind: 'class' | 'module' | 'variable' | 'namespace';
  name: string;
  qualifiedName: string;
  signature: string;
}
⋮----
function describeBlock(type: string, labels: string[]): BlockDecl | null
⋮----
function emitLocals(
  body: SyntaxNode | null,
  ctx: Parameters<NonNullable<LanguageExtractor['visitNode']>>[1]
): void
⋮----
interface EmitRefsOptions {
  suppressScoped?: boolean;
  skipTopAttrs?: Set<string>;
}
⋮----
function emitReferencesInBody(
  body: SyntaxNode,
  ctx: Parameters<NonNullable<LanguageExtractor['visitNode']>>[1],
  fromNodeId: string,
  opts?: EmitRefsOptions
): void
⋮----
function readStringAttr(body: SyntaxNode, name: string, source: string): string | null
⋮----
function emitProviderSelectionRef(
  body: SyntaxNode,
  ctx: Parameters<NonNullable<LanguageExtractor['visitNode']>>[1],
  fromNodeId: string
): void
⋮----
function emitModuleProvidersRefs(
  body: SyntaxNode,
  ctx: Parameters<NonNullable<LanguageExtractor['visitNode']>>[1],
  fromNodeId: string
): void
⋮----
function providerSelectionFromExpr(expr: SyntaxNode, source: string): string | null
</file>

<file path="src/extraction/languages/typescript.ts">
import { getNodeText, getChildByField } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
import { hasFlowPragma } from '../grammars';
import type { Node as SyntaxNode } from 'web-tree-sitter';
⋮----
export function classifyTsClassMember(node: SyntaxNode): 'method' | 'property'
⋮----
export function blankFlowSyntax(source: string, filePath?: string): string
</file>

<file path="src/extraction/languages/vbnet.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText } from '../tree-sitter-helpers';
import type { LanguageExtractor } from '../tree-sitter-types';
⋮----
export function ensureTrailingNewline(source: string): string
⋮----
function hasModifier(node: SyntaxNode, re: RegExp): boolean
⋮----
function extractVbnetReturnType(node: SyntaxNode, source: string): string | undefined
⋮----
t = t.replace(/\?+$/, ''); // nullable `Foo?`
t = t.replace(/\(\s*Of\b[^)]*\)/gi, ''); // generics `List(Of Foo)` → `List`
⋮----
// VB Modules are static containers (Shared members, no instantiation) —
// indexed as classes so their members get normal containment/qualification.
</file>

<file path="src/extraction/astro-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
import { TreeSitterExtractor } from './tree-sitter';
import { isLanguageSupported } from './grammars';
⋮----
export class AstroExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
extract(): ExtractionResult
⋮----
private createComponentNode(): Node
⋮----
private extractFrontmatter():
⋮----
// Closing fence
⋮----
private extractScriptBlocks(): Array<
⋮----
// Calculate the 0-indexed line where the content begins. The content
// starts right after the opening tag's `>` — its leading `\n` is part
⋮----
private processScriptContent(
    block: { content: string; startLine: number },
    componentNodeId: string,
    label: 'frontmatter' | 'script'
): void
⋮----
private getCoveredRanges(
    frontmatter: { startLine: number; endLine: number } | null
): Array<[number, number]>
⋮----
private extractTemplateCalls(
    componentNodeId: string,
    coveredRanges: Array<[number, number]>
): void
⋮----
// Extract function calls: identifiers followed by (
// Matches: cn(...), formatDate(...), obj.method(...)
⋮----
// Skip control-flow keywords valid inside expressions
⋮----
private extractTemplateComponents(
    componentNodeId: string,
    coveredRanges: Array<[number, number]>
): void
</file>

<file path="src/extraction/cfml-extractor.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference, Language } from '../types';
import { generateNodeId, NodeIdAllocator } from './tree-sitter-helpers';
import { TreeSitterExtractor } from './tree-sitter';
import { getParser } from './grammars';
⋮----
export class CfmlExtractor
⋮----
constructor(filePath: string, source: string, language: Language = 'cfml')
⋮----
extract(): ExtractionResult
⋮----
private extractBareScript(): void
⋮----
private extractTagBased(): void
⋮----
private createFileNode(): Node
⋮----
private walkProgram(root: SyntaxNode, fileNodeId: string): void
⋮----
private extractComponent(openTag: SyntaxNode, containerId: string | undefined): SyntaxNode
⋮----
private extractFunctionTag(tag: SyntaxNode, parentClassId: string | undefined, containerId: string | undefined, parentClassName?: string): void
⋮----
private delegateNestedTags(node: SyntaxNode, containerId: string | undefined, parentClassName?: string): void
⋮----
private delegateScriptTag(scriptTag: SyntaxNode, parentId: string | undefined, parentClassName?: string): void
⋮----
private delegateQueryTag(queryTag: SyntaxNode, parentId: string | undefined): void
⋮----
private tagAttr(tag: SyntaxNode, attrName: string): string | undefined
⋮----
private componentNameFromPath(): string
⋮----
/**
 * Sniff whether CFML source is bare-script (`component { ... }`, modern style)
 * vs tag-based (`<cfcomponent>`, `<cfif>`, HTML). Skips a leading UTF-8 BOM
 * (endemic in CFML's Windows-editor history — 17% of ColdBox's files carry
 * one; both grammars parse fine with it once routed correctly), whitespace,
 * and `//`/`/* *\/` comments to find the first real token; tag-based files
 * start with `<`, script-based files don't.
 */
export function isBareScriptCfml(source: string): boolean
</file>

<file path="src/extraction/dfm-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
⋮----
export class DfmExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
extract(): ExtractionResult
⋮----
private createFileNode(): Node
⋮----
private parseComponents(fileNode: Node): void
</file>

<file path="src/extraction/extraction-version.ts">

</file>

<file path="src/extraction/function-ref.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { getNodeText, getChildByField } from './tree-sitter-helpers';
⋮----
export interface FnRefCandidate {
  name: string;
  line: number;
  column: number;
  mode: CaptureMode;
  explicitRef: boolean;
  skipGate?: boolean;
}
⋮----
type CaptureMode =
  | 'args'
  | 'rhs'
  | 'value'
  | 'list'
  | 'varinit';
⋮----
interface CaptureRule {
  mode: CaptureMode;
  field?: string;
}
⋮----
export interface FnRefSpec {
  idTypes: Set<string>;
  dispatch: Map<string, CaptureRule>;
  layers?: Map<string, string | null>;
  unwrap?: Map<string, string | null>;
  special?: Set<string>;
  ungatedModes?: Set<CaptureMode>;
  addressOfOnly?: boolean;
}
⋮----
function cFamilySpec(extra?:
⋮----
function isRubyHookCall(name: string): boolean
⋮----
export function captureFnRefCandidates(
  container: SyntaxNode,
  rule: CaptureRule,
  spec: FnRefSpec,
  source: string
): FnRefCandidate[]
⋮----
interface NormalizedRef {
  name: string;
  node: SyntaxNode;
  skipGate?: boolean;
}
⋮----
function normalizeValue(
  node: SyntaxNode,
  spec: FnRefSpec,
  source: string,
  depth: number
): NormalizedRef[]
⋮----
function lastNamedOfType(node: SyntaxNode, types: Set<string>): SyntaxNode | null
⋮----
function normalizeSpecial(
  node: SyntaxNode,
  type: string,
  source: string
): NormalizedRef[]
⋮----
// `this.handleClick` (TS/JS) — object must be EXACTLY `this`. The name
// keeps the `this.` prefix so resolution can scope it to the enclosing
// class (see resolveThisMemberFnRef) instead of bare name-matching.
⋮----
/** Content of a PHP string literal node (single- or double-quoted). */
function phpStringContent(node: SyntaxNode, source: string): string | null
⋮----
function phpEnclosingCallName(node: SyntaxNode): string | null
⋮----
function rubyEnclosingCall(node: SyntaxNode): SyntaxNode | null
</file>

<file path="src/extraction/generated-detection.ts">
export function isGeneratedFile(filePath: string): boolean
⋮----
/**
 * Openers/closers for block comments, so a banner on an unprefixed line
 * inside `/* … *\/` (or `<!-- … -->`, or a Python module docstring) still
 * counts. Deliberately naive — it only runs over a file's first few dozen
 * lines, where a `/*` inside a string literal is vanishingly rare, and the
 * worst case of a mis-tracked state is a ranking hint, not a wrong answer.
 */
⋮----
export function hasGeneratedHeader(content: string): boolean
⋮----
export function detectGeneratedFile(filePath: string, content: string): boolean
⋮----
export function isMinifiedContent(filePath: string, content: string): boolean
</file>

<file path="src/extraction/grammars.ts">
import { Parser, Language as WasmLanguage } from 'web-tree-sitter';
import { Language } from '../types';
⋮----
export type GrammarLanguage = Exclude<Language, 'svelte' | 'vue' | 'astro' | 'liquid' | 'razor' | 'yaml' | 'twig' | 'xml' | 'properties' | 'unknown'>;
⋮----
export function isMpegTransportStream(head: Uint8Array): boolean
⋮----
export function hasMpegTsExtension(filePath: string): boolean
⋮----
export function isSourceFile(filePath: string, overrides?: Record<string, Language>): boolean
⋮----
export function isShopifyLiquidJson(filePath: string): boolean
⋮----
export function isErlangAppFile(filePath: string): boolean
⋮----
export function isPlayRoutesFile(filePath: string): boolean
⋮----
export async function initGrammars(): Promise<void>
⋮----
function resolveWasmPath(lang: GrammarLanguage): string
⋮----
function expandGrammarLanguages(languages: Language[]): Language[]
⋮----
export async function readGrammarWasmBytes(languages: Language[]): Promise<Record<string, Uint8Array>>
⋮----
export async function loadGrammarsForLanguages(languages: Language[], wasmBytes?: Record<string, Uint8Array>): Promise<void>
⋮----
export async function loadAllGrammars(): Promise<void>
⋮----
export function isGrammarsInitialized(): boolean
⋮----
export function getParser(language: Language): Parser | null
⋮----
export function detectLanguage(filePath: string, source?: string, overrides?: Record<string, Language>): Language
⋮----
export function hasFlowPragma(source: string): boolean
⋮----
/**
 * A class/struct BASE CLAUSE — `struct Derived : Base {`, `class Foo final :
 * public Bar, private Baz {`, `struct D : ns::B<T> {` — which is never valid
 * C. In C the only thing that can follow `struct <tag>` is `{`, `;`, `*`, an
 * identifier (declarator), or a closing `)`: a bit-field's `:` sits after a
 * member NAME inside the body (`unsigned a : 3;`), a ternary's `:` is
 * separated from the tag by `)` / `*` / a declarator (`sizeof(struct foo) :
 * 0`), and a label such as `struct_end:` has no whitespace after `struct`. An
 * optional access specifier / `virtual` after the colon and an optional
 * `final` before it cover the spelled-out forms; the base may be scoped
 * (`ns::Base`) and carry template arguments, and must be followed by the
 * body's `{` or a `,` introducing the next base — prose like
 * `struct timeval: seconds and microseconds` inside a string never has that
 * terminator. Comments are stripped before the scan (see `looksLikeCpp`).
 */
⋮----
function looksLikeCpp(source: string): boolean
⋮----
function looksLikeObjc(source: string): boolean
⋮----
export function hasTreeSitterGrammar(language: string | undefined | null): boolean
⋮----
export function isLanguageSupported(language: Language): boolean
⋮----
export function isGrammarLoaded(language: Language): boolean
⋮----
export function isFileLevelOnlyLanguage(language: Language): boolean
⋮----
export function getSupportedLanguages(): Language[]
⋮----
export function resetParser(language: Language): void
⋮----
export function clearParserCache(): void
⋮----
export function getUnavailableGrammarErrors(): Partial<Record<Language, string>>
⋮----
export function getLanguageDisplayName(language: Language): string
</file>

<file path="src/extraction/index.ts">
import { execFileSync } from 'child_process';
import {
  Language,
  FileRecord,
  ExtractionResult,
  ExtractionError,
  Node,
  Edge,
  UnresolvedReference,
  ReferenceKind,
} from '../types';
import { QueryBuilder } from '../db/queries';
import { extractFromSource } from './tree-sitter';
import { ParseWorkerPool, resolveParsePoolSize, resolveParseTimeoutMs } from './parse-pool';
import { StoreWriter, StoreBundle, finalizeStoreBundle } from './store-writer';
import { materializeKernelResult } from './kernel';
import { detectGeneratedFile } from './generated-detection';
import { detectLanguage, isSourceFile, isLanguageSupported, isFileLevelOnlyLanguage, initGrammars, loadGrammarsForLanguages, readGrammarWasmBytes, isMpegTransportStream, hasMpegTsExtension, MPEG_TS_SNIFF_BYTES } from './grammars';
import { loadExtensionOverrides, loadIncludeIgnoredPatterns, loadExcludePatterns, loadIncludePatterns, PROJECT_CONFIG_FILENAME } from '../project-config';
import { isCodeGraphDataDir } from '../directory';
import { logDebug, logWarn } from '../errors';
import { validatePathWithinRoot, normalizePath } from '../utils';
import ignore, { Ignore } from 'ignore';
import { detectFrameworks, getFrameworkResolver } from '../resolution/frameworks';
import { declaredDependencies } from '../resolution/frameworks/package-deps';
import type { ResolutionContext } from '../resolution/types';
import { createYielder, type MaybeYield } from '../resolution/cooperative-yield';
import { MAX_SOURCE_FILE_SIZE_BYTES, oversizeStamp, readBoundedSource, readBoundedSourceSync } from '../file-limits';
⋮----
export interface IndexProgress {
  phase: 'scanning' | 'parsing' | 'storing' | 'resolving' | 'linking';
  current: number;
  total: number;
  currentFile?: string;
}
⋮----
export interface IndexResult {
  success: boolean;
  filesIndexed: number;
  filesSkipped: number;
  filesErrored: number;
  filesDiscovered?: number;
  filesSkippedUnsupported?: number;
  topUnsupportedExtensions?: { ext: string; count: number }[];
  nodesCreated: number;
  edgesCreated: number;
  errors: ExtractionError[];
  durationMs: number;
}
⋮----
export interface SyncResult {
  pendingRefsProcessed?: number;
  pendingRefsResolved?: number;
  pendingRefsUnresolved?: number;
  filesChecked: number;
  filesAdded: number;
  filesModified: number;
  filesRemoved: number;
  nodesUpdated: number;
  durationMs: number;
  changedFilePaths?: string[];
  failedFilePaths?: string[];
  definitionDelta?: string[];
}
⋮----
export function hashContent(content: string): string
⋮----
function readSourceOrStamp(fullPath: string): string | null
⋮----
function isMpegTsBytes(filePath: string, bytes: Buffer): boolean
⋮----
function isValidUtf8(buf: Buffer): boolean
⋮----
function readGitignorePatterns(giPath: string): string
⋮----
return ''; // unreadable (permissions / race) — treat as absent
⋮----
// A NUL byte never appears in real gitignore text, and a fatal UTF-8 decode
// catches the rest. Such a file isn't ignore patterns at all.
⋮----
function resolveGitDir(repoRoot: string): string | null
⋮----
function expandUserPath(p: string): string
⋮----
function readGitExcludeExtraPatterns(rootDir: string): string
⋮----
function listGitIgnoredDirectories(rootDir: string): string[]
⋮----
export function buildDefaultIgnore(rootDir: string): Ignore
⋮----
function defaultsOnlyIgnore(): Ignore
⋮----
function loadIncludeIgnoredMatcher(rootDir: string): Ignore | null
⋮----
function loadExcludeMatcher(rootDir: string): Ignore | null
⋮----
function loadIncludeMatcher(rootDir: string): Ignore | null
⋮----
function includeStaticRoots(patterns: string[]): string[]
⋮----
... (340 lines truncated)
</file>

<file path="src/extraction/liquid-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference } from '../types';
import { generateNodeId, NodeIdAllocator } from './tree-sitter-helpers';
⋮----
export class LiquidExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
extract(): ExtractionResult
⋮----
private createFileNode(): Node
⋮----
private extractShopifyJsonSections(fromNodeId: string): void
⋮----
private findTagOccurrences(
    tagPattern: string,
    argPattern: string,
): Array<
⋮----
private extractSnippetReferences(fileNodeId: string): void
⋮----
private extractSectionReferences(fileNodeId: string): void
⋮----
private extractSchema(fileNodeId: string): void
⋮----
private extractAssignments(fileNodeId: string): void
⋮----
private getLineNumber(index: number): number
⋮----
private getLineStart(lineNumber: number): number
</file>

<file path="src/extraction/mybatis-extractor.ts">
import { Edge, ExtractionError, ExtractionResult, Node, UnresolvedReference } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
⋮----
export class MyBatisExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
private static stripXmlComments(source: string): string
⋮----
extract(): ExtractionResult
⋮----
private createFileNode(): Node
⋮----
private findMapperRoot():
    | { namespace: string; dialect: 'mybatis' | 'ibatis'; bodyStart: number; bodyEnd: number }
    | null {
    const mapper = /<mapper\b([^>]*)>/.exec(this.source);
⋮----
private extractMapper(
    fileNodeId: string,
    namespace: string,
    dialect: 'mybatis' | 'ibatis',
    bodyStart: number,
    bodyEnd: number
): void
⋮----
// Accept either quote style (`(["'])…\1`). The identifier-shaped MyBatis
⋮----
private buildSignature(elemType: string, attrs: string, isSqlFragment: boolean): string
⋮----
// A vendor-split statement carries `databaseId`; surface it so the two
// otherwise-identical `<namespace>::<id>` nodes are distinguishable.
⋮----
private qualifyStatement(namespace: string, id: string):
⋮----
private previewSql(body: string): string
⋮----
private computeLineStarts(): void
⋮----
private getLineNumber(offset: number): number
</file>

<file path="src/extraction/parse-pool.ts">
import { Worker } from 'worker_threads';
import type { Language, ExtractionResult } from '../types';
⋮----
export interface ParsePoolWorker {
  postMessage(msg: unknown): void;
  terminate(): Promise<number> | void;
  on(event: 'message', cb: (m: unknown) => void): void;
  on(event: 'error', cb: (e: Error) => void): void;
  on(event: 'exit', cb: (code: number) => void): void;
}
⋮----
postMessage(msg: unknown): void;
terminate(): Promise<number> | void;
on(event: 'message', cb: (m: unknown)
on(event: 'error', cb: (e: Error)
on(event: 'exit', cb: (code: number)
⋮----
export interface ParseTask {
  filePath: string;
  content: string;
  language: Language;
  frameworkNames?: string[];
}
⋮----
export function resolveParseTimeoutMs(envVal: string | undefined): number
⋮----
/**
 * Per-file soft timeout. Size scaling helps legitimate large sources, but an
 * uncapped linear budget gave data-only headers near the 1 MiB file limit a
 * 4.5–5 minute hard-kill window (#1555). Explicit larger base overrides remain
 * respected for slow storage.
 */
export function resolveParseBudgetMs(baseMs: number, contentLength: number): number
⋮----
export function resolveParsePoolSize(envVal: string | undefined, cpuCount: number): number
⋮----
// non-numeric / negative → fall through to the default
⋮----
interface ParseJob {
  id: number;
  task: ParseTask;
  resolve: (r: ExtractionResult) => void;
  reject: (e: Error) => void;
  settled: boolean;
  timer?: ReturnType<typeof setTimeout>;
  /** Full budget for this parse (base timeout + size scaling), for late-result logging. */
  budgetMs?: number;
  /** The base timer fired with no result yet — accept a late result, kill at the backstop. */
  timerExpired?: boolean;
  hardKillTimer?: ReturnType<typeof setTimeout>;
}
⋮----
/** Full budget for this parse (base timeout + size scaling), for late-result logging. */
⋮----
/** The base timer fired with no result yet — accept a late result, kill at the backstop. */
⋮----
/** Shape of a message a worker posts back (grammar-load ack or a parse result). */
interface ParseWorkerMessage {
  type?: string;
  id?: number;
  result?: ExtractionResult;
  /** Worker-side parse duration — the worker's own clock, immune to main-thread stalls. */
  parseMs?: number;
}
⋮----
/** Worker-side parse duration — the worker's own clock, immune to main-thread stalls. */
⋮----
export interface ParseWorkerPoolOptions {
  languages: Language[];
  size: number;
  workerScriptPath?: string;
  recycleInterval?: number;
  parseTimeoutMs?: number;
  createWorker?: () => ParsePoolWorker;
  log?: (msg: string) => void;
  grammarBuffers?: Record<string, Uint8Array>;
}
⋮----
export class ParseWorkerPool
⋮----
constructor(opts: ParseWorkerPoolOptions)
⋮----
prewarm(): void
⋮----
get size(): number
⋮----
get liveWorkers(): number
⋮----
get healthy(): boolean
⋮----
requestParse(task: ParseTask): Promise<ExtractionResult>
⋮----
private spawnOne(): void
⋮----
private onMessage(w: ParsePoolWorker, m: ParseWorkerMessage): void
⋮----
// Recycle the worker once it's done enough parses to have grown its WASM
⋮----
private onWorkerGone(w: ParsePoolWorker, message: string): void
⋮----
... (18 lines truncated)
</file>

<file path="src/extraction/parse-worker.ts">
import { parentPort } from 'worker_threads';
import { extractFromSource } from './tree-sitter';
import { detectLanguage, loadGrammarsForLanguages, resetParser } from './grammars';
import { tryKernelExtractRaw } from './kernel';
import { getAllFrameworkResolvers, getApplicableFrameworks } from '../resolution/frameworks';
import type { Language, ExtractionResult } from '../types';
</file>

<file path="src/extraction/razor-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
import { TreeSitterExtractor } from './tree-sitter';
import { isLanguageSupported } from './grammars';
⋮----
export class RazorExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
extract(): ExtractionResult
⋮----
private createComponentNode(): Node
⋮----
private lastSegment(s: string): string
⋮----
private typeNames(expr: string): string[]
⋮----
private pushRef(componentId: string, name: string, line: number, column: number): void
⋮----
private extractDirectives(componentId: string): void
⋮----
private extractComponentTags(componentId: string): void
⋮----
/**
   * Find the matching `}` for the `{` at `openIdx`, skipping string literals and
   * comments so a brace inside `"{"` / `// }` doesn't throw off the count.
   * Returns the index of the closing brace, or -1 if unbalanced.
   */
private matchBrace(src: string, openIdx: number): number
⋮----
private extractCodeBlocks(): Array<
⋮----
private processCodeBlocks(componentId: string): void
</file>

<file path="src/extraction/store-worker.ts">
import { parentPort } from 'worker_threads';
import { QueryBuilder } from '../db/queries';
import { createDatabase, SqliteDatabase } from '../db/sqlite-adapter';
import { finalizeStoreBundle, type KernelStoreBundle, type StoreBundle } from './store-writer';
import { decodeExtractBuffers } from './kernel/decode';
⋮----
type InMessage =
  | { type: 'open'; dbPath: string; fastInit: boolean }
  | { type: 'bundle'; bundle: StoreBundle | KernelStoreBundle }
  | { type: 'drain'; id: number }
  | { type: 'close' };
⋮----
function decodeKernelBundle(bundle: KernelStoreBundle): StoreBundle
⋮----
const asBuf = (u: Uint8Array)
</file>

<file path="src/extraction/store-writer.ts">
import { Worker } from 'worker_threads';
import { ExtractionResult, Language, Node, Edge, UnresolvedReference, FileRecord } from '../types';
⋮----
export interface StoreBundle {
  nodes: Node[];
  edges: Edge[];
  refs: UnresolvedReference[];
  file: FileRecord;
}
⋮----
export interface KernelStoreBundle {
  kernel: true;
  filePath: string;
  language: Language;
  buffers: NonNullable<ExtractionResult['kernelBuffers']>;
  file: FileRecord;
}
⋮----
export function finalizeStoreBundle(
  result: Pick<ExtractionResult, 'nodes' | 'edges' | 'unresolvedReferences'>,
  filePath: string,
  language: Language,
  file: FileRecord
): StoreBundle
⋮----
export class StoreWriter
⋮----
constructor(workerScriptPath: string, dbPath: string, fastInit: boolean)
⋮----
private failAll(err: Error): void
⋮----
private settleOne(): void
⋮----
ready(): Promise<void>
⋮----
send(bundle: StoreBundle | KernelStoreBundle): void
⋮----
waitBelow(limit: number): Promise<void>
⋮----
drain(): Promise<void>
⋮----
async close(): Promise<void>
</file>

<file path="src/extraction/svelte-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference, Language } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
import { TreeSitterExtractor } from './tree-sitter';
import { isLanguageSupported } from './grammars';
⋮----
export class SvelteExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
extract(): ExtractionResult
⋮----
private createComponentNode(): Node
⋮----
private extractScriptBlocks(): Array<
⋮----
// Detect TypeScript from lang attribute
⋮----
// Detect module script
⋮----
private processScriptBlock(
    block: { content: string; startLine: number; isModule: boolean; isTypeScript: boolean },
    componentNodeId: string
): void
⋮----
private extractTemplateCalls(
    componentNodeId: string,
    _scriptBlocks: Array<{ content: string; startLine: number }>
): void
⋮----
private extractTemplateComponents(componentNodeId: string): void
</file>

<file path="src/extraction/syntax-tokens.ts">
import type { Node as SyntaxNode } from 'web-tree-sitter';
import { Language } from '../types';
import { EXTRACTORS } from './languages';
import { getParser, loadGrammarsForLanguages } from './grammars';
import type { LanguageExtractor } from './tree-sitter-types';
⋮----
export type SyntaxTokenClass = (typeof SYNTAX_TOKEN_CLASSES)[number];
⋮----
export interface SyntaxSpan {
  start: number;
  end: number;
  cls: SyntaxTokenClass;
}
⋮----
function isCommentType(type: string): boolean
⋮----
function isStringType(type: string): boolean
⋮----
function isInterpolationType(type: string): boolean
⋮----
function isNumberType(type: string): boolean
⋮----
function isTypeNameType(type: string): boolean
⋮----
function definitionTypesFor(extractor: LanguageExtractor): ReadonlySet<string>
⋮----
interface WalkContext {
  source: string;
  out: SyntaxSpan[];
  defTypes: ReadonlySet<string>;
  nameField: string;
  defStarts: Set<number>;
  offset: number;
}
⋮----
export function classifyTree(
  root: SyntaxNode,
  source: string,
  language: Language,
  offset = 0
): SyntaxSpan[]
⋮----
function visit(node: SyntaxNode, ctx: WalkContext, inString: boolean): void
⋮----
function leafClass(node: SyntaxNode, ctx: WalkContext, inString: boolean): SyntaxTokenClass
⋮----
function emit(ctx: WalkContext, start: number, end: number, cls: SyntaxTokenClass): void
⋮----
export interface SyntaxRegion {
  start: number;
  end: number;
  language: Language;
}
⋮----
/** Astro's frontmatter: a `---` fence at the very top of the file. */
⋮----
export function syntaxRegionsFor(source: string, language: Language): SyntaxRegion[] | null
⋮----
export interface TokenizeResult {
  spans: SyntaxSpan[];
  grammars: string[];
}
⋮----
export async function tokenizeSource(
  source: string,
  language: Language
): Promise<TokenizeResult | null>
⋮----
async function tokenizeRegion(
  source: string,
  language: Language,
  offset: number
): Promise<SyntaxSpan[] | null>
</file>

<file path="src/extraction/tree-sitter-helpers.ts">
import { Node as SyntaxNode } from 'web-tree-sitter';
⋮----
import { NodeKind } from '../types';
⋮----
export function generateNodeId(
  filePath: string,
  kind: NodeKind,
  name: string,
  line: number
): string
⋮----
export class NodeIdAllocator
⋮----
generate(filePath: string, kind: NodeKind, name: string, line: number, column: number): string
⋮----
export function getNodeText(node: SyntaxNode, source: string): string
⋮----
export function getChildByField(node: SyntaxNode, fieldName: string): SyntaxNode | null
⋮----
function cleanCommentMarkers(comment: string): string
⋮----
.replace(/^\/\/[/!]?\s?/gm, '') // // , and Rust/Swift doc lines /// //!
.replace(/^--\s?/gm, '') //        Lua/Luau line comments
.replace(/^#\s?/gm, '') //         Python/Ruby/shell line comments
.replace(/^%+\s?/gm, '') //        Erlang line comments (% / %% / %%%)
.replace(/^\s*\*\s?/gm, '') //     block-comment continuation (* foo)
⋮----
/**
 * Get the docstring/comment preceding a node
 */
export function getPrecedingDocstring(node: SyntaxNode, source: string): string | undefined
⋮----
// Climb out of any wrapper(s) so a comment preceding the WHOLE construct
// (export-, decorator-, or const-arrow-wrapped) is reachable as a sibling.
// The emitted node's own `previousNamedSibling` is empty (export/const) or a
</file>

<file path="src/extraction/tree-sitter-types.ts">
import { Node as SyntaxNode } from 'web-tree-sitter';
import {
  Node,
  NodeKind,
  UnresolvedReference,
} from '../types';
⋮----
export interface ImportInfo {
  moduleName: string;
  signature: string;
  handledRefs?: boolean;
}
⋮----
export interface VariableInfo {
  name: string;
  kind: NodeKind;
  signature?: string;
  delegateToFunction?: SyntaxNode;
  positionNode?: SyntaxNode;
}
⋮----
export interface ExtractorContext {
  createNode(kind: NodeKind, name: string, node: SyntaxNode, extra?: Partial<Node>): Node | null;
  visitNode(node: SyntaxNode): void;
  visitFunctionBody(body: SyntaxNode, functionId: string): void;
  addUnresolvedReference(ref: UnresolvedReference): void;
  pushScope(nodeId: string): void;
  popScope(): void;
  readonly filePath: string;
  readonly source: string;
  readonly nodeStack: readonly string[];
  readonly nodes: readonly Node[];
}
⋮----
createNode(kind: NodeKind, name: string, node: SyntaxNode, extra?: Partial<Node>): Node | null;
⋮----
visitNode(node: SyntaxNode): void;
⋮----
visitFunctionBody(body: SyntaxNode, functionId: string): void;
⋮----
addUnresolvedReference(ref: UnresolvedReference): void;
⋮----
pushScope(nodeId: string): void;
⋮----
popScope(): void;
⋮----
export interface LanguageExtractor {
  preParse?: (source: string, filePath?: string) => string;
  functionTypes: string[];
  classTypes: string[];
  methodTypes: string[];
  interfaceTypes: string[];
  structTypes: string[];
  unionTypes?: string[];
  enumTypes: string[];
  enumMemberTypes?: string[];
  typeAliasTypes: string[];
  importTypes: string[];
  callTypes: string[];
  variableTypes: string[];
  fieldTypes?: string[];
  propertyTypes?: string[];
  nameField: string;
  bodyField: string;
  paramsField: string;
  returnField?: string;
  resolveName?: (node: SyntaxNode, source: string) => string | undefined;
  recoverMangledName?: (name: string) => string;
  extractPropertyName?: (node: SyntaxNode, source: string) => string | null;
  getSignature?: (node: SyntaxNode, source: string) => string | undefined;
  getBodyDocstring?: (node: SyntaxNode, source: string) => string | undefined;
  getVisibility?: (node: SyntaxNode) => 'public' | 'private' | 'protected' | 'internal' | undefined;
  isExported?: (node: SyntaxNode, source: string) => boolean;
  isAsync?: (node: SyntaxNode) => boolean;
  isStatic?: (node: SyntaxNode) => boolean;
  isAbstract?: (node: SyntaxNode) => boolean | undefined;
  isConst?: (node: SyntaxNode) => boolean;
  extractModifiers?: (node: SyntaxNode) => string[] | undefined;
  extraClassNodeTypes?: string[];
  methodsAreTopLevel?: boolean;
  skipBodilessClass?: boolean;
  allowBodilessStruct?: boolean;
  interfaceKind?: NodeKind;
  visitNode?: (node: SyntaxNode, ctx: ExtractorContext) => boolean;
  synthesizeMembers?: (classNode: SyntaxNode, ctx: ExtractorContext) => void;
  classifyClassNode?: (node: SyntaxNode) => 'class' | 'struct' | 'enum' | 'interface' | 'trait' | 'module';
  classifyMethodNode?: (node: SyntaxNode) => 'method' | 'property' | 'skip';
  resolveBody?: (node: SyntaxNode, bodyField: string) => SyntaxNode | null;
  extractImport?: (node: SyntaxNode, source: string) => ImportInfo | null;
  extractVariables?: (node: SyntaxNode, source: string) => VariableInfo[];
  getReceiverType?: (node: SyntaxNode, source: string) => string | undefined;
  getReturnType?: (node: SyntaxNode, source: string) => string | undefined;
  resolveTypeAliasKind?: (node: SyntaxNode, source: string) => NodeKind | undefined;
  isMisparsedFunction?: (name: string, node: SyntaxNode) => boolean;
  extractBareCall?: (node: SyntaxNode, source: string) => string | undefined;
  packageTypes?: string[];
  extractPackage?: (node: SyntaxNode, source: string) => string | null;
}
</file>

<file path="src/extraction/tree-sitter.ts">
import { Node as SyntaxNode, Tree } from 'web-tree-sitter';
⋮----
import {
  Language,
  Node,
  Edge,
  NodeKind,
  ExtractionResult,
  ExtractionError,
  UnresolvedReference,
} from '../types';
import { getParser, detectLanguage, isLanguageSupported, isFileLevelOnlyLanguage } from './grammars';
import { NodeIdAllocator, getNodeText, getChildByField, getPrecedingDocstring } from './tree-sitter-helpers';
import { FN_REF_SPECS, captureFnRefCandidates, type FnRefSpec, type FnRefCandidate } from './function-ref';
import { isGeneratedFile } from './generated-detection';
import type { LanguageExtractor, ExtractorContext } from './tree-sitter-types';
import { EXTRACTORS } from './languages';
import { stripCppTemplateArgs, isCppConstructorDeclaration } from './languages/c-cpp';
import { rustImplTypeName } from './languages/rust';
import { LiquidExtractor } from './liquid-extractor';
import { RazorExtractor } from './razor-extractor';
import { SvelteExtractor } from './svelte-extractor';
import { AstroExtractor } from './astro-extractor';
import { DfmExtractor } from './dfm-extractor';
import { VueExtractor } from './vue-extractor';
import { MyBatisExtractor } from './mybatis-extractor';
import { CfmlExtractor } from './cfml-extractor';
import { tryKernelExtract, takeDeferredPreParse } from './kernel';
import {
  getAllFrameworkResolvers,
  getApplicableFrameworks,
} from '../resolution/frameworks';
⋮----
function extractName(node: SyntaxNode, source: string, extractor: LanguageExtractor): string
⋮----
function extractNameRaw(node: SyntaxNode, source: string, extractor: LanguageExtractor): string
⋮----
function scalaBaseTypeName(node: SyntaxNode | null, source: string): string | null
⋮----
function cDeclaratorIdentifier(node: SyntaxNode | null): SyntaxNode | null
⋮----
function firstSimpleIdentifier(node: SyntaxNode | null): SyntaxNode | null
⋮----
function swiftPropertyInfo(
  node: SyntaxNode,
  source: string,
):
⋮----
function hasFunctionAncestor(node: SyntaxNode): boolean
⋮----
function isUnresolvedTsJsChain(node: SyntaxNode, source: string): boolean
⋮----
function peelTsJsReceiver(node: SyntaxNode): SyntaxNode
⋮----
function keepsBareTsJsReceiver(node: SyntaxNode, source: string): boolean
⋮----
export class TreeSitterExtractor
⋮----
private docstringFor(node: SyntaxNode): string | undefined
⋮----
constructor(
    filePath: string,
    source: string,
    language?: Language,
    options?: { sourceIsPreParsed?: boolean }
)
⋮----
extract(): ExtractionResult
⋮----
/**
   * Function-as-value capture (#756): if this node is one of the language's
   * value-position containers (call arguments, assignment RHS, struct/object
   * initializer, array/table literal), collect candidate function names from
   * it. Candidates are gated & flushed at end-of-file (flushFnRefCandidates).
   */
private maybeCaptureFnRefs(node: SyntaxNode, nodeType: string): void
⋮----
private scanFnRefSubtree(node: SyntaxNode, depth: number): void
⋮----
private flushFnRefCandidates(): void
⋮----
private captureValueRefScope(kind: NodeKind, name: string, id: string, node: SyntaxNode): void
⋮----
private flushValueRefs(): void
⋮----
const bump = (nameNode: SyntaxNode | null) =>
⋮----
private visitNode(node: SyntaxNode): void
⋮----
// C# block namespaces scope only their own body: serilog's Guard.cs opens
⋮----
// A field initializer can also register callbacks
// (`static handlers = { click: onClick }`) — scan it for
// function-as-value candidates (capture-only, halts at functions).
⋮----
skipChildren = true; // extractMethod visits children via visitFunctionBody
⋮----
// Check for interface/protocol/trait declarations
⋮----
skipChildren = true; // extractInterface visits body children
... (543 lines truncated)
</file>

<file path="src/extraction/vue-extractor.ts">
import { Node, Edge, ExtractionResult, ExtractionError, UnresolvedReference, Language } from '../types';
import { generateNodeId } from './tree-sitter-helpers';
import { TreeSitterExtractor } from './tree-sitter';
import { isLanguageSupported } from './grammars';
import { vueOptionsMembers } from './vue-options-api';
⋮----
function kebabToPascal(name: string): string
⋮----
/**
 * VueExtractor - Extracts code relationships from Vue Single-File Component files
 *
 * Vue SFCs are multi-language (script + template + style). Rather than
 * parsing the full Vue grammar, we extract the <script> block content
 * and delegate it to the TypeScript/JavaScript TreeSitterExtractor.
 *
 * Every .vue file produces a component node (Vue components are always importable).
 */
export class VueExtractor
⋮----
constructor(filePath: string, source: string)
⋮----
/**
   * Extract from Vue source
   */
extract(): ExtractionResult
⋮----
// Create component node for the .vue file itself
⋮----
// Extract and process script blocks
⋮----
// Extract component usages from the <template> (<ComponentName>).
// Without this, a Vue component used only in another component's
⋮----
private createComponentNode(): Node
⋮----
private addOptionsMembers(
    block: { content: string; startLine: number },
    result: ExtractionResult,
    componentNodeId: string
): void
⋮----
const lineAt = (offset: number)
const colAt = (offset: number)
⋮----
const memberAt = (line: number): Node | undefined =>
⋮----
const isFileLevel = (id: string)
⋮----
private extractScriptBlocks(): Array<
⋮----
// Detect TypeScript from lang attribute
⋮----
// Detect <script setup>
⋮----
// Calculate the 0-indexed line where the content begins. The content
// starts right after the opening tag's `>` — its leading `\n` is part
⋮----
private processScriptBlock(
    block: { content: string; startLine: number; isSetup: boolean; isTypeScript: boolean },
    componentNodeId: string
): void
⋮----
private extractTemplateComponents(componentNodeId: string): void
</file>

<file path="src/extraction/vue-options-api.ts">
export interface OptionsMember {
  name: string;
  start: number;
  end: number;
}
⋮----
function skipQuoted(s: string, at: number): number
⋮----
/** The index of the bracket closing the one at `open`; -1 if unbalanced. */
function matchClose(s: string, open: number): number
⋮----
interface RawMember {
  name: string;
  start: number;
  valueAt: number;
  end: number;
  shorthand: boolean;
}
⋮----
function objectMembers(s: string, open: number): RawMember[]
⋮----
// A computed key — `[KEY]() {}` — has no static name; step over it.
⋮----
// Where this member ends: the next depth-0 comma, or the object's end.
⋮----
/** Whether a member's value is a function: a shorthand method, `function (…) {…}`, or an arrow. */
function isFunctionValue(s: string, m: RawMember): boolean
⋮----
/** The `{` of the options object the default export is, or -1. */
function optionsObjectStart(script: string): number
⋮----
/** Every function a Vue Options API component declares, in source order. */
export function vueOptionsMembers(script: string): OptionsMember[]
⋮----
// `computed: { x: { get() {}, set() {} } }` and `watch: { y: { handler() {} } }`
// are functions too; a watcher written as a method NAME (`z: 'onZ'`) is not.
</file>

<file path="src/extraction/wasm-runtime-flags.ts">
import { spawnSync } from 'child_process';
⋮----
export function nodeRuntimeFlagsFor(nodeVersion: string): readonly string[]
⋮----
export function processHasWasmRuntimeFlags(
  execArgv: readonly string[] = process.execArgv
): boolean
⋮----
export function buildRelaunchArgv(
  scriptPath: string,
  scriptArgs: readonly string[],
  execArgv: readonly string[] = process.execArgv
): string[]
⋮----
export function relaunchWithWasmRuntimeFlagsIfNeeded(scriptPath: string): void
</file>

<file path="src/graph/branch-guards.ts">
import type { Node as SyntaxNode, Tree } from 'web-tree-sitter';
import type { Language } from '../types';
import { getParser, loadGrammarsForLanguages } from '../extraction/grammars';
⋮----
export type GuardForm = 'if' | 'else' | 'ternary' | 'case' | 'guard' | 'and' | 'or' | 'catch';
⋮----
export type GuardExit = 'return' | 'throw' | 'exit';
⋮----
export interface BranchGuard {
  text: string;
  negated: boolean;
  form: GuardForm;
  line: number;
  branch: string;
  armExit?: GuardExit;
  exit?: GuardExit;
}
⋮----
export function supportsBranchGuards(language: Language | string | undefined | null): boolean
⋮----
export function guardLabel(guards: readonly BranchGuard[]): string
⋮----
function renderGuard(g: BranchGuard): string
⋮----
function flipComparison(text: string): string | null
⋮----
function hasTopLevelOr(text: string): boolean
⋮----
function isSimpleOperand(text: string): boolean
⋮----
// A name, a member chain, or one call on it — `Objects.equals(owner.getId(), id)`
// included: the parens must balance and nothing may sit outside them.
⋮----
// =============================================================================
// Trees, cached per file version
// =============================================================================
⋮----
interface CachedTree {
  key: string;
  tree: Tree;
  source: string;
}
⋮----
/**
 * Files above this size are not parsed for labels. A 300 KB source file costs
 * tens of milliseconds to parse, and a Symbol view is budgeted at 100 ms end
 * to end; a call site in such a file simply shows no `when`.
 */
⋮----
function remember(path: string, entry: CachedTree): void
⋮----
async function treeFor(absPath: string, language: Language): Promise<CachedTree | null>
⋮----
async function parse(source: string, language: Language): Promise<Tree | null>
⋮----
export interface CallSite {
  line: number;
  column?: number | null;
  callee?: string;
}
⋮----
export function siteKey(site: CallSite): string
⋮----
export async function guardsForFile(
  absPath: string,
  language: Language,
  sites: readonly CallSite[]
): Promise<Map<string, BranchGuard[]>>
⋮----
export function guardsForFileSync(
  absPath: string,
  language: Language,
  sites: readonly CallSite[]
): Map<string, BranchGuard[]>
⋮----
export async function callArgumentsForFile(
  absPath: string,
  language: Language,
  sites: readonly CallSite[]
): Promise<Map<string, string>>
⋮----
export async function callArgumentsInSource(
  source: string,
  language: Language,
  line: number,
  column: number | null
): Promise<string | null>
⋮----
export function callArgumentsInTree(
  root: SyntaxNode,
  source: string,
  line: number,
  column: number | null
): string | null
⋮----
export interface CallSiteText {
  callee: string;
  args: string;
  argList: string[];
  status?: number;
... (357 lines truncated)
</file>

<file path="src/graph/dead-code.ts">
import fs from 'fs';
import path from 'path';
import type CodeGraph from '../index';
import type { Node, NodeKind } from '../types';
import { isTestFile } from '../search/query-utils';
⋮----
export interface DeadCodeEntry {
  node: Node;
  members: Node[];
  lines: number;
  exported: boolean;
}
⋮----
export interface DeadCodeExclusions {
  tests: number;
  generated: number;
  exported: number;
  exportsUnknown: number;
  declarations: number;
  decorated: number;
  overriding: number;
  implicit: number;
  vendored: number;
  testScope: number;
  markup: number;
  unreachableFile: number;
  unresolvedName: number;
  ambiguousName: number;
  mentioned: number;
  unreadable: number;
  nested: number;
}
⋮----
export interface DeadCodeReport {
  entries: DeadCodeEntry[];
  total: number;
  candidates: number;
  excluded: DeadCodeExclusions;
  kinds: NodeKind[];
  includeExported: boolean;
  bounded: boolean;
  corroborated: boolean;
}
⋮----
export interface DeadCodeQuery {
  kinds?: readonly NodeKind[];
  includeExported?: boolean;
  includeTests?: boolean;
  includeGenerated?: boolean;
  limit?: number;
  readSource?: ((filePath: string) => string | null) | null;
}
⋮----
export function buildDeadCodeReport(cg: CodeGraph, query: DeadCodeQuery =
⋮----
const read = (file: string): string | null =>
⋮----
function defaultSourceReader(cg: CodeGraph): (filePath: string) => string | null
⋮----
export function mentionCount(source: string, name: string, stopAt = Number.MAX_SAFE_INTEGER): number
⋮----
function isIdentifierChar(char: string | undefined): boolean
⋮----
function filesNothingReaches(cg: CodeGraph, filePaths: readonly string[]): Set<string>
⋮----
export function isHeaderFile(filePath: string): boolean
⋮----
export function isTestScope(qualifiedName: string): boolean
⋮----
export function isVendoredPath(filePath: string): boolean
⋮----
export function isImplicitEntryName(name: string): boolean
⋮----
function normalizeKinds(requested: readonly NodeKind[] | undefined): NodeKind[]
⋮----
function containersOf(cg: CodeGraph, nodes: readonly Node[]): Map<string, Node>
⋮----
function overrideCandidates(
  cg: CodeGraph,
  nodes: readonly Node[],
  containers: ReadonlyMap<string, Node>
): Set<string>
</file>

<file path="src/graph/dynamic-boundary-report.ts">
import type CodeGraph from '../index';
import type { Edge, Node } from '../types';
import { scanDynamicDispatch, type BoundaryMatch } from '../mcp/dynamic-boundaries';
import { validatePathWithinRoot } from '../utils';
import { existsSync, readFileSync } from 'fs';
⋮----
export interface BoundaryCandidate {
  node: Node;
  display: string;
  named: boolean;
}
⋮----
export interface BoundarySite extends BoundaryMatch {
  candidates: BoundaryCandidate[];
  candidateNote: string | null;
}
⋮----
export interface NodeBoundary {
  node: Node;
  sites: BoundarySite[];
}
⋮----
export interface BoundaryContinuation {
  node: Node;
  line: number | null;
  confidence: number | null;
}
⋮----
export interface BoundaryContinuations {
  resolved: BoundaryContinuation[];
  uncertain: BoundaryContinuation[];
}
⋮----
export interface BoundaryScanOptions {
  maxSites?: number;
  named?: ReadonlyMap<string, Node>;
}
⋮----
export function findDynamicBoundaries(
  cg: CodeGraph,
  scanList: readonly Node[],
  opts: BoundaryScanOptions = {}
): NodeBoundary[]
⋮----
// =============================================================================
// Candidates
// =============================================================================
⋮----
const normalizeName = (s: string): string
⋮----
/**
 * Shortlist the runtime targets a dispatch key could reach.
 *
 * Exact conventional names first (`save` → `onSave` / `handleSave`;
 * `CreateCmd` → `CreateCmdHandler`), then FTS, with a normalized-containment
 * post-filter — FTS camel-splitting is fuzzier than a candidate list should be,
 * and a shortlist that is mostly wrong is worse than none. Symbols the caller
 * already named sort first and are marked.
 *
 * A key too short or too common to narrow down returns no candidates and a
 * `note` saying so, rather than four arbitrary rows.
 */
export function shortlistBoundaryCandidates(
  cg: CodeGraph,
  key: string,
  keyIsType: boolean,
  named: ReadonlyMap<string, Node>,
  selfId: string
):
⋮----
const consider = (n: Node | undefined | null): void =>
⋮----
/* an exact probe that misses is the normal case */
⋮----
/* FTS syntax edge — the exact probes already ran */
⋮----
// A constructor candidate duplicates its class: extractors emit constructors
// as METHOD nodes named like the class (C#/Java `Foo::Foo`) — keep the class.
⋮----
const isNamed = (n: Node): boolean
⋮----
function handlerMethodOf(cg: CodeGraph, cls: Node): Node | null
⋮----
export function continuationsFrom(
  cg: CodeGraph,
  node: Node,
  exclude: ReadonlySet<string> = new Set()
): BoundaryContinuations
⋮----
const byLine = (a: BoundaryContinuation, b: BoundaryContinuation): number
</file>

<file path="src/graph/index.ts">

</file>

<file path="src/graph/named-symbol-flow.ts">
import type CodeGraph from '../index';
import type { Node, Edge } from '../types';
import { isTestFile } from '../search/query-utils';
⋮----
import { lastQualifierPart, matchesSymbol } from './symbol-lookup';
⋮----
export function findAllSymbols(cg: CodeGraph, symbol: string):
⋮----
// Direct index — every exact-name overload, case-sensitive. Avoids FTS
// ranking a differently-cased sibling above the real node (#1473 Fetch).
⋮----
// Mirror findSymbolMatches — FTS strips colons, so re-search by bare tail.
⋮----
// Same generated-file down-rank as findSymbol — keeps callers/callees
// /impact aggregation aligned (a query against "Send" returns the
// hand-written implementations before the protobuf scaffold).
⋮----
/** Node kinds that can sit on a call chain. */
⋮----
export interface FlowStep {
  node: Node;
  edge: Edge | null;
}
⋮----
export interface FlowChain {
  steps: FlowStep[];
  callSites: Map<string, number>;
}
⋮----
export interface NamedSymbolFlowOptions {
  mode?: 'named' | 'directed';
  from?: string;
  to?: string;
  maxHops?: number;
  maxBridge?: number;
  maxChains?: number;
}
⋮----
export interface NamedSymbolFlow {
  tokens: string[];
  named: Map<string, Node>;
  dynNamed: Map<string, Node>;
  tokenNodes: Map<string, string[]>;
  tokenFamily: Map<string, Node[]>;
  uniqueNamedNodeIds: Set<string>;
  preciseNamedIds: Set<string>;
  chains: FlowChain[];
}
⋮----
const EMPTY_FLOW = (): NamedSymbolFlow => (
⋮----
function rankForDirected(nodes: readonly Node[]): Node[]
⋮----
function isPreciseToken(token: string): boolean
⋮----
export function flowTokens(query: string): string[]
⋮----
/**
 * Resolve a query's tokens to nodes, with the overload rules described in the
 * module header. No graph traversal happens here.
 */
export function resolveNamedTokens(
  cg: CodeGraph,
  query: string,
  opts: NamedSymbolFlowOptions = {}
): NamedSymbolFlow
⋮----
const hasHeuristicEdge = (id: string): boolean
⋮----
// Same token, non-callable synthesized endpoints. Capped per token so one
// token's many endpoints cannot fill the pool before later tokens get a slot,
⋮----
function callSitesOf(steps: readonly FlowStep[]): Map<string, number>
⋮----
function walkCalls(
  cg: CodeGraph,
  seed: Node,
  named: ReadonlySet<string>,
  maxHops: number,
  maxBridge: number
):
⋮----
function walkBidirectional(
  cg: CodeGraph,
  seed: Node,
  sinks: ReadonlySet<string>,
  maxHops: number
): FlowStep[] | null
⋮----
const meetAt = (): string | null =>
⋮----
function chainTo(
  parent: Map<string, { prev: string | null; edge: Edge | null; node: Node }>,
  target: string
): FlowStep[]
⋮----
export function resolveNamedSymbolFlow(
  cg: CodeGraph,
  query: string,
  opts: NamedSymbolFlowOptions = {}
... (10 lines truncated)
</file>

<file path="src/graph/queries.ts">
import { Node, Edge, Context, Subgraph, EdgeKind } from '../types';
import { QueryBuilder } from '../db/queries';
import { GraphTraverser } from './traversal';
⋮----
export class GraphQueryManager
⋮----
constructor(queries: QueryBuilder)
⋮----
getContext(nodeId: string): Context
⋮----
getFileDependencies(filePath: string): string[]
⋮----
getFileDependents(filePath: string): string[]
⋮----
getExportedSymbols(filePath: string): Node[]
⋮----
findByQualifiedName(pattern: string): Node[]
⋮----
getModuleStructure(): Map<string, string[]>
⋮----
findCircularDependencies(): string[][]
⋮----
const dfs = (filePath: string, path: string[]): void =>
⋮----
getNodeMetrics(nodeId: string):
⋮----
findDeadCode(kinds?: Node['kind'][]): Node[]
⋮----
getFilteredSubgraph(
    filter: (node: Node) => boolean,
    includeEdges: boolean = true
): Subgraph
⋮----
getTraverser(): GraphTraverser
</file>

<file path="src/graph/symbol-lookup.ts">
import type { Node } from '../types';
⋮----
export function isQualifiedSymbol(symbol: string): boolean
⋮----
export function lastQualifierPart(symbol: string): string
⋮----
/**
 * Rewrite every scope separator to `.` so a query and a stored qualifiedName
 * written in different conventions can be compared directly. The extractors
 * join hierarchy with `::` while users type the language's own spelling
 * (`Session.request`, `stage_apply::run`, `pkg/mod.Fn`).
 */
function canonicalScope(text: string): string
⋮----
export function matchesSymbol(node: Node, symbol: string): boolean
⋮----
// File basename match ("product-card" matches "product-card.liquid").
⋮----
// Stage 1: qualified-name containment under the extractor's `::` convention.
⋮----
/** The slice of CodeGraph a symbol lookup needs — keeps this module testable. */
export interface SymbolLookupHost {
  getNodesByName(name: string): Node[];
  searchNodes(query: string, options?: { limit?: number }): Array<{ node: Node }>;
  generatedFilePredicate(paths: string[]): (path: string) => boolean;
}
⋮----
getNodesByName(name: string): Node[];
searchNodes(query: string, options?:
generatedFilePredicate(paths: string[]): (path: string)
⋮----
export interface SymbolLookupResult {
  /** Every definition the query names, keepers before generated stubs. */
  nodes: Node[];
  /**
   * The query named more than one distinct definition. Callers that aggregate
   * across all of them MUST surface this — an aggregate presented as one
   * symbol's answer is the over-reporting failure described at the top.
   */
  ambiguous: boolean;
}
⋮----
/** Every definition the query names, keepers before generated stubs. */
⋮----
/**
   * The query named more than one distinct definition. Callers that aggregate
   * across all of them MUST surface this — an aggregate presented as one
   * symbol's answer is the over-reporting failure described at the top.
   */
⋮----
export function groupDefinitions(
  nodes: Node[],
  fileFilter?: string
):
⋮----
export function lookupSymbolNodes(cg: SymbolLookupHost, symbol: string): SymbolLookupResult
⋮----
export function describeSymbolNode(node: Node): string
</file>

<file path="src/graph/traversal.ts">
import { Node, Edge, Subgraph, TraversalOptions, EdgeKind } from '../types';
import { QueryBuilder } from '../db/queries';
⋮----
interface TraversalStep {
  node: Node;
  edge: Edge | null;
  depth: number;
}
⋮----
export class GraphTraverser
⋮----
constructor(queries: QueryBuilder)
⋮----
traverseBFS(startId: string, options: TraversalOptions =
⋮----
const edgeKey = (e: Edge)
⋮----
const priority = (e: Edge)
⋮----
traverseDFS(startId: string, options: TraversalOptions =
⋮----
private dfsRecursive(
    node: Node,
    depth: number,
    opts: Required<TraversalOptions>,
    nodes: Map<string, Node>,
    edges: Edge[],
    visited: Set<string>
): void
⋮----
private getAdjacentEdges(
    nodeId: string,
    direction: 'outgoing' | 'incoming' | 'both',
    edgeKinds?: EdgeKind[]
): Edge[]
⋮----
private enterAtDepth(visited: Map<string, number>, nodeId: string, depth: number): boolean
⋮----
private nearerThanBefore(visited: Map<string, number>, nodeId: string, depth: number): boolean
⋮----
getCallers(nodeId: string, maxDepth: number = 1): Array<
⋮----
private getCallersRecursive(
    nodeId: string,
    maxDepth: number,
    currentDepth: number,
    result: Array<{ node: Node; edge: Edge }>,
    visited: Map<string, number>,
    reported: Set<string>
): void
⋮----
getCallees(nodeId: string, maxDepth: number = 1): Array<
⋮----
private getCalleesRecursive(
    nodeId: string,
    maxDepth: number,
    currentDepth: number,
    result: Array<{ node: Node; edge: Edge }>,
    visited: Map<string, number>,
    reported: Set<string>
): void
⋮----
getCallGraph(nodeId: string, depth: number = 2): Subgraph
⋮----
getTypeHierarchy(nodeId: string): Subgraph
⋮----
private getTypeAncestors(
    nodeId: string,
    nodes: Map<string, Node>,
    edges: Edge[],
    visited: Set<string>
): void
⋮----
private getTypeDescendants(
    nodeId: string,
    nodes: Map<string, Node>,
    edges: Edge[],
    visited: Set<string>
): void
⋮----
findUsages(nodeId: string): Array<
⋮----
getImpactRadius(nodeId: string, maxDepth: number = 3): Subgraph
⋮----
private getImpactRecursive(
    nodeId: string,
    maxDepth: number,
    currentDepth: number,
    nodes: Map<string, Node>,
    edges: Edge[],
    visited: Map<string, number>,
    expanded: Set<string>
): void
⋮----
findPath(
    fromId: string,
    toId: string,
    edgeKinds: EdgeKind[] = []
): Array<
⋮----
... (4 lines truncated)
</file>

<file path="src/graph/type-hierarchy.ts">
import type CodeGraph from '../index';
import type { Edge, EdgeKind, Node, NodeKind } from '../types';
⋮----
export type HierarchyRelation = 'extends' | 'implements';
⋮----
export interface HierarchyEntry {
  node: Node;
  depth: number;
  parentId: string;
  relation: HierarchyRelation;
  edge: Edge;
  synthesized: boolean;
  hiddenSubtypes: number;
}
⋮----
export interface OverrideMatch {
  memberId: string;
  baseId: string;
  baseTypeId: string;
  baseTypeName: string;
  relation: HierarchyRelation;
}
⋮----
export interface TypeHierarchy {
  focus: Node;
  ancestors: HierarchyEntry[];
  descendants: HierarchyEntry[];
  directSubtypes: number;
  directImplementers: number;
  bounded: boolean;
  polymorphic: boolean;
  overrides: Map<string, OverrideMatch>;
}
⋮----
export function canHaveHierarchy(node: Node): boolean
⋮----
export function buildTypeHierarchy(
  cg: CodeGraph,
  focus: Node,
  options: { overrides?: boolean } = {}
): TypeHierarchy | null
⋮----
function walkAncestors(cg: CodeGraph, focus: Node): HierarchyEntry[]
⋮----
function walkDescendants(cg: CodeGraph, focus: Node):
⋮----
function hierarchyEdges(cg: CodeGraph, ids: readonly string[], direction: 'up' | 'down'): Edge[]
⋮----
function toEntry(node: Node, depth: number, parentId: string, edge: Edge): HierarchyEntry
⋮----
function sortLevel(level: HierarchyEntry[]): void
⋮----
function matchOverrides(
  cg: CodeGraph,
  focus: Node,
  ancestors: readonly HierarchyEntry[]
): Map<string, OverrideMatch>
⋮----
function membersOf(
  cg: CodeGraph,
  containerIds: readonly string[]
): Array<
⋮----
export function countImplementers(cg: CodeGraph, typeId: string): number
</file>

<file path="src/installer/targets/antigravity.ts">
import { execSync } from 'child_process';
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  jsonDeepEqual,
  readJsonFile,
  writeJsonFile,
} from './shared';
⋮----
function unifiedConfigDir(): string
function unifiedMcpConfigPath(): string
function legacyConfigDir(): string
function legacyMcpConfigPath(): string
function migratedMarkerPath(): string
⋮----
function preferredMcpConfigPath(): string
⋮----
function resolveCodegraphCommand(): string
⋮----
function buildAntigravityEntry():
⋮----
class AntigravityTarget implements AgentTarget
⋮----
supportsLocation(loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(): WriteResult['files'][number]
⋮----
function cleanupLegacyEntry(): WriteResult['files'][number] | null
⋮----
function removeCodegraphFromFile(file: string): WriteResult['files'][number]
</file>

<file path="src/installer/targets/claude.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  getCodeGraphPermissions,
  getMcpServerConfig,
  jsonDeepEqual,
  readJsonFile,
  removeMarkedSection,
  writeJsonFile,
  upsertInstructionsEntry,
} from './shared';
import {
  CODEGRAPH_SECTION_END,
  CODEGRAPH_SECTION_START,
} from '../instructions-template';
⋮----
function getClaudeMcpServerConfig()
⋮----
function globalConfigDir(): string
function configDir(loc: Location): string
function mcpJsonPath(loc: Location): string
⋮----
function legacyLocalMcpPath(): string
function settingsJsonPath(loc: Location): string
function instructionsPath(loc: Location): string
⋮----
class ClaudeCodeTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
export function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function cleanupLegacyLocalMcp(): WriteResult['files'][number] | null
⋮----
function isLegacyCodegraphHookCommand(command: unknown): boolean
⋮----
function isPromptHookCommand(command: unknown): boolean
⋮----
function removeHookCommandsMatching(
  loc: Location,
  match: (command: unknown) => boolean,
): WriteResult['files'][number]
⋮----
export function cleanupLegacyHooks(loc: Location): WriteResult['files'][number]
⋮----
export function removePromptHookEntry(loc: Location): WriteResult['files'][number]
⋮----
export function writePermissionsEntry(loc: Location): WriteResult['files'][number]
⋮----
export function writePromptHookEntry(loc: Location): WriteResult['files'][number]
⋮----
export function removeInstructionsEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/codex.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  atomicWriteFileSync,
  getMcpServerConfig,
  removeMarkedSection,
  upsertInstructionsEntry,
} from './shared';
import {
  CODEGRAPH_SECTION_END,
  CODEGRAPH_SECTION_START,
} from '../instructions-template';
import { buildTomlTable, removeTomlTable, upsertTomlTable } from './toml';
⋮----
function configDir(loc: Location): string
function tomlConfigPath(loc: Location): string
function instructionsPath(loc: Location): string
⋮----
function trustNote(): string
⋮----
class CodexTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
try { fs.unlinkSync(tomlPath); } catch { /* ignore */ }
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function buildCodegraphBlock(): string
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeInstructionsEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/copilot-cli.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  getMcpServerConfig,
  jsonDeepEqual,
  readJsonFile,
  writeJsonFile,
} from './shared';
⋮----
function configDir(): string
⋮----
function mcpConfigPath(): string
⋮----
function cliConfigDirPresent(): boolean
⋮----
function copilotOnPath(): boolean
⋮----
function buildCopilotMcpConfig():
⋮----
class CopilotCliTarget implements AgentTarget
⋮----
supportsLocation(loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(): WriteResult['files'][number]
</file>

<file path="src/installer/targets/copilot-jetbrains.ts">
import { parse as parseJsonc, modify, applyEdits } from 'jsonc-parser';
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  atomicWriteFileSync,
  getMcpServerConfig,
  jsonDeepEqual,
} from './shared';
⋮----
function copilotConfigRoot(): string
⋮----
function intellijDir(): string
⋮----
function mcpJsonPath(): string
⋮----
function jetbrainsConfigDirExists(): boolean
⋮----
function readConfigText(file: string): string
⋮----
function parseConfig(text: string): Record<string, any>
⋮----
class CopilotJetbrainsTarget implements AgentTarget
⋮----
supportsLocation(loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(): WriteResult['files'][number]
⋮----
function removeMcpEntry(): WriteResult['files'][number]
</file>

<file path="src/installer/targets/copilot-vscode.ts">
import { parse as parseJsonc, modify, applyEdits } from 'jsonc-parser';
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  atomicWriteFileSync,
  getMcpServerConfig,
  jsonDeepEqual,
} from './shared';
⋮----
function vscodeUserDir(): string
⋮----
function mcpJsonPath(loc: Location): string
⋮----
function buildVscodeServerEntry(loc: Location):
⋮----
function readConfigText(file: string): string
⋮----
function parseConfig(text: string): Record<string, any>
⋮----
class CopilotVscodeTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeMcpEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/cursor.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  atomicWriteFileSync,
  getMcpServerConfig,
  jsonDeepEqual,
  readJsonFile,
  writeJsonFile,
} from './shared';
import {
  CODEGRAPH_SECTION_END,
  CODEGRAPH_SECTION_START,
} from '../instructions-template';
⋮----
function mcpJsonPath(loc: Location): string
⋮----
function rulesPath(): string
⋮----
class CursorTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function buildCursorMcpConfig(loc: Location):
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeRulesEntry(): WriteResult['files'][number]
⋮----
try { fs.unlinkSync(file); } catch { /* ignore */ }
</file>

<file path="src/installer/targets/gemini.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  getMcpServerConfig,
  jsonDeepEqual,
  readJsonFile,
  removeMarkedSection,
  writeJsonFile,
  upsertInstructionsEntry,
} from './shared';
import {
  CODEGRAPH_SECTION_END,
  CODEGRAPH_SECTION_START,
} from '../instructions-template';
⋮----
function configDir(loc: Location): string
function settingsJsonPath(loc: Location): string
function instructionsPath(loc: Location): string
⋮----
class GeminiTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeInstructionsEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/hermes.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import { atomicWriteFileSync } from './shared';
⋮----
type LineRange = { start: number; end: number };
⋮----
class HermesTarget implements AgentTarget
⋮----
supportsLocation(loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function hermesHome(): string
⋮----
function configPath(): string
⋮----
function readText(file: string): string
⋮----
function writeHermesConfig(): WriteResult['files'][number]
⋮----
function ensureTrailingNewline(text: string): string
⋮----
function splitLines(content: string): string[]
⋮----
function joinLines(lines: string[]): string
⋮----
function topLevelRange(lines: string[], key: string): LineRange | null
⋮----
function childRange(lines: string[], parent: LineRange, child: string): LineRange | null
⋮----
/**
 * Block-range for a 2-space-indented child whose value is a YAML block list.
 *
 * Unlike `childRange`, this handles PyYAML's default `default_flow_style=False`
 * serialization, where list items sit at the SAME indent as the parent key:
 *
 *     cli:
 *     - hermes-cli       # indent 2 — belongs to cli, not a sibling
 *     - browser
 *
 * `childRange`'s `^  \S` heuristic mistakes that first `  - hermes-cli` line
 * for the next sibling key and truncates the block, causing inserts to land
 * before the existing items at a different indent (issue #456). This helper
 * recognizes a `  - ` line as part of the block instead, and reports back
 * the actual indent used by existing items so the inserter matches it.
 */
function listChildBlock(
  lines: string[],
  parent: LineRange,
  child: string,
): (LineRange &
⋮----
function escapeRegExp(value: string): string
⋮----
function renderCodeGraphMcpChild(): string[]
⋮----
function renderCodeGraphMcpBlock(): string[]
⋮----
function hasCodeGraphMcpServer(content: string): boolean
⋮----
function upsertCodeGraphMcpServer(content: string): string
⋮----
function removeCodeGraphMcpServer(content: string): string
⋮----
function upsertCodeGraphToolset(content: string): string
⋮----
function removeCodeGraphToolset(content: string): string
⋮----
function arrayEqual(a: string[], b: string[]): boolean
</file>

<file path="src/installer/targets/kiro.ts">
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  getMcpServerConfig,
  jsonDeepEqual,
  readJsonFile,
  writeJsonFile,
} from './shared';
⋮----
function configDir(loc: Location): string
function mcpJsonPath(loc: Location): string
function steeringPath(loc: Location): string
⋮----
class KiroTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeSteeringEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/opencode.ts">
import { parse as parseJsonc, modify, applyEdits } from 'jsonc-parser';
import {
  AgentTarget,
  DetectionResult,
  InstallOptions,
  Location,
  WriteResult,
} from './types';
import {
  atomicWriteFileSync,
  jsonDeepEqual,
  removeMarkedSection,
  upsertInstructionsEntry,
} from './shared';
import {
  CODEGRAPH_SECTION_END,
  CODEGRAPH_SECTION_START,
} from '../instructions-template';
⋮----
function globalConfigDir(): string
⋮----
function legacyWindowsConfigDir(): string | null
⋮----
function configBaseDir(loc: Location): string
⋮----
function configPath(loc: Location): string
⋮----
function instructionsPath(loc: Location): string
⋮----
function readConfigText(file: string): string
⋮----
function parseConfig(text: string): Record<string, any>
⋮----
function getOpencodeServerEntry():
⋮----
function hasCodegraphEntry(config: Record<string, any>): boolean
⋮----
class OpencodeTarget implements AgentTarget
⋮----
supportsLocation(_loc: Location): boolean
⋮----
detect(loc: Location): DetectionResult
⋮----
install(loc: Location, _opts: InstallOptions): WriteResult
⋮----
uninstall(loc: Location): WriteResult
⋮----
printConfig(loc: Location): string
⋮----
describePaths(loc: Location): string[]
⋮----
function writeMcpEntry(loc: Location): WriteResult['files'][number]
⋮----
function removeMcpEntryAt(file: string): WriteResult['files'][number]
⋮----
function cleanupLegacyWindowsState(): WriteResult['files']
⋮----
function removeInstructionsEntry(loc: Location): WriteResult['files'][number]
</file>

<file path="src/installer/targets/registry.ts">
import { AgentTarget, Location, TargetId } from './types';
import { claudeTarget } from './claude';
import { cursorTarget } from './cursor';
import { codexTarget } from './codex';
import { opencodeTarget } from './opencode';
import { hermesTarget } from './hermes';
import { geminiTarget } from './gemini';
import { antigravityTarget } from './antigravity';
import { kiroTarget } from './kiro';
import { copilotVscodeTarget } from './copilot-vscode';
import { copilotCliTarget } from './copilot-cli';
import { copilotJetbrainsTarget } from './copilot-jetbrains';
⋮----
export function getTarget(id: string): AgentTarget | undefined
⋮----
export function listTargetIds(): TargetId[]
⋮----
export function detectAll(loc: Location): Array<
⋮----
export function resolveTargetFlag(value: string, loc: Location): AgentTarget[]
</file>

<file path="src/installer/targets/shared.ts">
import {
  CODEGRAPH_INSTRUCTIONS_BLOCK,
  CODEGRAPH_SECTION_START,
  CODEGRAPH_SECTION_END,
} from '../instructions-template';
⋮----
export function getMcpServerConfig():
⋮----
export function getCodeGraphPermissions(): string[]
⋮----
export function readJsonFile(filePath: string): Record<string, any>
⋮----
export function atomicWriteFileSync(filePath: string, content: string): void
⋮----
function backupUnparseableJson(filePath: string): void
⋮----
export function writeJsonFile(filePath: string, data: Record<string, any>): void
⋮----
export function jsonDeepEqual(a: unknown, b: unknown): boolean
⋮----
export function replaceOrAppendMarkedSection(
  filePath: string,
  body: string,
  startMarker: string,
  endMarker: string,
): 'created' | 'updated' | 'appended' | 'unchanged'
⋮----
export function upsertInstructionsEntry(file: string):
⋮----
export function removeMarkedSection(
  filePath: string,
  startMarker: string,
  endMarker: string,
): 'removed' | 'not-found' | 'kept'
⋮----
try { fs.unlinkSync(filePath); } catch { /* ignore */ }
</file>

<file path="src/installer/targets/toml.ts">
export function serializeTomlTableBody(values: Record<string, string | string[]>): string
⋮----
function quoteString(s: string): string
⋮----
/**
 * Build a full table block: header line + body. Suitable for direct
 * insertion into a TOML file.
 */
export function buildTomlTable(header: string, values: Record<string, string | string[]>): string
⋮----
/**
 * Insert or replace a top-level dotted-key TOML table block in the
 * given file content. Preserves all other content verbatim.
 *
 * Returns `'inserted'` when the table was newly added, `'replaced'`
 * when an existing one was rewritten, `'unchanged'` when the
 * existing block already matches `block` byte-for-byte.
 */
export function upsertTomlTable(
  fileContent: string,
  header: string,
  block: string,
):
⋮----
export function removeTomlTable(
  fileContent: string,
  header: string,
):
⋮----
function findHeaderIndex(content: string, headerLine: string): number
⋮----
function findNextTableHeader(content: string, from: number): number
⋮----
type MultilineStringDelimiter = '"""' | "'''";
⋮----
interface TomlLexState {
  multilineString: MultilineStringDelimiter | null;
  arrayDepth: number;
  inlineTableDepth: number;
}
⋮----
function isTomlTableHeader(line: string): boolean
⋮----
/** Track value constructs that may legally span lines so bracket-shaped string
 * content and nested arrays cannot be mistaken for sibling table headers. */
function scanTomlLine(line: string, state: TomlLexState): void
⋮----
function findMultilineStringEnd(
  line: string,
  from: number,
  delimiter: MultilineStringDelimiter,
): number
⋮----
function isBackslashEscaped(line: string, index: number): boolean
⋮----
function skipSingleLineString(line: string, start: number, quote: '"' | "'"): number
</file>

<file path="src/installer/targets/types.ts">
export type Location = 'global' | 'local';
⋮----
export type TargetId = 'claude' | 'cursor' | 'codex' | 'opencode' | 'hermes' | 'gemini' | 'antigravity' | 'kiro' | 'copilot-vscode' | 'copilot-cli' | 'copilot-jetbrains';
⋮----
export interface DetectionResult {
  installed: boolean;
  alreadyConfigured: boolean;
  configPath?: string;
}
⋮----
export interface WriteResult {
  files: Array<{
    path: string;
    action: 'created' | 'updated' | 'unchanged' | 'removed' | 'not-found' | 'kept';
  }>;
  notes?: string[];
}
⋮----
export interface InstallOptions {
  autoAllow: boolean;
  promptHook?: boolean;
}
⋮----
export interface AgentTarget {
  readonly id: TargetId;
  readonly displayName: string;
  readonly docsUrl?: string;
  supportsLocation(loc: Location): boolean;
  detect(loc: Location): DetectionResult;
  install(loc: Location, opts: InstallOptions): WriteResult;
  uninstall(loc: Location): WriteResult;
  printConfig(loc: Location): string;
  describePaths(loc: Location): string[];
}
⋮----
supportsLocation(loc: Location): boolean;
⋮----
detect(loc: Location): DetectionResult;
install(loc: Location, opts: InstallOptions): WriteResult;
⋮----
uninstall(loc: Location): WriteResult;
⋮----
printConfig(loc: Location): string;
⋮----
describePaths(loc: Location): string[];
</file>

<file path="src/installer/beta-signup.ts">
interface BetaSignupChoiceFile {
  status: 'subscribed' | 'declined';
  updated_at: string;
}
⋮----
export interface BetaSignupDeps {
  dir?: string;
  fetchImpl?: typeof fetch;
  now?: () => Date;
  source?: 'cli-install' | 'cli-upgrade';
  stdinIsTTY?: boolean;
  stdoutIsTTY?: boolean;
}
⋮----
function choicePath(deps: BetaSignupDeps =
⋮----
export function hasBetaSignupChoice(deps: BetaSignupDeps =
⋮----
export function recordBetaSignupChoice(
  subscribed: boolean,
  deps: BetaSignupDeps = {},
): void
⋮----
export async function submitBetaSignup(
  email: string,
  deps: BetaSignupDeps = {},
): Promise<boolean>
⋮----
export function shouldOfferBetaSignup(deps: BetaSignupDeps =
⋮----
export async function maybeOfferBetaSignup(deps: BetaSignupDeps =
</file>

<file path="src/installer/clack.d.ts">
export function intro(title?: string): void;
export function outro(message?: string): void;
export function cancel(message?: string): void;
export function isCancel(value: unknown): value is symbol;
⋮----
export function confirm(opts: {
    message: string;
    active?: string;
    inactive?: string;
    initialValue?: boolean;
  }): Promise<boolean | symbol>;
⋮----
export function select<Value>(opts: {
    message: string;
    options: { value: Value; label: string; hint?: string }[];
    initialValue?: Value;
  }): Promise<Value | symbol>;
⋮----
export function multiselect<Value>(opts: {
    message: string;
    options: { value: Value; label: string; hint?: string }[];
    initialValues?: Value[];
    required?: boolean;
  }): Promise<Value[] | symbol>;
⋮----
export function text(opts: {
    message: string;
    placeholder?: string;
    defaultValue?: string;
    initialValue?: string;
validate?: (value: string | undefined)
⋮----
export function spinner():
⋮----
start(message?: string): void;
stop(message?: string): void;
message(message?: string): void;
⋮----
export function note(message: string, title?: string): void;
⋮----
message(message: string): void;
info(message: string): void;
success(message: string): void;
step(message: string): void;
warn(message: string): void;
error(message: string): void;
</file>

<file path="src/installer/config-writer.ts">
import {
  writeMcpEntry,
  writePermissionsEntry,
} from './targets/claude';
import { readJsonFile } from './targets/shared';
⋮----
export type InstallLocation = 'global' | 'local';
⋮----
export function writeMcpConfig(location: InstallLocation): void
⋮----
export function writePermissions(location: InstallLocation): void
⋮----
export function hasMcpConfig(location: InstallLocation): boolean
⋮----
export function hasPermissions(location: InstallLocation): boolean
</file>

<file path="src/installer/index.ts">
import { execSync } from 'child_process';
⋮----
import {
  ALL_TARGETS,
  detectAll,
  getTarget,
  resolveTargetFlag,
} from './targets/registry';
import type { AgentTarget, Location, TargetId } from './targets/types';
⋮----
import { watchDisabledReason } from '../sync/watch-policy';
import { isGitRepo, isSyncHookInstalled, installGitSyncHook } from '../sync/git-hooks';
import { getCodeGraphDir } from '../directory';
import { getTelemetry, TELEMETRY_DOCS } from '../telemetry';
import { maybeOfferBetaSignup } from './beta-signup';
⋮----
function getVersion(): string
⋮----
export interface RunInstallerOptions {
  target?: string;
  location?: Location;
  autoAllow?: boolean;
  yes?: boolean;
}
⋮----
export async function runInstaller(): Promise<void>
⋮----
export async function runInstallerWithOptions(opts: RunInstallerOptions): Promise<void>
⋮----
export interface RunUninstallerOptions {
  target?: string;
  location?: Location;
  yes?: boolean;
  keepCli?: boolean;
  cliFilename?: string;
}
⋮----
export type UninstallStatus = 'removed' | 'not-configured' | 'unsupported';
⋮----
export interface UninstallReport {
  id: TargetId;
  displayName: string;
  status: UninstallStatus;
  removedPaths: string[];
  notes: string[];
}
⋮----
export function uninstallTargets(
  targets: readonly AgentTarget[],
  location: Location,
): UninstallReport[]
⋮----
export type RefreshStatus = 'refreshed' | 'unchanged' | 'not-configured' | 'unsupported';
⋮----
export interface RefreshReport {
  id: TargetId;
  displayName: string;
  location: Location;
  status: RefreshStatus;
  changedPaths: string[];
}
⋮----
export function refreshTargets(
  targets: readonly AgentTarget[],
  location: Location,
): RefreshReport[]
⋮----
export async function runUninstaller(opts: RunUninstallerOptions): Promise<void>
⋮----
/**
 * Replace home-directory prefix in a path with `~/` for cleaner log
 * lines. Pure cosmetic.
 */
function tildify(p: string): string
⋮----
async function resolveTargets(
  clack: typeof import('@clack/prompts'),
  opts: RunInstallerOptions,
  location: Location,
  useDefaults: boolean,
): Promise<AgentTarget[]>
⋮----
// Explicit --target flag wins.
⋮----
// --yes implies auto-detect.
⋮----
// Interactive multi-select.
⋮----
// If nothing detected, default to Claude alone (matches the
// historical default and the smallest-surprise outcome).
⋮----
/**
 * When the live file watcher will be disabled for this project (e.g. WSL2
 * /mnt drives, or CODEGRAPH_NO_WATCH), the index would silently go stale.
 * Explain that, and offer to keep it fresh automatically via git hooks
 * (commit / pull / checkout) instead of manual `codegraph sync`.
 *
 * No-op on environments where the watcher runs normally, so it's safe to
 * call unconditionally after init.
 */
... (6 lines truncated)
</file>

<file path="src/installer/instructions-template.ts">

</file>

<file path="src/mcp/answer-freshness.ts">
import { createHash } from 'crypto';
import { createReadStream } from 'fs';
import { stat } from 'fs/promises';
import { MAX_SOURCE_FILE_SIZE_BYTES, oversizeStamp } from '../file-limits';
import { validatePathWithinRoot } from '../utils';
⋮----
export interface AnswerFile {
  path: string;
  contentHash: string | null;
}
⋮----
export async function validateAnswerFiles(root: string, files: AnswerFile[]): Promise<
</file>

<file path="src/mcp/daemon-manager.ts">
import type { DaemonRecord, StopResult } from './daemon-registry';
⋮----
export interface PickItem {
  value: string;
  label: string;
  hint?: string;
}
⋮----
export function formatUptime(ms: number): string
⋮----
export function buildPickItems(daemons: DaemonRecord[], cwdRoot: string | null, now: number): PickItem[]
⋮----
export interface PickerDeps {
  list: () => DaemonRecord[] | Promise<DaemonRecord[]>;
  stop: (root: string) => Promise<StopResult>;
  stopAll: () => Promise<StopResult[]>;
  /** Realpath'd root of the current project's daemon, or null. */
  cwdRoot: string | null;
  now: () => number;
  select: (opts: { message: string; options: PickItem[]; initialValue: string }) => Promise<unknown>;
  isCancel: (v: unknown) => boolean;
  note: (msg: string) => void;
  done: (msg: string) => void;
}
⋮----
/** Realpath'd root of the current project's daemon, or null. */
⋮----
export async function runDaemonPicker(deps: PickerDeps): Promise<void>
</file>

<file path="src/mcp/daemon-paths.ts">
import { getCodeGraphDir } from '../directory';
⋮----
function projectHash(projectRoot: string): string
⋮----
function tmpdirSocketPath(projectRoot: string): string
⋮----
export function getDaemonSocketCandidates(projectRoot: string): string[]
⋮----
export function getDaemonSocketPath(projectRoot: string): string
⋮----
export function getDaemonPidPath(projectRoot: string): string
⋮----
export interface DaemonLockInfo {
  pid: number;
  version: string;
  socketPath: string;
  startedAt: number;
}
⋮----
export function canProbeDaemonIdentity(info: DaemonLockInfo): boolean
⋮----
export function probeDaemonIdentity(info: DaemonLockInfo, timeoutMs = 1_000): Promise<boolean>
⋮----
const finish = (ok: boolean) =>
⋮----
export function encodeLockInfo(info: DaemonLockInfo): string
⋮----
export function decodeLockInfo(raw: string): DaemonLockInfo | null
</file>

<file path="src/mcp/daemon-registry.ts">
import {
  getDaemonPidPath,
  getDaemonSocketCandidates,
  decodeLockInfo,
  canProbeDaemonIdentity,
  probeDaemonIdentity,
  type DaemonLockInfo,
} from './daemon-paths';
import { readWriterLock, releaseWriterLock, tryAcquireWriterLock } from './writer-lock';
⋮----
export interface DaemonRecord {
  root: string;
  pid: number;
  version: string;
  socketPath: string;
  startedAt: number;
}
⋮----
export function getRegistryDir(): string
⋮----
function recordPath(root: string): string
⋮----
export function isProcessAlive(pid: number): boolean
⋮----
export function registerDaemon(rec: DaemonRecord): void
⋮----
export function deregisterDaemon(root: string): void
⋮----
export function listDaemons(opts:
⋮----
export async function listVerifiedDaemons(opts:
⋮----
function cleanupDaemonArtifacts(
  root: string,
  expectedLockContents: string | null,
): boolean
⋮----
export async function clearStaleDaemonArtifacts(root: string): Promise<boolean>
⋮----
const sleep = (ms: number): Promise<void>
⋮----
async function waitForDeath(pid: number, timeoutMs: number): Promise<boolean>
⋮----
export interface StopResult {
  root: string;
  pid: number | null;
  outcome: 'term' | 'kill' | 'still-running' | 'not-running' | 'no-daemon' | 'unverified';
}
⋮----
export async function stopDaemonAt(root: string, options:
⋮----
const sameLock = (): boolean =>
⋮----
export async function stopAllDaemons(): Promise<StopResult[]>
</file>

<file path="src/mcp/daemon.ts">
import { MCPEngine } from './engine';
import { MCPSession } from './session';
import { SocketTransport } from './transport';
import {
  DaemonLockInfo,
  decodeLockInfo,
  encodeLockInfo,
  getDaemonPidPath,
  getDaemonSocketCandidates,
  getDaemonSocketPath,
} from './daemon-paths';
import { CodeGraphPackageVersion } from './version';
import {
  releaseWriterLock,
  tryAcquireWriterLock,
  assertNoRebuild,
  writerLockHeldMessage,
} from './writer-lock';
import { registerDaemon, deregisterDaemon } from './daemon-registry';
⋮----
export function finalizeDaemonExit(
  platform: NodeJS.Platform,
  exit: (code: number) => void,
): NodeJS.Timeout | null
⋮----
export interface DaemonHello {
  codegraph: string;
  pid: number;
  socketPath: string;
  protocol: 1;
}
⋮----
export interface DaemonClientHello {
  codegraph_client: 1;
  pid: number;
  hostPid: number | null;
}
⋮----
export interface DaemonStartResult {
  socketPath: string;
  lock: DaemonLockInfo;
}
⋮----
export class Daemon
⋮----
constructor(
    private projectRoot: string,
    opts: { idleTimeoutMs?: number; maxIdleMs?: number } = {},
)
⋮----
async start(): Promise<DaemonStartResult>
⋮----
const listen = (socketPath: string): Promise<net.Server>
⋮----
getClientCount(): number
⋮----
getSocketPath(): string
⋮----
async stop(reason: string = 'stop'): Promise<void>
⋮----
private handleConnection(socket: net.Socket): void
⋮----
private dropClient(session: MCPSession): void
⋮----
private armIdleTimer(): void
⋮----
private disarmIdleTimer(): void
⋮----
private startLivenessTimers(): void
⋮----
backstopShouldExit(isAlive: (pid: number) => boolean): boolean
⋮----
reapDeadClients(isAlive: (pid: number) => boolean): number
⋮----
private cleanupLockfile(): void
⋮----
export function refreshDaemonLock(
  pidPath: string,
  initialContents: string,
  lock: DaemonLockInfo,
  platform: NodeJS.Platform = process.platform,
): void
⋮----
try { fs.unlinkSync(tmpPid); } catch { /* renamed, or best-effort cleanup */ }
⋮----
/**
 * Result of `tryAcquireDaemonLock`. Either we got the lockfile (caller becomes
 * the daemon), or it already existed (caller should connect to the existing
 * daemon as a proxy, or — if the holder is dead — clear it and retry).
 */
export type AcquireResult =
  | { kind: 'acquired'; pidPath: string; info: DaemonLockInfo }
  | {
      kind: 'taken';
      existing: DaemonLockInfo | null;
      lockContents: string | null;
      pidPath: string;
    };
⋮----
export function tryAcquireDaemonLock(projectRoot: string): AcquireResult
... (56 lines truncated)
</file>

<file path="src/mcp/dynamic-boundaries.ts">
import { blankStringContents, stripCommentsForRegex, type CommentLang } from '../resolution/strip-comments';
⋮----
export interface BoundaryMatch {
  form: string;
  label: string;
  snippet: string;
  line: number;
  key?: string;
  keyIsType?: boolean;
  moreSites?: number;
}
⋮----
interface FormSpec {
  form: string;
  label: string;
  langs?: Set<string>;
  re: RegExp;
  keyFrom?: (orig: string) => { key: string; keyIsType?: boolean } | undefined;
  keyWindow?: number;
  accept?: (stripped: string, original: string, end: number) => boolean;
}
⋮----
function isRuntimeImportArgument(stripped: string, original: string, start: number): boolean
⋮----
if (quote === ')') return false; // `import()` — nothing to resolve
⋮----
// Skip escape pairs: \${ is literal text, but \\${ interpolates.
⋮----
// `)` ends the call; `,` starts import()'s options argument. Anything else
⋮----
function singleStringLiteral(text: string): string | undefined
⋮----
// handlers[action.type](payload) / registry[key](args) / table[k](...) —
// the `](` adjacency is the gate; a word/`)`/`]` char must precede `[` so
// array literals and markdown-ish text in prose can't fire.
⋮----
// import(expr) / require(expr) with a NON-literal argument → runtime module
// choice. Literal imports are ordinary edges and never reach this scanner.
⋮----
// obj.send(:method_name) / public_send / method(:name) — ruby metaprogramming.
⋮----
// call_user_func([$this, 'method']) / $this->$method() / $callback() —
// PHP variable functions and callables.
⋮----
// Reflection: Method.invoke / getMethod("x") / Class.forName / Go
// reflect MethodByName / C# Activator.CreateInstance, GetMethod.
⋮----
// new Proxy(target, handler) / Reflect.get|apply — JS metaobject dispatch.
⋮----
// mediator.Send(new CreateTodoItemCommand(...)) / bus.publish(new OrderEvent(...))
// — typed message dispatch (MediatR/CQRS/event-bus). The request TYPE is the
// key; the conventional target is `<Type>Handler`.
⋮----
function commentLang(language: string): CommentLang | null
⋮----
export function scanDynamicDispatch(body: string, language: string, fileStartLine: number): BoundaryMatch[]
⋮----
function scanPythonGetattr(stripped: string, original: string, fileStartLine: number, out: BoundaryMatch[], seen: Map<string, BoundaryMatch>): void
⋮----
// Immediate call: getattr(...)(
⋮----
function matchBalancedParen(text: string, open: number): number
⋮----
function countNewlines(text: string, end: number): number
⋮----
function snippetAround(text: string, index: number): string
</file>

<file path="src/mcp/early-ppid.ts">

</file>

<file path="src/mcp/engine.ts">
import type CodeGraph from '../index';
import { resolveServerRoot } from '../directory';
import { ToolHandler } from './tools';
import { WslSharedIndexError } from '../db/wsl-shared-index';
import { assertNoRebuild, releaseWriterLock, tryAcquireWriterLock, writerLockHeldMessage } from './writer-lock';
import { QueryPool, resolvePoolSize } from './query-pool';
import { acquireProject, ProjectLease } from './project-lifecycle';
⋮----
const loadCodeGraph = (): typeof import('../index').default
⋮----
export interface MCPEngineOptions {
  readOnly?: boolean;
  watch?: boolean;
  queryPool?: boolean;
  queryPoolDefaultMax?: number;
  writerLockRoot?: string;
}
⋮----
export class MCPEngine
⋮----
constructor(opts: MCPEngineOptions =
⋮----
private maybeStartPool(root: string | null): void
⋮----
setProjectPathHint(projectPath: string): void
⋮----
getProjectPath(): string | null
⋮----
getToolHandler(): ToolHandler
⋮----
hasDefaultCodeGraph(): boolean
⋮----
async ensureInitialized(searchFrom: string): Promise<void>
⋮----
retryInitializeSync(searchFrom: string): void
⋮----
stop(): Promise<void>
⋮----
private releaseExplicitProject(cg: CodeGraph): void | Promise<void>
⋮----
private watchOptions(): Parameters<CodeGraph['watch']>[0]
⋮----
private async doInitialize(searchFrom: string): Promise<void>
⋮----
private logSubprojectAdoption(searchFrom: string, root: string): void
⋮----
private startWatching(): void
⋮----
private catchUpSync(afterReopen = false): void
⋮----
export function parseDebounceEnv(raw: string | undefined): number | undefined
</file>

<file path="src/mcp/explore-dedup.ts">
import { createHash } from 'crypto';
import type { ExploreLineRange, ExploreProjectState } from './explore-session-state';
⋮----
export function exploreDedupEnabled(): boolean
⋮----
export function fileFingerprint(content: string): string
⋮----
export function mergeRanges(ranges: ReadonlyArray<ExploreLineRange>): ExploreLineRange[]
⋮----
export function intersectRange(
  range: ExploreLineRange,
  served: ReadonlyArray<ExploreLineRange>,
): ExploreLineRange[]
⋮----
export function subtractRange(
  range: ExploreLineRange,
  cut: ReadonlyArray<ExploreLineRange>,
): ExploreLineRange[]
⋮----
export interface RangeDedup {
  emit: ExploreLineRange[];
  covered: ExploreLineRange[];
}
⋮----
export function dedupeRange(
  range: ExploreLineRange,
  served: ReadonlyArray<ExploreLineRange>,
  minCovered: number = EXPLORE_DEDUP.MIN_COVERED_LINES,
): RangeDedup
⋮----
export function servedRangesForFile(
  prior: ExploreProjectState | null,
  filePath: string,
  fingerprint: string,
): ExploreLineRange[]
⋮----
export function formatSpans(spans: ReadonlyArray<ExploreLineRange>): string
⋮----
export function formatBackReference(
  filePath: string,
  covered: ReadonlyArray<ExploreLineRange>,
  symbols: ReadonlyArray<string>,
  opts: { partial: boolean },
): string
⋮----
/** Symbol names whose definitions fall inside the withheld spans. */
export function symbolsInSpans(
  nodes: ReadonlyArray<{ name: string; kind: string; startLine: number; endLine: number }>,
  spans: ReadonlyArray<ExploreLineRange>,
): string[]
</file>

<file path="src/mcp/explore-diagnostics.ts">
import { appendFileSync } from 'fs';
import type { ExploreProjectState } from './explore-session-state';
⋮----
export type ExploreRenderMode =
  | 'whole'
  | 'clusters'
  | 'focused'
  | 'skeleton'
  | 'stale-omitted'
  | 'backref'
  | 'dropped';
⋮----
export type ExploreSkipReason =
  | 'max-files'
  | 'cliff'
  | 'budget-whole-file'
  | 'budget-clusters'
  | 'unreadable'
  | 'no-ranges';
⋮----
export interface ExploreCandidateMeta {
  rank: number;
  score: number;
  graphScore: number;
  termHits: number;
  nodes: number;
  pinned?: boolean;
  named: boolean;
  central: boolean;
  entry: boolean;
  spine: boolean;
  lowValue: boolean;
  generated: boolean;
  ambientDeclaration: boolean;
  penalty: number;
  kinds: string;
}
⋮----
interface FileRecord extends ExploreCandidateMeta {
  path: string;
  allowance: number | null;
  spendable: number | null;
  funded: number | null;
  render?: ExploreRenderMode;
  dedupSavedChars: number;
  dedupCovered: Array<[number, number]>;
  emittedChars: number;
  finalChars: number;
  share: number;
  allocatedShare: number;
  clipped: boolean;
  skipped?: ExploreSkipReason;
}
⋮----
interface StageCounts {
  grouped: number;
  pastLowValueFilter: number;
  pastScoreFloor: number;
  pastRelevanceGate: number;
}
⋮----
interface BudgetShape {
  maxOutputChars: number;
  maxCharsPerFile: number;
  defaultMaxFiles: number;
}
⋮----
export interface ExploreDiagnosticFile extends ExploreCandidateMeta {
  path: string;
  allowance: number | null;
  spendable: number | null;
  funded: number | null;
  render: ExploreRenderMode | null;
  skipped: ExploreSkipReason | null;
  clipped: boolean;
  dedupSavedChars: number;
  dedupCovered: Array<[number, number]>;
  emittedChars: number;
  finalChars: number;
  share: number;
  allocatedShare: number;
}
⋮----
export interface ExploreDiagnosticSession {
  callIndex: number;
  priorCalls: number;
  priorResponseChars: number;
  priorFiles: Array<{ path: string; ranges: Array<[number, number]>; bytes: number }>;
}
⋮----
export interface ExploreDiagnosticReport {
  tool: 'codegraph_explore';
  query: string;
  projectRoot: string;
  indexedFileCount: number;
  note?: string;
  session?: ExploreDiagnosticSession;
  budget: {
    maxOutputChars: number;
    maxCharsPerFile: number;
... (153 lines truncated)
</file>

<file path="src/mcp/explore-session-state.ts">
export interface ExploreLineRange {
  start: number;
  end: number;
}
⋮----
export interface ExploreFileEmission {
  path: string;
  ranges: ExploreLineRange[];
  bytes: number;
  fingerprint?: string;
  rangesTruncated?: boolean;
}
⋮----
export interface ExploreEmission {
  projectRoot: string;
  query: string;
  files: ExploreFileEmission[];
  sourceBytes: number;
  responseBytes: number;
}
⋮----
export interface ExploreCallRecord extends ExploreEmission {
  index: number;
}
⋮----
export interface ExploreProjectState {
  projectRoot: string;
  callCount: number;
  responseBytes: number;
  calls: ExploreCallRecord[];
}
⋮----
export interface ExploreSessionView {
  projects: ExploreProjectState[];
}
⋮----
export function exploreProjectKey(projectRoot: string): string
⋮----
export function coalesceRanges(
  ranges: ReadonlyArray<ExploreLineRange>,
  max: number = EXPLORE_SESSION_LIMITS.MAX_RANGES_PER_FILE,
):
⋮----
export function rangesCover(ranges: ReadonlyArray<ExploreLineRange>, line: number): boolean
⋮----
interface MutableProjectState {
  projectRoot: string;
  callCount: number;
  responseBytes: number;
  calls: ExploreCallRecord[];
}
⋮----
export class ExploreSessionState
⋮----
record(emission: ExploreEmission): ExploreCallRecord | null
⋮----
/** Full state for one project, or `null` if it was never queried this session. */
forProject(projectRoot: string): ExploreProjectState | null
⋮----
/** Explore calls made this session against a project (including evicted ones). */
callCount(projectRoot: string): number
⋮----
/** Every project this session has queried, least-recently-used first. */
snapshot(): ExploreProjectState[]
⋮----
/**
   * The bounded view passed INTO a tool call. Trimmed to the most recent
   * {@link EXPLORE_SESSION_LIMITS.MAX_VIEW_CALLS} calls per project: it crosses a
   * worker boundary on every explore, so it carries what a dedup/decay decision
   * needs and not the whole history.
   */
view(): ExploreSessionView
⋮----
/** Drop everything. Used by tests; a real session just goes away instead. */
clear(): void
⋮----
/**
   * Fetch a project's state, creating it if new, and mark it most-recently-used.
   * Evicts the LRU project past the bound — dropping a project entirely (rather
   * than its detail) is right here: a session that has moved on to four other
   * repos is not about to re-ask the first one.
   */
private touch(key: string, projectRoot: string): MutableProjectState
⋮----
private boundFiles(files: ReadonlyArray<ExploreFileEmission> | undefined): ExploreFileEmission[]
⋮----
function cloneProject(state: MutableProjectState): ExploreProjectState
⋮----
export function readExploreSessionView(args: Record<string, unknown>): ExploreSessionView | null
⋮----
export function viewForProject(
  view: ExploreSessionView | null,
  projectRoot: string,
): ExploreProjectState | null
</file>

<file path="src/mcp/index-freshness-worker.ts">
import { parentPort, workerData } from 'worker_threads';
</file>

<file path="src/mcp/index-freshness.ts">
import { existsSync } from 'fs';
⋮----
import { Worker } from 'worker_threads';
⋮----
export interface PendingChangeCounts {
  added: number;
  modified: number;
  removed: number;
}
⋮----
export function measurePendingChanges(root: string): Promise<PendingChangeCounts | null>
⋮----
function runMeasurement(root: string): Promise<PendingChangeCounts | null>
⋮----
const finish = (counts: PendingChangeCounts | null) =>
</file>

<file path="src/mcp/index.ts">
import { spawn, StdioOptions } from 'child_process';
import { resolveServerRoot, getCodeGraphDir } from '../directory';
import { StdioTransport } from './transport';
import { MCPEngine } from './engine';
import { MCPSession } from './session';
import {
  Daemon,
  clearStaleDaemonLock,
  isProcessAlive,
  tryAcquireDaemonLock,
} from './daemon';
import { clearStaleDaemonArtifacts } from './daemon-registry';
import { connectWithHello, runLocalHandshakeProxy } from './proxy';
import {
  readWriterLock,
  assertNoRebuild,
  releaseWriterLock,
  tryAcquireWriterLock,
  writerLockHeldMessage,
} from './writer-lock';
import {
  canProbeDaemonIdentity,
  decodeLockInfo,
  getDaemonPidPath,
  getDaemonSocketCandidates,
  probeDaemonIdentity,
} from './daemon-paths';
import { getTelemetry } from '../telemetry';
import { checkForUpdateInBackground } from '../upgrade/update-check';
import { EARLY_PPID } from './early-ppid';
import { supervisionLostReason, parsePpidPollMs, parseHostPpid } from './ppid-watchdog';
import { installMainThreadWatchdog, WatchdogHandle } from './liveness-watchdog';
import { armStartupHandshakeTimeout } from './startup-handshake';
import { treatStdinFailureAsShutdown } from './stdin-teardown';
import { HOST_PPID_ENV } from '../extraction/wasm-runtime-flags';
⋮----
function readOnlyFallback(holder: string): MCPEngine
⋮----
function makeFallbackEngine(root: string): MCPEngine
⋮----
function daemonOptOutSet(): boolean
⋮----
function daemonInternalSet(): boolean
⋮----
export function timestampStderrLines(): void
⋮----
export function stampLogChunk(chunk: string | Uint8Array): string | Uint8Array
⋮----
export function watchdogProgressPaths(root: string | null):
⋮----
function resolveDaemonRoot(explicitPath: string | null): string | null
⋮----
function spawnDetachedDaemon(root: string): void
⋮----
export class MCPServer
⋮----
constructor(projectPath?: string)
⋮----
async start(): Promise<void>
⋮----
async stop(): Promise<void>
⋮----
private async startDirect(reason: string): Promise<void>
⋮----
private async startDaemonProcess(): Promise<void>
⋮----
private async runProxyWithLocalHandshake(root: string): Promise<void>
⋮----
const connectAnyCandidate = async (): Promise<Awaited<ReturnType<typeof connectWithHello>>> =>
const getDaemonSocket = async () =>
⋮----
private installSignalHandlers(): void
⋮----
private installPpidWatchdog(): void
⋮----
function sleep(ms: number): Promise<void>
</file>

<file path="src/mcp/liveness-watchdog.ts">
import { spawn, ChildProcess } from 'child_process';
⋮----
function isEnvTruthy(raw: string | undefined): boolean
⋮----
export function parseWatchdogTimeoutMs(
  raw: string | undefined,
  fallback: number = DEFAULT_WATCHDOG_TIMEOUT_MS
): number
⋮----
export function deriveCheckIntervalMs(timeoutMs: number): number
⋮----
function debug(msg: string): void
⋮----
export interface WatchdogHandle {
  stop(): void;
}
⋮----
stop(): void;
⋮----
export interface WatchdogOptions {
  progressPaths?: string[];
}
⋮----
export function installMainThreadWatchdog(options: WatchdogOptions =
⋮----
stop(): void
</file>

<file path="src/mcp/ppid-watchdog.ts">
export interface SupervisionState {
  originalPpid: number;
  currentPpid: number;
  hostPpid: number | null;
  isAlive: (pid: number) => boolean;
  platform?: NodeJS.Platform;
}
⋮----
export function supervisionLostReason(state: SupervisionState): string | null
⋮----
export function parsePpidPollMs(raw: string | undefined): number
⋮----
/**
 * Parse the host PID propagated across the `--liftoff-only` re-exec
 * (`CODEGRAPH_HOST_PPID`). Returns a positive integer PID, or null when
 * unset/invalid — the direct-launch path, where the watchdog falls back to
 * `process.ppid` divergence. PIDs of 0/1 are rejected (0 = unknown, 1 = init,
 * i.e. already orphaned), so the watchdog doesn't latch onto init.
 */
export function parseHostPpid(raw: string | undefined): number | null
</file>

<file path="src/mcp/project-lifecycle.ts">
import { realpathSync } from 'fs';
import type { Socket } from 'net';
import type CodeGraph from '../index';
import { isInitialized } from '../directory';
import { LockUnavailableError, watchDisabledReason } from '../sync';
import { getDaemonSocketCandidates } from './daemon-paths';
import { connectWithHello } from './proxy';
import { markWriterReady, readWriterLock, releaseWriterLock, tryAcquireWriterLock } from './writer-lock';
⋮----
interface Project {
  cg: CodeGraph;
  refs: number;
  owner: boolean;
  caughtUp: boolean;
  retirement: Promise<void> | null;
  gate: Promise<void> | null;
  socket: Socket | null;
  timer: NodeJS.Timeout;
  options: Parameters<CodeGraph['watch']>[0];
}
⋮----
export interface ProjectLease {
  cg: CodeGraph;
  ready(): Promise<void>;
  release(): Promise<void>;
}
⋮----
ready(): Promise<void>;
release(): Promise<void>;
⋮----
export function acquireProject(
  root: string,
  open: () => CodeGraph,
  options: Parameters<CodeGraph['watch']>[0],
): ProjectLease
⋮----
function retire(root: string, project: Project): Promise<void>
⋮----
const finish = (): void =>
⋮----
function ready(root: string, project: Project): Promise<void>
⋮----
async function activate(root: string, project: Project): Promise<void>
⋮----
function daemonCatchUp(socket: Socket): Promise<void>
⋮----
const onData = (chunk: string | Buffer): void =>
</file>

<file path="src/mcp/proxy.ts">
import { HOST_PPID_ENV } from '../extraction/wasm-runtime-flags';
import { DaemonClientHello, DaemonHello, MAX_HELLO_LINE_BYTES } from './daemon';
import { EARLY_PPID } from './early-ppid';
import { supervisionLostReason } from './ppid-watchdog';
import { armStartupHandshakeTimeout } from './startup-handshake';
import { treatStdinFailureAsShutdown } from './stdin-teardown';
import { CodeGraphPackageVersion } from './version';
import { SERVER_INFO, PROTOCOL_VERSION, initializeInstructions } from './session';
import { SERVER_INSTRUCTIONS } from './server-instructions';
import { getStaticTools } from './tools';
import { ExploreSessionState } from './explore-session-state';
import { getTelemetry, ClientInfo } from '../telemetry';
import { installMainThreadWatchdog, WatchdogHandle } from './liveness-watchdog';
import type { MCPEngine } from './engine';
⋮----
export function logAttachedDaemon(socketPath: string, hello: DaemonHello): void
⋮----
export interface ProxyResult {
  outcome: 'proxied' | 'fallback-needed';
  reason?: string;
}
⋮----
export async function runProxy(
  socketPath: string,
  expectedVersion: string = CodeGraphPackageVersion,
): Promise<ProxyResult>
⋮----
export async function connectWithHello(
  socketPath: string,
  expectedVersion: string = CodeGraphPackageVersion,
): Promise<net.Socket | 'version-mismatch' | null>
⋮----
function sendClientHello(socket: net.Socket): void
⋮----
type JsonRpc = Record<string, unknown>;
⋮----
export interface LocalHandshakeDeps {
  getDaemonSocket(): Promise<net.Socket | null>;
  makeEngine(): MCPEngine;
  root: string;
}
⋮----
getDaemonSocket(): Promise<net.Socket | null>;
⋮----
makeEngine(): MCPEngine;
⋮----
export async function runLocalHandshakeProxy(deps: LocalHandshakeDeps): Promise<void>
⋮----
const trackInflight = (line: string): void =>
⋮----
const writeClient = (obj: JsonRpc | string): void =>
const shutdown = (): void =>
const ensureEngine = (): Promise<void> =>
⋮----
const handleLocally = async (line: string): Promise<void> =>
const routeToDaemon = (line: string): void =>
⋮----
const onDaemonLost = (): void =>
⋮----
function startPpidWatchdogNoSocket(onDeath: () => void): void
⋮----
function readHelloLine(socket: net.Socket): Promise<DaemonHello>
⋮----
const cleanup = () =>
const onData = (chunk: string | Buffer) =>
const onError = (err: Error) =>
const onClose = () =>
⋮----
function pipeUntilClose(socket: net.Socket): Promise<void>
⋮----
const done = () =>
⋮----
const teardown = () =>
⋮----
function startPpidWatchdog(socket: net.Socket): void
⋮----
function parsePollMs(raw: string | undefined): number
⋮----
function parseHostPpid(raw: string | undefined): number | null
⋮----
function isProcessAliveLocal(pid: number): boolean
</file>

<file path="src/mcp/query-pool.ts">
import { Worker } from 'worker_threads';
⋮----
import type { ToolResult } from './tools';
⋮----
export interface PoolWorker {
  postMessage(msg: unknown): void;
  terminate(): Promise<number> | void;
  on(event: 'message', cb: (m: unknown) => void): void;
  on(event: 'error', cb: (e: Error) => void): void;
  on(event: 'exit', cb: (code: number) => void): void;
}
⋮----
postMessage(msg: unknown): void;
terminate(): Promise<number> | void;
on(event: 'message', cb: (m: unknown)
on(event: 'error', cb: (e: Error)
on(event: 'exit', cb: (code: number)
⋮----
interface WorkerMessage {
  type?: string;
  ok?: boolean;
  id?: number;
  result?: ToolResult;
}
⋮----
interface Job {
  id: number;
  toolName: string;
  args: Record<string, unknown>;
  resolve: (r: ToolResult) => void;
  retries: number;
  settled: boolean;
  enqueuedAt: number;
  softTimer?: NodeJS.Timeout;
}
⋮----
export interface QueryPoolOptions {
  root: string | null;
  size?: number;
  softTimeoutMs?: number;
  maxRetries?: number;
  createWorker?: () => PoolWorker;
}
⋮----
export function resolvePoolSize(envVal: string | undefined, cpuCount: number): number
⋮----
// non-numeric / negative → fall through to the default
⋮----
function resolveBusyTimeoutMs(): number
⋮----
/** Success-shaped overload guidance (NEVER isError — see the abandonment rule). */
function busyGuidance(waitedMs: number): ToolResult
⋮----
export class QueryPool
⋮----
constructor(opts: QueryPoolOptions)
⋮----
get size(): number
⋮----
get liveWorkers(): number
⋮----
get healthy(): boolean
⋮----
get ready(): boolean
⋮----
private spawnOne(): void
⋮----
private onMessage(w: PoolWorker, m: WorkerMessage): void
⋮----
private onWorkerGone(w: PoolWorker): void
⋮----
private drain(): void
⋮----
private settle(job: Job, result: ToolResult): void
⋮----
run(toolName: string, args: Record<string, unknown>): Promise<ToolResult>
⋮----
async destroy(): Promise<void>
</file>

<file path="src/mcp/query-worker.ts">
import { parentPort, workerData } from 'worker_threads';
import type { ToolResult } from './tools';
⋮----
interface WorkerInit {
  root: string | null;
}
⋮----
interface CallMessage {
  type: 'call';
  id: number;
  toolName: string;
  args: Record<string, unknown>;
}
⋮----
const loadCodeGraph = (): typeof import('../index').default
const loadToolHandler = (): typeof import('./tools').ToolHandler
⋮----
const serve = async (msg: CallMessage): Promise<void> =>
⋮----
function errorResult(text: string): ToolResult
</file>

<file path="src/mcp/server-instructions.ts">

</file>

<file path="src/mcp/session.ts">
import { JsonRpcRequest, JsonRpcNotification, JsonRpcTransport, ErrorCodes } from './transport';
import { MCPEngine } from './engine';
import { tools } from './tools';
import { SERVER_INSTRUCTIONS, SERVER_INSTRUCTIONS_NO_ROOT_INDEX } from './server-instructions';
import { CodeGraphPackageVersion } from './version';
import { resolveServerRoot } from '../directory';
import { getTelemetry, ClientInfo } from '../telemetry';
import { getUpdateNotice } from '../upgrade/update-check';
import { ExploreSessionState } from './explore-session-state';
⋮----
export function initializeInstructions(base: string, notice: string | null = getUpdateNotice()): string
⋮----
function fileUriToPath(uri: string): string
⋮----
/** First usable filesystem path from a `roots/list` result, or null. */
function firstRootPath(result: unknown): string | null
⋮----
export interface MCPSessionOptions {
  explicitProjectPath?: string | null;
}
⋮----
export class MCPSession
⋮----
constructor(
    private transport: JsonRpcTransport,
    private engine: MCPEngine,
    opts: MCPSessionOptions = {},
)
⋮----
start(): void
⋮----
stop(): void
⋮----
getTransport(): JsonRpcTransport
⋮----
getExploreSessionState(): ExploreSessionState
⋮----
private async handleMessage(message: JsonRpcRequest | JsonRpcNotification): Promise<void>
⋮----
private async handleInitialize(request: JsonRpcRequest): Promise<void>
⋮----
private async handleToolsList(request: JsonRpcRequest): Promise<void>
⋮----
private async handleToolsCall(request: JsonRpcRequest): Promise<void>
⋮----
private async retryInitIfNeeded(): Promise<void>
⋮----
private async initFromRoots(): Promise<void>
</file>

<file path="src/mcp/startup-handshake.ts">
export function parseStartupHandshakeTimeoutMs(raw: string | undefined): number
⋮----
/**
 * Arm the backstop. `onAbandoned` runs at most once, only if no `'data'` event
 * arrives on `stream` within the timeout. Returns a disarm function (idempotent;
 * also detaches the listener). `stream`/`timeoutMs` are injectable for tests.
 */
export function armStartupHandshakeTimeout(
  onAbandoned: () => void,
  stream: NodeJS.ReadableStream = process.stdin,
  timeoutMs: number = parseStartupHandshakeTimeoutMs(process.env[STARTUP_HANDSHAKE_TIMEOUT_ENV]),
): () => void
⋮----
const onFirstData = (): void =>
</file>

<file path="src/mcp/stdin-teardown.ts">
export function treatStdinFailureAsShutdown(
  onTerminal: () => void,
  stream: NodeJS.ReadableStream = process.stdin
): void
⋮----
const fire = (): void =>
⋮----
(stream as Partial<
</file>

<file path="src/mcp/tools.ts">
import type CodeGraph from '../index';
import type { QueryPool } from './query-pool';
import { findNearestCodeGraphRoot, isSameIndexRoot } from '../directory';
import { WslSharedIndexError } from '../db/wsl-shared-index';
⋮----
const loadCodeGraph = (): typeof import('../index').default
⋮----
export function __setLoadCodeGraphForTests(cls: typeof import('../index').default | null): void
import {
  detectWorktreeIndexMismatch,
  worktreeMismatchWarning,
  worktreeMismatchNotice,
  type WorktreeIndexMismatch,
} from '../sync/worktree';
import type { PendingFile } from '../sync';
import type { Node, Edge, SearchResult, Subgraph, NodeKind } from '../types';
import { isTestFile, normalizeNameToken } from '../search/query-utils';
import { groupDefinitions, isQualifiedSymbol, lastQualifierPart, matchesSymbol } from '../graph/symbol-lookup';
import {
  extractQueryPaths,
  queryMightContainPaths,
  type QueryLineAnchor,
  type QuerySetAsideMatch,
} from '../search/query-paths';
import {
  existsSync,
  readFileSync,
  realpathSync,
  statSync,
} from 'fs';
import { createHash } from 'crypto';
import { clamp, validatePathWithinRoot, validateProjectPath, isConfigLeafNode, CONFIG_LEAF_LANGUAGES } from '../utils';
import { guardLabel, guardsForFileSync, siteKey, supportsBranchGuards, warmBranchGuardGrammars } from '../graph/branch-guards';
import { findDynamicBoundaries, type BoundarySite } from '../graph/dynamic-boundary-report';
import { countImplementers } from '../graph/type-hierarchy';
import {
  findAllSymbols,
  resolveNamedSymbolFlow,
} from '../graph/named-symbol-flow';
import { getUpdateNotice } from '../upgrade/update-check';
import { measurePendingChanges } from './index-freshness';
import { validateAnswerFiles, type AnswerFile } from './answer-freshness';
import { ExploreDiagnostics } from './explore-diagnostics';
import {
  EXPLORE_EMISSION_KEY,
  EXPLORE_SESSION_VIEW_ARG,
  ExploreSessionState,
  readExploreSessionView,
  viewForProject,
  type ExploreEmission,
  type ExploreFileEmission,
  type ExploreLineRange,
} from './explore-session-state';
import {
  EXPLORE_DEDUP,
  dedupeRange,
  exploreDedupEnabled,
  fileFingerprint,
  formatBackReference,
  mergeRanges,
  servedRangesForFile,
  symbolsInSpans,
} from './explore-dedup';
⋮----
export class NotIndexedError extends Error
⋮----
function wslSharedIndexGuidance(err: WslSharedIndexError): string
⋮----
import { PathRefusalError } from '../errors';
import { indexedHashInput } from '../file-limits';
import { resolve as resolvePath, relative as relativePath } from 'path';
⋮----
export function normalizeQuerySpelling(query: string): string
⋮----
function pathIsProjectFile(projectRoot: string, relPath: string): boolean
⋮----
function filesDefiningSymbol(cg: CodeGraph, symbol: string): string[]
⋮----
export function getExploreBudget(fileCount: number): number
⋮----
export interface ExploreOutputBudget {
  maxOutputChars: number;
  defaultMaxFiles: number;
  maxCharsPerFile: number;
  gapThreshold: number;
  maxSymbolsInFileHeader: number;
  maxEdgesPerRelationshipKind: number;
  includeRelationships: boolean;
  includeAdditionalFiles: boolean;
  includeCompletenessSignal: boolean;
  includeBudgetNote: boolean;
}
⋮----
export function getExploreOutputBudget(fileCount: number): ExploreOutputBudget
⋮----
export interface ExploreAllocationCandidate {
  path: string;
  score: number;
  worth: number;
  spine: boolean;
... (1035 lines truncated)
</file>

<file path="src/mcp/transport.ts">
import type { Socket } from 'net';
⋮----
export interface JsonRpcRequest {
  jsonrpc: '2.0';
  id: string | number;
  method: string;
  params?: unknown;
}
⋮----
export interface JsonRpcResponse {
  jsonrpc: '2.0';
  id: string | number | null;
  result?: unknown;
  error?: JsonRpcError;
}
⋮----
export interface JsonRpcError {
  code: number;
  message: string;
  data?: unknown;
}
⋮----
export interface JsonRpcNotification {
  jsonrpc: '2.0';
  method: string;
  params?: unknown;
}
⋮----
export type MessageHandler = (message: JsonRpcRequest | JsonRpcNotification) => Promise<void>;
⋮----
export interface JsonRpcTransport {
  start(handler: MessageHandler): void;
  stop(): void;
  send(response: JsonRpcResponse): void;
  notify(method: string, params?: unknown): void;
  request(method: string, params?: unknown, timeoutMs?: number): Promise<unknown>;
  sendResult(id: string | number, result: unknown): void;
  sendError(id: string | number | null, code: number, message: string, data?: unknown): void;
}
⋮----
start(handler: MessageHandler): void;
stop(): void;
send(response: JsonRpcResponse): void;
notify(method: string, params?: unknown): void;
request(method: string, params?: unknown, timeoutMs?: number): Promise<unknown>;
sendResult(id: string | number, result: unknown): void;
sendError(id: string | number | null, code: number, message: string, data?: unknown): void;
⋮----
abstract class LineBasedJsonRpcTransport implements JsonRpcTransport
⋮----
abstract start(handler: MessageHandler): void;
protected abstract write(line: string): void;
protected abstract idPrefix(): string;
abstract stop(): void;
⋮----
request(method: string, params?: unknown, timeoutMs = 5000): Promise<unknown>
⋮----
send(response: JsonRpcResponse): void
⋮----
notify(method: string, params?: unknown): void
⋮----
sendResult(id: string | number, result: unknown): void
⋮----
sendError(id: string | number | null, code: number, message: string, data?: unknown): void
⋮----
protected rejectPending(reason: string): void
⋮----
protected async handleLine(line: string): Promise<void>
⋮----
private handleResponse(msg: Record<string, unknown>): void
⋮----
private isValidMessage(msg: unknown): boolean
⋮----
export interface StdioTransportOptions {
  exitOnClose?: boolean;
  onClose?: () => void;
}
⋮----
export class StdioTransport extends LineBasedJsonRpcTransport
⋮----
constructor(opts: StdioTransportOptions =
⋮----
start(handler: MessageHandler): void
⋮----
const onStreamEnd = (): void =>
⋮----
stop(): void
⋮----
protected write(line: string): void
⋮----
protected idPrefix(): string
⋮----
export class SocketTransport extends LineBasedJsonRpcTransport
⋮----
constructor(private socket: Socket, private prefix: string = 'cg-sock')
⋮----
onClose(handler: () => void): void
⋮----
writeRaw(line: string): void
⋮----
... (2 lines truncated)
</file>

<file path="src/mcp/version.ts">
function readPackageVersion(): string
</file>

<file path="src/mcp/writer-lock.ts">
import { getCodeGraphDir } from '../directory';
⋮----
function isProcessAlive(pid: number): boolean
⋮----
export function getWriterPidPath(projectRoot: string, lockName: 'writer.pid' | 'rebuild.pid' = 'writer.pid'): string
⋮----
export interface WriterLockInfo {
  pid: number;
  mode: string;
  startedAt: number;
  ready?: boolean;
}
⋮----
export type WriterAcquireResult =
  | { kind: 'acquired'; pidPath: string; info: WriterLockInfo }
  | { kind: 'taken'; existing: WriterLockInfo | null; pidPath: string };
⋮----
function encode(info: WriterLockInfo): string
⋮----
export function decodeWriterLockInfo(raw: string): WriterLockInfo | null
⋮----
export function tryAcquireWriterLock(
  projectRoot: string,
  mode: string,
  lockName: 'writer.pid' | 'rebuild.pid' = 'writer.pid',
): WriterAcquireResult
⋮----
const attempt = (): WriterAcquireResult =>
⋮----
export function markWriterReady(projectRoot: string): void
⋮----
export function releaseWriterLock(projectRoot: string, lockName: 'writer.pid' | 'rebuild.pid' = 'writer.pid'): void
⋮----
export function readWriterLock(projectRoot: string, lockName: 'writer.pid' | 'rebuild.pid' = 'writer.pid'): WriterLockInfo | null
⋮----
export function writerLockHeldMessage(
  existing: WriterLockInfo | null,
  pidPath: string,
): string
⋮----
export class RebuildInProgressError extends Error
⋮----
constructor()
⋮----
export function assertNoRebuild(root: string): void
</file>

<file path="src/resolution/frameworks/angular-router.ts">
import type { Node } from '../../types';
import type { FrameworkExtractionResult, FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import { resolveImportPath } from '../import-resolver';
import { stripCommentsForRegex } from '../strip-comments';
import { matchBracket, readFields, skipString, topLevelObjects } from './object-literal';
import { dependsOn } from './package-deps';
import {
  addRouteTo,
  appRootFor,
  firstArgumentText,
  HOLE,
  toHref,
  nthArgumentText,
  parseHrefExpression,
  readStringAt,
  routesForFile,
  type HrefLiteral,
  type RootedRouteTable,
  type RouteTable,
} from './expo-router';
import { destinationsForHref } from './nextjs';
⋮----
export type AngularComponentRef = { name: string; spec: null } | { name: string | null; spec: string };
⋮----
export interface AngularRoute {
  path: string;
  line: number;
  component: AngularComponentRef | null;
  layouts: AngularComponentRef[];
}
⋮----
export interface AngularRedirect {
  from: string;
  to: string;
  absolute: boolean;
}
⋮----
export interface AngularMount {
  prefix: string;
  spec: string;
  line: number;
}
⋮----
/**
 * Where a routes array opens: typed `Routes` / `Route[]`, handed to
 * `RouterModule.forRoot/forChild` or `provideRouter`, or a routes file's
 * default export. `children: [` is reached by walking an entry, never here.
 */
⋮----
/** The fields that make an object a route rather than any object in an array. */
⋮----
/** A path value the pass can name later: `internalRoutes.account.path`. */
⋮----
/** A `$localize` tagged template's default text: `` $localize`:kebab-case@@routes.about:about` `` is `about`. */
export function localizeDefault(text: string): string | null
⋮----
// `:meaning|description@@id:text` — the metadata block is the leading `:…:`.
⋮----
/**
 * A string written statically: a literal, a `$localize` default, or `+`
 * between those — `'/' + $localize`:…:about``, as Ghostfolio builds its
 * links. Null when any part is computed.
 */
export function staticString(text: string): string | null
⋮----
/** A route's own path segment(s): a string, a `$localize` default, or a constant kept as `{expr}`; null when it cannot be named. */
function pathSegments(text: string): string[] | null
⋮----
// `` `issue/:${ProjectConst.IssueId}` ``: a template whose holes are constants.
⋮----
// `internalRoutes.account.subRoutes.access.path + '/:id'`: each part a
// string or a constant, the constant a whole segment of its own.
⋮----
/** An expression's `+` operands at depth 0, strings and brackets stepped over. */
function splitPlus(text: string): string[]
⋮----
/** The component a `component:` / `loadComponent:` value names. */
function componentRef(field: 'component' | 'loadComponent', text: string): AngularComponentRef | null
⋮----
/** `() => import('./x')` → `./x`; `.then(m => m.X)` / `.then((c) => c.X)` names the member. */
function lazyImport(text: string):
⋮----
function joinPath(segs: readonly string[]): string
⋮----
export function parseAngularRoutes(content: string):
⋮----
const lineOf = (at: number)
⋮----
const walk = (open: number, close: number, prefix: readonly string[], depth: number, layouts: readonly AngularComponentRef[]): void =>
⋮----
function routeId(filePath: string, line: number, inFilePath: string): string
⋮----
export function isAngularRoute(node: Node): boolean
⋮----
function inFilePath(node: Node): string
⋮----
export function componentClassesIn(content: string): Array<
⋮----
function lazyComponent(spec: string, member: string | null, fromFile: string, context: ResolutionContext): Node | null
⋮----
... (106 lines truncated)
</file>

<file path="src/resolution/frameworks/astro.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath: string, _content: string)
⋮----
// Underscore-prefixed segments are excluded from routing by Astro;
// a stray `*.config.*` in a pages dir is never a route.
⋮----
function isPascalCase(str: string): boolean
⋮----
function resolveComponent(
  name: string,
  fromFile: string,
  context: ResolutionContext
): string | null
⋮----
function filePathToAstroRoute(afterPages: string): string
⋮----
// index files map to their parent path (index -> /, blog/index -> /blog)
⋮----
// Convert Astro param syntax
</file>

<file path="src/resolution/frameworks/cargo-workspace.ts">
import picomatch from 'picomatch';
import { ResolutionContext } from '../types';
⋮----
function getSection(content: string, sectionName: string): string | null
⋮----
function extractQuotedValues(valueList: string): string[]
⋮----
function escapeRegExp(value: string): string
⋮----
function getArrayValue(section: string, key: string): string | null
⋮----
function parseWorkspaceMembers(cargoToml: string): string[]
⋮----
function parsePackageName(cargoToml: string): string | null
⋮----
function addCrateAlias(map: Map<string, string>, crateName: string, memberPath: string): void
⋮----
function cleanPath(memberPath: string): string
⋮----
function expandGlobMember(member: string, context: ResolutionContext): string[]
⋮----
function walk(dir: string, depth: number): void
⋮----
function expandMembers(members: string[], context: ResolutionContext): string[]
⋮----
/**
 * Build a map from crate-name aliases to workspace member directory paths.
 * Example: "mytool-core" and "mytool_core" -> "crates/mytool-core"
 *
 * Supports glob members (e.g. `members = ["crates/*"]`) via picomatch
 * when the context exposes `listDirectories`.
 */
export function getCargoWorkspaceCrateMap(context: ResolutionContext): Map<string, string>
</file>

<file path="src/resolution/frameworks/cics.ts">
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { Node } from '../../types';
⋮----
function buildIndex(context: ResolutionContext): Map<string, string>
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/csharp.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { pickByNameAndKind } from './name-heuristic';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
// [HttpGet], [HttpGet("path")], [HttpPost("path", Name="x")] — BARE or with a
// path. (The old regex required a string, so bare attributes — with the route
// on the class [Route] — were missed; eShopOnWeb was 24 bare / 2 string.)
⋮----
// `app.MapGet("api/todos", …)` serves `/api/todos`.
⋮----
// A second verb call (`Get(...); Post(...)`) is a second route; stop at Configure's end.
⋮----
/** Route names only the whole repository can give: FastEndpoints constant paths, endpoint-group prefixes. */
postExtract(context: ResolutionContext): Node[]
⋮----
/**
 * A FastEndpoints route named by a constant (`Post(CreateContributorRequest.Route)`)
 * gets the constant's value: `public const string Route = "/Contributors";` in
 * that class, wherever it is declared. Idempotent — the qualified name keeps the
 * expression.
 */
function fastEndpointConstantRoutes(context: ResolutionContext): Node[]
⋮----
/**
 * The endpoint-group prefix convention, read once from the app: the
 * `MapGroup($"/api/{groupName}")` that registers every `IEndpointGroup`
 * (or `EndpointGroupBase`) under a head — `/api/` — before the class name.
 * A group route extracted as `POST /TodoItems` becomes `POST /api/TodoItems`;
 * a class with its own `RoutePrefix` literal already has its path. Idempotent:
 * `qualifiedName` keeps the group and the sub-path.
 */
function endpointGroupRoutes(context: ResolutionContext): Node[]
⋮----
function joinCsPath(prefix: string, sub: string): string
⋮----
/** Extract last identifier from an expression like `MyService.Handler` or `Handler`. */
function extractCSharpTailIdent(expr: string): string | null
⋮----
// Directory patterns
⋮----
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kinds: Set<string>,
  preferredDirPatterns: string[],
  context: ResolutionContext,
): string | null
</file>

<file path="src/resolution/frameworks/drupal.ts">
import { generateNodeId } from '../../extraction/tree-sitter-helpers';
import { Node } from '../../types';
import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
⋮----
function lastSegment(fqcn: string): string | null
⋮----
/**
 * Derive the Drupal module name from a file path.
 * e.g. `web/modules/custom/my_module/my_module.module` → `my_module`
 */
function moduleNameFromPath(filePath: string): string | null
⋮----
// ---------------------------------------------------------------------------
// Route extraction helpers
// ---------------------------------------------------------------------------
⋮----
/**
 * Extract route nodes and handler references from a Drupal `*.routing.yml` file.
 *
 * Drupal routing YAML format:
 *
 *   route.name:
 *     path: '/some/path'
 *     defaults:
 *       _controller: '\Drupal\module\Controller\MyController::method'
 *       _form: '\Drupal\module\Form\MyForm'
 *       _title: 'Page title'
 *     requirements:
 *       _permission: 'access content'
 *     methods: [GET, POST]   # optional
 */
function extractDrupalRoutes(
  filePath: string,
  content: string
):
⋮----
type PendingRoute = { name: string; lineNum: number };
⋮----
const flushRoute = () =>
⋮----
function isDrupalHookFile(filePath: string): boolean
⋮----
function extractDrupalHooks(
  filePath: string,
  content: string
):
⋮----
const emitHookRef = (hookName: string, funcName: string) =>
⋮----
claimsReference(name: string): boolean
⋮----
detect(context: ResolutionContext): boolean
⋮----
// Primary: composer.json identifies a Drupal project/module/theme/profile.
// A contrib module often has an EMPTY `require` (no `drupal/*` dep) but still
// declares `"name": "drupal/<module>"` and `"type": "drupal-module"`, so check
// those too — checking deps alone misses every standalone contrib module.
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath: string, content: string):
</file>

<file path="src/resolution/frameworks/expo-modules.ts">
import type { Node } from '../../types';
import {
  FrameworkExtractionResult,
  FrameworkResolver,
  ResolutionContext,
  ResolvedRef,
  UnresolvedRef,
} from '../types';
import { resolveImportPath } from '../import-resolver';
import { stripCommentsForRegex } from '../strip-comments';
⋮----
/**
 * Match the module name literal `Name("ExpoX")`. Used to enrich each emitted
 * method's qualifiedName so the same JS callsite to `Foo.fn` doesn't ambiguate
 * across multiple Expo modules in a monorepo.
 */
⋮----
/**
 * Heuristic class-name match — used as a fallback if `Name(...)` literal
 * isn't found. Detects `class XxxModule: Module` (Swift) or
 * `class XxxModule : Module` (Kotlin / with whitespace tolerance).
 */
⋮----
function isExpoModuleSource(source: string): boolean
⋮----
function extractExpoMethods(filePath: string, source: string, language: 'swift' | 'kotlin'): Node[]
⋮----
detect(context)
⋮----
extract(filePath, source): FrameworkExtractionResult
⋮----
resolve()
⋮----
interface NativeBinding {
  /** The `Name("…")` the module declares. */
  module: string;
  /** The declared JS type, from `requireNativeModule<CameraNativeModule>(…)`. */
  type: string | null;
  /** The file the binding (and its type) is written in. */
  file: string;
}
⋮----
/** The `Name("…")` the module declares. */
⋮----
/** The declared JS type, from `requireNativeModule<CameraNativeModule>(…)`. */
⋮----
/** The file the binding (and its type) is written in. */
⋮----
/**
 * What `name` is bound to in `file`: `const X = requireNativeModule('N')`
 * here, or the import of a module whose default export (or a named export)
 * is one — expo-camera's `import CameraManager from './ExpoCameraManager'`,
 * whose whole body is `export default requireNativeModule<CameraNativeModule>('ExpoCamera')`.
 */
function nativeBinding(name: string, file: string, context: ResolutionContext): NativeBinding | null
⋮----
/**
 * JS calls into an Expo module, bound by the module's NAME, not by the
 * method name alone: expo-camera calls its module `CameraManager`, so
 * `CameraManager.isAvailableAsync()` went to `CameraView`'s own static
 * `isAvailableAsync` in the same file. The native functions the module
 * declares are the targets — Swift first, Kotlin beside it — and when it
 * declares none of that name, the method on the type the binding is given
 * (`requireNativeModule<CameraNativeModule>`).
 */
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/expo-router.ts">
import type { Language, Node } from '../../types';
import type {
  FrameworkResolver,
  ResolutionContext,
  ResolvedRef,
  UnresolvedRef,
} from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { dependsOn } from './package-deps';
⋮----
export function routePathForFile(filePath: string): string | null
⋮----
export function apiRoutePathForFile(filePath: string): string | null
⋮----
function languageForFile(filePath: string): Language
⋮----
export function defaultExportName(stripped: string):
⋮----
export function navVerb(name: string): string | null
⋮----
function matchParen(s: string, open: number): number
⋮----
/** Index of the closing backtick for the template starting at `open`. */
function skipTemplate(s: string, open: number): number
⋮----
/** Index of the quote that closes the string literal opening at `at` (or the end of `s`). */
export function stringEnd(s: string, at: number): number
⋮----
/**
 * A string literal (`'…'`, `"…"`, or a template) starting at `at`, as text
 * with every `${…}` replaced by {@link HOLE}. Null when `at` is not a string.
 */
export function readStringAt(s: string, at: number): string | null
⋮----
export interface HrefLiteral {
  /** The path part, `${…}` holes kept as {@link HOLE}; query and hash removed. */
  path: string;
  /** The literal as written, holes rendered as `${…}` — for the edge metadata. */
  display: string;
  /**
   * The OTHER destinations, when the argument was a conditional. A link
   * written `!isAdmin ? keyword ? '/search/…' : '/page/…' : '/admin/…'` names
   * three places a user can end up, and each is drawn.
   */
  alternates?: HrefLiteral[];
}
⋮----
/** The path part, `${…}` holes kept as {@link HOLE}; query and hash removed. */
⋮----
/** The literal as written, holes rendered as `${…}` — for the edge metadata. */
⋮----
/**
   * The OTHER destinations, when the argument was a conditional. A link
   * written `!isAdmin ? keyword ? '/search/…' : '/page/…' : '/admin/…'` names
   * three places a user can end up, and each is drawn.
   */
⋮----
/** Every destination an href names — itself first, then its other arms. */
export function hrefArms(href: HrefLiteral): HrefLiteral[]
⋮----
/** Index of the first `ch` at bracket depth 0 and outside strings, or -1. */
function indexAtDepth0(s: string, ch: string, from: number): number
⋮----
else if (c === '?' && (s[i + 1] === '.' || s[i + 1] === '?')) i++; // `?.` / `??`
⋮----
export function toHref(literal: string | null): HrefLiteral | null
⋮----
/**
 * The href in one argument expression: a string, a template, an `Href` object
 * with a literal `pathname`, or a conditional whose two arms are each one of
 * those (`cond ? \`/x?id=${id}\` : '/x'`). Anything else is not static.
 */
⋮----
function ternaryColon(s: string, q: number): number
⋮----
export function parseHrefExpression(expr: string): HrefLiteral | null
⋮----
// `(a ? b : c)` — unwrap one layer of grouping parens.
⋮----
// Every arm is a destination, flattened — an arm that is itself a
// conditional contributes its own arms rather than being reduced to one.
// `const redirect = location.search ? location.search.split('=')[1] : '/'`
// then `history.push(redirect)` contributes just the `/`, which is where
// that lands by default; reading neither arm lost the whole transition.
⋮----
/**
 * The destination of the navigation call at (`line`, `column`) in `lines`.
 *
 * Handles the three shapes Expo Router accepts: a string, a template literal
 * (static prefix kept, interpolations become holes), and an `Href` object
 * whose `pathname` is one of those. Anything else — a variable, a call, a
 * spread — is not a literal and returns null.
 */
export function readHrefArgument(
  lines: readonly string[],
  line: number,
  column: number,
  method: string
): HrefLiteral | null
⋮----
... (95 lines truncated)
</file>

<file path="src/resolution/frameworks/express.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { resolveImportPath } from '../import-resolver';
import { dependsOn } from './package-deps';
⋮----
function extractTailIdent(expr: string): string | null
⋮----
/**
 * Index of the delimiter matching the one at `open`, skipping string/template
 * literals so a `)` or `}` inside a string doesn't throw off the balance.
 */
function matchDelim(s: string, open: number, oc: string, cc: string): number
⋮----
// Express res/req methods + common JS builtins — calls to these inside a handler
// body are framework/noise, not the business flow we want to surface as route edges.
⋮----
function handlerCallNames(body: string): string[]
⋮----
/**
 * The replies an inline handler makes — `res.status(404).json({…})`,
 * `res.json(user)`, `reply.send(…)`, `ctx.body = …` aside — as references the
 * Steps view's effect table reads at their own line and column. The body's
 * plain calls above skip these names as framework noise on purpose (they are
 * not the business flow); for the endpoint's contract they are the point.
 */
⋮----
function replyRefs(safe: string, bodyStart: number, bodyEnd: number, fromNodeId: string, filePath: string, language: 'typescript' | 'javascript'): UnresolvedRef[]
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
const sameFile = (id: string | null): string | null
⋮----
extract(filePath, content)
⋮----
// Inline arrow handler (`router.post('/x', async (req,res) => {…})`). The
// arrow is anonymous, so its body — the actual request→service flow — would
// be lost. Attribute the body's calls to the route node as `calls` edges so
⋮----
postExtract(context: ResolutionContext): Node[]
⋮----
// Compose prefixes down the mount tree until nothing changes; a file
// reached at two different paths is ambiguous and dropped.
⋮----
/** Top-level comma split of an argument list, strings and brackets respected. */
function splitTopLevel(args: string): string[]
⋮----
/** `/api` + `/users` → `/api/users`; `/api/` + `/` → `/api`. */
function joinPaths(prefix: string, path: string): string
⋮----
/**
 * The file a mount's last argument names: an inline `require('./x')`, an
 * identifier imported from a project file, or one bound to `require('./x')`
 * in the same file. `x.default` / `x.router` count as `x`.
 */
function mountTarget(expr: string, safe: string, file: string, lang: 'typescript' | 'javascript', context: ResolutionContext): string | null
⋮----
/**
 * Check if a name looks like middleware
 */
function isMiddlewareName(name: string): boolean
⋮----
/**
 * Resolve middleware reference using name-based lookup
 */
/** Node kinds a middleware can be declared as. */
⋮----
function resolveMiddleware(
  name: string,
  context: ResolutionContext,
  fromFile?: string,
): string | null
⋮----
// Try exact name first — the calling file's own first. A middleware is a
// declaration (a function, a value, a class), never the file's import of a
// package (`import cors from 'cors'`) nor a heading or a module node.
⋮----
// Try without Middleware suffix
⋮----
/**
 * Resolve controller method using name-based lookup
 */
function resolveControllerMethod(
  controller: string,
  method: string,
  context: ResolutionContext
): string | null
⋮----
// Look for the method name directly
⋮----
function resolveServiceMethod(
  serviceName: string,
  method: string,
  context: ResolutionContext
): string | null
⋮----
function detectLanguage(filePath: string): 'typescript' | 'javascript'
</file>

<file path="src/resolution/frameworks/fabric.ts">
import type { Node } from '../../types';
import {
  FrameworkExtractionResult,
  FrameworkResolver,
} from '../types';
⋮----
/**
 * Legacy Paper view manager macros — older RN libs (still very common,
 * especially small libs that haven't migrated to Codegen) declare a
 * ViewManager class and expose props via these macros. Both shapes:
 *
 *   RCT_EXPORT_VIEW_PROPERTY(values, NSArray)
 *   RCT_EXPORT_VIEW_PROPERTY(onChange, RCTBubblingEventBlock)
 *   RCT_CUSTOM_VIEW_PROPERTY(text, NSString, RNCMyView) { … }
 *   RCT_REMAP_VIEW_PROPERTY(jsName, nativeKeyPath, NSString)
 *
 * Capture the FIRST argument — that's the JS-visible prop name.
 */
⋮----
/**
 * ObjC `@implementation Foo` extraction. Used to identify the ViewManager
 * class so we can derive a JS-visible component name (strip the `Manager`
 * suffix and a leading `RCT` prefix, both standard conventions).
 */
⋮----
/**
 * Derive the JS-visible component name from a native ViewManager class.
 * Strip a trailing `Manager` (and optionally `ViewManager`) — RN's view
 * registry maps `XXXManager` ↔ JS `<XXX/>` by this convention. The
 * leading `RCT` prefix is also stripped (matches what
 * `defaultObjcModuleName` does for RN's legacy bridge modules).
 */
function deriveComponentNameFromManager(className: string): string
⋮----
// Trim ViewManager > Manager > View, in order.
⋮----
/**
 * Cheap source-level detector — must contain `codegenNativeComponent` to
 * be worth parsing. The presence of that import is the canonical Fabric
 * spec signal.
 */
function isFabricSpec(source: string): boolean
⋮----
// A Paper-era module names its native view the same way:
// segmented-control's `module.exports = requireNativeComponent('RNCSegmentedControl')`.
⋮----
/**
 * Pull the `NativeProps` interface body out of a Fabric spec source.
 * Returns `null` when the interface isn't declared in the expected shape.
 */
function findNativePropsBody(source: string): string | null
⋮----
// Permissive: `export interface NativeProps [extends X, Y] { … }`.
⋮----
/**
 * Parse the NativeProps interface body and return prop names.
 * Each prop is `name?: Type;` or `name: Type;` on its own line.
 * We don't care about types — just the JS-visible name.
 */
function extractPropNames(body: string): string[]
⋮----
// Anchor to start-of-line (after optional whitespace), then capture an
// identifier, then optional `?`, then `:`. Skip lines that look like
// method declarations (`name(`) — those are TurboModule spec methods,
// not view props.
⋮----
// Exclude any line that immediately turns into a function-shape (e.g.
// `onTap?: () => void` is fine — it's a prop, not a method body —
// but a literal `name(arg: T): R` is a method declaration).
⋮----
if (/^\s*\(/.test(after)) continue; // method-shape, skip
⋮----
/**
 * Extract legacy Paper view-manager declarations from a .m/.mm file.
 * Emits a `component` node named after the JS-visible name (derived from
 * the @implementation class) plus a `property` node per
 * `RCT_EXPORT_VIEW_PROPERTY(name, ...)` macro.
 *
 * Returns `[]` if the file doesn't look like a ViewManager (no
 * RCT_EXPORT_VIEW_PROPERTY macros).
 */
function extractLegacyViewManagerNodes(filePath: string, source: string): Node[]
⋮----
// Cheap gate: no view-property macros at all → not a view manager.
⋮----
// Only process actual ViewManagers — classes ending in Manager or
// (legacy) ViewManager. Classes with view-property macros that don't
// follow the naming convention are unusual; skip to keep precision.
⋮----
// Component node — same shape as Codegen Fabric's, so the
// fabricNativeImplEdges synthesizer linking component → native class
// works for legacy too. The native class IS the manager itself in this
// case; the convention-based suffix lookup in the synthesizer
// (`Manager`, `ViewManager`) will find it.
⋮----
// Property nodes per RCT_EXPORT_VIEW_PROPERTY macro.
⋮----
/**
 * Java/Kotlin `@ReactProp("name")` extraction. The annotation precedes a
 * setter method on a class that extends `ViewManager` /
... (24 lines truncated)
</file>

<file path="src/resolution/frameworks/go.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { pickByNameAndKind } from './name-heuristic';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
// The first argument must be URL-shaped, or this is just a method that
// happens to share a verb name — `cache.Put("key", val)`, `store.Get(...)`,
// `bus.Handle("user.created", h)` all polluted the route index (#1259).
// Real registrations use "/path" (every router), or net/http's Go 1.22
// "METHOD /path" patterns on Handle/HandleFunc.
⋮----
// "GET /users/{id}" -> method GET, path /users/{id}
⋮----
/**
 * Go 1.22 net/http mux patterns: `mux.HandleFunc("GET /users/{id}", h)`.
 * Returns the HTTP method when the pattern starts with one, null otherwise.
 * Only Handle/HandleFunc take these — Gin/Chi verb methods take a bare path.
 */
function matchGo122MethodPattern(routePath: string, rawMethod: string): string | null
⋮----
/** Extract the last identifier from an expression like `pkg.Sub.handler` or `handler`. */
function extractGoTailIdent(expr: string): string | null
⋮----
// Directory patterns for framework resolution
⋮----
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kind: string | null,
  preferredDirs: string[],
  context: ResolutionContext,
  kinds?: Set<string>
): string | null
</file>

<file path="src/resolution/frameworks/goframe.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
⋮----
/** Marker embedded in a route node's qualifiedName so the synthesizer can read
 *  back the request type to join on. The value after it is the package-qualified
 *  request type (`cash.ListReq`) — the package disambiguates the many identical
 *  bare names (`ListReq`, `GetReq`) a large app defines, one per module. Falls
 *  back to the bare type when no `package` declaration is found. */
⋮----
detect(context: ResolutionContext): boolean
⋮----
extract(filePath, content)
⋮----
resolve(_ref: UnresolvedRef, _context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/index.ts">
import { FrameworkResolver, ResolutionContext } from '../types';
import type { Language } from '../../types';
import { drupalResolver } from './drupal';
import { laravelResolver } from './laravel';
import { expressResolver } from './express';
import { nestjsResolver } from './nestjs';
import { reactResolver } from './react';
import { nextjsResolver } from './nextjs';
import { reactRouterResolver } from './react-router';
import { tanstackRouterResolver } from './tanstack-router';
import { vueRouterResolver } from './vue-router';
import { angularRouterResolver } from './angular-router';
import { svelteKitRouterResolver } from './sveltekit-router';
import { svelteResolver } from './svelte';
import { vueResolver, nuxtResolver } from './vue';
import { astroResolver } from './astro';
import { djangoResolver, flaskResolver, fastapiResolver } from './python';
import { railsResolver } from './ruby';
import { springResolver } from './java';
import { playResolver } from './play';
import { goResolver } from './go';
import { goframeResolver } from './goframe';
import { rustResolver } from './rust';
import { aspnetResolver } from './csharp';
import { swiftUIResolver, uikitResolver, vaporResolver } from './swift';
import { swiftObjcBridgeResolver } from './swift-objc';
import { reactNativeBridgeResolver } from './react-native';
import { expoModulesResolver, expoModulesJsResolver } from './expo-modules';
import { expoRouterResolver } from './expo-router';
import { fabricViewResolver } from './fabric';
import { cicsResolver } from './cics';
import { terraformResolver } from './terraform';
⋮----
export function getAllFrameworkResolvers(): FrameworkResolver[]
⋮----
export function getFrameworkResolver(name: string): FrameworkResolver | undefined
⋮----
export function detectFrameworks(context: ResolutionContext): FrameworkResolver[]
⋮----
export function getApplicableFrameworks(
  detected: FrameworkResolver[],
  language: Language
): FrameworkResolver[]
⋮----
export function registerFrameworkResolver(resolver: FrameworkResolver): void
</file>

<file path="src/resolution/frameworks/java.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { pickByNameAndKind } from './name-heuristic';
⋮----
claimsReference(name: string): boolean
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
const score = (n: Node) =>
⋮----
extract(filePath, content)
⋮----
// Class-level @RequestMapping prefix (an @RequestMapping whose tail leads to a
// `class`). Joined onto each method's path — and, crucially, NOT treated as a
// route itself (the old regex did, creating one bogus class route and missing
// every BARE method mapping like `@PostMapping` with the path on the class).
⋮----
// Verb-specific method mappings — always method-level, BARE or with a path.
⋮----
// Method it decorates: first declared method after (skip stacked annotations;
// Java puts the return type before the name). Bounded so we don't grab a far one.
⋮----
// Method-level @RequestMapping (older style: `@RequestMapping(value="/x",
⋮----
if (/^\s*(?:@[\w.]+(?:\([^)]*\))?\s*)*(?:public\s+|final\s+|abstract\s+|open\s+|data\s+|sealed\s+)*class\b/.test(after)) continue; // class-level prefix
⋮----
function isSpringConfigFile(filePath: string): boolean
⋮----
/**
 * Parse a Spring config file (YAML or .properties) and emit one `constant`
 * node per LEAF key, with `qualifiedName` = the dotted path. Leaf keys are
 * what `@Value("${k}")` references hit; intermediate keys aren't bound by
 * Spring's `@Value` (a `@ConfigurationProperties` class binds a SUBTREE, and
 * those references are resolved at lookup time by prefix-suffix matching).
 */
function extractSpringConfig(
  filePath: string,
  content: string,
):
⋮----
const emitLeaf = (dottedKey: string, line: number, valueText: string) =>
⋮----
// YAML: indent-based. We track a stack of (indent, key) so the dotted path
// is built by joining ancestor keys with `.`. A leaf is a line with a value
// on the same line (after `:`). List items, flow-style scalars, and `---`
// separators are ignored — they don't bind to `@Value` anyway.
⋮----
// A leaf with an inline value (or a flow-mapping like `{ a: 1 }` — we
// emit it as a leaf, not as a subtree; precision is fine for `@Value`).
⋮----
/** Append `@Value("${k}")` and `@ConfigurationProperties(prefix=...)`
 * references discovered in `safe` (comments stripped) into the caller's
 * `nodes`/`references` arrays. */
function extractSpringValueBindings(
  filePath: string,
  safe: string,
  lang: 'java' | 'kotlin',
  now: number,
  nodes: Node[],
  references: UnresolvedRef[],
): void
⋮----
function canonicalConfigKey(key: string): string
⋮----
// Directory patterns
⋮----
function parseMappingPaths(args: string, consts: Map<string, string>): string[]
⋮----
if (!scope) paths.push(''); // An explicitly empty path array also inherits the prefix.
⋮----
/** Join a class-level prefix and a method sub-path into one normalized `/path`. */
function joinPath(prefix: string, sub: string): string
⋮----
/** A framework name heuristic's pick (see name-heuristic.ts), preferring these folders. */
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kinds: Set<string>,
  preferredDirPatterns: string[],
  context: ResolutionContext,
): string | null
</file>

<file path="src/resolution/frameworks/laravel.ts">
import { posix } from 'path';
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
postExtract(context: ResolutionContext): Node[]
⋮----
function isLaravelRoute(n: Node): boolean
⋮----
interface RouteGroup {
  open: number;
  close: number;
  prefix: string;
  args: string[];
}
⋮----
function routeGroups(safe: string): RouteGroup[]
⋮----
function prefixAt(groups: RouteGroup[], at: number): string
⋮----
function routeFileMounts(
  safe: string,
  file: string,
  context: ResolutionContext
):
⋮----
const add = (expr: string, prefix: string) =>
⋮----
// `require(__DIR__.'/x.php')` — drop parens only when they wrap the whole expression.
⋮----
/**
 * A PHP path expression naming a file in the project: `base_path('routes/x.php')`,
 * `__DIR__.'/../routes/x.php'`, `dirname(__DIR__).'/routes/x.php'` or a bare
 * `'routes/x.php'` literal. Null for anything computed, or not in the index.
 */
function resolvePhpPath(expr: string, file: string, context: ResolutionContext): string | null
⋮----
/** `'admin'` → `admin`; anything that is not a plain string literal → `{prefix}`. */
function literalOrPlaceholder(expr: string): string
⋮----
/**
 * Join route path segments the way Laravel does: `('api', 'v1/', '/users')` →
 * `/api/v1/users`. Leading and trailing slashes don't matter; the root is `/`.
 */
function joinRoutePath(...parts: string[]): string
⋮----
/** Index of the `)` closing the `(` at `open`, skipping PHP strings; -1 if unbalanced. */
function matchParen(s: string, open: number): number
⋮----
/** Top-level comma split of an argument list; strings and brackets respected. */
function splitArgs(args: string): string[]
⋮----
/**
 * Parse a Laravel route handler expression and return the symbol to link.
 *  - `[Class::class, 'method']`  -> `method`
 *  - `'Controller@method'`       -> `method`
 *  - `Class::class`              -> `Class`
 *  - anything else (closure etc) -> null
 */
function extractLaravelHandler(expr: string): string | null
⋮----
const short = (s: string) => s.split('\\').pop()!; // strip namespace
⋮----
// [Class::class, 'method'] → `Class@method` (PRECISE — keep the controller, so
// common action names like `index`/`show` resolve to the RIGHT controller, not
// whichever one name-matching happens to pick first).
⋮----
// 'Controller@method' (possibly namespaced) → `Controller@method`
⋮----
function resolveModelCall(
  className: string,
  methodName: string,
  context: ResolutionContext
): string | null
⋮----
function resolveControllerMethod(
  controller: string,
  method: string,
  context: ResolutionContext
): string | null
</file>

<file path="src/resolution/frameworks/name-heuristic.ts">
import { Node } from '../../types';
import { UnresolvedRef, ResolutionContext } from '../types';
import { isLexicallyReachable, isVisibleAcrossFiles } from '../name-matcher';
⋮----
export interface NamePickOptions {
  sameDirectory?: boolean;
  accept?: (n: Node) => boolean;
}
⋮----
export function pickByNameAndKind(
  ref: UnresolvedRef,
  kinds: ReadonlySet<string>,
  inPreferredDir: (filePath: string) => boolean,
  context: ResolutionContext,
  options: NamePickOptions = {},
): string | null
⋮----
function isNestedType(n: Node, context: ResolutionContext): boolean
</file>

<file path="src/resolution/frameworks/nestjs.ts">
import { Node } from '../../types';
import {
  FrameworkResolver,
  UnresolvedRef,
  ResolvedRef,
  ResolutionContext,
} from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { declaredDependencies } from './package-deps';
⋮----
type JsLang = 'typescript' | 'javascript';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
const addRoute = (
      index: number,
      method: string,
      path: string,
      length: number,
      handler: string | null
): void =>
⋮----
// GraphQL operations: only inside an @Resolver class (disambiguates the
// REST `@Query()` parameter decorator, which lives inside @Controller classes).
⋮----
// WebSocket message handlers, prefixed with the gateway namespace when present.
⋮----
postExtract(context: ResolutionContext): Node[]
⋮----
// Route → what the app adds to it. A RouterModule prefix binds through the
// controller class's line range; the bootstrap's prefix and versioning
⋮----
// ---------------------------------------------------------------------------
// The app's bootstrap: global prefix and URI versioning
⋮----
interface NestAppConfig {
  prefix: string;
  excludes: string[];
  uri: boolean;
  defaultVersion: string | null;
  versionPrefix: string;
}
⋮----
interface NestBootstrap {
  root: string;
  config: NestAppConfig;
}
⋮----
function appRootOf(filePath: string): string
⋮----
/**
 * The config of the app that holds `filePath`: the bootstrap with the longest
 * root above it, else — for a file outside every app, like an Nx `libs/`
 * controller — the app, when there is only one.
 */
function bootstrapFor(bootstraps: readonly NestBootstrap[], filePath: string): NestAppConfig | null
⋮----
// A seed or migration script creates the same app without serving it: the
// bootstrap that configures the app is the one that serves it.
⋮----
/** One version value: `'2'`, `['1', '2']` (the first), `VERSION_NEUTRAL`. */
function versionValue(text: string): string | null
⋮----
/** `setGlobalPrefix` and `enableVersioning` from the file that calls `NestFactory.create`. */
function readBootstrap(safe: string): NestAppConfig
⋮----
/** A route excluded from the global prefix: `health`, `health/(.*)`, `health{/*wildcard}`, `health/*`. */
function isExcluded(path: string, excludes: readonly string[]): boolean
⋮----
/**
 * The version a route is served at: `@Version(…)` among its own decorators,
 * else its controller's (`@Version(…)` on the class, `@Controller({ version })`).
 * Undefined when neither says.
 */
function routeVersion(safe: string, hit: DecoratorHit, scope: ClassScope): string | null | undefined
⋮----
// The class's decorators, on either side of `@Controller`.
⋮----
function decoratorChainStart(safe: string, at: number, floor: number): number
⋮----
function applyAppConfig(route: Node, modulePrefix: string, config: NestAppConfig | null, version: string | null | undefined): Node | null
⋮----
// ---------------------------------------------------------------------------
// Provider resolution conventions
// ---------------------------------------------------------------------------
⋮----
// ---------------------------------------------------------------------------
// Decorator scanning
// ---------------------------------------------------------------------------
⋮----
interface DecoratorHit {
  /** Decorator name without the leading `@` (e.g. `Get`). */
  name: string;
  /** Raw text between the decorator's parentheses. */
  args: string;
  index: number;
... (135 lines truncated)
</file>

<file path="src/resolution/frameworks/nextjs.ts">
import type { Language, Node } from '../../types';
import type { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { dependsOn } from './package-deps';
import {
  HOLE,
  hrefArms,
  defaultExportName,
  firstArgumentText,
  matchRoute,
  parseHrefExpression,
  readHrefViaLocal,
  type HrefLiteral,
  type RouteTable,
} from './expo-router';
⋮----
export interface NextRouteFile {
  kind: 'page' | 'handler' | 'api';
  path: string;
  root: string;
}
⋮----
function nextSegment(seg: string): string
⋮----
export function nextRouteForFile(filePath: string): NextRouteFile | null
⋮----
function languageForFile(filePath: string): Language
⋮----
interface NextTable extends RouteTable {
  roots: string[];
}
⋮----
export function nextRouteTable(context: ResolutionContext): NextTable
⋮----
function hrefSegments(href: HrefLiteral): string[] | null
⋮----
function decode(s: string): string
⋮----
export interface HrefDestination {
  node: Node;
  href: HrefLiteral;
}
⋮----
export function destinationsForHref(href: HrefLiteral, table: RouteTable): HrefDestination[]
⋮----
export function pageForHref(href: HrefLiteral, table: RouteTable): Node | null
⋮----
export function nextNavVerb(name: string): string | null
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
extract(filePath: string, content: string)
⋮----
const lineOf = (index: number): number
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/object-literal.ts">
export function matchBracket(s: string, open: number): number
⋮----
export function skipString(s: string, at: number): number
⋮----
/** Each `{…}` written directly in `[from, to)`, as its own extent. */
⋮----
/** An object's own fields — key to its value text and where the key sits. Nested structures are stepped over. */
export function readFields(s: string, start: number, end: number): Map<string,
</file>

<file path="src/resolution/frameworks/package-deps.ts">
import type { ResolutionContext } from '../types';
⋮----
export function declaredDependencies(context: ResolutionContext): Set<string>
⋮----
export function dependsOn(context: ResolutionContext, ...deps: string[]): boolean
</file>

<file path="src/resolution/frameworks/play.ts">
import { Node } from '../../types';
import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import { isPlayRoutesFile } from '../../extraction/grammars';
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath: string, content: string):
</file>

<file path="src/resolution/frameworks/python.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolutionContext, FrameworkExtractionResult } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { resolveImportPath } from '../import-resolver';
import { pickByNameAndKind } from './name-heuristic';
⋮----
detect(context)
⋮----
resolve(ref, context)
⋮----
claimsReference(name)
⋮----
extract(filePath, content)
⋮----
function resolveModelIterableIter(context: ResolutionContext): string | null
⋮----
function resolveHandlerName(expr: string):
⋮----
// Drop any other trailing method call
⋮----
postExtract(context)
⋮----
interface Mount {
      fromVar: string;
      prefix: string;
      target: { file: string; variable: string };
    }
⋮----
if (!literal && /\bprefix\s*=/.test(rest)) continue; // a computed prefix: unknown, not guessed
⋮----
// The include-derived base of each (file, variable): the mounting router's
⋮----
const key = (file: string, variable: string): string => `$
⋮----
/** `/api/v1` + `/items` → `/api/v1/items`; `/items` + `` → `/items`; `` + `` → ``. */
function joinPyPaths(prefix: string, path: string): string
⋮----
/**
 * The file and variable an `include_router` argument names: `items.router`
 * through the module's import, `items_router` through an alias import, or a
 * router defined in the same file.
 */
function includedRouter(
  expr: string,
  file: string,
  local: Map<string, string>,
  context: ResolutionContext
):
⋮----
interface DecoratorRouteOpts {
  decoratorRegex: RegExp;
  defaultMethod: string;
  methodGroup?: number;
  methodFromGroup?: number;
  pathGroup: number;
  handlerGroup?: number;
  findHandler?: boolean;
  language: 'python';
}
⋮----
function extractDecoratorRoutes(filePath: string, content: string, opts: DecoratorRouteOpts): FrameworkExtractionResult
⋮----
/**
 * Flask-RESTful: `api.add_resource(ResourceClass, '/path'[, '/path2'])`
 * (and variants like redash's `add_org_resource`). The ResourceClass holds the
 * HTTP-verb methods (get/post/…), so the route references the class — its verb
 * methods resolve as the handlers via the class. Method is ANY (the class
 * decides which verbs it serves).
 */
function extractFlaskRestful(filePath: string, safe: string): FrameworkExtractionResult
⋮----
/**
 * Flask's imperative registration: `bp.add_url_rule('/path', 'name',
 * view_func=View.as_view('name'), methods=[…])`, and a project's own wrapper
 * around it — any call handing a list of path strings and a `view_func=`
 * over, like flaskbb's `register_view(auth, routes=["/login"],
 * view_func=Login.as_view("login"))`. A class-based view (`X.as_view(…)`)
 * serves whatever verbs it defines, so its route is ANY unless `methods=`
 * says; a plain function defaults to GET, as Flask does.
 */
function extractFlaskUrlRules(filePath: string, safe: string): FrameworkExtractionResult
⋮----
// `view_func=X` / `view_func=X.as_view(…)`, or add_url_rule's third positional argument.
⋮----
/** The text between an opening `(` at `open` and its matching `)`, or null. Strings are skipped. */
function balancedArgs(text: string, open: number): string | null
⋮----
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kinds: Set<string>,
  preferredDirPatterns: string[],
  context: ResolutionContext,
): string | null
</file>

<file path="src/resolution/frameworks/react-native.ts">
import type { Node } from '../../types';
import {
  FrameworkResolver,
  ResolutionContext,
} from '../types';
⋮----
interface NativeMethod {
  moduleName: string;
  jsName: string;
  node: Node;
}
⋮----
function defaultObjcModuleName(className: string): string
⋮----
function parseObjcRNExports(
  source: string,
  className: string | null
): Array<
⋮----
const lineOf = (idx: number): number =>
⋮----
function findObjcClassName(source: string): string | null
⋮----
export function parseObjcRNExterns(
  source: string
): Array<
⋮----
export function collectNativeModuleAliases(
  source: string,
  aliases: Map<string, string>,
  ambiguous: Set<string>
): void
⋮----
const bind = (alias: string, moduleName: string): void =>
⋮----
function parseJvmRNExports(
  source: string
): Array<
⋮----
// Class name fallback.
⋮----
// @ReactMethod annotations — followed (after optional modifiers / args /
// newlines) by either `void <name>(` (Java) or `fun <name>(` (Kotlin).
⋮----
/**
 * Parse a TS file for a TurboModule spec declaration. The spec file is
 * the JS↔native source-of-truth in the new architecture — its interface
 * lists every JS-visible method, and a `TurboModuleRegistry.get*<Spec>(...)`
 * default export pins the module name.
 *
 * Returns `null` when the file isn't a TurboModule spec.
 */
function parseTurboModuleSpec(
  source: string
):
⋮----
// `TurboModuleRegistry.getEnforcing<Spec>('ModuleName')` or
// `TurboModuleRegistry.get<Spec>('ModuleName')`. The literal must be a
// single-or-double-quoted string.
⋮----
// Find `export interface Spec extends TurboModule { … }` and pull each
// method declaration's name. We don't need types — just names.
⋮----
// Method shape: `name(args): ReturnType;` or `name(): void;`. Skip
// properties (no parens before colon).
⋮----
// ─── Map building ───────────────────────────────────────────────────────────
⋮----
/**
 * RCTEventEmitter built-ins that every emitter subclass inherits. JS code
 * doesn't directly call these — they're internal plumbing for the
 * `NativeEventEmitter` abstraction. If we leave them in the bridge map,
 * every JS `addListener` / `remove` call (Firestore subscribers, RxJS
 * pipelines, plain Array.remove, etc.) gets mis-bridged to whichever
 * emitter happens to define them. Skip during map building.
 */
⋮----
function buildRNMaps(context: ResolutionContext):
⋮----
// Pre-index native methods by name for fast lookup when matching to
// their bridge exports.
⋮----
// Legacy bridge — ObjC side.
⋮----
// Resolve to the native node by selector first-keyword. Multiple
// ObjC methods may share a first keyword across modules; filter by
// file path to attribute the export to this module's
// implementation file.
⋮----
// Swift-backed module: the shim names the class; the implementation is
// the Swift method of that name on the class or one of its extensions.
// Class-scoped, so a same-named method on another Swift type (a
// `syncSettings` on `CaptureSettings` beside the one on `CaptureView`)
// is never the answer.
⋮----
// JS side: the local names bound to `NativeModules.<Module>`.
⋮----
// Legacy bridge — Java/Kotlin side.
⋮----
// TurboModule spec — TS side.
... (41 lines truncated)
</file>

<file path="src/resolution/frameworks/react-router.ts">
import type { Language, Node } from '../../types';
import type { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import { dependsOn } from './package-deps';
import {
  addRouteTo,
  appRootFor,
  firstArgumentText,
  parseHrefExpression,
  readHrefViaLocal,
  routesForFile,
  type RootedRouteTable,
  type RouteTable,
} from './expo-router';
⋮----
import { destinationsForHref } from './nextjs';
import { configHrefExpression } from './react';
⋮----
export type ReactRouterTable = RootedRouteTable;
⋮----
function isReactRouterRoute(node: Node): boolean
⋮----
function isOptionalParam(seg: string): boolean
⋮----
export function reactRouterTable(context: ResolutionContext): ReactRouterTable
⋮----
const tableAt = (root: string): RouteTable =>
⋮----
export function reactRouterNavVerb(name: string): string | null
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/react.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { dependsOn } from './package-deps';
import { resolveImportPath } from '../import-resolver';
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
postExtract(context: ResolutionContext): Node[]
⋮----
interface RoutePart {
  lit?: string;
  expr?: string;
}
⋮----
function composeRoutePath(parts: string[]): string
⋮----
function constantPathValue(expr: string, fromFile: string, context: ResolutionContext): string | null
⋮----
export function configHrefExpression(expr: string, fromFile: string, context: ResolutionContext): string | null
⋮----
// `/auth/login${redirectTo ? … : ''}`: a hole glued to a segment is a suffix, not a segment.
⋮----
/** Remove each `${…}` of a template literal that is not a whole path segment. */
function dropGluedTemplateHoles(template: string): string
⋮----
/** Walk `keys` into the object literal opening at `at`; the final value's source text, or null. */
function readObjectValue(text: string, at: number, keys: string[]): string | null
⋮----
const skipString = (j: number): number =>
const skipValue = (j: number): number =>
⋮----
/** Walk `keys` into the object literal opening at `at`; the string literal at the end, or null. */
function readObjectPath(text: string, at: number, keys: string[]): string | null
⋮----
/** The component a lazy route module renders: its default export, else its `Component` export. */
function lazyRouteComponent(spec: string, fromFile: string, context: ResolutionContext): string | null
⋮----
interface RouteDeclaration {
  path: string;
  parts: RoutePart[];
  component?: string;
  lazy?: string;
  at: number;
}
⋮----
interface RouteScope {
  part: RoutePart;
  at: number;
  end: number;
  component?: string;
  lazy?: string;
  jsx?: boolean;
}
⋮----
function scanRouteDeclarations(source: string, allowJsx: boolean): RouteDeclaration[]
⋮----
const literal = (value: string): string | undefined =>
// A guard or boundary wrapping the screen (`<ProtectedRoute><AppRoot/></ProtectedRoute>`,
// `<Suspense>`) is not what the route renders; the first element inside it is.
⋮----
const componentName = (value: string | undefined, jsx: boolean): string | undefined =>
// The few characters before `at`, trailing whitespace skipped: enough for the
// end-anchored checks below without copying the whole prefix per `/` or `<`.
const tokenBefore = (at: number): string =>
const trivia = (at: number): number =>
function unit(at: number): number
⋮----
// A regex can contain braces or JSX-looking text without ending an expression.
⋮----
// `count<limit` and `factory<Type>()` are not JSX opening tags.
⋮----
function jsx(at: number): number
⋮----
const expression = (name: string) => attrs.get(name)?.replace(/^\
⋮----
// A child route's path is relative to the routes around it: compose each
⋮----
function isPascalCase(str: string): boolean
⋮----
function isBuiltInType(name: string): boolean
⋮----
function resolveComponent(
  name: string,
  fromFile: string,
  context: ResolutionContext
): string | null
⋮----
function isEsmLanguage(language?: string): boolean
⋮----
function resolveHook(name: string, fromFile: string, context: ResolutionContext, language?: string): string | null
⋮----
const nested = (n: Node): boolean
⋮----
function resolveContext(name: string, ref: UnresolvedRef, context: ResolutionContext): string | null
... (3 lines truncated)
</file>

<file path="src/resolution/frameworks/ruby.ts">
import { Node } from '../../types';
import { FrameworkResolver, FrameworkExtractionResult, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
⋮----
claimsReference(name: string): boolean
⋮----
detect(context: ResolutionContext): boolean
⋮----
// Check for config/application.rb (Rails signature)
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
const symList = (s: string)
⋮----
// `resources :articles` → ArticlesController; `resource :user` → UsersController.
⋮----
interface RailsFrame {
  kind: 'namespace' | 'scope' | 'resource' | 'member' | 'collection' | 'block';
  path: string;
  module: string;
  controller?: string;
  collectionPath?: string;
  memberPath?: string;
}
⋮----
function extractScopedRailsRoutes(filePath: string, safe: string): FrameworkExtractionResult
⋮----
const top = ()
const join = (...parts: string[])
const sym = (s: string)
const option = (tail: string, key: string) => new RegExp(`\\b$
const emit = (method: string, path: string, target: string, line: number) =>
⋮----
// A statement whose `[` / `(` continues on the next lines (`only: [\n :a,\n :b ]`).
const open = (t: string)
⋮----
function singularize(w: string): string
⋮----
// RESTful action → HTTP verb + path. `resources` gets all seven; a singular
// `resource` omits `index`.
⋮----
function pluralize(w: string): string
⋮----
function camelize(s: string): string
⋮----
/** Resolve a `controller#action` route ref to the action method in that controller. */
function resolveControllerAction(ctrlPath: string, action: string, context: ResolutionContext): string | null
⋮----
// Rails convention: `articles` → app/controllers/articles_controller.rb.
⋮----
function resolveModel(name: string, context: ResolutionContext): string | null
⋮----
function resolveController(name: string, context: ResolutionContext): string | null
⋮----
function resolveHelper(name: string, context: ResolutionContext): string | null
⋮----
function resolveService(name: string, context: ResolutionContext): string | null
</file>

<file path="src/resolution/frameworks/rust.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { getCargoWorkspaceCrateMap } from './cargo-workspace';
import { isRustNameInScope } from '../name-matcher';
import { pickByNameAndKind } from './name-heuristic';
⋮----
function inRustScope(id: string, ref: UnresolvedRef, context: ResolutionContext): boolean
⋮----
function getCachedCargoWorkspaceCrateMap(context: ResolutionContext): Map<string, string>
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, content)
⋮----
// Actix-web builder API (the dominant actix routing style; attribute macros
// are handled above). The handler lives in `.to(handler)`, not `get(handler)`.
const pushActixRoute = (routePath: string, method: string, handlerExpr: string, line: number) =>
⋮----
// web::resource("/path") { .route(web::METHOD().to(h)) | .to(h) } — possibly chained.
⋮----
// Bound the resource's method chain at the next resource() to avoid bleed.
⋮----
// Direct `.resource("/x").to(handler)` (all methods) when no explicit verb route.
⋮----
// App-level: .route("/path", web::METHOD().to(handler)).
⋮----
// Directory patterns
⋮----
/** Index of the ')' that matches the '(' at openIdx, or -1 if unbalanced. */
function findMatchingParen(s: string, openIdx: number): number
⋮----
/** A framework name heuristic's pick (see name-heuristic.ts): in scope by its `use`s and module paths. */
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kinds: Set<string>,
  preferredDirPatterns: string[],
  context: ResolutionContext,
): string | null
⋮----
interface ModuleResolution {
  targetId: string;
  fromWorkspace: boolean;
}
⋮----
function resolveModule(name: string, context: ResolutionContext): ModuleResolution | null
</file>

<file path="src/resolution/frameworks/svelte.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
extract(filePath, _content)
⋮----
// Only a `+page.svelte` is a URL. A `+layout.svelte` and a `+error.svelte`
// sit at the same path as the page beside them, so emitting a route for
// them put the same address in the index two and three times over — one
// `/` for the page, one for the layout, one for the error page — which the
// Screens picture then drew as three separate screens.
⋮----
function isRuneReference(name: string): boolean
⋮----
function isPascalCase(str: string): boolean
⋮----
function resolveComponent(
  name: string,
  fromFile: string,
  context: ResolutionContext
): string | null
⋮----
function getSvelteKitRouteInfo(fileName: string): string | null
⋮----
function filePathToSvelteKitRoute(filePath: string): string | null
⋮----
// A `(group)` directory shares a layout and never appears in the URL:
// `(app)/(layout)/blocks` is `/blocks`. A parameter's `=matcher` checks
</file>

<file path="src/resolution/frameworks/sveltekit-router.ts">
import type { Language, Node } from '../../types';
import type { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import { dependsOn } from './package-deps';
import {
  addRouteTo,
  appRootFor,
  nthArgumentText,
  parseHrefExpression,
  readHrefViaLocal,
  routesForFile,
  type RootedRouteTable,
  type RouteTable,
} from './expo-router';
import { destinationsForHref } from './nextjs';
⋮----
export type SvelteKitTable = RootedRouteTable;
⋮----
function isSvelteKitPage(node: Node): boolean
⋮----
function isOptionalParam(seg: string): boolean
⋮----
export function svelteKitTable(context: ResolutionContext): SvelteKitTable
⋮----
const tableAt = (root: string): RouteTable =>
⋮----
export function svelteKitHrefArgument(name: string): 0 | 1 | null
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/swift-objc.ts">
import { FrameworkResolver, ResolutionContext, ResolvedRef, UnresolvedRef } from '../types';
import type { Node } from '../../types';
import {
  swiftBaseNamesForObjcSelector,
  isObjcExposed,
} from '../swift-objc-bridge';
⋮----
function buildObjcMap(context: ResolutionContext): Map<string, Node[]>
⋮----
function declarationSourceWindow(node: Node, context: ResolutionContext): string
⋮----
function resolveSwiftCallToObjc(
  ref: UnresolvedRef,
  context: ResolutionContext
): ResolvedRef | null
⋮----
function resolveObjcCallToSwift(
  ref: UnresolvedRef,
  context: ResolutionContext
): ResolvedRef | null
⋮----
detect(context)
⋮----
claimsReference(name)
⋮----
resolve(ref, context)
</file>

<file path="src/resolution/frameworks/swift.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { pickByNameAndKind } from './name-heuristic';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
claimsReference(name: string): boolean
⋮----
extract(filePath, content)
⋮----
const segJoin = (existing: string, segsStr: string): string =>
⋮----
// let X = Y.grouped("a", "b")
⋮----
// Y.group("a") { X in ... }
⋮----
// Vapor: <builder>.METHOD([path segs,] use: handler). Any receiver (app,
// routes, or a grouped var); path segments optional and may be non-string
// (`BlogUser.parameter`, `:id`, a path constant) so accept any comma-separated
// args before `use:` — the label keeps only the string parts. `use:`
// discriminates a real route from Environment.get("X")/req.parameters.get("X").
// Each arg repetition must end at a comma, and `,` is outside the char class,
// so the split is unique and matching stays linear. The earlier
// `(?:[^,()]+,\s*)*` was ambiguous — the trailing `\s*` and the next
// iteration's `[^,()]+` could both claim the same spaces — which backtracked
⋮----
const pathArgs = (argText: string)
⋮----
// A route whose handler is a trailing closure — `app.get("hello") { req in … }`,
// `app.webSocket("chat") { req, ws in … }`, `routes.on(.GET, "x") { … }`. It has
// no handler symbol; the closure's calls belong to the function registering it.
// An HTTP client's `req.client.get("https://…") { … }` is not a route.
⋮----
// A route registration is a statement: `if let v = req.parameters.get("x") {`
// opens the `if` body, not a trailing closure.
⋮----
function vaporHandlerRef(expr: string, receiverTypes: ReadonlyMap<string, string>): string | null
⋮----
function oneOwnersMethod(candidates: Node[], ownerOf: (n: Node) => string, context: ResolutionContext): string | null
⋮----
const earliest = (nodes: Node[])
⋮----
function resolveVaporHandler(typePath: string | null, method: string, ref: UnresolvedRef, context: ResolutionContext): string | null
⋮----
const ownerOf = (n: Node): string
⋮----
function resolveByNameAndKind(
  ref: UnresolvedRef,
  kinds: Set<string>,
  preferredDirPatterns: string[],
  context: ResolutionContext,
): string | null
</file>

<file path="src/resolution/frameworks/tanstack-router.ts">
import type { Language, Node } from '../../types';
import type {
  FrameworkExtractionResult,
  FrameworkResolver,
  ResolutionContext,
  ResolvedRef,
  UnresolvedRef,
} from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { dependsOn } from './package-deps';
import { matchBracket, readFields } from './object-literal';
import {
  addRouteTo,
  appRootFor,
  firstArgumentText,
  parseHrefExpression,
  readHrefViaLocal,
  readStringAt,
  routesForFile,
  toHref,
  type HrefLiteral,
  type RootedRouteTable,
  type RouteTable,
} from './expo-router';
import { destinationsForHref } from './nextjs';
⋮----
export function tanstackPath(raw: string): string | null
⋮----
function isPathlessLayout(raw: string): boolean
⋮----
function isLayoutFile(filePath: string, content: string): boolean
⋮----
function languageForFile(filePath: string): Language
⋮----
export interface TanstackRouteEntry {
  path: string;
  component: string | null;
  index: boolean;
  fileBased: boolean;
  line: number;
}
⋮----
export function parseTanstackRoutes(content: string): TanstackRouteEntry[]
⋮----
const lineOf = (index: number): number
⋮----
function composePath(
  name: string,
  decls: Map<string, { path: string | null; parent: string | null }>
): string | null
⋮----
function chainAfter(s: string, at: number): string
⋮----
function componentIn(text: string): string | null
⋮----
/** The id a TanStack route carries — a verbatim reconstruction, so the table can recognise its own. */
function routeId(filePath: string, line: number, path: string): string
⋮----
export type TanstackTable = RootedRouteTable;
⋮----
function isTanstackRoute(node: Node): boolean
⋮----
export function tanstackTable(context: ResolutionContext): TanstackTable
⋮----
export function tanstackNavVerb(name: string): string | null
⋮----
export function tanstackDestination(expr: string): HrefLiteral | null
⋮----
function toKeyOf(args: string): string | null
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
extract(filePath: string, content: string): FrameworkExtractionResult
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
</file>

<file path="src/resolution/frameworks/terraform.ts">
import type { Node } from '../../types';
import type { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
⋮----
detect(context: ResolutionContext): boolean
⋮----
claimsReference(name: string): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
function nearestAncestorMatch<T extends
⋮----
function resolveScopedModuleRef(
  ref: UnresolvedRef,
  moduleName: string,
  child: string,
  refDir: string,
  context: ResolutionContext
): ResolvedRef | null
⋮----
if (dirs.size > 1) return null; // two directories claim this component name — never guess
⋮----
// Registry / git / absolute sources are out-of-repo: stay unresolved.
⋮----
// child is `var.X` or `output.X` — the child module's own qualified names.
⋮----
/**
 * A direct string-literal attribute (`source = "…"`, `component = "…"`) of a
 * module declaration, re-read from its file (project paths are stored
 * relative; node metadata isn't persisted, so the declaration's line span +
 * cached file lines are the durable carrier). Non-literal values (variables,
 * expressions) return null — dynamic wiring is never guessed.
 */
function readModuleAttr(decl: Node, name: string, context: ResolutionContext): string | null
⋮----
/** First capture of `re` across the node's line span, or null. */
function readNodeSpanMatch(node: Node, re: RegExp, context: ResolutionContext): string | null
⋮----
function dirOf(p: string): string
⋮----
/** Parent directory, or null above the project root. */
function parentOf(dir: string): string | null
⋮----
/** Join a base directory with a `./`/`../` relative source path. */
function joinDirs(base: string, rel: string): string
⋮----
/** Normalize to the stored path shape: forward slashes, '.' for the root. */
function normalizeRel(p: string): string
</file>

<file path="src/resolution/frameworks/vue-router.ts">
import type { Language, Node } from '../../types';
import type {
  FrameworkExtractionResult,
  FrameworkResolver,
  ResolutionContext,
  ResolvedRef,
  UnresolvedRef,
} from '../types';
import { stripCommentsForRegex } from '../strip-comments';
import { matchBracket, readFields, topLevelObjects } from './object-literal';
import { dependsOn } from './package-deps';
import {
  addRouteTo,
  appRootFor,
  firstArgumentText,
  parseHrefExpression,
  readHrefViaLocal,
  readStringAt,
  routesForFile,
  toHref,
  type HrefLiteral,
  type RootedRouteTable,
  type RouteTable,
} from './expo-router';
import { destinationsForHref } from './nextjs';
import { resolveImportPath } from '../import-resolver';
⋮----
export interface VueRouteEntry {
  path: string;
  name: string | null;
  component: string | null;
  spec: string | null;
  layouts: VueLayout[];
  line: number;
}
⋮----
export interface VueLayout {
  component: string;
  spec: string | null;
}
⋮----
/** A file in a `router/` or `routes/` directory, or named `router.js` / `routes.ts`. */
⋮----
/**
 * Where a routes table starts: a `routes: [` field, or a declaration named
 * for what it holds — `export const constantRoutes = [`, `const routes:
 * RouteRecordRaw[] = [`, vue-element-admin's per-module `const tableRouter = {`.
 */
⋮----
/**
 * Every route a file's routes tables declare.
 *
 * The tables are walked, not pattern-matched: a `name` is written ABOVE the
 * `path` it belongs to, so reading fields out of a window around each `path`
 * hands an entry its PREDECESSOR's name — vue-realworld's `login` came out as
 * `/register`, silently, for every route in the file. So each `{…}` is
 * matched as a unit and only its own depth-1 fields are read; a `meta: {…}`
 * and a lazy `component: () => import(…)` are stepped over rather than
 * searched, and `children` are walked in turn with the parent's path in front
 * of theirs.
 *
 * A route with children is a layout: its component renders the outlet they
 * fill. It is a screen of its own only when no child claims its address and
 * it does not `redirect` elsewhere — vue-element-admin's `{ path: '/table',
 * component: Layout, redirect: '/table/complex-table', children }` is the
 * frame around four tables, not a fifth page.
 *
 * A top-level entry whose path does not start with `/` (`*`, a catch-all) is
 * not an address. A table is read from a file that builds a router, imports
 * `vue-router`, or lives in a `router/` directory.
 */
export function parseVueRoutes(content: string, filePath = ''): VueRouteEntry[]
⋮----
const lineOf = (at: number)
⋮----
const visit = (obj:
⋮----
else if (prefix === null) return; // a top-level `*` or relative path is no address
⋮----
/** The component an entry names: an identifier, or the file a lazy import names. */
function componentOf(value: string): VueLayout | null
⋮----
function languageForFile(filePath: string): Language
⋮----
function routeId(filePath: string, line: number, path: string): string
⋮----
export interface VueAppRoutes extends RouteTable {
  byName: Map<string, Node>;
}
⋮----
export type VueRouteTable = RootedRouteTable<VueAppRoutes>;
⋮----
function isVueConfigRoute(node: Node): boolean
⋮----
function isNuxtPage(node: Node): boolean
⋮----
export function vueRouteTable(context: ResolutionContext): VueRouteTable
⋮----
const tableAt = (root: string): VueAppRoutes =>
⋮----
... (32 lines truncated)
</file>

<file path="src/resolution/frameworks/vue.ts">
import { Node } from '../../types';
import { FrameworkResolver, UnresolvedRef, ResolvedRef, ResolutionContext } from '../types';
import { dependsOn } from './package-deps';
⋮----
detect(context: ResolutionContext): boolean
⋮----
resolve(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
resolve(): ResolvedRef | null
⋮----
extract(filePath: string, _content: string)
⋮----
.replace(/\.[^/.]+$/, '') // Remove extension
.replace(/(?:^|\/)index$/, '') // index -> parent path
⋮----
function isPascalCase(str: string): boolean
⋮----
function resolveComponent(
  name: string,
  fromFile: string,
  context: ResolutionContext
): string | null
⋮----
const componentIn = (file: string): string | null =>
⋮----
function filePathToNuxtRoute(normalized: string, afterPagesStart: number): string | null
⋮----
// Remove /index suffix (index.vue -> parent route)
⋮----
// Convert Nuxt param syntax [param] to :param
</file>

<file path="src/resolution/alias-binding.ts">
import type { Node } from '../types';
import type { ResolutionContext } from './types';
import { resolveObjectLiteralBinding } from './name-matcher';
⋮----
function escapeRegExp(s: string): string
⋮----
export function aliasTargetName(
  signature: string | undefined | null,
  memberName: string | null
): string | null
⋮----
export function resolveAliasBinding(
  aliasNode: Node,
  memberName: string | null,
  context: ResolutionContext
): Node | null
⋮----
export function extractLocalExportAliases(content: string): Array<
</file>

<file path="src/resolution/angular-template-synthesizer.ts">
import type { Edge, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { isTestPath } from '../search/query-utils';
import { stripCommentsForRegex } from './strip-comments';
import { matchBracket, readFields, skipString } from './frameworks/object-literal';
import { dependsOn } from './frameworks/package-deps';
import { appRootFor, HOLE, toHref, type HrefLiteral } from './frameworks/expo-router';
import { destinationsForHref } from './frameworks/nextjs';
import { angularDestination, angularRouteTable, angularRoutesFor, namesSomewhere, staticString, templatePathFor } from './frameworks/angular-router';
⋮----
interface AngularComponent {
  node: Node;
  file: string;
  selectors: string[];
  template: { file: string; text: string; firstLine: number; inline: boolean } | null;
}
⋮----
const lineOfOffset = (text: string, at: number): number =>
⋮----
function componentsIn(file: string, content: string, nodes: readonly Node[], ctx: ResolutionContext): AngularComponent[]
⋮----
export function angularComponents(ctx: ResolutionContext): AngularComponent[]
⋮----
/** `(click)="save()"` / `(ngSubmit)="submitForm()"` — an event binding, not `[(ngModel)]`'s two-way half. */
⋮----
/** A call a template statement makes on its component: `save()`, `this.toggle(item)` — not `form.reset()`. */
⋮----
/** The element a binding at `at` is written on: the last opening tag before it. */
function elementAt(text: string, at: number): string | null
⋮----
/** A `routerLink:` field of an object literal written in a class. */
⋮----
/** An object field's value text from `at`, up to its `,` or closing brace at depth 0. */
function fieldValue(text: string, at: number): string | null
⋮----
function plainHref(value: string): HrefLiteral | null
⋮----
export async function angularTemplateEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
const childFor = (tag: string, parent: AngularComponent): AngularComponent | null =>
⋮----
const siteLine = (at: number)
const registeredAt = (at: number) => `$
</file>

<file path="src/resolution/c-fnptr-synthesizer.ts">
import type { Edge, Node } from '../types';
import type { QueryBuilder } from '../db/queries';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { memoryBudgetBytes } from './memory-budget';
import { LRUCache } from './lru-cache';
import { stripCommentsForRegex } from './strip-comments';
import { getKernel } from '../extraction/kernel/loader';
import type { CfnptrFactsOut, CfnptrFileIn } from '../extraction/kernel/loader';
⋮----
interface FieldInfo {
  name: string;
  index: number;
  isFnPtr: boolean;
  type: string;
}
⋮----
interface RawFieldDecl {
  name: string | null;
  index: number;
  ptr: boolean;
  type: string;
}
⋮----
function sliceLinesPre(lines: string[], startLine?: number, endLine?: number): string
⋮----
function matchBrace(src: string, open: number): number
⋮----
function splitTopLevel(body: string, sep: string): string[]
⋮----
function matchParen(src: string, open: number): number
⋮----
interface MacroDef {
  params: string[];
  expansion: string;
}
⋮----
function parseFunctionMacros(stripped: string): Map<string, MacroDef>
⋮----
function parseObjectMacros(stripped: string): Map<string, string>
⋮----
function parseDefinedNames(stripped: string): Set<string>
⋮----
function evalConditionals(text: string, defined: Set<string>): string
⋮----
const activeNow = (): boolean
const condDefined = (expr: string): boolean | null =>
⋮----
const cond = c === null ? true : c; // unevaluable → keep
⋮----
if (!activeNow()) lines[i] = ''; // blank an inactive line (keep the newline)
⋮----
function resolveTypeName(name: string, objEnv: Map<string, string> | undefined): string
⋮----
function substituteMacro(def: MacroDef, args: string[]): string
⋮----
/**
 * Expand known function-like macro calls in `text` to a fixpoint (depth-capped).
 * `MAKE_CMD("get",…,getCommand,…)` → the positional value list whose slots line
 * up with the struct's fields, so the existing positional registration can read
 * `getCommand` straight out of the `proc` slot.
 */
function expandMacroCalls(text: string, env: Map<string, MacroDef>): string
⋮----
/** Included files worth scanning for registration tables (e.g. a generated `.def`). */
⋮----
/** `#define NAME single_identifier` (possibly `struct`-prefixed) — an
 *  object-macro that COULD alias a struct type name (`resolveTypeName`'s exact
 *  value shape). The extraction sweep collects every such NAME into a global
 *  set: an initializer type token that direct-misses the struct layouts still
 *  survives the registration filter when it is alias-SHAPED anywhere, so the
 *  per-file macro-env alias resolution (redis' `COMMAND_STRUCT`) keeps working
 *  without retaining per-file object-macro tables (6.1M `#define`s on the
 *  Linux tree — the amdgpu register headers — rule that out). Numeric values
 *  are excluded: `resolveTypeName` would rewrite to a dead-end token that can
 *  never name a struct, so skipping them is exact, and it drops the register
 *  flood. */
⋮----
/** `(?:struct )?TYPE name[opt] = {` initializers, where TYPE is a struct that
 *  has ≥1 fn-pointer field. Handles both single (`= {…}`) and array
 *  (`[] = { {…}, {…} }`) forms. Macro calls inside an element are expanded first. */
⋮----
/** `struct TAG { … } var[opt] [= {…}]` — the struct is defined INLINE with the
 *  table (vim's `cmdname`/`nv_cmd`); its layout never became a node, so parse it
 *  here and register it before reading the entries. No leading anchor: a
 *  `struct TAG {` with a brace body is always a definition (it may be preceded
 *  by a `#define …` line ending in a digit, as in vim), and the trailing
 *  `var … = {` check below is what distinguishes a TABLE from a plain type. */
⋮----
/** `(?:static …)* ELEMTYPE [*] name[…] = { … }` — a bare array of function
 *  pointers (no struct wrapper). The optional `*` covers a function-TYPE
 *  typedef element (`opcode_t *opcodes[]`); a function-pointer typedef element
 *  (`zend_rc_dtor_func_t t[]`) needs none. The typedef-set membership gate
 *  is what separates this from a plain data/struct array. */
⋮----
/** Dispatch sites: `base->…->field(` or `base.…field(` where `field` is a known
 *  fn-pointer field. The base may be a chain (`c->cmd->proc`) or carry array
 *  subscripts (`cmdnames[i].cmd_func`). An optional `)` before the call covers
 *  the parenthesized form `(cmdnames[i].cmd_func)(&ea)` vim uses. */
⋮----
... (189 lines truncated)
</file>

<file path="src/resolution/callback-synthesizer.ts">
import type { Edge, Language, Node, NodeKind } from '../types';
import type { QueryBuilder } from '../db/queries';
import type { ResolutionContext } from './types';
import { isGeneratedFile } from '../extraction/generated-detection';
import { stripCommentsForRegex } from './strip-comments';
import { cFnPointerDispatchEdges } from './c-fnptr-synthesizer';
import { goframeRouteEdges } from './goframe-synthesizer';
import { expoRouterReturnEdges } from './expo-router-synthesizer';
import { nextLinkEdges } from './next-router-synthesizer';
import { reactRouterLinkEdges } from './react-router-synthesizer';
import { tanstackLinkEdges } from './tanstack-router-synthesizer';
import { vueRouterLinkEdges } from './vue-router-synthesizer';
import { angularTemplateEdges } from './angular-template-synthesizer';
import { svelteKitLinkEdges, svelteKitPageComponentEdges } from './sveltekit-synthesizer';
import { createYielder, type MaybeYield } from './cooperative-yield';
import { crossTierEdges, hasCrossTierPattern, hasTestRequestPattern, testRequestEdges } from './tier-synthesizer';
import { enclosingFn, makeLineAt } from './synth-utils';
import { resolveImportPath } from './import-resolver';
import { crossesCodeBoundary } from './name-matcher';
⋮----
// Composable/hook destructure: `const { close: closeSidebar } = useSidebarControl()`.
// Captures the destructure body + the called composable; only `use*` calls qualify.
⋮----
// Closure-collection dynamic dispatch (language-agnostic, Swift-first). A method
// appends a closure to a collection property; another method iterates that
// property *invoking each element* (`coll.forEach { $0() }` / `{ it() }`). The
// element-invoke (`$0(` / `it(`) PROVES the collection holds closures, so pairing
// a dispatcher to same-named registrars (`.append`/`.add`/`.push`/`.insert`,
// incl. Swift `prop.write { $0.append }`) is high-precision. Cross-file/class by
// design: Alamofire appends in `DataRequest.validate` but iterates in the base
// `Request.didCompleteTask` — neither same-file nor same-class pairing reaches it.
⋮----
const CC_FANOUT_CAP = 8; // skip a field name with more dispatchers/registrars than this (too generic to pair confidently)
// The dispatcher gate — `{ $0( ` / `{ it( ` element-invocation — is Swift/Kotlin
// trailing-closure syntax, so ONLY those languages can ever contribute a
// dispatcher, and a cross-language registrar pairing (a JS `.push(` against a
// Swift dispatcher's field name) would be a wrong edge, not a missed one.
// Gating both sides here isn't just precision: `.push(`/`.add(` is everywhere
// in JS/PHP, so an ungated scan slices + regexes nearly every function on repos
// where the pass cannot emit a single edge — on a 12k-file PHP/JS app that was
// 20+ minutes of the "Resolving refs" tail and a #850 watchdog kill (#1235).
⋮----
function kebabToPascal(s: string): string
⋮----
/**
 * Nuxt auto-import name for a component, derived from its path UNDER `components/`:
 * `components/media/Card.vue` → `MediaCard`, `components/base/foo/Bar.vue` →
 * `BaseFooBar`. Each directory segment and the filename is PascalCased and
 * concatenated; a directory whose PascalCase name prefixes the next segment is
 * collapsed (Nuxt's de-dup: `base/BaseButton.vue` → `BaseButton`, not
 * `BaseBaseButton`). Returns null for a flat component (`components/NavBar.vue`)
 * — its node is already named by basename, so a direct tag match finds it.
 */
function nuxtComponentName(filePath: string): string | null
⋮----
function sliceLines(content: string, startLine?: number, endLine?: number): string | null
⋮----
function registrarField(src: string): string | null
⋮----
function dispatcherField(src: string): string | null
⋮----
async function fieldChannelEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
async function closureCollectionEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
const addReg = (field: string | undefined, node: Node, absLine: number) =>
⋮----
async function eventEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
async function reactRenderEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
async function flutterBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
async function arkuiStateBuildEdges(queries: QueryBuilder, ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
async function arkuiEmitterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
interface Site { nodeId: string; file: string; line: number }
⋮----
const moduleScopeOf = (file: string): string =>
⋮----
/**
 * Phase 4b-ets3: HarmonyOS page navigation. `router.pushUrl({ url:
 * 'pages/Detail' })` reaches the `@Entry struct` of
 * `<module>/src/main/ets/pages/Detail.ets`, but the hop is a string — no
 * static edge — so "tap → openDetail → ???" ends at the router call. Bridge
 * literal urls to the page struct: the url resolves against the standard
 * `src/main/ets/` layout (what main_pages.json entries name); candidates
 * prefer the caller's own workspace module (routes are module-scoped), and
 * anything still ambiguous is dropped rather than guessed. Only `@Entry`
 * structs qualify as targets — the decorator is what makes a file a page.
 */
async function arkuiRouterEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
if (candidates.length !== 1) continue; // ambiguous or unresolved — never guess
⋮----
/**
 * Phase 4c: C++ virtual override. A call through a base/interface pointer
 * (`db->Get(...)`, `iter->Next()`) dispatches at runtime to a subclass override,
 * but that hop is a vtable indirection — no static call edge — so a flow stops at
... (624 lines truncated)
</file>

<file path="src/resolution/cooperative-yield.ts">
export type MaybeYield = () => Promise<void> | undefined;
⋮----
export function createYielder(budgetMs: number = DEFAULT_YIELD_BUDGET_MS): MaybeYield
</file>

<file path="src/resolution/cpp-constructor.ts">
import type { Node } from '../types';
import type { ResolvedRef, ResolutionContext, UnresolvedRef } from './types';
⋮----
export function isCppConstructorRef(ref: UnresolvedRef): boolean
⋮----
function constructorShape(signature: string | undefined):
⋮----
// Split on top-level commas only: `std::map<K, V>`, `int (*cb)(int, int)`
// and `T x = f(a, b)` all nest their commas.
⋮----
// A comparison in a default argument would be mistaken for a `=` default
// or a template bracket — leave those to a compiler.
⋮----
// Strip an optional parameter name, retaining unnamed built-in types
// (`unsigned int`, `long long`) and qualifiers. Complex declarators stay
// distinct unless their spelling matches; uncertainty must not merge overloads.
⋮----
export function matchCppConstructor(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
// Innermost lexical namespace first, then outward, then global.
⋮----
// A prototype and its out-of-line definition describe one overload.
// Merge their admissible ranges, then prefer the executable definition.
</file>

<file path="src/resolution/cpp-macro-visibility.ts">
import { maskCppRawStrings } from '../extraction/languages/c-cpp';
import { CPP_DEFINE_SIGNATURE, type ResolutionContext, type UnresolvedRef } from './types';
import { resolveImportPath } from './import-resolver';
⋮----
type Truth = boolean | undefined;
type FileEvent =
  | { kind: 'define' | 'undef'; name: string; line: number; functionLike: boolean; value: string; wrapsItself: boolean }
  | { kind: 'include'; quote: string; spec: string; line: number }
  | { kind: 'branch'; op: string; expression: string; guard: boolean; line: number }
  | { kind: 'once'; line: number };
type Event = { line: number; defined: Truth };
type Cache = {
  summaries: Map<string, FileEvent[]>;
  includes: Map<string, string | null>;
  byBasename: Map<string, string[]> | null;
  roots: Map<string, Map<string, Event[]>>;
};
⋮----
const and = (a: Truth, b: Truth): Truth
const or = (a: Truth, b: Truth): Truth
const not = (a: Truth): Truth
⋮----
export function clearCppMacroVisibility(context: ResolutionContext): void
⋮----
const isDefine = (n:
⋮----
/**
 * Is this C/C++ `calls` ref a macro expansion rather than a call? True when
 * the index knows the name as a function-like macro (extraction mints a
 * `constant` per `preproc_function_def`) and either nothing but macros bears
 * the name — there is no function to call, and a case-insensitive fuzzy
 * match (`SWAP` → `swap`) must not invent one — or the macro is definitely
 * visible at the call site.
 */
export function isVisibleCppMacro(ref: UnresolvedRef, context: ResolutionContext): boolean
⋮----
function cacheFor(context: ResolutionContext): Cache
⋮----
function summarize(file: string, context: ResolutionContext, cache: Cache): FileEvent[]
⋮----
/**
 * The file's lines with comments removed — only as far as the preprocessor
 * needs: a line inside a block comment is blank, a directive line loses its
 * trailing `//` / `/* … *\/`, and every other line is kept verbatim (its
 * content is never read, only whether a block comment opens on it). The
 * generic comment stripper is a regex pass over the whole file and this walk
 * touches every header of a translation unit, vendor trees included.
 */
function directiveLines(source: string): string[]
⋮----
/** Does the body of the `#define NAME(` at `index` (continuation lines included) call `NAME`? */
function callsItself(lines: string[], index: number, name: string): boolean
⋮----
/**
 * The include-guard idiom: `#ifndef X_H` (or `#if !defined(X_H)`) whose next
 * directive is `#define X_H`. Nothing in the file defines the guard before
 * the test, so this is the first inclusion and the guarded body is active.
 * The same shape around a fallback function-like macro (`#ifndef MIN` /
 * `#define MIN(a, b) …`) is read the same way. A default VALUE
 * (`#ifndef ENABLE_X` / `#define ENABLE_X 0`) is not: that is the flag a
 * build overrides on the command line, so it stays unknown.
 */
function guardsItself(lines: string[], index: number, op: string, expression: string): boolean
⋮----
function resolveInclude(
  file: string,
  quote: string,
  spec: string,
  language: UnresolvedRef['language'],
  context: ResolutionContext,
  cache: Cache
): string | null
⋮----
function walkTranslationUnit(
  rootFile: string,
  language: UnresolvedRef['language'],
  context: ResolutionContext,
  cache: Cache
): Map<string, Event[]>
⋮----
const condition = (expression: string): Truth =>
const scan = (file: string, inherited: Truth, includeLine?: number): void =>
</file>

<file path="src/resolution/expo-router-synthesizer.ts">
import type { Edge, Language, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { stripCommentsForRegex } from './strip-comments';
import {
  matchRoute,
  normalizeHrefPath,
  readStringAt,
  routeTable,
  stringEnd,
  toHref,
} from './frameworks/expo-router';
⋮----
interface NavSite {
  file: string;
  line: number;
  method: string;
  callee: string;
}
⋮----
export async function expoRouterReturnEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
function resolveHelper(site: NavSite, ctx: ResolutionContext): Node | null
⋮----
function screensInBody(
  helper: Node,
  ctx: ResolutionContext,
  table: ReturnType<typeof routeTable>
): Array<
</file>

<file path="src/resolution/go-module.ts">
export interface GoModule {
  modulePath: string;
  rootDir: string;
}
⋮----
export function loadGoModule(projectRoot: string): GoModule | null
⋮----
// Strip optional quoting around the module path.
</file>

<file path="src/resolution/goframe-synthesizer.ts">
import type { Edge, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { GOFRAME_ROUTE_MARKER } from './frameworks/goframe';
⋮----
function pointerParamTypes(sig: string): string[]
⋮----
function addonRoot(p: string): string
⋮----
/**
 * Pick the one handler for a route from same-request-type candidates. Usually a
 * single candidate. When several share the request type (a cloned addon module),
 * keep controller-dir methods, then the one in the route's own module (core route
 * → core handler, addon route → that addon's handler). Ambiguity left over ⇒ no
 * edge (silent beats wrong).
 */
function selectHandler(candidates: Node[], routeFile: string): Node | null
⋮----
export async function goframeRouteEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
</file>

<file path="src/resolution/import-resolver.ts">
import { Language, Node } from '../types';
import { UnresolvedRef, ResolvedRef, ResolutionContext, ImportMapping, ReExport } from './types';
import { applyAliases } from './path-aliases';
import { extractLocalExportAliases } from './alias-binding';
import { resolveWorkspaceImport } from './workspace-packages';
import {
  resolveMethodOnType,
  resolveObjectLiteralMember,
  resolveObjectLiteralBinding,
  localReceiverTypePatterns,
  normalizeInferredTypeName,
} from './name-matcher';
⋮----
export function isNixPathImportRef(ref: UnresolvedRef): boolean
⋮----
/**
 * Resolve an import path to an actual file
 */
// Per-context memos for the two hottest pure lookups on the resolution path:
// import-specifier → file resolution and exported-symbol lookup. Both are pure
// given a stable file set + node table, which is exactly the window between
// ReferenceResolver.clearCaches() calls — clearImportResolverMemos() is invoked
// there, so the staleness discipline matches the resolver's own caches.
⋮----
/**
 * Per-file index of exported symbols, replacing repeated linear `.find`s over
 * `getNodesInFile` arrays (a barrel-heavy repo scans its biggest files once
 * per referencing symbol otherwise). First-wins insertion preserves exactly
 * the array-order semantics of the `.find` calls it replaces.
 *
 * Built from the file's exported rows alone: every worker of the resolver
 * pool builds its own index for each file an import reaches, and decoding
 * whole files there cost more than resolving through them. The two answers
 * that need more — the default-export binding and names a local export
 * clause introduces — read the source and name-targeted rows on first use.
 */
interface FileExportIndex {
  /** Exported declarations by name. Read through {@link exportedByName}. */
  byName: Map<string, Node>;
  defaultComponent: Node | undefined;
  defaultFnClass: Node | undefined;
  /**
   * The node an `export default NAME` statement names, exported at its
   * declaration or not — the precise answer where `defaultFnClass` is a
   * guess. `const Home = () => …; export default Home` and the namespace
   * object `const UploadApi = { uploadARCapture }; export default UploadApi`
   * are both invisible to the `isExported` index above: neither declaration
   * has an `export_statement` ancestor. `undefined` until first read through
   * {@link defaultExportBindingNode}; `null` when there is none.
   */
  defaultBinding?: Node | null;
  /**
   * Names a local export clause (`export { impl as alias }`) binds to a
   * declaration the extractor never flagged isExported, for names not in
   * `byName`. `undefined` until first read through {@link exportedByName}.
   */
  clauseAliases?: Map<string, Node>;
}
⋮----
/** Exported declarations by name. Read through {@link exportedByName}. */
⋮----
/**
   * The node an `export default NAME` statement names, exported at its
   * declaration or not — the precise answer where `defaultFnClass` is a
   * guess. `const Home = () => …; export default Home` and the namespace
   * object `const UploadApi = { uploadARCapture }; export default UploadApi`
   * are both invisible to the `isExported` index above: neither declaration
   * has an `export_statement` ancestor. `undefined` until first read through
   * {@link defaultExportBindingNode}; `null` when there is none.
   */
⋮----
/**
   * Names a local export clause (`export { impl as alias }`) binds to a
   * declaration the extractor never flagged isExported, for names not in
   * `byName`. `undefined` until first read through {@link exportedByName}.
   */
⋮----
/** The identifier `export default NAME` names in a JS-family file, or null. */
function defaultExportBinding(filePath: string, context: ResolutionContext): string | null
⋮----
/**
 * `module.exports = …` (also `exports = module.exports = …`): the name it
 * binds (`createApplication`, `function name(`, `class Name`) or the module
 * it forwards (`require('./lib/express')`), or null.
 */
⋮----
function commonJsDefaultExport(filePath: string, context: ResolutionContext):
⋮----
function getFileExportIndex(filePath: string, context: ResolutionContext): FileExportIndex
⋮----
/** The file's nodes named `name`, in `getNodesInFile` order. */
function nodesInFileNamed(filePath: string, name: string, context: ResolutionContext): Node[]
⋮----
/** The declaration `export default NAME` names in this file (see FileExportIndex.defaultBinding). */
function defaultExportBindingNode(filePath: string, idx: FileExportIndex, context: ResolutionContext): Node | undefined
⋮----
/** What this file exports as `name`: an exported declaration, else a local export clause's binding. */
function exportedByName(filePath: string, idx: FileExportIndex, name: string, context: ResolutionContext): Node | undefined
⋮----
// Bind names introduced by a local export clause to their declarations, so
... (413 lines truncated)
</file>

<file path="src/resolution/index.ts">
import { Language, Node, UnresolvedReference, Edge } from '../types';
import { QueryBuilder } from '../db/queries';
import { SynthesisStage } from '../db/synthesis-stage';
import {
  UnresolvedRef,
  ResolvedRef,
  ResolutionResult,
  ResolutionContext,
  FrameworkResolver,
  ImportMapping,
  isSupertypeTarget,
  isInheritanceRef,
  isImportableKind,
  CPP_DEFINE_SIGNATURE,
} from './types';
import { matchJsStoreBindingCall, isUnresolvedJsMemberCall, isVisibleAcrossFiles, matchReference, matchFunctionRef, matchDottedCallChain, matchScopedCallChain, matchMethodCall, sameLanguageFamily, crossesCodeBoundary, gateLanguageMatch, dumpNameMatcherProfile, clearNameMatcherMemos, isRustNameInScope, CASE_INSENSITIVE_LANGUAGES } from './name-matcher';
import { isVisibleCppMacro, clearCppMacroVisibility } from './cpp-macro-visibility';
import { isCppConstructorRef, matchCppConstructor } from './cpp-constructor';
import { gateSwiftTypeTarget, clearSwiftTypeVisibility, swiftExtendedConformances } from './swift-type-visibility';
import { gateTypeParameter, clearTypeParameterMemos } from './type-parameters';
import { resolveViaImport, resolvePhpImportedStaticCall, resolveJvmImport, extractImportMappings, extractReExports, loadCppIncludeDirs, isPhpIncludePathRef, isCobolCopybookRef, isNixPathImportRef, isBoundToOutOfRepoImport, clearImportResolverMemos, resolveImportPath, isExternalImport } from './import-resolver';
import { ResolverPool, minRefsForPool } from './resolver-pool';
import { resolveAliasBinding } from './alias-binding';
import { detectFrameworks } from './frameworks';
import { synthesizeCallbackEdges } from './callback-synthesizer';
import { createYielder, type MaybeYield } from './cooperative-yield';
import { MAX_SOURCE_FILE_SIZE_BYTES } from '../file-limits';
import { loadProjectAliases, type AliasMap } from './path-aliases';
import { loadGoModule, type GoModule } from './go-module';
import { loadWorkspacePackages, type WorkspacePackages } from './workspace-packages';
import { logDebug } from '../errors';
import { lexicalPathWithinRoot } from '../utils';
import type { ReExport } from './types';
import { LRUCache } from './lru-cache';
import { JS_BUILT_INS } from './js-builtins';
import { builtinModules } from 'module';
import { parse as parseJsonc } from 'jsonc-parser';
⋮----
function resolveCacheLimit(): number
⋮----
export class ReferenceResolver
⋮----
private advanceSupertypeGeneration(): void
⋮----
constructor(projectRoot: string, queries: QueryBuilder)
⋮----
initialize(): void
⋮----
runPostExtract(): number
⋮----
warmCaches(): void
⋮----
async warmCachesYielding(onYield: MaybeYield): Promise<void>
⋮----
private nodeById(id: string): Node | null
⋮----
clearCaches(): void
⋮----
private readFileCached(filePath: string): string | null
⋮----
private fileContains(filePath: string, needle: string): boolean
⋮----
private createContext(): ResolutionContext
⋮----
resolveAll(
    unresolvedRefs: UnresolvedReference[],
    onProgress?: (current: number, total: number) => void
): ResolutionResult
⋮----
private hasAnyPossibleMatchIgnoringCase(name: string): boolean
⋮----
private hasAnyPossibleMatch(name: string): boolean
⋮----
private matchesAnyImport(ref: UnresolvedRef): boolean
⋮----
resolveOne(ref: UnresolvedRef): ResolvedRef | null
⋮----
private resolveOneInner(ref: UnresolvedRef): ResolvedRef | null
⋮----
// PHP, Pascal, CFML, COBOL and VB.NET names ignore case: `formatprice()`
// calls `FormatPrice`, which the exact-name set never lists.
⋮----
createEdges(resolved: ResolvedRef[]): Edge[]
⋮----
private static partitionResolvedCleanup(resolved: ResolvedRef[]):
⋮----
private static partitionFailedCleanup(unresolved: UnresolvedRef[]):
⋮----
private nonDeferredFailures(unresolved: UnresolvedRef[]): UnresolvedRef[]
⋮----
private deferReference(ref: UnresolvedRef, queue: UnresolvedRef[]): void
⋮----
resolveAndPersist(
    unresolvedRefs: UnresolvedReference[],
    onProgress?: (current: number, total: number) => void
): ResolutionResult
⋮----
async resolveAndPersistListYielding(refs: UnresolvedReference[]): Promise<ResolutionResult>
⋮----
private async persistResolutionResult(result: ResolutionResult, maybeYield: MaybeYield): Promise<number>
... (127 lines truncated)
</file>

<file path="src/resolution/js-builtins.ts">

</file>

<file path="src/resolution/lru-cache.ts">
export class LRUCache<K, V>
⋮----
constructor(max: number)
⋮----
get size(): number
⋮----
get(key: K): V | undefined
⋮----
has(key: K): boolean
⋮----
set(key: K, value: V): void
⋮----
clear(): void
</file>

<file path="src/resolution/memory-budget.ts">
import { execFileSync } from 'child_process';
⋮----
function readCgroupBytes(path: string): number | null
⋮----
function readInactiveFile(statPath: string): number
⋮----
export function cgroupMemoryAvailable(): number | null
⋮----
export function darwinMemoryAvailable(): number | null
⋮----
const count = (label: string): number =>
⋮----
export function memoryBudgetBytes(): number
</file>

<file path="src/resolution/name-matcher.ts">
import { Language, Node } from '../types';
import { UnresolvedRef, ResolvedRef, ResolutionContext, isSupertypeTarget, CPP_DEFINE_SIGNATURE, isInheritanceRef, isImportableKind } from './types';
import { blankStringContents, stripCommentsForRegex } from './strip-comments';
import { JS_BUILT_INS, JS_BUILTIN_METHODS, TS_PRIMITIVE_TYPES } from './js-builtins';
import { SWIFT_TYPE_PATH_CALL, resolveSwiftTypePathCall } from './swift-type-visibility';
import { isTestPath } from '../search/query-utils';
import { isMinifiedContent } from '../extraction/generated-detection';
import { getCargoWorkspaceCrateMap } from './frameworks/cargo-workspace';
⋮----
function resolveAmbiguousNameCeiling(): number
⋮----
export function matchByFilePath(
  ref: UnresolvedRef,
  context: ResolutionContext
): ResolvedRef | null
⋮----
function pickClosestFileNode(candidates: Node[], ref: UnresolvedRef): Node
⋮----
const dirOf = (p: string): string =>
⋮----
/**
 * Language families that share a type system / runtime, so a same-language-only
 * reference may still resolve across them (a Kotlin `Foo.BAR` can name a Java
 * `Foo`). Anything not listed forms its own singleton family.
 */
⋮----
export function sameLanguageFamily(a: string, b: string): boolean
⋮----
export function crossesCodeBoundary(a: string, b: string): boolean
⋮----
function hasBridgeEvidence(candidate: Node, ref: UnresolvedRef, context: ResolutionContext): boolean
⋮----
export function gateLanguageMatch(
  result: ResolvedRef | null,
  ref: UnresolvedRef,
  context: ResolutionContext
): ResolvedRef | null
⋮----
function matchMemberFunctionRef(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
const result = (nodes: Node[], confidence = 0.9): ResolvedRef | null =>
⋮----
function pythonRefClass(name: string, ref: UnresolvedRef, context: ResolutionContext): Node | null
⋮----
function pythonBases(cls: Node, ref: UnresolvedRef, context: ResolutionContext): Node[]
⋮----
function pythonDerivesFrom(cls: Node, base: Node, ref: UnresolvedRef, context: ResolutionContext, seen = new Set<string>()): boolean
⋮----
function pythonMembers(cls: Node, member: string, ref: UnresolvedRef, context: ResolutionContext, seen = new Set<string>()): Node[]
⋮----
// Instance assignments also shadow methods, even though they are not nodes.
⋮----
function isPythonProperty(node: Node, context: ResolutionContext): boolean
⋮----
function pythonMemberLines(filePath: string, context: ResolutionContext): string[]
⋮----
function pythonLocalType(receiver: string, ref: UnresolvedRef, context: ResolutionContext): string | null
⋮----
/** Read a field's own annotation/initializer, or a constructor parameter assigned to it. */
function pythonFieldType(receiver: string, owner: Node, ref: UnresolvedRef, context: ResolutionContext): string | null
⋮----
// Conflicting assignments are known-but-ambiguous, never a name-only fallback.
⋮----
/**
 * Resolve a function-as-value reference (#756) — a function name used as a
 * callback/function-pointer value (`register(handler)`, `o->cb = handler`,
 * `{ .cb = handler }`, `signal(SIGINT, handler)`). The ONLY strategy allowed
 * for `function_ref` refs: exact name, function/method targets only, same
 * language family, same-file first for bare names, and unique-only cross-file.
 * Member values use receiver/type/import scope before a unique-name fallback.
 * A wrong callback edge is worse than none.
 */
export function matchFunctionRef(
  ref: UnresolvedRef,
  context: ResolutionContext
): ResolvedRef | null
⋮----
// `this.<member>` refs are resolved ONLY by the class-scoped resolver in
// resolveOne (resolveThisMemberFnRef) — never by name matching here.
⋮----
// In JS/TS/Python a bare identifier can never be a method value (methods
// are only reachable through a receiver — `this.m` / `self.m` /
// `Cls.m`), so bare fn-refs match FUNCTIONS only. This also sidesteps the
// pre-existing TS quirk of class fields extracting as method-kind nodes,
// which otherwise soaked up local names passed as arguments (excalidraw
// A/B finding; same pattern in vendored docopt.py). Python's `self.m`
// form keeps method targets via its own capture shape. C++ likewise: a
// bare identifier can only be a FREE function (member values need
// `&Cls::method`). PHP string callables name global FUNCTIONS (methods
// need the `[$obj, 'm']` array form, which carries its own shape). Other
// languages keep method targets: C# method groups, Swift/Dart
// implicit-self, Java/Kotlin method references.
⋮----
// Python additionally accepts CLASS targets for bare identifiers (#1478):
// class-as-value is a core Python idiom (`return SomeSerializer`,
// `Meta.model = Org`, registry dicts, `admin.site.register(Model, Admin)`)
// and, unlike TS, Python has no type-annotation recovery path. The
// false-positive mechanism behind the function-only rule was lowercase
// locals colliding with same-named METHODS (docopt.py) — a candidate must
// be an exact-name CLASS node here, and the extraction gate (same-file
... (1326 lines truncated)
</file>

<file path="src/resolution/next-router-synthesizer.ts">
import type { Edge } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { stripCommentsForRegex } from './strip-comments';
import { isTestPath } from '../search/query-utils';
import { readStringAt, toHref } from './frameworks/expo-router';
import { nextRouteTable, destinationsForHref } from './frameworks/nextjs';
import { enclosingFn, makeLineAt } from './synth-utils';
⋮----
/** Links a single component may carry before it is a navigation menu, not a decision. */
⋮----
export async function nextLinkEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
// `href={…}`: a string, a template, or an object with a literal pathname.
</file>

<file path="src/resolution/path-aliases.ts">
import { logDebug } from '../errors';
⋮----
export interface AliasPattern {
  prefix: string;
  suffix: string;
  hasWildcard: boolean;
  replacements: string[];
}
⋮----
export interface AliasMap {
  baseUrl: string;
  patterns: AliasPattern[];
}
⋮----
function stripJsonc(src: string): string
⋮----
interface RawTsconfig {
  extends?: string | string[];
  compilerOptions?: {
    baseUrl?: string;
    paths?: Record<string, string[]>;
  };
}
⋮----
interface EffectiveOptions {
  baseUrl?: string;
  paths?: Record<string, string[]>;
  pathsDir?: string;
}
⋮----
function resolveExtendsTarget(spec: string, fromDir: string): string | null
⋮----
const isFile = (p: string): boolean =>
⋮----
function loadEffectiveOptions(
  filePath: string,
  stack: Set<string>,
  depth: number
): EffectiveOptions | null
⋮----
function readTsconfigLike(filePath: string): RawTsconfig | null
⋮----
function splitWildcard(pattern: string):
⋮----
/**
 * Load aliases for `projectRoot`. Returns `null` when no tsconfig /
 * jsconfig is present or when the file has no usable `paths`.
 *
 * Cheap to call repeatedly — caching is the caller's job (the
 * resolver does it via {@link aliasCache}).
 */
export function loadProjectAliases(projectRoot: string): AliasMap | null
⋮----
export function applyAliases(
  importPath: string,
  aliases: AliasMap,
  projectRoot: string
): string[]
⋮----
// Literal pattern must match exactly.
⋮----
// baseUrl is absolute; produce a path relative to projectRoot
⋮----
// Skip if the rewrite escapes the project root (unsafe + can't
</file>

<file path="src/resolution/react-router-synthesizer.ts">
import type { Edge, Language } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { stripCommentsForRegex } from './strip-comments';
import { isTestPath } from '../search/query-utils';
import { parseHrefExpression, routesForFile, toHref, type HrefLiteral } from './frameworks/expo-router';
import { matchBracket } from './frameworks/object-literal';
import { destinationsForHref } from './frameworks/nextjs';
import { reactRouterTable } from './frameworks/react-router';
import { configHrefExpression } from './frameworks/react';
import { enclosingFn, makeLineAt } from './synth-utils';
import { resolveImportPath } from './import-resolver';
⋮----
function linkTagPattern(tags: readonly string[]): RegExp
⋮----
/** `const HeaderLink = styled(Link)` — a styled wrapper is the link it wraps. */
⋮----
interface LinkWrappers {
  /** File → the wrapper components it declares by name. */
  named: Map<string, Set<string>>;
  /** Files whose default export is a wrapper. */
  defaults: Set<string>;
}
⋮----
/** File → the wrapper components it declares by name. */
⋮----
/** Files whose default export is a wrapper. */
⋮----
/**
 * Every styled-components / emotion wrapper of `Link` or `NavLink` in the
 * project — react-boilerplate's header links are `export default
 * styled(Link)`…``, used as `<HeaderLink to="/features">` from another file.
 */
function linkWrappers(ctx: ResolutionContext): LinkWrappers
⋮----
/** The link tags `file` can write: React Router's own and the wrappers in scope there. */
function linkTagsFor(file: string, wrappers: LinkWrappers, ctx: ResolutionContext): string[]
⋮----
function languageOf(file: string): Language
⋮----
export async function reactRouterLinkEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
</file>

<file path="src/resolution/resolver-pool.ts">
import { Worker } from 'worker_threads';
⋮----
import type { Edge, UnresolvedReference } from '../types';
import type { ResolvedRef, UnresolvedRef } from './types';
import { memoryBudgetBytes } from './memory-budget';
⋮----
export interface SynthPassResult {
  edges: Edge[];
  ms: number;
}
⋮----
export interface ChunkResult {
  resolved: ResolvedRef[];
  unresolved: UnresolvedRef[];
  deferredChain: UnresolvedRef[];
  deferredThisMember: UnresolvedRef[];
  byMethod: Record<string, number>;
}
⋮----
interface PoolWorker {
  worker: Worker;
  ready: Promise<void>;
  busy: number;
}
⋮----
export function minRefsForPool(): number
⋮----
export class ResolverPool
⋮----
static resolvePoolSize(opts: {
    explicit?: string;
    availableParallelism: number;
    memoryBudget: number;
    dbSizeBytes: number;
}): number | null
⋮----
// No floor: at ap=2 the pool LOSES to sequential outright — measured on
// the kernel-scale 2-cpuset envelope: resolution 853s sequential vs
// 1,150s pooled-6-on-2 (§7a.1), and synthesis is Amdahl-bound by its
// dominant pass (cFnPtrEdges 306s of 358s) so pooling it bought nothing.
// ap−1 < 2 ⇒ sequential is the fast path, not a fallback.
⋮----
/**
   * Create a pool when the compiled worker exists (absent when running from
   * source in tests → callers use the sequential path), the kill switch is
   * off, and the machine has the cores AND memory to carry it. Returns null
   * otherwise. `CODEGRAPH_RESOLVE_WORKERS` overrides the computed size
   * (0 disables the pool; values are capped at 16).
   */
static tryCreate(dbPath: string, projectRoot: string): ResolverPool | null
⋮----
private constructor(workerScript: string, dbPath: string, projectRoot: string, size: number)
⋮----
private fail(err: Error): void
⋮----
get size(): number
⋮----
static worthParallel(batchLength: number): boolean
⋮----
async ready(): Promise<void>
⋮----
async resolveBatch(refs: UnresolvedReference[]): Promise<ChunkResult>
⋮----
async runSynthPass(passName: string): Promise<SynthPassResult>
⋮----
async recycleWorkers(): Promise<void>
⋮----
async destroy(): Promise<void>
</file>

<file path="src/resolution/resolver-worker.ts">
import { parentPort, threadId } from 'worker_threads';
import { createDatabase, SqliteDatabase } from '../db/sqlite-adapter';
import { QueryBuilder } from '../db/queries';
import { ReferenceResolver } from './index';
import { SYNTH_PASSES } from './callback-synthesizer';
import { createYielder } from './cooperative-yield';
import type { UnresolvedReference } from '../types';
⋮----
type InMessage =
  | { type: 'open'; dbPath: string; projectRoot: string }
  | { type: 'recycle'; id: number }
  | { type: 'resolve'; id: number; refs: UnresolvedReference[] }
  | { type: 'synth'; id: number; pass: string }
  | { type: 'close' };
</file>

<file path="src/resolution/strip-comments.ts">
export function blankStringContents(text: string): string
⋮----
// A quote inside a JS regex is data, not the beginning of a string.
// Expression-start punctuation and keywords distinguish these from division.
⋮----
export type CommentLang =
  | 'python'
  | 'javascript'
  | 'typescript'
  | 'php'
  | 'ruby'
  | 'java'
  | 'csharp'
  | 'swift'
  | 'go'
  | 'rust'
  | 'c'
  | 'cpp'
  | 'erlang';
⋮----
export function stripCommentsForRegex(content: string, lang: CommentLang): string
⋮----
function blankRange(buf: string[], start: number, end: number, src: string): void
⋮----
function stripPython(src: string): string
⋮----
// Triple-quoted string: """...""" or '''...'''
⋮----
// Single-line string: '...' or "..."
⋮----
// ---------- Ruby ----------
⋮----
function stripRuby(src: string): string
⋮----
// =begin / =end block comments must be at start of line (after optional whitespace)
⋮----
// ---------- C-style (JS/TS/Java/C#/Swift) ----------
⋮----
function stripCStyle(src: string, allowSingleQuoteStrings: boolean): string
⋮----
// Block comment
⋮----
// Line comment
⋮----
// Template literal can span lines; regular strings break on newline (treat as unterminated)
⋮----
// ---------- PHP ----------
⋮----
function stripPhp(src: string): string
⋮----
// Block comment
⋮----
// // line comment
⋮----
// # line comment (PHP supports both)
⋮----
// String literals: ', ", ` (PHP doesn't really use backticks for strings,
⋮----
// ---------- Go ----------
⋮----
function stripGo(src: string): string
⋮----
// Block comment
⋮----
// Line comment
⋮----
// ---------- Rust ----------
⋮----
function stripRust(src: string): string
⋮----
// Nested block comment /* ... /* ... */ ... */
⋮----
// Line comment
⋮----
// Char literal — keep simple: skip 'x' or '\x'
⋮----
// Could be a lifetime, e.g. 'a, but those don't contain routing text
⋮----
// ---------- Erlang ----------
⋮----
/**
 * Erlang: `%` starts a line comment unless it sits inside a `"string"`, a
 * `'quoted atom'`, or is the character literal `$%`. Strings and quoted atoms
 * are left intact (a behaviour callback name can be a quoted atom); only the
 * comment text is blanked.
 */
function stripErlang(src: string): string
⋮----
// Character literal: `$x`, `$\n`, `$%` — the next char (or escape) is data.
</file>

<file path="src/resolution/sveltekit-synthesizer.ts">
import type { Edge, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { isTestPath } from '../search/query-utils';
import { HOLE, readStringAt, routesForFile, toHref } from './frameworks/expo-router';
import { destinationsForHref } from './frameworks/nextjs';
import { svelteKitTable } from './frameworks/sveltekit-router';
import { enclosingFn, makeLineAt } from './synth-utils';
⋮----
/** Links a single component may carry before it is a navigation menu, not a decision. */
⋮----
export async function svelteKitLinkEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
// `href={…}`: a string or a template with holes.
⋮----
export async function svelteKitPageComponentEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
</file>

<file path="src/resolution/swift-objc-bridge.ts">
function capFirst(s: string): string
⋮----
function lowerFirst(s: string): string
⋮----
export function objcSelectorForSwiftMethod(
  baseName: string,
  externalLabels: (string | null)[],
  explicitObjcName?: string | null
): string | null
⋮----
/**
 * Compute the bridged ObjC selector for a Swift `init(...)` declaration.
 *
 * **Init rules** (different from regular methods — Apple always uses
 * `initWith` regardless of whether the first label is `_`):
 * - `init()`                       → `init`
 * - `init(_ name: String)`         → `initWithName:`  (uses the INTERNAL
 *                                    name when external is `_`, per Apple's
 *                                    bridging conventions)
 * - `init(name: String)`           → `initWithName:`
 * - `init(name: String, age: Int)` → `initWithName:age:`
 *
 * For the `_` case we need the internal (second identifier) name —
 * passed via `internalNames`.
 */
export function objcSelectorForSwiftInit(
  externalLabels: (string | null)[],
  internalNames: string[],
  explicitObjcName?: string | null
): string | null
⋮----
/**
 * Compute the bridged ObjC getter + setter for a Swift `@objc` property.
 *
 * - `var name: String`        → getter `name`, setter `setName:`
 * - `var isReady: Bool`       → getter `isReady`, setter `setIsReady:`
 *   (no special `is` handling — Swift's `isReady` stays as `isReady` in ObjC;
 *   `@objc(name:)` overrides if a Cocoa-style getter `isReady` / setter
 *   `setReady:` pairing is needed — that's the responsibility of the
 *   declaration's `@objc(customGetter)` annotation, which we surface via
 *   `explicitObjcName`.)
 */
export function objcAccessorsForSwiftProperty(
  swiftName: string,
  explicitObjcName?: string | null
):
⋮----
export function swiftBaseNamesForObjcSelector(selector: string): string[]
⋮----
// Always a candidate: the raw first keyword. Covers
//   `play:`           → `play`
//   `play:by:`        → `play`
//   `playWithSong:`   → `playWithSong` (a literal Swift name)
//   `tableView:...:`  → `tableView`
⋮----
// `initWith<X>:` and `initWith<X>:<more>:` always reduce to `init`.
⋮----
export function detectExplicitObjcName(sourceSlice: string): string | null
⋮----
export function isObjcExposed(sourceSlice: string): boolean
</file>

<file path="src/resolution/swift-type-visibility.ts">
import type { Node } from '../types';
import type { ResolutionContext, ResolvedRef, UnresolvedRef } from './types';
⋮----
interface Memo {
  extension: Map<string, boolean>;
  declaration: Map<string, Node | null>;
  conformances: Map<string, string[]>;
  clauses: Map<string, string[]>;
  inherited: Map<string, ReadonlySet<string>>;
  owners: Map<string, string | null>;
}
⋮----
function memoFor(context: ResolutionContext): Memo
⋮----
export function clearSwiftTypeVisibility(context: ResolutionContext): void
⋮----
export function isSwiftExtension(node: Node, context: ResolutionContext): boolean
⋮----
export function declaresExtension(lines: readonly string[], node: Pick<Node, 'startLine' | 'startColumn' | 'endLine'>): boolean
⋮----
// An attribute's string argument (`message: "use class Foo"`) is not a keyword.
⋮----
/** A declaration's inheritance clause: `struct HomeView: View, Sendable {` → `View, Sendable`. */
⋮----
/** The supertypes a Swift type node's own declaration names: `View`, `Sendable` for `struct HomeView: View, Sendable {`. */
function declaredSupertypes(node: Node, context: ResolutionContext): string[]
⋮----
/**
 * The types a Swift type node's own declaration conforms to that the project
 * only extends — `View` for `struct HomeView: View` when `extension View {}`
 * is all the index holds of it. Those conformances resolve to nothing (an
 * extension is not the type), yet the members the extensions add are the
 * conformer's: the supertype walk reads them from here. From the source, once
 * per node — the resolved edges it would otherwise come from do not exist.
 */
export function swiftExtendedConformances(node: Node, context: ResolutionContext): string[]
⋮----
function inheritedTypeNames(typeName: string, context: ResolutionContext): ReadonlySet<string>
⋮----
function parentPath(node: Node): string | null
⋮----
function bareScopeDepth(target: Node, from: Node | null, context: ResolutionContext): number | null
⋮----
const inside = (path: string): boolean =>
⋮----
function linesOf(filePath: string, context: ResolutionContext): string[] | null
⋮----
/**
 * The reference as its site writes it. The index keeps a Swift type
 * reference by its last segment — `Build.Id` is a ref named `Id` — so whether
 * the name was qualified is read back from the line: a type annotation's
 * column is the name's (`Build.|Id`), a construction's is the chain's
 * (`|API.PackageController.GetRoute.Model(`).
 */
function writtenName(ref: UnresolvedRef, context: ResolutionContext): string
⋮----
const clean = (qualifier: string): string => `$
⋮----
function writtenPath(written: string, name: string): string | null
⋮----
function fitsPath(node: Node, path: string, context: ResolutionContext): boolean
⋮----
function sharedDirs(a: string, b: string): number
⋮----
function declarationFor(name: string, written: string, ref: UnresolvedRef, from: Node | null, context: ResolutionContext): Node | null
⋮----
export function gateSwiftTypeTarget(result: ResolvedRef | null, ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
export function resolveSwiftTypePathCall(ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
const onPath = (kinds: ReadonlySet<Node['kind']>): Node[] =>
⋮----
function isReducerEnum(member: Node, context: ResolutionContext): boolean
⋮----
function moduleQualified(owner: string, path: string, context: ResolutionContext): boolean
⋮----
function ownerPath(member: Node, context: ResolutionContext): string | null
⋮----
function extendedPath(node: Node, context: ResolutionContext): string | null
</file>

<file path="src/resolution/synth-utils.ts">
import type { Node } from '../types';
⋮----
export function makeLineAt(src: string, baseLine: number): (idx: number) => number
⋮----
export function enclosingFn(nodesInFile: readonly Node[], line: number): Node | null
⋮----
export function enclosingValue(nodesInFile: readonly Node[], line: number): Node | null
</file>

<file path="src/resolution/tanstack-router-synthesizer.ts">
import type { Edge } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { stripCommentsForRegex } from './strip-comments';
import { isTestPath } from '../search/query-utils';
import { readStringAt, routesForFile } from './frameworks/expo-router';
import { destinationsForHref } from './frameworks/nextjs';
import { tanstackDestination, tanstackTable } from './frameworks/tanstack-router';
import { enclosingFn, makeLineAt } from './synth-utils';
⋮----
/** A tag this pass could possibly match — the cheap prefilter. */
⋮----
/** Links a single component may carry before it is a navigation menu, not a decision. */
⋮----
export async function tanstackLinkEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
// `to={…}`: a string or a template.
</file>

<file path="src/resolution/tier-synthesizer.ts">
import type { Edge, Language, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { stripCommentsForRegex } from './strip-comments';
import { resolveImportPath } from './import-resolver';
import { isGeneratedFile } from '../extraction/generated-detection';
import { isTestPath } from '../search/query-utils';
import { HOLE, readStringAt } from './frameworks/expo-router';
import { enclosingFn, enclosingValue, makeLineAt } from './synth-utils';
⋮----
function closeParen(s: string, open: number): number
⋮----
/** Index of the backtick closing the template opening at `open`. */
function templateEnd(s: string, open: number): number
⋮----
/** The arguments of the call whose `(` is at `open`, split at depth-0 commas. */
function argumentsAt(s: string, open: number): string[] | null
⋮----
/** The first string literal in `text`, holes kept; null when it opens with anything else. */
function leadingString(text: string): string | null
⋮----
// `new URL('/x', base)` — the path is the first argument of the URL.
⋮----
/** `method: 'POST'` inside an options object / config, upper-cased; null when absent or computed. */
function methodIn(text: string): string | null
⋮----
function firstLiteral(args: string): string | null
⋮----
/** Every string literal in a decorator's arguments, for `@OnEvent(['a', 'b'])`. */
function allLiterals(args: string): string[]
⋮----
function methodNameAfter(safe: string, from: number):
⋮----
const eat = (): void =>
⋮----
function decorators(safe: string, name: string): Array<
⋮----
interface FileFacts {
  file: string;
  safe: string;
  readonly nodes: Node[];
  lineOf: (idx: number) => number;
  columnOf: (idx: number) => number;
  readonly routeLines: Set<number>;
  clients: Map<string, { baseURL: string | null }>;
  defaultClient: { baseURL: string | null } | null;
  queues: Map<string, string>;
  socketServer: boolean;
}
⋮----
function baseUrlIn(safe: string, open: number): string | null
⋮----
function readFacts(ctx: ResolutionContext, file: string): FileFacts | null
⋮----
get nodes()
⋮----
get routeLines()
⋮----
/** Facts for the file a local name is imported from, when the import resolves to a project file. */
function importedFacts(
  ctx: ResolutionContext,
  facts: FileFacts,
  localName: string,
  cache: Map<string, FileFacts | null>
):
⋮----
// The mappings name the module as written; the file it is comes from the
// same resolution the import resolver uses (aliases, extensions, index files).
⋮----
// =============================================================================
// 1. HTTP client → route
// =============================================================================
⋮----
/** A receiver that is an HTTP client by name alone. */
⋮----
/** A receiver that registers routes, never a client — unless it was made by a client factory. */
⋮----
/** A type argument between the callee and its `(` — `useSWR<TeamData>('/api/team')`, `ky.get<User>('/x')`. */
⋮----
/**
 * Where a receiver chain (`this.api.client`) may begin: not after an earlier
 * identifier-start character of the same word (the second lookbehind is the
 * whole rule; the first is its one-character fast path). A match from the
 * middle of a word implies one from its first letter — the chain regexes read
 * the rest of the word either way — and each of their matches ends on a
 * non-word character, so a scan never resumes mid-word: this only skips starts
 * bound to fail. Without it every letter of every identifier re-read the
 * dotted chain behind it, which on vscode made this the slowest pass.
 */
⋮----
interface HttpRoute {
  node: Node;
  method: string;
  segs: string[];
}
⋮----
interface HttpSite {
  fn: Node;
  file: string;
  line: number;
... (214 lines truncated)
</file>

<file path="src/resolution/type-parameters.ts">
import type { Node } from '../types';
import type { ResolutionContext, ResolvedRef, UnresolvedRef } from './types';
⋮----
export function clearTypeParameterMemos(context: ResolutionContext): void
⋮----
export function gateTypeParameter(resolved: ResolvedRef | null, ref: UnresolvedRef, context: ResolutionContext): ResolvedRef | null
⋮----
function scalaMemberInScope(result: ResolvedRef, ref: UnresolvedRef, context: ResolutionContext): boolean
⋮----
const inside = (o: Node): boolean
⋮----
function enclosingDeclarations(ref: UnresolvedRef, context: ResolutionContext): Node[]
⋮----
function declaredTypeParameters(node: Node, context: ResolutionContext): ReadonlySet<string>
⋮----
function declaredValueParameters(node: Node, context: ResolutionContext): ReadonlySet<string>
⋮----
const skipSpace = (): void =>
⋮----
/**
 * The declared name's position in its head: the whole word, past attributes
 * and modifiers. A plain search — a declared name can be an operator (Scala's
 * `*`, `|+|`), which no pattern built from it could match safely.
 */
function nameIndex(head: string, name: string): number
⋮----
/** Add the parameter names of the bracket group opening at `open`. */
function collect(text: string, open: number, names: Set<string>): void
⋮----
// Past annotations (`@sp(Int, Long) A`, `@NonNull T`), variance and keywords.
⋮----
function matchingBracket(text: string, open: number): number
⋮----
function splitTopLevel(inner: string, angle: boolean): string[]
⋮----
function isOpener(c: string, angle: boolean): boolean
⋮----
function isCloser(c: string, angle: boolean, previous: string | undefined): boolean
</file>

<file path="src/resolution/types.ts">
import { EdgeKind, Language, Node, ReferenceKind } from '../types';
⋮----
export interface UnresolvedRef {
  fromNodeId: string;
  referenceName: string;
  referenceKind: ReferenceKind;
  line: number;
  column: number;
  filePath: string;
  language: Language;
  candidates?: string[];
  rowId?: number;
}
⋮----
export interface ResolvedRef {
  original: UnresolvedRef;
  targetNodeId: string;
  confidence: number;
  resolvedBy: 'exact-match' | 'import' | 'qualified-name' | 'framework' | 'fuzzy' | 'instance-method' | 'file-path' | 'function-ref';
  edgeKind?: EdgeKind;
  metadata?: Record<string, unknown>;
  alsoTargets?: { targetNodeId: string; metadata?: Record<string, unknown> }[];
}
⋮----
export interface ResolutionResult {
  resolved: ResolvedRef[];
  unresolved: UnresolvedRef[];
  stats: {
    total: number;
    resolved: number;
    unresolved: number;
    byMethod: Record<string, number>;
  };
}
⋮----
export interface ResolutionContext {
  getNodesInFile(filePath: string): Node[];
  fileHasExportedNode?(filePath: string): boolean;
  getExportedNodesInFile?(filePath: string): Node[];
  getNodesInFileNamed?(filePath: string, name: string): Node[];
  getNodesByName(name: string): Node[];
  getNodesByQualifiedName(qualifiedName: string): Node[];
  getNodesByKind(kind: Node['kind']): Node[];
  iterateNodesByKind?(kind: Node['kind']): IterableIterator<Node>;
  fileExists(filePath: string): boolean;
  readFile(filePath: string): string | null;
  fileContains?(filePath: string, needle: string): boolean;
  getFileLines?(filePath: string): string[] | null;
  getMethodMatches?(typeName: string, methodName: string, language: Language): Node[];
  getProjectRoot(): string;
  getAllFiles(): string[];
  getNodesByLowerName(lowerName: string): Node[];
  getSupertypes?(typeName: string, language: Language): string[];
  getNodeById?(id: string): Node | null;
  getImportMappings(filePath: string, language: Language): ImportMapping[];
  resolveImport?(ref: UnresolvedRef): ResolvedRef | null;
  isOutOfRepoImport?(source: string, fromFile: string, language: Language): boolean;
  getProjectAliases?(): import('./path-aliases').AliasMap | null;
  getNearestAliases?(fromFile: string): import('./path-aliases').AliasMap | null;
  getGoModule?(): import('./go-module').GoModule | null;
  getWorkspacePackages?(): import('./workspace-packages').WorkspacePackages | null;
  getReExports?(filePath: string, language: Language): ReExport[];
  listDirectories?(relativePath: string): string[];
  getCppIncludeDirs?(): string[];
}
⋮----
getNodesInFile(filePath: string): Node[];
⋮----
fileHasExportedNode?(filePath: string): boolean;
⋮----
getExportedNodesInFile?(filePath: string): Node[];
⋮----
getNodesInFileNamed?(filePath: string, name: string): Node[];
⋮----
getNodesByName(name: string): Node[];
⋮----
getNodesByQualifiedName(qualifiedName: string): Node[];
⋮----
getNodesByKind(kind: Node['kind']): Node[];
⋮----
iterateNodesByKind?(kind: Node['kind']): IterableIterator<Node>;
⋮----
fileExists(filePath: string): boolean;
⋮----
readFile(filePath: string): string | null;
⋮----
fileContains?(filePath: string, needle: string): boolean;
⋮----
getFileLines?(filePath: string): string[] | null;
⋮----
getMethodMatches?(typeName: string, methodName: string, language: Language): Node[];
⋮----
getProjectRoot(): string;
⋮----
getAllFiles(): string[];
⋮----
getNodesByLowerName(lowerName: string): Node[];
⋮----
getSupertypes?(typeName: string, language: Language): string[];
⋮----
... (80 lines truncated)
</file>

<file path="src/resolution/vue-router-synthesizer.ts">
import type { Edge, Node } from '../types';
import type { ResolutionContext } from './types';
import type { MaybeYield } from './cooperative-yield';
import { isTestPath } from '../search/query-utils';
import { readStringAt, routesForFile, toHref } from './frameworks/expo-router';
import { destinationsForHref } from './frameworks/nextjs';
import { parseVuePathObject, routeNameInExpression, vueRouteTable } from './frameworks/vue-router';
import { enclosingFn, makeLineAt } from './synth-utils';
⋮----
/** A tag this pass could possibly match — the cheap prefilter. */
⋮----
/** Links a single component may carry before it is a navigation menu, not a decision. */
⋮----
export async function vueRouterLinkEdges(ctx: ResolutionContext, onYield: MaybeYield): Promise<Edge[]>
⋮----
// A bound `:to` holds an expression; a plain `to` holds a literal path.
</file>

<file path="src/resolution/workspace-packages.ts">
import { logDebug } from '../errors';
⋮----
export interface WorkspacePackages {
  byName: Map<string, string>;
  entryByName?: Map<string, string>;
}
⋮----
export function loadWorkspacePackages(projectRoot: string): WorkspacePackages | null
⋮----
function readOhpmMain(projectRoot: string, dirRel: string): string | null
⋮----
function collectOhpmFileDeps(projectRoot: string): Map<string, string>
⋮----
if (targetRel.startsWith('..')) continue; // escapes the project
⋮----
/** Parse one oh-package.json5's dependencies → [name, file-target] pairs. */
function readOhpmFileDeps(manifestAbs: string): Array<[string, string]>
⋮----
export function resolveWorkspaceImport(
  importPath: string,
  ws: WorkspacePackages
): string | null
⋮----
function readWorkspaceGlobs(projectRoot: string): string[]
⋮----
function parsePnpmPackages(yaml: string): string[]
⋮----
// A non-list, non-blank line ends the `packages:` block.
⋮----
/** Expand one level of a `packages/*` / `apps/**` glob to member dirs. */
function expandWorkspaceGlob(projectRoot: string, pattern: string): string[]
⋮----
if (star === -1) return [norm]; // exact directory
⋮----
// Everything before the wildcard segment is the base to enumerate.
⋮----
function readPackageName(dirAbs: string): string | null
</file>

<file path="src/search/identifier-segments.ts">
export function splitIdentifierSegments(name: string): string[]
⋮----
export function normalizeProseWord(word: string): string
⋮----
/** Candidate cap: a prompt's first words carry its subject; scanning an essay
 *  buys nothing and the vocab lookup cost scales with this. */
⋮----
export function extractProseCandidates(prompt: string): string[]
⋮----
export function extractSegmentSearchWords(query: string): string[]
⋮----
export function segmentLookupVariants(word: string): string[]
</file>

<file path="src/search/query-parser.ts">
import { NODE_KINDS, LANGUAGES } from '../types';
import type { NodeKind, Language } from '../types';
⋮----
export interface ParsedQuery {
  text: string;
  kinds: NodeKind[];
  languages: Language[];
  pathFilters: string[];
  nameFilters: string[];
}
⋮----
function unquote(s: string): string
⋮----
export function parseQuery(raw: string): ParsedQuery
⋮----
// Tokenise on whitespace, preserving quoted spans as part of the
// current token. Quotes can appear at the start (`"…"`) OR mid-token
// (`path:"…"`); in both cases everything from the opening `"` to the
// matching `"` is included in the token, whitespace and all.
⋮----
// Unterminated quote — swallow the rest of the input as
// one token. Forgiving rather than throwing.
⋮----
export function boundedEditDistance(a: string, b: string, maxDist: number): number
</file>

<file path="src/search/query-paths.ts">
export interface QueryPathExtraction {
  strippedQuery: string;
  pinnedFiles: string[];
  unresolvedPathSpans: string[];
  lineAnchors: QueryLineAnchor[];
  setAsideMatches: QuerySetAsideMatch[];
}
⋮----
export interface QuerySetAsideMatch {
  span: string;
  files: string[];
}
⋮----
export interface QueryLineAnchor {
  file: string;
  start: number;
  end: number;
}
⋮----
export function queryMightContainPaths(query: string): boolean
⋮----
/**
 * Longest span→suffix walk tried per span. 8 covers an absolute macOS path
 * (`/Users/<user>/dev/<repo>/…`) over a deeply nested repo-relative file;
 * deeper prefixes buy nothing.
 */
⋮----
/** Spans examined per query — a prose sentence is not 50 paths. */
⋮----
/** `name.ext` shape with a plausible source extension (no slash required). */
⋮----
/**
 * Extension-less kebab basename (`background-image-table`). Hyphens are
 * illegal in identifiers, so consuming these tokens can never steal one from
 * the named-symbol seeder; ≥2 segments keeps single words out.
 */
⋮----
/** A basename's last dot-extension, same shape DOTTED_BASENAME accepts. */
⋮----
function isPreciseSymbolToken(t: string): boolean
⋮----
function querySymbolTokens(tokens: readonly string[], indexedBasenames: ReadonlySet<string>): string[]
⋮----
/**
 * Lowercased basename stems of the hyphen-named indexed files, stem → paths.
 * A stem drops only the LAST extension (`a-b.module.scss` → `a-b.module`), so
 * a bare kebab token can't accidentally pin a same-named stylesheet or
 * `.d.ts` sibling of the source file it names; an extension-less basename
 * (`pre-commit`) is its own stem. Hyphen-free basenames are skipped — a
 * KEBAB_BASENAME token can never equal one, and the filter keeps the map
 * near-empty in repos that don't name files this way.
 */
function buildBasenameStems(indexedPaths: readonly string[]): Map<string, string[]>
⋮----
/**
 * Line references that ride along in agent-written paths: `foo.ts:123`,
 * `foo.ts:12-40`, `foo.ts#L88`, `foo.ts#L88-L120`.
 */
⋮----
/**
 * A standalone line-number token: `900`, `900-1003`, `900–1003`, `900..1003`,
 * `L900`, `L900-L1003`. The `L` form is unambiguous on its own; a bare number
 * only counts after a `line`/`lines` word or directly after a path.
 */
⋮----
/** `lines 900 to 1003` — the connective between two bare numbers. */
⋮----
/** Nothing real is this long; a larger number is a port, an id, a year typo. */
⋮----
function lineSpan(a: string | undefined, b: string | undefined):
⋮----
/** Prose punctuation a line-number token can carry: "lines 900-1003," / "(L88)". */
function stripLineTokenPunctuation(token: string): string
⋮----
/**
 * Strip prose punctuation wrapped around a token without eating punctuation
 * that is PART of the path: quotes/backticks always strip; a trailing `)`/`]`
 * strips only when the token has no matching opener (so `(protected)` and
 * `[id]` segments survive, while "…(see src/foo.ts)" loses its parenthesis);
 * a leading `(`/`[` mirrors that. Trailing sentence punctuation strips last,
 * so "src/foo.ts." resolves. A trailing line reference is split off and
 * returned separately — the file is what resolves, the lines are what the
 * agent wants from it.
 */
function stripWrapping(token: string):
⋮----
/** Normalize a span into the repo-relative shape the files table stores. */
function normalizeSpan(span: string): string
⋮----
/** Path-shaped beyond doubt: ≥2 segments and a dot-extension on the last. */
function isClearlyPathShaped(normalized: string): boolean
⋮----
/**
 * Resolve one normalized span against the indexed paths: exact match first,
 * then segment-aligned suffix matches, dropping leading segments one at a
 * time (so an absolute path, or one prefixed with the repo directory name,
 * still lands on the indexed repo-relative file). Suffixes only get shorter —
 * and therefore only match MORE — so the walk stops at the first suffix that
 * matches anything: within budget it resolves, over budget it is ambiguous.
 */
... (35 lines truncated)
</file>

<file path="src/search/query-utils.ts">
import { Node } from '../types';
⋮----
export function normalizeNameToken(raw: string): string
⋮----
/**
 * Tokens that name the PROJECT as a whole — its `go.mod` module, `package.json`
 * name, or repo root directory — rather than any specific symbol. A user
 * naturally puts the project name in a query as context ("MyApp backend
 * routes"), but it carries no discriminative signal: when it's also a substring
 * of a symbol or path on one stack (a `MyAppFrontend/` dir, a `MyAppApp` class)
 * it lexically inflates that stack and buries the rest (#720).
 *
 * Returned normalized (lowercase, alphanumerics only) so a query word can be
 * compared by its normalized form. Only names ≥5 chars are kept — short ones
 * (`api`, `app`, `core`, `web`) collide with real query terms too often to
 * safely down-weight.
 */
export function deriveProjectNameTokens(projectRoot: string): Set<string>
⋮----
const add = (raw: string | undefined | null): void =>
⋮----
} catch { /* no / invalid package.json */ }
⋮----
// Repo root directory name — a fallback when neither manifest names the project.
⋮----
/**
 * Common stop words to filter from search queries.
 * Includes generic English + code-specific noise words.
 */
⋮----
// English
⋮----
export function getStemVariants(term: string): string[]
⋮----
export function extractSearchTerms(query: string, options?:
⋮----
export function scorePathRelevance(
  filePath: string,
  query: string,
  projectNameTokens?: Set<string>,
  isDeprioritized?: boolean,
): number
⋮----
export function isTestFile(filePath: string): boolean
⋮----
export function isTestPath(filePath: string): boolean
⋮----
function matchesNonProductionDir(lowerPath: string): boolean
⋮----
/**
 * Bonus when a node's name matches the search query.
 * Exact matches get the largest boost; prefix matches get smaller boosts.
 * Multi-word queries also check individual term matches against the name.
 */
export function nameMatchBonus(nodeName: string, query: string): number
⋮----
// Exact match: query exactly equals the node name
⋮----
// Exact match on a query token: "CacheBuilder build" and node name is "build"
⋮----
// Name starts with query — scale by length ratio so "Pod"→"Pod" (exact, handled above)
// scores much higher than "Pod"→"PodGCControllerOptions" (ratio 0.125).
⋮----
// All camelCase-split terms appear in the name
⋮----
// Name contains the full query as substring
⋮----
/**
 * Kind-based bonus for search ranking
 * Functions and classes are typically more relevant than variables/imports
 */
export function kindBonus(kind: Node['kind']): number
⋮----
export function isDistinctiveIdentifier(token: string): boolean
</file>

<file path="src/sync/git-hooks.ts">
import { execFileSync } from 'child_process';
⋮----
export type GitHookName = 'post-commit' | 'post-merge' | 'post-checkout';
⋮----
export interface GitHookResult {
  installed: GitHookName[];
  hooksDir: string | null;
  skipped?: string;
}
⋮----
export function isGitRepo(projectRoot: string): boolean
⋮----
function gitHooksDir(projectRoot: string): string | null
⋮----
function markerBlock(): string
⋮----
function stripMarkerBlock(content: string): string
⋮----
function isEffectivelyEmpty(content: string): boolean
⋮----
function chmodExecutable(file: string): void
⋮----
export function installGitSyncHook(
  projectRoot: string,
  hooks: GitHookName[] = DEFAULT_SYNC_HOOKS,
): GitHookResult
⋮----
/**
 * Remove the CodeGraph sync hooks. Strips only our marker block; deletes the
 * hook file entirely when nothing but a shebang remains, otherwise rewrites
 * the user's content untouched.
 */
export function removeGitSyncHook(
  projectRoot: string,
  hooks: GitHookName[] = DEFAULT_SYNC_HOOKS,
): GitHookResult
⋮----
export function isSyncHookInstalled(
  projectRoot: string,
  hooks: GitHookName[] = DEFAULT_SYNC_HOOKS,
): boolean
</file>

<file path="src/sync/index.ts">

</file>

<file path="src/sync/watch-policy.ts">
import { normalizePath } from '../utils';
⋮----
export function detectWsl(): boolean
⋮----
export function isWindowsDriveMount(projectRoot: string): boolean
⋮----
export function isWslWindowsDrive(p: string): boolean
⋮----
export interface WatchProbe {
  env?: NodeJS.ProcessEnv;
  isWsl?: boolean;
}
⋮----
export function watchDisabledReason(projectRoot: string, probe: WatchProbe =
⋮----
export function __resetWslCacheForTests(): void
⋮----
export function __setWslWindowsDriveForTests(fn: ((p: string) => boolean) | null): void
</file>

<file path="src/sync/watcher.ts">
import { isSourceFile, buildScopeIgnore, type ScopeIgnore } from '../extraction';
import { loadExtensionOverrides, PROJECT_CONFIG_FILENAME } from '../project-config';
import { logDebug, logWarn } from '../errors';
import { normalizePath } from '../utils';
import { isCodeGraphDataDir } from '../directory';
import { watchDisabledReason } from './watch-policy';
⋮----
function isWatchResourceExhaustion(err: unknown): boolean
⋮----
function isInotifyWatchExhaustion(err: unknown): boolean
⋮----
function supportsRecursiveWatch(): boolean
⋮----
type WatchFn = typeof fs.watch;
⋮----
export function __setFsWatchForTests(fn: WatchFn | null): void
⋮----
function maxDirWatches(): number
⋮----
export interface WatchOptions {
  debounceMs?: number;
  onSyncComplete?: (result: { filesChanged: number; durationMs: number }) => void;
  onSyncError?: (error: Error) => void;
  onDegraded?: (reason: string) => void;
  inertForTests?: boolean;
}
⋮----
export class LockUnavailableError extends Error
⋮----
constructor(message = 'CodeGraph file lock unavailable; another process is writing')
⋮----
export interface PendingFile {
  path: string;
  firstSeenMs: number;
  lastSeenMs: number;
  indexing: boolean;
}
⋮----
export class FileWatcher
⋮----
constructor(
    projectRoot: string,
    syncFn: (paths?: string[]) => Promise<{ filesChanged: number; durationMs: number }>,
    options: WatchOptions = {},
    isFileStateCurrent?: (relativePath: string) => boolean
)
⋮----
start(): boolean
⋮----
private startRecursive(): void
⋮----
private refreshWatchTree(): void
⋮----
const walk = (dir: string, linked: boolean): void =>
⋮----
private scheduleTreeRefresh(): void
⋮----
private watchDirectory(dir: string, real: string, recursive: boolean): void
⋮----
private handleDirEvent(dir: string, filename: string | Buffer | null): void
⋮----
private handleChange(rel: string): void
⋮----
private refreshScope(rel: string): void
⋮----
private maybeScheduleForRemovedDir(rel: string): void
⋮----
private unwatchDir(dir: string): void
⋮----
private isAlwaysIgnored(rel: string): boolean
⋮----
private shouldIgnoreDir(dirPath: string): boolean
⋮----
private degrade(reason: string, context: Record<string, unknown> =
⋮----
private warnInotifyLimit(context: Record<string, unknown> =
⋮----
isDegraded(): boolean
⋮----
getDegradedReason(): string | null
⋮----
isRecoveringFromLock(): boolean
⋮----
rearmAfterLockContention(): boolean
⋮----
stop(): void
⋮----
ingestEventForTests(relPath: string): void
⋮----
isActive(): boolean
⋮----
waitUntilReady(timeoutMs = 10000): Promise<void>
⋮----
const handler = () =>
⋮----
private scheduleSync(): void
⋮----
private scheduleRetrySync(delayMs: number): void
⋮----
private async flush(): Promise<void>
... (5 lines truncated)
</file>

<file path="src/sync/worktree.ts">
import { execFileSync } from 'child_process';
⋮----
export function gitWorktreeRoot(dir: string): string | null
⋮----
export function gitCommonDir(dir: string): string | null
⋮----
export interface WorktreeIndexMismatch {
  worktreeRoot: string;
  indexRoot: string;
}
⋮----
export function detectWorktreeIndexMismatch(
  startPath: string,
  indexRoot: string,
): WorktreeIndexMismatch | null
⋮----
export function worktreeMismatchWarning(m: WorktreeIndexMismatch): string
⋮----
export function worktreeMismatchNotice(m: WorktreeIndexMismatch): string
⋮----
function realpath(p: string): string
</file>

<file path="src/telemetry/index.ts">
import { randomUUID } from 'crypto';
⋮----
export type UsageKind = 'mcp_tool' | 'cli_command';
export type LifecycleEvent = 'install' | 'index' | 'uninstall';
⋮----
export function bucketFileCount(n: number): '<100' | '100-1k' | '1k-10k' | '10k+'
⋮----
export function bucketDuration(ms: number): '<10s' | '10-60s' | '1-5m' | '5m+'
⋮----
export function recordIndexEvent(
  cg: { getStats(): { filesByLanguage: Record<string, number> } },
  result: { filesIndexed: number; durationMs: number },
): void
⋮----
cg:
⋮----
export interface ClientInfo {
  name?: string;
  version?: string;
}
⋮----
interface ConfigFile {
  enabled: boolean;
  machine_id: string | null;
  consent_source: 'installer' | 'default-notice' | 'cli';
  first_run_notice_shown?: boolean;
  updated_at: string;
}
⋮----
export interface TelemetryStatus {
  enabled: boolean;
  decidedBy: 'DO_NOT_TRACK' | 'CODEGRAPH_TELEMETRY' | 'config' | 'default';
  machineId: string | null;
  configPath: string;
}
⋮----
interface CountLine {
  v: number;
  d: string;
  k: UsageKind;
  n: string;
  c: number;
  e: number;
  cn?: string;
  cv?: string;
}
interface EventLine {
  v: number;
  ev: LifecycleEvent;
  ts: string;
  props: Record<string, unknown>;
}
type BufferLine = CountLine | EventLine;
⋮----
export interface TelemetryOptions {
  dir?: string;
  fetchImpl?: typeof globalThis.fetch;
  now?: () => Date;
  env?: NodeJS.ProcessEnv;
  stderr?: (line: string) => void;
  installExitHook?: boolean;
}
⋮----
function registerForExit(instance: Telemetry): void
⋮----
export class Telemetry
⋮----
constructor(opts: TelemetryOptions =
⋮----
get configPath(): string
get queuePath(): string
⋮----
getStatus(): TelemetryStatus
⋮----
isEnabled(): boolean
⋮----
setEnabled(enabled: boolean, source: 'installer' | 'cli'): void
⋮----
hasStoredChoice(): boolean
⋮----
recordUsage(kind: UsageKind, name: string, ok: boolean, client?: ClientInfo): void
⋮----
recordLifecycle(event: LifecycleEvent, props: Record<string, unknown>): void
⋮----
maybeFlush(): void
⋮----
async flushNow(timeoutMs: number = DEFAULT_FLUSH_TIMEOUT_MS): Promise<void>
⋮----
startInterval(everyMs: number = 6 * 60 * 60_000): void
⋮----
stopInterval(): void
⋮----
private utcDay(): string
⋮----
private clearPending(): void
⋮----
private canUseIdentity(identity: string | null): boolean
⋮----
private readConfig(): ConfigFile | null
⋮----
... (22 lines truncated)
</file>

<file path="src/ui/color.ts">
export function ansiColorsEnabled(): boolean
</file>

<file path="src/ui/glyphs.ts">
export function supportsUnicode(): boolean
⋮----
export interface Glyphs {
  ok: string;
  err: string;
  info: string;
  warn: string;
  spinner: string[];
  barFilled: string;
  barEmpty: string;
  rail: string;
  phaseDone: string;
  dash: string;
  hLine: string;
  treeBranch: string;
  treeLast: string;
  treePipe: string;
}
⋮----
export function getGlyphs(): Glyphs
⋮----
export function supportsUnicodeRawWrites(): boolean
⋮----
export function getRawWriteGlyphs(): Glyphs
⋮----
export function _resetGlyphsCache(): void
</file>

<file path="src/ui/shimmer-progress.ts">
import { Worker } from 'worker_threads';
⋮----
import { ansiColorsEnabled } from './color';
import { getGlyphs } from './glyphs';
⋮----
export interface IndexProgress {
  phase: string;
  current: number;
  total: number;
}
⋮----
export interface ShimmerProgress {
  onProgress: (progress: IndexProgress) => void;
  stop: () => Promise<void>;
}
⋮----
export function createShimmerProgress(): ShimmerProgress
⋮----
// The persistent "phase done" lines — the ones that stay in scrollback —
// are printed HERE, on the main thread, not by the worker. process.stdout
// reaches a Windows console through the wide-char API, so these lines can
// carry the same Unicode glyphs @clack/prompts draws around them (#398);
// the worker's raw fs.writeSync path can't (codepage mojibake, #168) and is
⋮----
const printPhaseDone = (): void =>
⋮----
// Leading \r + erase clears the worker's in-flight animation line; one
⋮----
onProgress(progress: IndexProgress)
⋮----
stop()
⋮----
const finish = (): void =>
⋮----
function createPlainProgress(): ShimmerProgress
</file>

<file path="src/ui/shimmer-worker.ts">
import { parentPort, workerData } from 'worker_threads';
import { writeSync } from 'fs';
import { getRawWriteGlyphs } from './glyphs';
import type { ShimmerWorkerMessage } from './types';
⋮----
function writeStdout(s: string): void
⋮----
function animFrame(): number
⋮----
function lerp(a: number, b: number, t: number): number
⋮----
function shimmerColor(frame: number): string
⋮----
function formatNumber(n: number): string
⋮----
function renderBar(frame: number, filled: number, empty: number): string
⋮----
// Mutable state
⋮----
function render(): void
⋮----
// Clear the in-flight animation line. The persistent "phase done" line is
// printed by the PARENT on the main thread (TTY-aware, codepage-immune) —
// this worker's raw-byte path must never leave bytes in scrollback (#398).
function clearLine(): void
⋮----
// Render loop — independent of main thread
</file>

<file path="src/ui/types.ts">
export type ShimmerWorkerMessage =
  | { type: 'update'; phase: string; phaseName: string; percent: number; count: number }
  | { type: 'stop' };
⋮----
export type ShimmerMainMessage =
  | { type: 'stopped' };
</file>

<file path="src/ui-server/api/deadcode.ts">
import type { CodeGraph } from '../../index';
import type { NodeKind } from '../../types';
import {
  buildDeadCodeReport,
  DEAD_CODE_ALLOWED_KINDS,
  MAX_CORROBORATION_BYTES,
  MAX_DEAD_CODE_CANDIDATES,
  type DeadCodeExclusions,
} from '../../graph/dead-code';
import { intParam } from './respond';
import { readIndexedFileText } from './source';
import { toNodeRef, wireList, type WireList, type WireNodeRef } from './wire';
⋮----
export interface WireDeadCodeRow extends WireNodeRef {
  lines: number;
  members: WireList<WireNodeRef>;
}
⋮----
export interface WireDeadCodeGroup {
  file: string;
  generated: boolean;
  test: boolean;
  lines: number;
  rows: WireDeadCodeRow[];
}
⋮----
export interface WireDeadCodeExclusion {
  reason: keyof DeadCodeExclusions;
  count: number;
  label: string;
}
⋮----
export interface WireDeadCode {
  rows: WireList<WireDeadCodeRow>;
  groups: WireDeadCodeGroup[];
  candidates: number;
  excluded: WireDeadCodeExclusion[];
  excludedTotal: number;
  kinds: NodeKind[];
  includeExported: boolean;
  includeTests: boolean;
  includeGenerated: boolean;
  bounded: boolean;
  corroborated: boolean;
  timing: { elapsedMs: number };
}
⋮----
export function parseDeadCodeQuery(query: URLSearchParams):
⋮----
export function buildDeadCode(
  cg: CodeGraph,
  projectRoot: string,
  query: URLSearchParams
): WireDeadCode
</file>

<file path="src/ui-server/api/effects.ts">
import type { Language } from '../../types';
⋮----
export type EffectCategory =
  | 'network'
  | 'storage'
  | 'device'
  | 'telemetry'
  | 'database'
  | 'response'
  | 'queue'
  | 'email'
  | 'payments'
  | 'cache'
  | 'auth'
  | 'process';
⋮----
export type ProjectKind = 'app' | 'api' | 'web';
⋮----
type Family = 'js' | 'py' | 'jvm' | 'cs' | 'go' | 'c' | 'rb' | 'php' | 'swift' | 'rs';
⋮----
export interface EffectRule {
  category: EffectCategory;
  test: RegExp;
  only?: readonly Family[];
  instantiates?: boolean;
}
⋮----
export interface EffectInput {
  text: string;
  kind: 'calls' | 'instantiates';
  language?: Language | null;
  project?: ProjectKind;
  receiverType?: string | null;
  args?: string | null;
  projectType?: boolean;
}
⋮----
export interface Effect {
  category: EffectCategory;
  model?: string;
  access?: 'read' | 'write';
}
⋮----
function familiesOf(language: Language | null | undefined): Family[]
⋮----
export function normaliseCall(text: string): string
⋮----
/**
 * Swift names the table knows from other stacks: Foundation's `Timer`
 * schedules work (Micrometer's is telemetry), `Calendar` does date math
 * (expo-calendar's is the device), and an `intent` is SiriKit configuration.
 */
⋮----
export function classifyEffect(input: EffectInput): Effect | null
⋮----
// A thrown web exception is a response, in a project that has endpoints.
⋮----
function withShape(category: EffectCategory, text: string, args: string | null, language: Language | null, receiverType: string | null): Effect
⋮----
function modelOf(segments: string[], args: string | null, receiverType: string | null): string | null
⋮----
// `prisma.user.create`, `db.users.insert`, `_context.TodoItems.Add`, `this.prisma.user.findMany`.
⋮----
// `User.objects.filter`, `User.query.get`, `User.find`, `Todo.query(on:)`, `User::find`.
⋮----
// Spring: `owners.save` where `owners` is an `OwnerRepository`.
⋮----
// `knex('users')`, `db.from('users')`, `collection('todos')`, `sql.table('x')`.
⋮----
// =============================================================================
// Response status
// =============================================================================
⋮----
function statusOfName(raw: string): number | null
⋮----
// `UserNotFound`, `InvalidTokenUnauthorized`: the status name ends the class name.
⋮----
/**
 * The status code a response site sends, when it is literal: the number in
 * `res.status(404)`, the name in `ResponseEntity.notFound()`,
 * `throw new NotFoundException()`, `c.JSON(http.StatusCreated, …)`,
 * `HTTPException(status_code=404)`, `Abort(.notFound)`. Null when the code
 * is a variable or the site sets none.
 */
export function responseStatus(text: string, args: string | null | undefined, _kind: 'calls' | 'instantiates' = 'calls'): number | null
⋮----
// The status is the argument: `res.status(404)`, `res.sendStatus(204)`, `abort(404)`, `StatusCode(500)`, `c.String(200, …)`, `http.Error(w, m, 500)`.
⋮----
// `new ModelAndView("redirect:/owners")` redirects; any other view renders (implicitResponseStatus).
⋮----
/**
 * The status a reply sends when it sets none — 200 — for the calls that send a
 * body and default to it: Express / Koa / Fastify / Hono `res.json`,
 * `res.send`, `res.render`, `reply.send`, `c.json`; `NextResponse.json`;
 * Python's `JSONResponse`, `jsonify`, `render_template`, `HttpResponse`;
 * Rails' `render`; Laravel's `response()->json`. Null when the chain sets a
 * status of its own (`res.status(code).json` — a variable code is unknown,
 * not 200), when the call ends a response without a body (`end`,
 * `sendStatus`), or when the call is not one of these.
 */
... (11 lines truncated)
</file>

<file path="src/ui-server/api/entrypoints.ts">
import type { CodeGraph } from '../../index';
import type { Node, NodeKind } from '../../types';
import { intParam } from './respond';
import { buildRoutes, type WireRoute } from './routes';
import { isTestFile, isTestPath } from '../../search/query-utils';
import { toNodeRef, toPosixPath, wireList, type WireList, type WireNodeRef } from './wire';
import { readIndexedFileText } from './source';
⋮----
export interface WireEntryFile extends WireNodeRef {
  calls: number;
  reaches: number;
  dependents: number;
}
⋮----
export interface WireEntryTest extends WireNodeRef {
  reaches: number;
  refs: number;
}
⋮----
export interface WireEntryHub extends WireNodeRef {
  dependents: number;
}
⋮----
export interface WireEntryPoints {
  frameworks: string[];
  routes: {
    routed: boolean;
    routeCount: number;
    items: WireList<WireRoute>;
  };
  files: WireList<WireEntryFile>;
  tests: WireList<WireEntryTest>;
  hubs: WireList<WireEntryHub>;
  index: { lastIndexedAt: number | null; files: number };
  timing: { elapsedMs: number; cached: boolean };
}
⋮----
export function resetEntryPointsCache(): void
⋮----
export function buildEntryPoints(cg: CodeGraph, query: URLSearchParams): WireEntryPoints
⋮----
function routeEntries(cg: CodeGraph, limit: number): WireEntryPoints['routes']
⋮----
function executableFiles(cg: CodeGraph, limit: number): WireList<WireEntryFile>
⋮----
function withoutPreviews<T extends
⋮----
export function swiftPreviewSpans(text: string): Array<[number, number]>
⋮----
function testFiles(cg: CodeGraph, limit: number): WireList<WireEntryTest>
⋮----
function hubs(cg: CodeGraph, limit: number): WireList<WireEntryHub>
⋮----
function directoryOf(filePath: string): string
</file>

<file path="src/ui-server/api/events.ts">
import type { IncomingMessage, ServerResponse } from 'http';
import type { CodeGraph } from '../../index';
import { getCodeGraphDir } from '../../directory';
import { FileWatcher } from '../../sync/watcher';
import type { GraphSession } from './session';
⋮----
export interface WireIndexRevision {
  lastIndexedAt: number | null;
  files: number;
}
⋮----
export interface WireEventHello {
  type: 'hello';
  index: WireIndexRevision | null;
  watching: { source: boolean; index: boolean };
  degraded: string | null;
  heartbeatMs: number;
  at: number;
}
⋮----
export interface WireEventChanged {
  type: 'changed';
  files: string[];
  total: number;
  truncated: boolean;
  scan: boolean;
  at: number;
}
⋮----
export interface WireEventIndex {
  type: 'index';
  index: WireIndexRevision;
  files: string[];
  total: number;
  truncated: boolean;
  at: number;
}
⋮----
export interface WireEventDegraded {
  type: 'degraded';
  reason: string;
  at: number;
}
⋮----
export type WireEvent =
  | WireEventHello
  | WireEventChanged
  | WireEventIndex
  | WireEventDegraded;
⋮----
interface Client {
  res: ServerResponse;
  heartbeat: ReturnType<typeof setInterval>;
}
⋮----
export class EventHub
⋮----
constructor(projectRoot: string, session: GraphSession)
⋮----
subscribe(req: IncomingMessage, res: ServerResponse, method: string): true
⋮----
const drop = (): void
⋮----
get size(): number
⋮----
close(): void
⋮----
private drop(client: Client): void
⋮----
private send(client: Client, event: WireEvent): void
⋮----
private broadcast(event: WireEvent): void
⋮----
private ensureWatching(): void
⋮----
private stopWatching(): void
⋮----
private startSourceWatcher(): void
⋮----
private announceChanged(paths?: string[]): void
⋮----
private startIndexWatcher(): void
⋮----
private scheduleProbe(): void
⋮----
private checkIndex(): void
⋮----
private probe(): WireIndexRevision | null
</file>

<file path="src/ui-server/api/file.ts">
import type { CodeGraph } from '../../index';
import type { Edge, Node } from '../../types';
import { isTestFile } from '../../search/query-utils';
import { hasDriftedOnDisk, resolveRequestedFile } from './source';
import {
  MAX_IMPORT_FILES,
  MAX_OUTLINE_NODES,
  toNodeRef,
  toPosixPath,
  wireList,
  type WireNodeRef,
} from './wire';
⋮----
export interface WireOutlineEntry extends WireNodeRef {
  parentId: string | null;
  depth: number;
  fanIn: number;
  fanOut: number;
}
⋮----
export interface WireImportRow {
  file: string;
  test: boolean;
  symbols: Array<{ id: string; name: string; kind: string; line: number }>;
  symbolCount: number;
}
⋮----
export function buildFile(cg: CodeGraph, projectRoot: string, requested: string): unknown
⋮----
export function buildOutlineEntries(
  cg: CodeGraph,
  nodes: readonly Node[]
):
⋮----
function resolveOutlineParent(
  id: string,
  parentOf: Map<string, string>,
  fileNodeId: string | undefined
): string | null
⋮----
function depthOf(
  id: string,
  parentOf: Map<string, string>,
  fileNodeId: string | undefined
): number
⋮----
function groupByFile(
  edges: readonly Edge[],
  endpoint: (edge: Edge) => string,
  nodes: Map<string, Node>
): WireImportRow[]
⋮----
function unresolvedImportsOf(
  cg: CodeGraph,
  fileNodeId: string
): Array<
</file>

<file path="src/ui-server/api/filecode.ts">
import type { CodeGraph } from '../../index';
import type { Edge, Node } from '../../types';
import { isTestFile } from '../../search/query-utils';
import { buildOutlineEntries, type WireOutlineEntry } from './file';
import { readFileShape, resolveRequestedFile } from './source';
import { badRequest } from './respond';
import {
  firstLine,
  groupRelations,
  toPosixPath,
  wireList,
  type WireList,
  type WireRelation,
} from './wire';
⋮----
export interface WireFileOutsideRef {
  line: number;
  col: number;
  name: string;
  kind: string;
}
⋮----
export interface WireFileCall {
  ownerId: string;
  ownerLine: number;
  relation: WireRelation;
}
⋮----
export interface WireFileCodePayload {
  file: {
    path: string;
    language: string;
    size: number;
    indexedAt: number;
    contentHash: string;
    generated: boolean;
    test: boolean;
    errors: string[];
    id: string | null;
    totalLines: number | null;
  };
  drift: boolean;
  reason?: string;
  outline: WireList<WireOutlineEntry>;
  calls: WireList<WireFileCall>;
  outside: WireList<WireFileOutsideRef>;
  intraFileCalls: number;
  timing: { elapsedMs: number };
}
⋮----
export function buildFileCode(
  cg: CodeGraph,
  projectRoot: string,
  requested: string
): WireFileCodePayload
⋮----
// Refusal first, index lookup second — see `resolveRequestedFile`.
⋮----
function buildCalls(
  cg: CodeGraph,
  nodes: readonly Node[],
  posixPath: string
):
⋮----
function buildOutsideRefs(
  cg: CodeGraph,
  storedPath: string
):
⋮----
/** The trailing segment of a dotted name — what actually appears in the source. */
function lastSegment(name: string): string
</file>

<file path="src/ui-server/api/flow.ts">
import type CodeGraph from '../../index';
import type { Edge, Language, Node } from '../../types';
import { guardLabel, guardsForFile, siteKey, supportsBranchGuards } from '../../graph/branch-guards';
import {
  resolveNamedSymbolFlow,
  normalizeToken,
  DIRECTED_MAX_HOPS,
} from '../../graph/named-symbol-flow';
import {
  continuationsFrom,
  findDynamicBoundaries,
  type BoundaryContinuation,
  type NodeBoundary,
} from '../../graph/dynamic-boundary-report';
import { highlightLines, type HighlightResult } from '../highlight';
import { badRequest, intParam } from './respond';
⋮----
import { MAX_TRAIL_HOPS } from './trail-store';
import { findIndexedFile, hasDriftedOnDisk, splitLines, toRequestPath } from './source';
import { resolveProjectFile } from '../security';
import {
  toNodeRef,
  toWireEdge,
  wireList,
  UNCERTAIN_BELOW,
  type WireEdge,
  type WireList,
  type WireNodeRef,
} from './wire';
⋮----
export interface WireFlowEdge extends WireEdge {
  label: string;
  upward: boolean;
  uncertain: boolean;
  synthesized: boolean;
}
⋮----
export interface WireFlowSource {
  file: string;
  language: string;
  from: number;
  to: number;
  lines?: string[];
  highlight?: HighlightResult;
  drift: boolean;
  reason?: string;
}
⋮----
export interface WireFlowCallRef {
  line: number;
  col: number | null;
  name: string;
  targetId: string;
  backwards: boolean;
}
⋮----
export interface WireFlowHop {
  node: WireNodeRef;
  edge: WireFlowEdge | null;
  callRef: WireFlowCallRef | null;
  source: WireFlowSource | null;
}
⋮----
export interface WireBoundaryCandidate {
  node: WireNodeRef;
  display: string;
  named: boolean;
}
⋮----
export interface WireBoundarySite {
  form: string;
  label: string;
  snippet: string;
  line: number;
  key: string | null;
  keyIsType: boolean;
  moreSites: number;
  candidates: WireBoundaryCandidate[];
  candidateNote: string | null;
}
⋮----
export interface WireFlowContinuation {
  node: WireNodeRef;
  line: number | null;
  confidence: number | null;
}
⋮----
export interface WireFlowBoundary {
  node: WireNodeRef;
  sites: WireBoundarySite[];
  uncertain: WireList<WireFlowContinuation>;
  further: WireList<WireFlowContinuation>;
  missed: WireNodeRef[];
}
⋮----
export interface WireFlow {
  id: string;
  label: string;
  hops: WireFlowHop[];
  boundary: WireFlowBoundary | null;
... (176 lines truncated)
</file>

<file path="src/ui-server/api/hierarchy.ts">
import type { CodeGraph } from '../../index';
import type { Node } from '../../types';
import {
  buildTypeHierarchy,
  canHaveHierarchy,
  type HierarchyEntry,
  type HierarchyRelation,
  type TypeHierarchy,
} from '../../graph/type-hierarchy';
import { toNodeRef, wireList, type WireList, type WireNodeRef } from './wire';
⋮----
export interface WireHierarchyNode extends WireNodeRef {
  depth: number;
  parentId: string;
  relation: HierarchyRelation;
  synthesized: boolean;
  via?: string;
  registeredAt?: string;
  hiddenSubtypes: number;
}
⋮----
export interface WireHierarchy {
  ancestors: WireList<WireHierarchyNode>;
  descendants: WireList<WireHierarchyNode>;
  direct: number;
  implementers: number;
  bounded: boolean;
  polymorphic: boolean;
}
⋮----
export interface WireOverride {
  baseId: string;
  baseTypeId: string;
  baseTypeName: string;
  relation: HierarchyRelation;
}
⋮----
export function buildHierarchy(
  cg: CodeGraph,
  node: Node
):
⋮----
function toWireHierarchyNode(entry: HierarchyEntry): WireHierarchyNode
</file>

<file path="src/ui-server/api/index.ts">
import type { UiApiHandler, UiRequestContext } from '../index';
import { PathRefusalError } from '../security';
import { GraphSession } from './session';
import { ApiError, badRequest, fail, notFound, ok, readJsonBody } from './respond';
import { buildStats } from './stats';
import { buildSearch } from './search';
import { buildNode } from './node';
import { buildSource } from './source';
import { buildFile } from './file';
import { buildFileCode } from './filecode';
import { buildRoutes } from './routes';
import { buildEntryPoints } from './entrypoints';
import { buildNodeRefs } from './nodes';
import { buildMap } from './map';
import { buildScreens } from './screens';
import { buildSteps } from './steps';
import { buildDeadCode } from './deadcode';
import { buildFlow } from './flow';
import { buildTrails, removeTrail, saveTrail, type TrailsOptions } from './trails';
import { EventHub } from './events';
⋮----
export interface GraphApi {
  handler: UiApiHandler;
  close(): void;
}
⋮----
close(): void;
⋮----
export interface GraphApiOptions {
  projectRoot: string;
  readOnly?: boolean;
  readOnlyReason?: string;
}
⋮----
export function createGraphApi(options: GraphApiOptions): GraphApi
⋮----
const handler: UiApiHandler = async (req, res, ctx) =>
⋮----
async function dispatchWrite(
  route: string,
  req: Parameters<UiApiHandler>[0],
  res: Parameters<UiApiHandler>[1],
  ctx: UiRequestContext,
  session: GraphSession,
  trails: TrailsOptions
): Promise<boolean>
⋮----
async function dispatchPathRoutes(
  route: string,
  res: Parameters<UiApiHandler>[1],
  ctx: UiRequestContext,
  session: GraphSession
): Promise<boolean>
⋮----
// Before `/api/file/`: that prefix is not a prefix of this route, but keeping
// the more specific one first means adding another `/api/file…` sibling later
// cannot silently start matching the shorter one.
⋮----
// `/api/node` and `/api/file` with no argument at all, so the message can say
// what the endpoint wants instead of falling through to a bare 404.
⋮----
function normalize(pathname: string): string
⋮----
function suffixAfter(route: string, prefix: string): string | null
</file>

<file path="src/ui-server/api/map.ts">
import type { CodeGraph } from '../../index';
import type { EdgeKind, Language } from '../../types';
import { isTestFile } from '../../search/query-utils';
import { badRequest } from './respond';
import { UNCERTAIN_BELOW, toPosixPath, wireList, type WireList } from './wire';
⋮----
export function rootFilesId(root: string): string
⋮----
export interface WireMapModule {
  id: string;
  label: string;
  files: number;
  symbols: number;
  languages: Array<{ language: Language; files: number }>;
  test: boolean;
  generated: number;
  generatedFiles: string[];
  facade: boolean;
  fileList: WireList<string>;
  dependents: { files: number; modules: number };
}
⋮----
export interface WireMapLink {
  source: string;
  target: string;
  count: number;
  declared: number;
  byKind: Array<{ kind: EdgeKind; count: number }>;
  topPairs: Array<{ from: string; to: string; count: number; declared: number }>;
}
⋮----
export interface WireMapCycle {
  size: number;
  files: string[];
  modules: string[];
}
⋮----
export interface WireMapPayload {
  root: string;
  depth: number;
  roots: Array<{ root: string; label: string; files: number }>;
  modules: WireMapModule[];
  links: WireMapLink[];
  cycles: { total: number; shown: number; truncated: boolean; items: WireMapCycle[] };
  excluded: {
    uncertainEdges: number;
    confidenceBelow: number;
  };
  index: { lastIndexedAt: number | null; edges: number; files: number };
  timing: { elapsedMs: number; cached: boolean };
}
⋮----
export interface MapQuery {
  root: string;
  depth: number;
}
⋮----
export function normalizeRoot(raw: string | undefined): string
⋮----
function stemOf(basename: string): string
⋮----
/**
 * Directories a module boundary never falls on: exactly one subdirectory and
 * no file of their own. A Maven project keeps every line of Java under
 * `src/main/java/org/springframework/samples/petclinic/`, and the first four
 * of those folders split nothing — cutting at any of them draws the whole
 * program as one box, and no depth the reader can pick gets past them. Such a
 * folder joins the level below it, so depth counts folders that fork.
 *
 * Read from every indexed file, tests included, so a module's id does not
 * change when the reader toggles tests. The repository root is never one.
 */
export function passThroughDirs(paths: Iterable<string>): Set<string>
⋮----
/**
 * Where each level of a file's directory path ends, as indexes into `dirs`: a
 * level is one folder plus every pass-through folder that follows it.
 */
function levelEnds(root: string, dirs: readonly string[], passThrough: ReadonlySet<string> | undefined): number[]
⋮----
function joinPath(root: string, segments: readonly string[]): string
⋮----
function levelLabel(root: string, dirs: readonly string[], ends: readonly number[]): string
⋮----
export function moduleIdFor(
  filePath: string,
  root: string,
  depth: number,
  passThrough?: ReadonlySet<string>
):
⋮----
/**
 * The root the map opens on: the directory holding the most non-test symbols.
 *
 * A repository's source almost always lives under one directory (`src`, `lib`,
 * `pkg`, `app`), and opening there is what keeps the default map about the
 * program rather than about its tests, scripts and sibling packages. The
 * fallback is the repository root, which is correct for a flat project.
 *
 * A directory only wins if it holds a clear majority of the symbols — anything
... (85 lines truncated)
</file>

<file path="src/ui-server/api/node.ts">
import type { CodeGraph } from '../../index';
import type { Edge, Node, NodeKind } from '../../types';
import { isTestFile } from '../../search/query-utils';
import { buildHierarchy, type WireOverride } from './hierarchy';
import { notFound } from './respond';
import { findIndexedFile, hasDriftedOnDisk } from './source';
import { annotateWhen } from './when';
import {
  BLAST_DEPTH,
  CALLER_EDGE_KINDS,
  CONTAINER_KINDS,
  HUB_THRESHOLD,
  MAX_INCOMING_GROUPS,
  MAX_OUTGOING_GROUPS,
  MAX_OUTLINE_NODES,
  MAX_OUTSIDE_INDEX_SAMPLES,
  MAX_TEST_FILES,
  TEST_CALLER_BUDGET,
  TEST_CALLER_HOPS,
  TYPE_KINDS,
  firstLine,
  groupRelations,
  toNodeDetail,
  toNodeRef,
  toPosixPath,
  wireList,
  type WireNodeRef,
} from './wire';
⋮----
export interface WireMember extends WireNodeRef {
  parentId: string;
  depth: number;
  fanIn: number;
  fanOut: number;
  overrides?: WireOverride;
}
⋮----
export async function buildNode(cg: CodeGraph, projectRoot: string, nodeId: string): Promise<unknown>
⋮----
function buildMembers(
  cg: CodeGraph,
  focal: Node,
  containsOut: readonly Edge[],
  endpoints: Map<string, Node>,
  overrides?: Map<string, WireOverride>
):
⋮----
export interface WireTestSummary {
  reached: boolean;
  hops: number | null;
  fileCount: number;
  files: string[];
  exhaustive: boolean;
  hopsSearched: number;
}
⋮----
function summarizeTestCallers(cg: CodeGraph, directCallers: readonly Node[]): WireTestSummary
⋮----
function summarizeOutsideIndex(
  cg: CodeGraph,
  nodeId: string
):
⋮----
export interface WireBlastSummary {
  direct: number;
  withinHops: number;
  hops: number;
  files: number;
  testFiles: number;
  routes: number;
  topFiles: Array<{ file: string; symbols: number; test: boolean }>;
}
⋮----
function summarizeBlast(cg: CodeGraph, node: Node, direct: number): WireBlastSummary | null
⋮----
function driftFor(cg: CodeGraph, projectRoot: string, filePath: string): boolean
</file>

<file path="src/ui-server/api/nodes.ts">
import type { CodeGraph } from '../../index';
import { badRequest } from './respond';
import { toNodeRef, type WireNodeRef } from './wire';
⋮----
export interface WireNodeRefs {
  items: WireNodeRef[];
  missing: string[];
}
⋮----
export function buildNodeRefs(cg: CodeGraph, query: URLSearchParams): WireNodeRefs
</file>

<file path="src/ui-server/api/program.ts">
import { guardLabel, type BranchGuard, type SiteLoop } from '../../graph/branch-guards';
import type { WireNodeRef } from './wire';
⋮----
export type WireArmEnd = 'reply' | 'return' | 'throw' | 'exit';
⋮----
export interface WireArm {
  when: string;
  not?: true;
  ends: WireArmEnd | null;
  body: WireBlock;
}
⋮----
export type WireBlock = WireItem[];
⋮----
export type WireItem =
  | { kind: 'step'; step: string; link?: string; within?: string; body?: WireBlock; again?: true }
  | { kind: 'fork'; on: string; form: 'if' | 'switch' | 'ternary' | 'try'; arms: WireArm[] }
  | {
      kind: 'block';
      block: 'inline' | 'loop' | 'later' | 'together';
      by?: string;
      loop?: 'each' | 'while';
      via?: WireNodeRef;
      within?: string;
      body: WireBlock;
      again?: true;
    }
  | { kind: 'cut'; why: 'folded' | 'depth' };
⋮----
export interface WireProgram {
  root: WireBlock;
  truncated: number;
}
⋮----
export interface ProgramSite {
  step?: string;
  link?: string;
  into?: string;
  at: { line: number; column: number; end: { line: number; column: number } };
  within?: string;
  guards: BranchGuard[];
  loops?: SiteLoop[];
  trigger?: { kind: string; name: string; of?: string | null };
}
⋮----
export interface ProgramInput {
  sites: ReadonlyMap<string, readonly ProgramSite[]>;
  root: string | null;
  node(id: string): WireNodeRef | null;
  step(id: string): { reply: boolean; into: string | null } | null;
}
⋮----
node(id: string): WireNodeRef | null;
⋮----
step(id: string):
⋮----
interface Reading {
  truncated: number;
  items: number;
  read: Set<string>;
}
⋮----
export function buildProgram(input: ProgramInput): WireProgram | null
⋮----
function blockFor(input: ProgramInput, fn: string, path: readonly string[], state: Reading): WireBlock
⋮----
const bodyAt = (depth: number): WireBlock
⋮----
interface Open {
  branch: string;
  fork?: Extract<WireItem, { kind: 'fork' }>;
  armKey?: string;
  body: WireBlock;
}
⋮----
type Scope = { kind: 'guard'; branch: string; guard: BranchGuard } | { kind: 'loop'; branch: string; loop: SiteLoop };
⋮----
function scopesOf(site: ProgramSite): Scope[]
⋮----
function at(branch: string): number
⋮----
function sameScope(open: Open, scope: Scope): boolean
⋮----
function openScope(into: WireBlock, scope: Scope): Open
⋮----
function itemFor(input: ProgramInput, site: ProgramSite, path: readonly string[], state: Reading): WireItem | null
⋮----
function open(fn: string, path: readonly string[], state: Reading): boolean
⋮----
function place(block: WireBlock, item: WireItem, site: ProgramSite): void
⋮----
function runFor(site: ProgramSite):
⋮----
function armFor(fork: Extract<WireItem,
⋮----
function armKey(g: BranchGuard): string
⋮----
function formOf(g: BranchGuard): 'if' | 'switch' | 'ternary' | 'try'
⋮----
function seal(input: ProgramInput, block: WireBlock): void
... (10 lines truncated)
</file>

<file path="src/ui-server/api/respond.ts">
import type { IncomingMessage, ServerResponse } from 'http';
import { sendJson } from '../static';
⋮----
export type ApiErrorCode =
  | 'bad-request'
  | 'not-found'
  | 'refused'
  | 'no-index'
  | 'index-unusable'
  | 'internal';
⋮----
export class ApiError extends Error
⋮----
constructor(code: ApiErrorCode, message: string, hint?: string)
⋮----
export function badRequest(message: string, hint?: string): ApiError
⋮----
export function notFound(message: string, hint?: string): ApiError
⋮----
export function ok(res: ServerResponse, payload: unknown, method: string): true
⋮----
export function fail(res: ServerResponse, err: unknown, method: string): true
⋮----
export async function readJsonBody(req: IncomingMessage): Promise<unknown>
⋮----
export function requiredParam(query: URLSearchParams, name: string): string
⋮----
/**
 * A bounded integer parameter.
 *
 * Out-of-range values are an error rather than silently clamped: a viewer
 * asking for line 10 000 000 of a 200-line file has a bug, and answering it
 * with line 200 would hide that.
 */
export function intParam(
  query: URLSearchParams,
  name: string,
  opts: { min: number; max: number; default?: number }
): number
⋮----
/**
 * Free-form text input, bounded.
 *
 * The same reasoning as the MCP tools' input ceiling: a huge string is never a
 * real query, and letting one through means a full-table LIKE scan or an FTS5
 * parse over megabytes.
 */
⋮----
export function textParam(query: URLSearchParams, name: string): string
⋮----
export function optionalTextParam(query: URLSearchParams, name: string): string
⋮----
function boundLength(raw: string, name: string): string
</file>

<file path="src/ui-server/api/route-roots.ts">
import type CodeGraph from '../../index';
import type { Node } from '../../types';
⋮----
export interface RouteRoot {
  node: Node;
  inline: boolean;
}
⋮----
export function looksLikeComponent(node: Node): boolean
⋮----
export function routeLayouts(cg: CodeGraph, routes: readonly Node[]): Map<string, string[]>
⋮----
export function routeRoots(cg: CodeGraph, routes: readonly Node[]): Map<string, RouteRoot>
⋮----
const rank = (n: Node): number
</file>

<file path="src/ui-server/api/routes.ts">
import type { CodeGraph } from '../../index';
import { intParam } from './respond';
import { toPosixPath } from './wire';
⋮----
export interface WireRoute {
  url: string;
  method: string | null;
  path: string;
  handler: string;
  handlerKind: string;
  file: string;
  line: number;
  handlerId: string | null;
  routeFile: string;
  routeLine: number;
  routeId: string;
}
⋮----
export interface WireRoutes {
  routed: boolean;
  routeCount: number;
  shown: number;
  truncated: boolean;
  topHandlerFile: string | null;
  topHandlerFileCount: number;
  entries: WireRoute[];
}
⋮----
export function splitRouteName(url: string):
⋮----
export function buildRoutes(cg: CodeGraph, query: URLSearchParams): WireRoutes
</file>

<file path="src/ui-server/api/screens.ts">
import type CodeGraph from '../../index';
import type { Edge, Node } from '../../types';
import { routeLayouts, routeRoots } from './route-roots';
import { resolveProjectFile } from '../security';
import { findIndexedFile, hasDriftedOnDisk } from './source';
import { createWhenReader } from './when';
import { toNodeRef, type WireNodeRef } from './wire';
⋮----
export interface WireScreen {
  id: string;
  path: string;
  file: string;
  line: number;
  component: WireNodeRef | null;
  incoming: number;
  outgoing: number;
}
⋮----
export interface WireScreenOrigin {
  id: string;
  node: WireNodeRef;
  outgoing: number;
  sharedBy?: number;
}
⋮----
export interface WireScreenSite {
  file: string;
  line: number;
  href: string;
  method: string;
  when: string;
}
⋮----
export interface WireScreenLink {
  id: string;
  from: string;
  to: string;
  fromOrigin: boolean;
  via: WireNodeRef[];
  when: string;
  sites: WireScreenSite[];
  synthesized: boolean;
}
⋮----
export interface WireScreensPayload {
  routed: boolean;
  entry: string | null;
  screens: WireScreen[];
  origins: WireScreenOrigin[];
  links: WireScreenLink[];
  dropped: number;
  index: { lastIndexedAt: number | null; edges: number; files: number };
  timing: { elapsedMs: number };
}
⋮----
function arrivesFromAnotherContext(edge: Edge): boolean
⋮----
function writtenHere(edge: Edge, holder: Node): boolean
⋮----
function isScreenRoute(route: Node): boolean
⋮----
export async function buildScreens(cg: CodeGraph, projectRoot: string): Promise<WireScreensPayload>
⋮----
const whenAt = (caller: Node, edge: Edge): Promise<string> => readWhen(caller,
⋮----
const bump = (id: string, key: 'incoming' | 'outgoing') =>
⋮----
interface Attribution {
  screenId: string | null;
  path: Array<{ node: Node; edge: Edge | null }>;
}
⋮----
async function attribute(
  cg: CodeGraph,
  projectRoot: string,
  holder: Node,
  screenOfComponent: Map<string, string[]>,
  routeByFile: Map<string, string>,
  known: Map<string, Node>
): Promise<Attribution[] | null>
⋮----
function collapseSharedChrome(starts: Attribution[], origins: Map<string, WireScreenOrigin>): Attribution[]
⋮----
function mentionsOf(cg: CodeGraph, projectRoot: string, value: Node): Edge[]
⋮----
function valueSpanning(cg: CodeGraph, filePath: string, line: number, memo: Map<string, Node[]>): Node | null
⋮----
function pathFrom(
  start: string,
  parent: Map<string, { prev: string | null; edge: Edge | null }>,
  nodes: Map<string, Node>
): Array<
⋮----
function complementary(a: string, b: string): boolean
⋮----
function toPosix(p: string): string
</file>

<file path="src/ui-server/api/search.ts">
import type { CodeGraph } from '../../index';
import type { Node, NodeKind } from '../../types';
import { parseQuery, type ParsedQuery } from '../../search/query-parser';
import { intParam, optionalTextParam } from './respond';
import { toNodeRef, wireList, type WireNodeRef } from './wire';
⋮----
export type MatchKind = 'exact' | 'prefix' | 'substring' | 'qualified' | 'file' | 'related';
⋮----
export interface WireSearchResult extends WireNodeRef {
  matchKind: MatchKind;
}
⋮----
function kindRank(kind: NodeKind): number
⋮----
function classify(node: Node, needle: string): MatchKind | null
⋮----
export function buildSearch(cg: CodeGraph, query: URLSearchParams): unknown
⋮----
// The filter grammar (`kind:function auth`) belongs to `searchNodes`; the
// name lookups only ever want the free-text part of what was typed.
⋮----
const remember = (node: Node): void =>
⋮----
// `searchNodes` applies the filter grammar to its own results, but the two
// direct name lookups above know nothing about it — so `kind:class Cache`
// would otherwise pull in `CacheKey` and every `Cache` method through the
// substring lookup. The gate belongs to the merged candidate set.
⋮----
// An empty text portion means the query was pure filters (`kind:route`);
// everything `searchNodes` returned already satisfies them, so there is no
// name match to grade and every row is equally "related".
⋮----
function isTestPath(filePath: string): boolean
⋮----
function matchesFilters(node: Node, parsed: ParsedQuery): boolean
⋮----
function emptySearch(raw: string): unknown
</file>

<file path="src/ui-server/api/session.ts">
import { CodeGraph } from '../../index';
import { getDatabasePath } from '../../db';
import { isInitialized } from '../../directory';
import { ApiError } from './respond';
⋮----
interface FileIdentity {
  ino: number;
  birthtimeMs: number;
  size: number;
  mtimeMs: number;
  walSize: number;
  walMtimeMs: number;
}
⋮----
function identify(dbPath: string): FileIdentity | null
⋮----
function sameFile(a: FileIdentity | null, b: FileIdentity | null): boolean
⋮----
function sameContent(a: FileIdentity | null, b: FileIdentity | null): boolean
⋮----
function noIndexError(projectRoot: string): ApiError
⋮----
export class GraphSession
⋮----
constructor(projectRoot: string)
⋮----
acquire(): CodeGraph
⋮----
close(): void
⋮----
private closeQuietly(): void
</file>

<file path="src/ui-server/api/source.ts">
import { createHash } from 'crypto';
⋮----
import type { FileRecord } from '../../types';
import type { CodeGraph } from '../../index';
import { resolveProjectFile } from '../security';
import { indexedHashInput } from '../../file-limits';
import { highlightLines, type HighlightResult } from '../highlight';
import { ApiError, badRequest, intParam, notFound, textParam } from './respond';
⋮----
export function findIndexedFile(
  cg: CodeGraph,
  requested: string
):
⋮----
export function toRequestPath(requested: string): string
⋮----
/**
 * Validate a viewer-supplied path, THEN look it up in the index.
 *
 * The order is the point. `resolveProjectFile` runs first, so a traversal, an
 * absolute path or a sensitive system directory is refused as what it is,
 * before the index is consulted — a 403 that says "outside the project", not a
 * 404 that says "not indexed" and quietly depends on the index lookup missing.
 * It also means the absolute path every reader uses has already been through
 * the chokepoint by construction, rather than by remembering to call it.
 *
 * @throws {PathRefusalError} the path is not one we would ever read.
 * @throws {ApiError} `not-found` when it is fine but not in the index.
 */
export function resolveRequestedFile(
  cg: CodeGraph,
  projectRoot: string,
  requested: string
):
⋮----
// Refusals happen here, ahead of everything.
⋮----
export function notIndexedError(file: string): ApiError
⋮----
/**
 * Split source the way the index counted it.
 *
 * Rows are `\n`-delimited — that is how tree-sitter numbers them — so a CRLF
 * file has the same line numbers here as in the graph. The trailing `\r` is
 * dropped per line so it does not render as a stray glyph.
 */
export function splitLines(content: string): string[]
⋮----
/**
 * The whole text of an INDEXED file, or `null` for anything unreadable.
 *
 * The dead code report's corroboration pass needs to count an identifier in a
 * file's text, and this module is the only one in `api/` that opens a file — so
 * the reader it uses lives here, behind the same chokepoint. Three refusals,
 * all answering `null` rather than throwing, because the caller's rule is
 * already "cannot read it → do not make the claim":
 *
 * - not in the index (the viewer never reads a file the graph does not know);
 * - outside the project (`resolveProjectFile` throws; caught here);
 * - bigger than `maxBytes`.
 *
 * Drift is deliberately NOT checked. The question being asked is "does anything
 * in this file write this name", and the file's current bytes are the better
 * answer to it than the bytes we indexed.
 */
export function readIndexedFileText(
  cg: CodeGraph,
  projectRoot: string,
  requested: string,
  maxBytes: number
): string | null
⋮----
export function hasDriftedOnDisk(
  projectRoot: string,
  storedPath: string,
  record: FileRecord
): boolean
⋮----
export function readFileShape(
  projectRoot: string,
  storedPath: string,
  record: FileRecord
):
⋮----
export interface SourceResult {
  file: string;
  language: string;
  drift: boolean;
  showing: 'indexed' | 'current' | 'none';
  contentHash: string;
  indexedAt: number;
  generated: boolean;
  totalLines: number | null;
  from?: number;
  to?: number;
  lines?: string[];
  truncated?: boolean;
  reason?: string;
  highlight?: HighlightResult;
}
... (11 lines truncated)
</file>

<file path="src/ui-server/api/stats.ts">
import type { CodeGraph } from '../../index';
import { BLAST_DEPTH, HUB_THRESHOLD, UNCERTAIN_BELOW } from './wire';
⋮----
export interface WireBlastScale {
  maxDirect: number;
  maxWithinHops: number;
  hops: number;
  sampled: number;
  estimated: boolean;
}
⋮----
export function blastScaleFor(
  cg: CodeGraph,
  projectRoot: string,
  edgeCount: number
): WireBlastScale
⋮----
export function resetBlastScaleCache(): void
⋮----
export function buildStats(cg: CodeGraph, projectRoot: string): unknown
</file>

<file path="src/ui-server/api/steps.ts">
import type CodeGraph from '../../index';
import type { Edge, Language, Node, UnresolvedReference } from '../../types';
import { badRequest, intParam, notFound } from './respond';
import { createSiteReader } from './when';
import type { BranchGuard, SiteLoop, SiteTrigger } from '../../graph/branch-guards';
import { buildProgram, type ProgramSite, type WireProgram } from './program';
import { classifyEffect, implicitResponseStatus, responseStatus, type Effect } from './effects';
import { guardLabel } from '../../graph/branch-guards';
import { looksLikeComponent, routeRoots } from './route-roots';
import { nextRouteForFile } from '../../resolution/frameworks/nextjs';
import { splitRouteName } from './routes';
import { HUB_THRESHOLD, UNCERTAIN_BELOW, toNodeRef, type WireNodeRef } from './wire';
import { isTestPath } from '../../search/query-utils';
⋮----
export type WireStepKind = 'anchor' | 'screen' | 'trigger' | 'bridge' | 'event' | 'store' | 'effect';
⋮----
export type WireStepLinkKind = 'calls' | 'navigates' | 'handler' | 'bridge' | 'event' | 'store' | 'effect';
⋮----
export interface WireStepSite {
  file: string;
  line: number;
  text: string;
  args?: string;
  when: string;
  trigger?: WireStepTrigger;
  status?: number;
  decision?: WireStepDecision;
}
⋮----
export interface WireStepDecision {
  branch: string;
  on: string;
  arm: string;
  form: 'if' | 'switch' | 'ternary' | 'try';
  not?: true;
}
⋮----
export interface WireStepTrigger extends SiteTrigger {
  in: string;
}
⋮----
export interface WireStep {
  id: string;
  kind: WireStepKind;
  anchor: boolean;
  node: WireNodeRef | null;
  label: string;
  sub: string;
  depth: number;
  cut: 'depth' | 'fan-out' | 'folded' | 'steps' | 'screen' | 'component' | null;
  event?: string;
  events?: string[];
  trigger?: WireStepTrigger;
  order?: number;
  region?: { id: string; label: string };
  screen?: { path: string; component: WireNodeRef | null; endpoint: boolean; inline: boolean };
  effect?: {
    api: string;
    apis: string[];
    category: string;
    by: WireNodeRef;
    line: number;
    model?: string;
    access?: 'read' | 'write';
    statuses?: number[];
  };
}
⋮----
export interface WireStepLink {
  id: string;
  from: string;
  to: string;
  kind: WireStepLinkKind;
  via: WireNodeRef[];
  when: string;
  label: string;
  within?: string;
  synthesized: boolean;
  uncertain: boolean;
  sites: WireStepSite[];
  trigger?: WireStepTrigger;
}
⋮----
export interface WireStepsPayload {
  anchor: WireNodeRef;
  ambiguous: WireNodeRef[];
  project: 'app' | 'api' | 'web';
  steps: WireStep[];
  links: WireStepLink[];
  program: WireProgram | null;
  defaultView: 'order' | 'tree';
  depth: number;
  limit: number;
  through: boolean;
  truncated: {
    steps: number;
    hubs: number;
    chrome: number;
  };
  index: { lastIndexedAt: number | null; edges: number; files: number };
... (195 lines truncated)
</file>

<file path="src/ui-server/api/trail-store.ts">
import { CODEGRAPH_DIR } from '../../directory';
import { resolveProjectFile } from '../security';
import { ApiError, badRequest } from './respond';
⋮----
export type StoredHopDirection = 'start' | 'down' | 'up';
⋮----
export interface StoredHop {
  dir: StoredHopDirection;
  name: string;
  qualifiedName: string;
  kind: string;
  file: string;
  line: number;
  id: string;
}
⋮----
export interface StoredTrail {
  version: number;
  id: string;
  name: string;
  note: string;
  author: string;
  createdAt: string;
  updatedAt: string;
  hops: StoredHop[];
}
⋮----
export function isTrailId(value: string): boolean
⋮----
export function slugify(name: string): string
⋮----
export function trailsDirectory(projectRoot: string): string
⋮----
export function trailPath(projectRoot: string, id: string): string
⋮----
export function parseTrail(id: string, text: string): StoredTrail | null
⋮----
export interface StoredTrailList {
  trails: StoredTrail[];
  skipped: number;
}
⋮----
export function listStoredTrails(projectRoot: string): StoredTrailList
⋮----
function readTrailFile(absolute: string, id: string): StoredTrail | null
⋮----
export function readStoredTrail(projectRoot: string, id: string): StoredTrail | null
⋮----
export function writeStoredTrail(projectRoot: string, trail: StoredTrail): void
⋮----
export function deleteStoredTrail(projectRoot: string, id: string): boolean
⋮----
export function uniqueTrailId(base: string, taken: ReadonlySet<string>): string
⋮----
function writeFailure(err: unknown): ApiError
</file>

<file path="src/ui-server/api/trails.ts">
import { execFileSync } from 'child_process';
⋮----
import type { CodeGraph } from '../../index';
import type { Node } from '../../types';
import { ApiError, badRequest, notFound } from './respond';
import {
  MAX_TRAIL_HOPS,
  MAX_TRAIL_NAME,
  MAX_TRAIL_NOTE,
  MAX_TRAILS,
  TRAILS_RELATIVE_DIR,
  TRAIL_FORMAT_VERSION,
  deleteStoredTrail,
  listStoredTrails,
  slugify,
  uniqueTrailId,
  writeStoredTrail,
  type StoredHop,
  type StoredHopDirection,
  type StoredTrail,
} from './trail-store';
import { toNodeRef } from './wire';
⋮----
export type WireTrailHopStatus = 'ok' | 'moved' | 'ambiguous' | 'missing';
⋮----
export interface WireTrailHop {
  dir: StoredHopDirection;
  name: string;
  qualifiedName: string;
  kind: string;
  savedFile: string;
  savedLine: number;
  status: WireTrailHopStatus;
  id: string | null;
  file: string | null;
  line: number | null;
  note: string | null;
}
⋮----
export interface WireTrail {
  id: string;
  name: string;
  note: string;
  author: string;
  createdAt: string;
  updatedAt: string;
  hops: WireTrailHop[];
  resolved: number;
  intact: boolean;
  encoded: string | null;
  openFrom: number;
  openCount: number;
  openId: string | null;
}
⋮----
export interface WireTrails {
  trails: WireTrail[];
  readOnly: boolean;
  readOnlyReason: string | null;
  directory: string;
  skipped: number;
  bounded: boolean;
  saved?: string;
  replaced?: boolean;
  deleted?: string;
}
⋮----
export function resolveHop(cg: CodeGraph, hop: StoredHop): WireTrailHop
⋮----
function matches(node: Node, hop: StoredHop): boolean
⋮----
/** The `t` param's own encoding — kept identical to `ui/src/lib/trail-codec.ts`. */
⋮----
export function encodeResolvedRun(hops: readonly WireTrailHop[]):
⋮----
export function resolveTrail(cg: CodeGraph, stored: StoredTrail): WireTrail
⋮----
export interface TrailsOptions {
  readOnly: boolean;
  readOnlyReason: string | null;
}
⋮----
export function buildTrails(
  cg: CodeGraph,
  projectRoot: string,
  options: TrailsOptions
): WireTrails
⋮----
export interface SaveTrailRequest {
  name: string;
  note?: string;
  hops: Array<{ dir?: string; id: string }>;
}
⋮----
export function saveTrail(
  cg: CodeGraph,
  projectRoot: string,
  body: unknown,
  options: TrailsOptions
): WireTrails
... (23 lines truncated)
</file>

<file path="src/ui-server/api/when.ts">
import type CodeGraph from '../../index';
import type { Language, Node } from '../../types';
import {
  callArgumentsForFile,
  callSitesForFile,
  decoratorsForFile,
  guardLabel,
  guardsForFile,
  loopsForFile,
  memberTypesForFile,
  returnsForFile,
  siteKey,
  supportsBranchGuards,
  triggersForFile,
  type BranchGuard,
  type CallSiteText,
  type DefinitionDecorators,
  type ReturnSite,
  type SiteLoop,
  type SiteTrigger,
} from '../../graph/branch-guards';
import { resolveProjectFile } from '../security';
import { declaresExtension } from '../../resolution/swift-type-visibility';
import { findIndexedFile, hasDriftedOnDisk } from './source';
import type { WireEdge } from './wire';
⋮----
export interface WhenBatch {
  file: string;
  edges: WireEdge[];
}
⋮----
export async function annotateWhen(cg: CodeGraph, projectRoot: string, batches: readonly WhenBatch[]): Promise<void>
⋮----
/**
 * A per-request reader of the conditions ONE call site sits under, for the
 * endpoints that walk chains rather than annotate rails (the Screens view's
 * transitions, the Steps view's links). Files are resolved once, drifted
 * files yield no label, and the count of sites labelled is bounded so a wide
 * walk cannot turn one request into a parse of the repository.
 */
export interface SiteReader {
  when(caller: { filePath: string; language: Language }, site: { line?: number; column?: number }): Promise<string>;
  guards(caller: { filePath: string; language: Language }, site: { line?: number; column?: number }): Promise<BranchGuard[]>;
  loops(caller: { filePath: string; language: Language }, site: { line?: number; column?: number }): Promise<SiteLoop[]>;
  args(caller: { filePath: string; language: Language }, site: { line?: number; column?: number }): Promise<string | null>;
  trigger(caller: { filePath: string; language: Language }, site: { line?: number; column?: number }): Promise<SiteTrigger | null>;
  callSite(caller: { filePath: string; language: Language }, site: { line?: number; column?: number; callee?: string }): Promise<CallSiteText | null>;
  decorators(definition: { filePath: string; language: Language; startLine: number }): Promise<DefinitionDecorators | null>;
  memberTypes(definition: { filePath: string; language: Language; startLine: number }): Promise<Map<string, string>>;
  returns(definition: { filePath: string; language: Language; startLine: number }): Promise<ReturnSite[]>;
  directive(definition: { filePath: string; language: Language; startLine: number }): Promise<{ file: 'server' | 'client' | null; own: boolean }>;
  swiftExtension(definition: Pick<Node, 'filePath' | 'language' | 'kind' | 'startLine' | 'startColumn' | 'endLine'>): Promise<boolean>;
}
⋮----
when(caller:
⋮----
guards(caller:
⋮----
loops(caller:
⋮----
args(caller:
⋮----
trigger(caller:
⋮----
callSite(caller:
⋮----
decorators(definition:
⋮----
memberTypes(definition:
⋮----
returns(definition:
⋮----
directive(definition:
⋮----
swiftExtension(definition: Pick<Node, 'filePath' | 'language' | 'kind' | 'startLine' | 'startColumn' | 'endLine'>): Promise<boolean>;
⋮----
export function createSiteReader(cg: CodeGraph, projectRoot: string, maxSites = 600): SiteReader
⋮----
const resolve = (caller:
⋮----
const readText = (abs: string): string | null =>
⋮----
const guards = async (
    caller: { filePath: string; language: Language },
    site: { line?: number; column?: number }
): Promise<BranchGuard[]> =>
⋮----
async when(caller, site)
async loops(caller, site)
async args(caller, site)
async trigger(caller, site)
async callSite(caller, site)
async decorators(definition)
async memberTypes(definition)
async returns(definition)
async directive(definition)
async swiftExtension(definition)
⋮----
export function createWhenReader(
  cg: CodeGraph,
... (4 lines truncated)
</file>

<file path="src/ui-server/api/wire.ts">
import type { Edge, EdgeKind, Language, Node, NodeKind } from '../../types';
import { isTestFile } from '../../search/query-utils';
⋮----
export interface WireNodeRef {
  id: string;
  kind: NodeKind;
  name: string;
  qualifiedName: string;
  file: string;
  line: number;
  endLine: number;
  language: Language;
  signature?: string;
  exported?: boolean;
  test: boolean;
  generated?: boolean;
}
⋮----
export interface WireNodeDetail extends WireNodeRef {
  startColumn: number;
  endColumn: number;
  docstring?: string;
  visibility?: string;
  async?: boolean;
  static?: boolean;
  abstract?: boolean;
  decorators?: string[];
  typeParameters?: string[];
  returnType?: string;
  lines: number;
}
⋮----
const rel = (p: string): string
⋮----
export function toNodeRef(node: Node): WireNodeRef
⋮----
export function toNodeDetail(node: Node): WireNodeDetail
⋮----
export interface WireEdge {
  kind: EdgeKind;
  line?: number;
  col?: number;
  confidence?: number;
  resolvedBy?: string;
  provenance?: string;
  synthesizedBy?: string;
  via?: string;
  registeredAt?: string;
  valueRef?: boolean;
  when?: string;
}
⋮----
export function toWireEdge(edge: Edge): WireEdge
⋮----
export interface WireRelation {
  node: WireNodeRef;
  edgeKinds: EdgeKind[];
  edges: WireEdge[];
  edgeCount: number;
  lines: number[];
  confidence: number | null;
  uncertain: boolean;
  synthesized: boolean;
  fanIn?: number;
  hub?: boolean;
}
⋮----
export interface WireList<T> {
  total: number;
  shown: number;
  truncated: boolean;
  items: T[];
}
⋮----
export function wireList<T>(items: T[], total: number): WireList<T>
⋮----
export function groupRelations(
  edges: readonly Edge[],
  endpoint: (edge: Edge) => string,
  nodes: Map<string, Node>
): WireRelation[]
⋮----
export function firstLine(relation: WireRelation): number
</file>

<file path="src/ui-server/highlight/index.ts">
import { SYNTAX_TOKEN_CLASSES, tokenizeSource, type SyntaxTokenClass } from '../../extraction/syntax-tokens';
import type { Language } from '../../types';
import { grammarFor } from './languages';
⋮----
export type WireToken = [number, string];
⋮----
export interface HighlightResult {
  engine: 'tree-sitter' | 'plain';
  grammar: string | null;
  classes: readonly string[];
  lines: WireToken[][];
  reason?: string;
}
⋮----
function cacheGet(key: string): HighlightResult | undefined
⋮----
function cachePut(key: string, value: HighlightResult): void
⋮----
export function clearHighlightCache(): void
⋮----
export function highlightCacheStats():
⋮----
export interface HighlightOptions {
  language?: string | null;
  cacheKey?: string;
}
⋮----
export async function highlightLines(
  lines: readonly string[],
  options: HighlightOptions = {}
): Promise<HighlightResult>
⋮----
async function highlightUncached(
  lines: readonly string[],
  language: string | null,
  grammar: string | null
): Promise<HighlightResult>
⋮----
function plain(lines: readonly string[], grammar: string | null, reason?: string): HighlightResult
⋮----
function toWireLines(
  lines: readonly string[],
  text: string,
  spans: readonly { start: number; end: number; cls: SyntaxTokenClass }[]
): WireToken[][]
⋮----
function pushPiece(row: WireToken[], text: string, cls: SyntaxTokenClass): void
⋮----
function atomizePlain(line: string): WireToken[]
⋮----
function splitIdentifiers(out: WireToken[], text: string, cls: SyntaxTokenClass): void
⋮----
function gapClass(cls: SyntaxTokenClass): SyntaxTokenClass
⋮----
function push(out: WireToken[], cls: SyntaxTokenClass, text: string): void
</file>

<file path="src/ui-server/highlight/languages.ts">
import type { Language } from '../../types';
import { hasTreeSitterGrammar } from '../../extraction/grammars';
⋮----
export function grammarFor(language: string | undefined | null): string | null
⋮----
export function isHighlightable(language: string | undefined | null): boolean
</file>

<file path="src/ui-server/assets.ts">
import { VIEWER_PATH_ENV } from './constants';
⋮----
export class ViewerMissingError extends Error
⋮----
constructor(searched: readonly string[])
⋮----
export function viewerDirCandidates(): string[]
⋮----
export function resolveViewerDir(): string
</file>

<file path="src/ui-server/constants.ts">

</file>

<file path="src/ui-server/index.ts">
import { resolveViewerDir } from './assets';
import {
  ALLOWED_METHODS,
  READ_METHODS,
  WRITE_HEADER,
  isAllowedHost,
  isAllowedOrigin,
  isSafeRequestPath,
  isWriteMethod,
  isWriteRequest,
  resolveStaticAsset,
} from './security';
import { sendFile, sendJson, sendText, shouldFallBackToIndex } from './static';
import { DEFAULT_PORT_ATTEMPTS, DEFAULT_UI_PORT, LOOPBACK_ADDRESS } from './constants';
⋮----
export interface UiRequestContext {
  pathname: string;
  query: URLSearchParams;
  projectRoot: string;
  method: string;
}
⋮----
export type UiApiHandler = (
  req: http.IncomingMessage,
  res: http.ServerResponse,
  ctx: UiRequestContext
) => boolean | Promise<boolean>;
⋮----
export interface UiServerOptions {
  projectRoot: string;
  port?: number;
  portFallback?: boolean;
  maxPortAttempts?: number;
  viewerDir?: string;
  api?: UiApiHandler;
}
⋮----
export interface UiServerHandle {
  port: number;
  url: string;
  viewerDir: string;
  server: http.Server;
  close(): Promise<void>;
}
⋮----
close(): Promise<void>;
⋮----
export async function startUiServer(options: UiServerOptions): Promise<UiServerHandle>
⋮----
close(): Promise<void>
⋮----
interface HandlerDeps {
  viewerDir: string;
  indexHtml: string;
  projectRoot: string;
  api: UiApiHandler | undefined;
  port: () => number;
}
⋮----
async function handleRequest(
  req: http.IncomingMessage,
  res: http.ServerResponse,
  deps: HandlerDeps
): Promise<void>
⋮----
function realpath(dir: string): string
⋮----
function forEcho(value: string | undefined): string
⋮----
function readHeader(req: http.IncomingMessage, name: string): string | undefined
⋮----
function safeDecode(value: string): string
⋮----
async function listenWithFallback(
  server: http.Server,
  opts: { port: number; fallback: boolean; attempts: number }
): Promise<number>
⋮----
function listenOnce(server: http.Server, port: number): Promise<void>
⋮----
const onError = (err: Error): void =>
const onListening = (): void =>
⋮----
function describeBindFailure(
  err: unknown,
  port: number,
  opts: { port: number; fallback: boolean; attempts: number }
): Error
</file>

<file path="src/ui-server/open-browser.ts">
import { spawn } from 'child_process';
import { BROWSER_ENV } from './constants';
⋮----
export interface OpenCommand {
  command: string;
  args: string[];
}
⋮----
export function browserOpenCommand(
  url: string,
  platform: NodeJS.Platform,
  override?: string
): OpenCommand | null
⋮----
export function openBrowser(url: string, platform: NodeJS.Platform = process.platform): boolean
</file>

<file path="src/ui-server/security.ts">
import { PathRefusalError } from '../errors';
import { validatePathWithinRoot, validateProjectPath } from '../utils';
⋮----
export function isWriteMethod(method: string): boolean
⋮----
export function isWriteRequest(
  pathname: string,
  headers: { marker: string | undefined; contentType: string | undefined }
):
⋮----
interface HostParts {
  hostname: string;
  /** `undefined` when the header carried no `:port` suffix. */
  port: number | undefined;
}
⋮----
/** `undefined` when the header carried no `:port` suffix. */
⋮----
/**
 * Split a `Host` header into hostname and port, or `null` if it is malformed.
 *
 * An unbracketed IPv6 literal (`::1`) is malformed per RFC 7230 and is rejected
 * rather than guessed at — no browser produces one, so accepting it would only
 * widen the parser for an attacker's benefit.
 */
function splitHostPort(host: string): HostParts | null
⋮----
function parsePortSuffix(suffix: string): number | undefined | null
⋮----
/**
 * Whether a request's `Host` header names this loopback server.
 *
 * A missing `Host` is rejected: HTTP/1.1 requires it, and the one client that
 * may legally omit it (HTTP/1.0) is not a browser we need to serve.
 */
export function isAllowedHost(host: string | undefined, port: number): boolean
⋮----
export function isAllowedOrigin(origin: string | undefined, port: number): boolean
⋮----
/**
 * Whether a raw request path is worth resolving at all.
 *
 * Rejects any `..` segment outright rather than letting containment sort it
 * out later. Containment WOULD catch it — but the SPA fallback sits behind
 * containment, so `GET /../../etc/passwd` would otherwise be answered with the
 * app shell (a 200) instead of the 404 a traversal attempt deserves. Nothing
 * outside the root leaks either way; this just stops the server from
 * pretending a hostile path was an ordinary route.
 *
 * Takes the RAW path from `req.url`, before WHATWG URL parsing folds `..`
 * segments away — that folding is what would hide the attempt.
 */
export function isSafeRequestPath(rawPath: string): boolean
⋮----
/**
 * Resolve a request path to a file inside the static asset root.
 *
 * Returns the absolute path, or `null` for anything that is not a readable file
 * inside `rootDir` — a traversal attempt, a symlink escape, a directory, a
 * missing file. Callers turn `null` into a 404 (never a 403): telling a prober
 * which of those it hit is free information.
 *
 * Percent-decoding happens HERE, before containment is checked, so an encoded
 * `..%2f` is caught by the same guard as a literal `../`.
 */
export function resolveStaticAsset(rootDir: string, urlPath: string): string | null
⋮----
/**
 * Percent-decode a URL path and reject the encodings that only ever show up in
 * an attack: NUL (truncates a path in some syscalls), other C0 control bytes,
 * and backslashes (a separator on Windows, a legal filename character on POSIX
 * — treating it as a separator everywhere is the safe direction, and no built
 * asset name contains one).
 *
 * @returns the decoded path, or `null` if it is unusable.
 */
function decodePath(urlPath: string): string | null
⋮----
return null; // malformed percent-encoding
⋮----
// eslint-disable-next-line no-control-regex -- rejecting raw control bytes IS the point
⋮----
/**
 * Resolve a project-relative source path to an absolute path that is safe to
 * read and hand to the browser.
 *
 * This is the single read chokepoint for anything served OUT OF THE USER'S
 * REPOSITORY (as opposed to the viewer's own bundled assets). The JSON API
 * built on top of this server must route every file read through it — that is
 * what keeps `/api/source?path=../../.ssh/id_rsa` from being a credential leak
 * over a port the user opened to read their own code.
 *
 * @throws {PathRefusalError} when the root is a sensitive system directory, or
 *   the path escapes the root by traversal or symlink.
 */
export function resolveProjectFile(projectRoot: string, relativePath: string): string
</file>

<file path="src/ui-server/static.ts">
import type { ServerResponse } from 'http';
⋮----
export function contentTypeFor(filePath: string): string
⋮----
export function cacheControlFor(relativePath: string): string
⋮----
export function sendFile(
  res: ServerResponse,
  absolutePath: string,
  options: { rootDir: string; method: string; extraHeaders?: Record<string, string> }
): void
⋮----
export function sendText(res: ServerResponse, status: number, message: string, method: string): void
⋮----
export function sendJson(res: ServerResponse, status: number, payload: unknown, method: string): void
⋮----
export function shouldFallBackToIndex(pathname: string): boolean
</file>

<file path="src/upgrade/index.ts">
import { spawnSync } from 'child_process';
import { ansiColorsEnabled } from '../ui/color';
⋮----
export type InstallMethod =
  | { kind: 'bundle'; os: 'unix' | 'windows'; bundleRoot: string; installDir: string | null }
  | { kind: 'npm'; scope: 'global' | 'local' }
  | { kind: 'npx' }
  | { kind: 'source'; root: string }
  | { kind: 'unknown'; reason: string };
⋮----
export interface DetectInput {
  filename: string;
  platform: NodeJS.Platform;
  cwd: string;
  exists?: (p: string) => boolean;
}
⋮----
function toPosix(p: string): string
⋮----
export function deriveInstallDir(
  bundleRoot: string,
  os: 'unix' | 'windows',
  exists: (p: string) => boolean
): string | null
⋮----
export function detectInstallMethod(input: DetectInput): InstallMethod
⋮----
export interface Semver {
  major: number;
  minor: number;
  patch: number;
  pre: string | null;
}
⋮----
export function parseSemver(version: string): Semver | null
⋮----
export function compareVersions(a: string, b: string): number
⋮----
export function isUpdateAvailable(current: string, latest: string): boolean
⋮----
export function normalizeVersion(v: string): string
⋮----
export function stripV(v: string): string
⋮----
export function parseLatestTagFromLocation(location: string | undefined): string | null
⋮----
function httpsGet(
  url: string,
  headers: Record<string, string>,
  timeoutMs: number
): Promise<
⋮----
export async function resolveLatestVersion(repo = REPO, timeoutMs = 12000): Promise<string>
⋮----
export interface UpgradeOptions {
  version?: string;
  check?: boolean;
  force?: boolean;
}
⋮----
export interface UpgradeDeps {
  currentVersion: string;
  method: InstallMethod;
  resolveLatest: (pin?: string) => Promise<string>;
  run: (cmd: string, args: string[], env?: NodeJS.ProcessEnv) => number;
  capture: (cmd: string, args: string[]) => { code: number; stdout: string } | null;
  hasCommand: (cmd: string) => boolean;
  log: (msg: string) => void;
  warn: (msg: string) => void;
  error: (msg: string) => void;
  platform: NodeJS.Platform;
  offerBetaSignup?: () => Promise<void>;
}
⋮----
export function reindexAdvisory(): string
⋮----
export async function runUpgrade(opts: UpgradeOptions, deps: UpgradeDeps): Promise<number>
⋮----
type VersionProbe = 'match' | 'mismatch' | 'inconclusive';
⋮----
export function verifyResolvedVersion(latest: string, deps: UpgradeDeps): VersionProbe
⋮----
function reportResolvedVersion(latest: string, deps: UpgradeDeps): VersionProbe
⋮----
function selfHealInstalledSurfaces(deps: UpgradeDeps): void
⋮----
async function selfHealPromptHook(deps: UpgradeDeps): Promise<void>
⋮----
function upgradeUnixBundle(
  method: Extract<InstallMethod, { kind: 'bundle' }>,
  pinned: string | undefined,
  deps: UpgradeDeps
): number
⋮----
// No "open a new terminal" hedge here — after the swap, runUpgrade probes
// the PATH-resolved `codegraph --version` and reports the real outcome.
⋮----
/** Build the in-place Windows upgrade script (exported for unit-testing). */
export function buildWindowsUpgradeScript(bundleRoot: string, version: string, arch: string): string
⋮----
... (46 lines truncated)
</file>

<file path="src/upgrade/remove-binary.ts">
import { spawnSync } from 'child_process';
import { detectInstallMethod, npmInvocation, NPM_PACKAGE } from './index';
⋮----
export interface RemoveBinaryProbes {
  filename: string;
  platform: NodeJS.Platform;
  cwd: string;
  env: NodeJS.ProcessEnv;
  homedir: string;
  exists: (p: string) => boolean;
  readlink: (p: string) => string | null;
  capture: (cmd: string, args: string[]) => { code: number; stdout: string } | null;
}
⋮----
export interface BinaryRemovalPlan {
  paths: string[];
  npmGlobal: boolean;
  npmRoot: string | null;
  sourceRoot: string | null;
  summary: string[];
}
⋮----
export function defaultProbes(filename: string): RemoveBinaryProbes
⋮----
/**
 * Path math keyed on the TARGET platform (not the host) — same convention as
 * `detectInstallMethod`, so the planner is deterministic when unit-tested with
 * a win32 fixture on a POSIX host and vice versa. In production the probe's
 * platform always matches the running host.
 */
function pathFor(platform: NodeJS.Platform): path.PlatformPath
⋮----
function stateDir(p: RemoveBinaryProbes): string
⋮----
function installDirCandidates(p: RemoveBinaryProbes): string[]
⋮----
export function planBinaryRemoval(p: RemoveBinaryProbes): BinaryRemovalPlan
⋮----
export interface RemoveBinaryDeps {
  platform: NodeJS.Platform;
  execPath: string;
  rm: (p: string) => void;
  rename: (from: string, to: string) => void;
  run: (cmd: string, args: string[]) => number;
}
⋮----
export interface BinaryRemovalResult {
  removed: string[];
  leftovers: string[];
  npm: 'removed' | 'failed' | 'skipped';
}
⋮----
export function defaultRemoveDeps(): RemoveBinaryDeps
⋮----
function moveLockedExeAside(dir: string, deps: RemoveBinaryDeps): string | null
⋮----
export function executeBinaryRemoval(
  plan: BinaryRemovalPlan,
  deps: RemoveBinaryDeps = defaultRemoveDeps(),
): BinaryRemovalResult
</file>

<file path="src/upgrade/update-check.ts">
import { resolveLatestVersion, isUpdateAvailable, parseSemver } from './index';
import { CodeGraphPackageVersion } from '../mcp/version';
⋮----
export interface UpdateCheckCacheFile {
  lastAttemptAt: number;
  lastSuccessAt?: number;
  latest?: string;
}
⋮----
export interface UpdateCheckDeps {
  dir?: string;
  env?: NodeJS.ProcessEnv;
  now?: () => number;
  resolveLatest?: () => Promise<string>;
  currentVersion?: string;
}
⋮----
interface ResolvedDeps {
  dir: string;
  env: NodeJS.ProcessEnv;
  now: () => number;
  resolveLatest: () => Promise<string>;
  currentVersion: string;
}
⋮----
function resolveDeps(deps: UpdateCheckDeps =
⋮----
function envTruthy(raw: string | undefined): boolean
⋮----
export function updateCheckDisabled(env: NodeJS.ProcessEnv = process.env): boolean
⋮----
export function updateCheckCachePath(dir: string): string
⋮----
export function readUpdateCheckCache(dir: string): UpdateCheckCacheFile | null
⋮----
function writeUpdateCheckCache(dir: string, cache: UpdateCheckCacheFile): void
⋮----
export function canonicalVersionTag(v: string): string | null
⋮----
export function formatUpdateNotice(current: string, latest: string): string
⋮----
function noticeFrom(cache: UpdateCheckCacheFile | null, d: ResolvedDeps): string | null
⋮----
function cacheIsFresh(cache: UpdateCheckCacheFile | null, nowMs: number): boolean
⋮----
export async function refreshUpdateCheck(deps: UpdateCheckDeps =
⋮----
export function getUpdateNotice(deps: UpdateCheckDeps =
⋮----
export function resetUpdateNoticeMemo(): void
⋮----
export function checkForUpdateInBackground(
  deps: UpdateCheckDeps = {},
  log: (line: string) => void = (line) => process.stderr.write(line),
): void
</file>

<file path="src/directory.ts">
import { isWslWindowsDrive } from './sync/watch-policy';
⋮----
export function codeGraphDirName(): string
⋮----
// stderr only — stdout is the MCP protocol channel.
⋮----
/**
 * CodeGraph directory name — a load-time snapshot of {@link codeGraphDirName}.
 * A running process's environment is fixed, so this equals the live value;
 * it's kept as a stable string export for backward compatibility. Internal code
 * resolves the name through {@link codeGraphDirName} / {@link getCodeGraphDir}
 * so the `CODEGRAPH_DIR` override always applies.
 */
⋮----
export function isCodeGraphDataDir(name: string): boolean
⋮----
export function codeGraphDirNameFor(projectRoot: string): string
⋮----
export function getCodeGraphDir(projectRoot: string): string
⋮----
export function isInitialized(projectRoot: string): boolean
⋮----
export function hasSchemalessDb(projectRoot: string): boolean
⋮----
export function hasForeignDbFile(projectRoot: string): boolean
⋮----
function hasCodeGraphSchema(dbPath: string, st: fs.Stats): boolean
⋮----
function probeSchema(dbPath: string): 'schema' | 'no-schema' | 'not-sqlite' | 'unknown'
⋮----
export function unsafeIndexRootReason(projectRoot: string): string | null
⋮----
const resolve = (p: string): string =>
⋮----
const norm = (p: string): string
⋮----
export function statInode(p: string): string | null
⋮----
export function isSameIndexRoot(a: string, b: string): boolean
⋮----
export function findNearestCodeGraphRoot(startPath: string): string | null
⋮----
function looksLikeProjectRoot(dir: string): boolean
⋮----
function escapeRegExp(s: string): string
⋮----
export function findIndexedSubprojectRoots(
  root: string,
  opts: { maxDepth?: number; max?: number } = {},
): string[]
⋮----
const walk = (dir: string, depth: number): void =>
⋮----
export interface ServerRootResolution {
  root: string | null;
  viaSubScan: boolean;
  candidates: string[];
}
⋮----
function eligibleForSubprojectScan(base: string): boolean
⋮----
export function resolveServerRoot(
  searchFrom: string,
  opts: { subprojectScan?: boolean } = {},
): ServerRootResolution
⋮----
export function hasStructuralKeyword(prompt: string): boolean
⋮----
export function extractCodeTokens(prompt: string): string[]
⋮----
export function isStructuralPrompt(prompt: string): boolean
⋮----
export function capPromptHookInjection(text: string, max = PROMPT_HOOK_INJECTION_MAX): string
⋮----
export interface FrontloadPlan {
  exploreRoot: string | null;
  nudgeProjects: string[];
  viaSubScan: boolean;
}
⋮----
export function planFrontload(cwd: string, prompt: string): FrontloadPlan
⋮----
function isStaleDefaultGitignore(content: string): boolean
⋮----
function ensureGitignore(gitignorePath: string): boolean
⋮----
export function createDirectory(projectRoot: string): void
⋮----
export function removeDirectory(projectRoot: string): void
⋮----
export function listDirectoryContents(projectRoot: string): string[]
⋮----
function walkDir(dir: string, prefix: string = ''): void
⋮----
// Skip symlinks to prevent following links outside .codegraph
⋮----
/**
 * Get the total size of the .codegraph directory in bytes
 */
export function getDirectorySize(projectRoot: string): number
... (17 lines truncated)
</file>

<file path="src/errors.ts">
export class CodeGraphError extends Error
⋮----
constructor(message: string, code: string, context?: Record<string, unknown>)
⋮----
export class FileError extends CodeGraphError
⋮----
constructor(message: string, filePath: string, cause?: Error)
⋮----
export class ParseError extends CodeGraphError
⋮----
constructor(
    message: string,
    filePath: string,
    options?: { line?: number; column?: number; cause?: Error }
)
⋮----
export class DatabaseError extends CodeGraphError
⋮----
constructor(message: string, operation: string, cause?: Error)
⋮----
export class SearchError extends CodeGraphError
⋮----
constructor(message: string, query: string, cause?: Error)
⋮----
export class VectorError extends CodeGraphError
⋮----
export class ConfigError extends CodeGraphError
⋮----
constructor(message: string, details?: Record<string, unknown>)
⋮----
export class PathRefusalError extends Error
⋮----
export interface Logger {
  debug(message: string, context?: Record<string, unknown>): void;
  warn(message: string, context?: Record<string, unknown>): void;
  error(message: string, context?: Record<string, unknown>): void;
}
⋮----
debug(message: string, context?: Record<string, unknown>): void;
warn(message: string, context?: Record<string, unknown>): void;
error(message: string, context?: Record<string, unknown>): void;
⋮----
debug(message: string, context?: Record<string, unknown>): void
warn(message: string, context?: Record<string, unknown>): void
error(message: string, context?: Record<string, unknown>): void
⋮----
debug(): void
warn(): void
error(): void
⋮----
export function setLogger(logger: Logger): void
⋮----
export function getLogger(): Logger
⋮----
export function logDebug(message: string, context?: Record<string, unknown>): void
⋮----
export function logWarn(message: string, context?: Record<string, unknown>): void
⋮----
export function logError(message: string, context?: Record<string, unknown>): void
</file>

<file path="src/file-limits.ts">
export function oversizeStamp(size: number): string
⋮----
export function indexedHashInput(size: number, content: () => string): string
⋮----
export interface BoundedSource {
  stats: fs.Stats;
  bytes: Buffer | null;
}
⋮----
function assertRegularFile(stats: fs.Stats): void
⋮----
export async function readBoundedSource(file: string): Promise<BoundedSource>
⋮----
export function readBoundedSourceSync(file: string): BoundedSource
</file>

<file path="src/index.ts">
import {
  Node,
  NodeKind,
  Edge,
  FileRecord,
  ExtractionResult,
  Subgraph,
  TraversalOptions,
  SearchOptions,
  SearchResult,
  SegmentMatch,
  Context,
  GraphStats,
  TaskInput,
  TaskContext,
  BuildContextOptions,
  FindRelevantContextOptions,
  UnresolvedReference,
} from './types';
import { DatabaseConnection, getDatabasePath, removeDatabaseFiles } from './db';
import { WalCheckpointValve, resolveWalValveMb } from './db/wal-valve';
import { QueryBuilder } from './db/queries';
import {
  isInitialized,
  createDirectory,
  removeDirectory,
  validateDirectory,
} from './directory';
import {
  ExtractionOrchestrator,
  IndexProgress,
  IndexResult,
  SyncResult,
  extractFromSource,
  initGrammars,
} from './extraction';
import {
  ReferenceResolver,
  createResolver,
  ResolutionResult,
} from './resolution';
import { hasSynthesisPattern } from './resolution/callback-synthesizer';
import { GraphTraverser, GraphQueryManager } from './graph';
import { ContextBuilder, createContextBuilder } from './context';
import { Mutex, FileLock } from './utils';
import { FileWatcher, WatchOptions, PendingFile, LockUnavailableError } from './sync';
import { EXTRACTION_VERSION } from './extraction/extraction-version';
import { getCodeGraphDir } from './directory';
import { deriveProjectNameTokens } from './search/query-utils';
import ignore from 'ignore';
import { loadDeprioritizePatterns } from './project-config';
import { CodeGraphPackageVersion } from './mcp/version';
import { extractSegmentSearchWords, segmentLookupVariants, splitIdentifierSegments } from './search/identifier-segments';
import { createYielder } from './resolution/cooperative-yield';
import { minRefsForPool } from './resolution/resolver-pool';
⋮----
export interface InitOptions {
  index?: boolean;
  onProgress?: (progress: IndexProgress) => void;
}
⋮----
export interface OpenOptions {
  sync?: boolean;
  readOnly?: boolean;
}
⋮----
export interface IndexOptions {
  onProgress?: (progress: IndexProgress) => void;
  signal?: AbortSignal;
  verbose?: boolean;
  paths?: string[];
}
⋮----
export class CodeGraph
⋮----
private constructor(
    db: DatabaseConnection,
    queries: QueryBuilder,
    projectRoot: string
)
⋮----
private wireLayers(): void
⋮----
private isFreshlyRecreated(): boolean
⋮----
reopenIfReplaced(): boolean
⋮----
private reopenReplacedDatabase(): boolean
⋮----
static async init(projectRoot: string, options: InitOptions =
⋮----
static initSync(projectRoot: string): CodeGraph
⋮----
static async open(projectRoot: string, options: OpenOptions =
⋮----
static async recreate(projectRoot: string): Promise<CodeGraph>
⋮----
static openSync(projectRoot: string, options: Pick<OpenOptions, 'readOnly'> =
⋮----
static isInitialized(projectRoot: string): boolean
... (230 lines truncated)
</file>

<file path="src/project-config.ts">
import { Language } from './types';
import { isLanguageSupported } from './extraction/grammars';
import { logWarn } from './errors';
⋮----
export interface ProjectConfig {
  extensions?: Record<string, string>;
  includeIgnored?: string[];
  exclude?: string[];
  include?: string[];
  deprioritize?: string[];
}
⋮----
interface ParsedConfig {
  extensions: Record<string, Language>;
  includeIgnored: string[];
  exclude: string[];
  deprioritize: string[];
  include: string[];
}
⋮----
interface CacheEntry {
  mtimeMs: number;
  config: ParsedConfig;
}
⋮----
function normalizeExtKey(raw: string): string | null
⋮----
/**
 * Read + JSON-parse a `codegraph.json` once and return its validated view.
 * Every failure mode degrades to the zero-config default — a missing file, bad
 * JSON, or a typo'd value never throws.
 */
function parseConfig(file: string): ParsedConfig
⋮----
function extractExtensions(parsed: object, file: string): Record<string, Language>
⋮----
function extractIncludeIgnored(parsed: object, file: string): string[]
⋮----
function extractPatternList(parsed: object, file: string, key: 'deprioritize'): string[]
⋮----
function extractExclude(parsed: object, file: string): string[]
⋮----
function extractInclude(parsed: object, file: string): string[]
⋮----
function loadParsedConfig(rootDir: string): ParsedConfig
⋮----
export function loadExtensionOverrides(rootDir: string): Record<string, Language>
⋮----
export function loadIncludeIgnoredPatterns(rootDir: string): string[]
⋮----
export function loadExcludePatterns(rootDir: string): string[]
⋮----
export function loadDeprioritizePatterns(rootDir: string): string[]
⋮----
export function loadIncludePatterns(rootDir: string): string[]
⋮----
export function clearProjectConfigCache(): void
⋮----
export function addIncludeIgnoredPatterns(rootDir: string, patterns: string[]): number
</file>

<file path="src/types.ts">
export type NodeKind = (typeof NODE_KINDS)[number];
⋮----
export type EdgeKind = (typeof EDGE_KINDS)[number];
⋮----
export type Language = (typeof LANGUAGES)[number];
⋮----
export interface Node {
  id: string;
  kind: NodeKind;
  name: string;
  qualifiedName: string;
  filePath: string;
  language: Language;
  startLine: number;
  endLine: number;
  startColumn: number;
  endColumn: number;
  docstring?: string;
  signature?: string;
  visibility?: 'public' | 'private' | 'protected' | 'internal';
  isExported?: boolean;
  isAsync?: boolean;
  isStatic?: boolean;
  isAbstract?: boolean;
  decorators?: string[];
  typeParameters?: string[];
  returnType?: string;
  updatedAt: number;
}
⋮----
export interface Edge {
  source: string;
  target: string;
  kind: EdgeKind;
  metadata?: Record<string, unknown>;
  line?: number;
  column?: number;
  provenance?: 'tree-sitter' | 'scip' | 'heuristic';
}
⋮----
export interface FileRecord {
  path: string;
  contentHash: string;
  language: Language;
  size: number;
  modifiedAt: number;
  indexedAt: number;
  nodeCount: number;
  errors?: ExtractionError[];
  generated?: boolean;
}
⋮----
export interface ExtractionResult {
  nodes: Node[];
  edges: Edge[];
  unresolvedReferences: UnresolvedReference[];
  errors: ExtractionError[];
  durationMs: number;
  kernelBuffers?: {
    meta: Uint8Array;
    nodes: Uint8Array;
    edges: Uint8Array;
    refs: Uint8Array;
    arena: Uint8Array;
  };
  kernelCounts?: { nodes: number; edges: number; refs: number };
}
⋮----
export interface ExtractionError {
  message: string;
  filePath?: string;
  line?: number;
  column?: number;
  severity: 'error' | 'warning';
  code?: string;
}
⋮----
export type ReferenceKind = EdgeKind | 'function_ref';
⋮----
export interface UnresolvedReference {
  fromNodeId: string;
  referenceName: string;
  referenceKind: ReferenceKind;
  line: number;
  column: number;
  filePath?: string;
  language?: Language;
  candidates?: string[];
  rowId?: number;
}
⋮----
export interface Subgraph {
  nodes: Map<string, Node>;
  edges: Edge[];
  roots: string[];
  confidence?: 'high' | 'low';
}
⋮----
export interface TraversalOptions {
  maxDepth?: number;
... (107 lines truncated)
</file>

<file path="src/utils.ts">
export function isConfigLeafNode(node:
⋮----
function isWithinDir(child: string, parent: string): boolean
⋮----
export function lexicalPathWithinRoot(projectRoot: string, filePath: string): string | null
⋮----
export function validatePathWithinRoot(
  projectRoot: string,
  filePath: string,
  options?: { allowSymlinkEscape?: boolean }
): string | null
⋮----
export function validateProjectPath(dirPath: string): string | null
⋮----
export function safeJsonParse<T>(value: string, fallback: T): T
⋮----
export function clamp(value: number, min: number, max: number): number
⋮----
export function normalizePath(filePath: string): string
⋮----
export class FileLock
⋮----
constructor(lockPath: string)
⋮----
acquire(): void
⋮----
release(): void
⋮----
withLock<T>(fn: () => T): T
⋮----
async withLockAsync<T>(fn: () => Promise<T>): Promise<T>
⋮----
private isProcessAlive(pid: number): boolean
⋮----
export async function processInBatches<T, R>(
  items: T[],
  batchSize: number,
  processor: (item: T, index: number) => Promise<R>,
  onBatchComplete?: (completed: number, total: number) => void
): Promise<R[]>
⋮----
export class Mutex
⋮----
async acquire(): Promise<() => void>
⋮----
async withLock<T>(fn: () => Promise<T> | T): Promise<T>
⋮----
isLocked(): boolean
⋮----
export function debounce<T extends (...args: unknown[]) => unknown>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void
⋮----
export function throttle<T extends (...args: unknown[]) => unknown>(
  fn: T,
  limit: number
): (...args: Parameters<T>) => void
⋮----
export function estimateSize(obj: unknown): number
⋮----
function sizeOf(value: unknown): number
⋮----
export class MemoryMonitor
⋮----
constructor(
    thresholdMB: number = 500,
    onThresholdExceeded?: (usage: number) => void
)
⋮----
start(intervalMs: number = 1000): void
⋮----
stop(): void
⋮----
getPeakUsage(): number
⋮----
getCurrentUsage(): number
</file>

<file path="src/web-tree-sitter.d.ts">
export interface Point {
    row: number;
    column: number;
  }
⋮----
export interface Range {
    startPosition: Point;
    endPosition: Point;
    startIndex: number;
    endIndex: number;
  }
⋮----
export interface Edit {
    startPosition: Point;
    oldEndPosition: Point;
    newEndPosition: Point;
    startIndex: number;
    oldEndIndex: number;
    newEndIndex: number;
  }
⋮----
export type ParseCallback = (index: number, position: Point) => string | undefined;
⋮----
export interface ParseOptions {
    includedRanges?: Range[];
    progressCallback?: (state: { currentOffset: number; hasError: boolean }) => void;
  }
⋮----
export interface EmscriptenModule {
    [key: string]: any;
  }
⋮----
export class Parser
⋮----
static init(moduleOptions?: EmscriptenModule): Promise<void>;
constructor();
delete(): void;
setLanguage(language: Language | null): this;
parse(callback: string | ParseCallback, oldTree?: Tree | null, options?: ParseOptions): Tree | null;
reset(): void;
getIncludedRanges(): Range[];
getTimeoutMicros(): number;
setTimeoutMicros(timeout: number): void;
setLogger(callback: ((message: string, isLex: boolean)
getLogger(): ((message: string, isLex: boolean)
⋮----
export class Language
⋮----
get name(): string | null;
get version(): number;
get abiVersion(): number;
get fieldCount(): number;
get stateCount(): number;
fieldIdForName(fieldName: string): number | null;
fieldNameForId(fieldId: number): string | null;
idForNodeType(type: string, named: boolean): number | null;
get nodeTypeCount(): number;
nodeTypeForId(typeId: number): string | null;
nodeTypeIsNamed(typeId: number): boolean;
nodeTypeIsVisible(typeId: number): boolean;
get supertypes(): number[];
subtypes(supertype: number): number[];
nextState(stateId: number, typeId: number): number;
lookaheadIterator(stateId: number): any;
query(source: string): any;
static load(input: string | Uint8Array): Promise<Language>;
⋮----
export class Tree
⋮----
copy(): Tree;
⋮----
get rootNode(): Node;
rootNodeWithOffset(offsetBytes: number, offsetExtent: Point): Node;
edit(edit: Edit): void;
walk(): TreeCursor;
getChangedRanges(other: Tree): Range[];
⋮----
export class Node
⋮----
get typeId(): number;
get grammarId(): number;
get type(): string;
get grammarType(): string;
get isNamed(): boolean;
get isExtra(): boolean;
get isError(): boolean;
get isMissing(): boolean;
get hasChanges(): boolean;
get hasError(): boolean;
get endIndex(): number;
get endPosition(): Point;
get text(): string;
get parseState(): number;
get nextParseState(): number;
equals(other: Node): boolean;
child(index: number): Node | null;
namedChild(index: number): Node | null;
childForFieldId(fieldId: number): Node | null;
childForFieldName(fieldName: string): Node | null;
fieldNameForChild(index: number): string | null;
... (60 lines truncated)
</file>

<file path="telemetry-dashboard/src/api.ts">
export interface ApiResult {
  body: unknown;
  status?: number;
  cacheControl?: string;
}
⋮----
const fail = (error: string, status = 400): ApiResult => (
⋮----
const rowsOf = <T>(result: D1Result | undefined): T[]
const firstOf = <T>(result: D1Result | undefined): T | undefined
⋮----
const utcDay = (atMs: number): string
⋮----
function isValidDay(day: string): boolean
⋮----
const dayMs = (day: string): number => Date.parse(`$
const addDays = (day: string, delta: number): string
const daysApart = (from: string, to: string): number
⋮----
export interface Range {
  from: string;
  to: string;
  days: number;
  clamped: boolean;
}
⋮----
function parseRange(url: URL): Range | ApiResult
⋮----
const isApiResult = (v: Range | ApiResult): v is ApiResult
⋮----
function dayList(range: Range): string[]
⋮----
function densify(labels: string[], byDay: Map<string, number>): number[]
⋮----
type Order = 'value_desc' | 'bucket' | 'version_desc';
⋮----
interface DimSpec {
  label: string;
  metric: 'machines' | 'count';
  event?: string;
  order: Order;
  buckets?: readonly string[];
}
⋮----
function compareVersionsDesc(a: string, b: string): number
⋮----
// ---------------------------------------------------------------------------
// /api/meta
// ---------------------------------------------------------------------------
⋮----
interface MetaRow {
  latest_rollup_day: string | null;
  earliest_rollup_day: string | null;
  latest_active_day: string | null;
  earliest_active_day: string | null;
  earliest_raw_day: string | null;
  latest_raw_day: string | null;
}
⋮----
/**
 * What the picker anchors on. The dashboard asks for this first and ends every
 * default range on `latest_day`, because the nightly cron has not rolled up
 * today yet — anchoring on the wall clock would put a phantom zero on the right
 * edge of every line chart.
 */
async function meta(env: Env): Promise<ApiResult>
⋮----
/** Below this day the activation funnel is blind — raw events are purged. */
⋮----
// ---------------------------------------------------------------------------
// /api/summary — the big numbers
// ---------------------------------------------------------------------------
⋮----
/**
 * One D1 batch, one round trip. Distinct-machine numbers come from
 * `machine_days` rather than by summing `daily_machines`: a machine active on
 * five days is one user, and summing the daily counts would call it five.
 */
async function summary(env: Env, range: Range): Promise<ApiResult>
⋮----
const eventCount = (name: string): number
⋮----
interface DayValueRow {
  day: string;
  a: number | null;
  b: number | null;
}
⋮----
interface SeriesSpec {
  title: string;
  labels: [string] | [string, string];
  sql: string;
  binds: (range: Range) => (string | number)[];
}
⋮----
async function timeseries(env: Env, url: URL, range: Range): Promise<ApiResult>
⋮----
async function durationBucketSeries(env: Env, range: Range): Promise<ApiResult>
⋮----
interface BreakdownRow {
... (23 lines truncated)
</file>

<file path="telemetry-dashboard/src/auth.ts">
interface SessionPayload {
  v: number;
  iat: number;
  exp: number;
  pw: string;
}
⋮----
function base64UrlEncode(bytes: Uint8Array): string
⋮----
function base64UrlDecode(text: string): Uint8Array | null
⋮----
// Importing the HMAC key costs a round through WebCrypto; cache it per isolate.
// A secret rotation ships a new deployment, which means new isolates.
⋮----
async function hmacKey(secret: string): Promise<CryptoKey>
⋮----
async function sign(secret: string, payload: string): Promise<Uint8Array>
⋮----
async function equalsInConstantTime(a: string, b: string): Promise<boolean>
⋮----
async function passwordFingerprint(password: string): Promise<string>
⋮----
export async function checkPassword(env: Env, submitted: string): Promise<boolean>
⋮----
export async function issueSession(env: Env): Promise<string>
⋮----
export async function hasValidSession(env: Env, request: Request): Promise<boolean>
⋮----
export function readSessionCookie(request: Request): string | null
⋮----
export function sessionCookie(token: string): string
⋮----
export function clearedSessionCookie(): string
⋮----
export function isSameOriginPost(request: Request): boolean
</file>

<file path="telemetry-dashboard/src/index.ts">
import { handleApi } from './api';
import {
  checkPassword,
  clearedSessionCookie,
  hasValidSession,
  isSameOriginPost,
  issueSession,
  sessionCookie,
} from './auth';
import { renderLoginPage } from './login-page';
⋮----
function securityHeaders(styleNonce?: string): Record<string, string>
⋮----
function withSecurityHeaders(response: Response, styleNonce?: string): Response
⋮----
function headersWith(defaults: Record<string, string>, extra?: HeadersInit): Headers
⋮----
function html(body: string, init: ResponseInit &
⋮----
function json(body: unknown, init: ResponseInit =
⋮----
function redirect(location: string, init: ResponseInit =
⋮----
function safeNextPath(candidate: string | null): string
⋮----
function loginRedirect(url: URL): Response
⋮----
function nonce(): string
⋮----
/** Best-effort brute-force cap on the shared password, keyed by client IP. */
async function loginRateLimitOk(env: Env, request: Request): Promise<boolean>
⋮----
// Note for auditors: unlike the ingest worker — which never reads the client
// IP — this admin login does, purely as a rate-limit key. It is not stored,
// logged or forwarded anywhere.
⋮----
async function handleLoginPage(env: Env, request: Request, url: URL): Promise<Response>
⋮----
async function handleLoginSubmit(env: Env, request: Request): Promise<Response>
⋮----
const fail = (error: string, status: number): Response
⋮----
async function apiResponse(env: Env, url: URL): Promise<Response>
⋮----
async function serveAsset(env: Env, request: Request): Promise<Response>
⋮----
async fetch(request, env): Promise<Response>
</file>

<file path="telemetry-dashboard/src/login-page.ts">
function escapeHtml(value: string): string
⋮----
export interface LoginPageOptions {
  /** Path to return to after a successful sign-in. Already validated same-origin. */
  next: string;
  /** Shown above the form when a previous attempt failed. */
  error?: string;
  /** CSP nonce for the inline stylesheet. */
  nonce: string;
}
⋮----
/** Path to return to after a successful sign-in. Already validated same-origin. */
⋮----
/** Shown above the form when a previous attempt failed. */
⋮----
/** CSP nonce for the inline stylesheet. */
⋮----
export function renderLoginPage(
</file>

<file path="telemetry-dashboard/package.json">
{
  "name": "codegraph-telemetry-dashboard",
  "private": true,
  "type": "module",
  "description": "Password-gated admin dashboard over the codegraph telemetry D1 database (stats.getcodegraph.com)",
  "scripts": {
    "vendor": "node scripts/vendor-assets.mjs",
    "dev": "npm run vendor && wrangler dev",
    "deploy": "npm run vendor && wrangler deploy",
    "types": "wrangler types",
    "check": "npm run vendor && wrangler types && tsc --noEmit && wrangler deploy --dry-run",
    "seed": "./scripts/seed-fixture.sh",
    "smoke:auth": "./scripts/smoke-auth.sh",
    "smoke:api": "./scripts/smoke-api.sh",
    "smoke:render": "npm run vendor && node scripts/render-check.mjs"
  },
  "devDependencies": {
    "chart.js": "^4.4.0",
    "typescript": "^5.0.0",
    "wrangler": "^4.36.0"
  }
}
</file>

<file path="telemetry-dashboard/README.md">
# codegraph telemetry dashboard

The private admin view behind `stats.getcodegraph.com`. Its sibling
[`telemetry-worker/`](../telemetry-worker/) writes anonymous usage events into a D1 database;
this worker reads them back and draws the charts. Two people use it, so the auth is
deliberately the simplest thing that is actually safe: one shared password in a secret, and
a long-lived signed cookie.

This directory is in the public repo for the same reason the ingest worker is — the code
that touches telemetry should be readable by the people it collects from. Nothing secret
lives here: the password and the cookie-signing key are deployment secrets, and the D1
database ID is an identifier, not a credential.

## What is gated

Everything except the login page and `robots.txt`. `assets.run_worker_first` is `true` in
`wrangler.jsonc`, so Cloudflare hands *every* request to `src/index.ts` before the static
asset server sees it — the dashboard HTML, its JS, its CSS and the chart library are all
behind the session check, and a request without a valid cookie gets a redirect (pages) or a
`401` (`/api/*`). The login page is rendered inline by the worker rather than served from
`public/`, so the asset directory needs no "is this file public?" judgement calls.

| Route | Auth | Notes |
|---|---|---|
| `GET /login` | public | Password form. Redirects to `/` if already signed in. |
| `POST /login` | public | Rate-limited per IP; sets the session cookie on success. |
| `POST /logout` | public | Clears the cookie. |
| `GET /robots.txt` | public | `Disallow: /`. |
| `GET /api/*` | required | JSON. `401` without a session. See the API below. |
| everything else | required | Static assets from `public/`. `302 /login` without a session. |

## The API

Every endpoint is `GET`, session-gated, and scoped by `?from=YYYY-MM-DD&to=YYYY-MM-DD`
(inclusive, UTC days). Ranges wider than 366 days are clamped and say so in
`range.clamped`. Responses come back Chart.js-shaped — `labels[] + datasets[]` — plus a
`rows[]` in the data's natural shape, which is what each panel's "Show numbers" table
renders. Bad input is a `400` with a message, never a guess. Chart data carries
`Cache-Control: private, max-age=300`.

| Endpoint | Answers |
|---|---|
| `/api/meta` | The days data actually exists for. The picker anchors its presets on `latest_day` so no chart ends on a day the nightly rollup has not written yet. |
| `/api/summary` | Big numbers: production users, active machines, new machines, installs, uninstalls, indexing runs, tool calls. |
| `/api/timeseries?metric=` | `installs_uninstalls`, `new_installs`, `production_users`, `indexing_activity`, `tool_calls`, `duration_buckets`. One dense point per day — a day with nothing is a zero, not a gap. |
| `/api/breakdown?dim=` | `os`, `arch`, `codegraph_version`, `node_major`, `language`, `file_count_bucket`, `duration_bucket`, `target`, `scope`, `kind`, `name`, `client_name`, `name_error`. Optional `&event=`, `&metric=count\|machines`, `&limit=`. |
| `/api/activation?window=7` | Install → first index funnel, plus the daily rate. |
| `/api/retention` | Day 0–14 cohort curve for machines first seen in the range. |
| `/api/health` | Liveness plus the latest event/rollup day. Uncached. |

Everything reads the `daily_*` rollups and `machine_days`, which are kept forever, so a
chart stays correct for days whose raw events have been purged. `/api/activation` is the
one exception — "did this machine ever run an index" is not a daily aggregate — so it
reads raw `events` and is bounded by the ingest worker's retention window. It reports
`raw_events_from` for that reason.

### Two numbers that are easy to misread

Both are labelled honestly in the UI rather than rounded off into something friendlier:

- **Machine-days, not users.** `daily_dim_counts.machines` is per day, so summing it over
  a range counts a machine once per day it was active. A range-wide distinct count per
  dimension value is not recoverable from the rollups at all, so the panels that use it
  say "machine-days" and are share-of-total panels where the distinction does not move the
  shape. Where a dimension rides several event types, the per-day figure is the largest
  single-event count rather than their sum, so one machine's install + index + usage on
  one day is not counted three times.
- **Recent cohorts have not finished converting.** A machine that installed yesterday has
  not had seven days to run an index, so the tail of the activation curve is a floor, not
  a result. The API marks those days (`complete: false`, `incomplete_from`) and the panel
  says so instead of drawing a cliff and calling it a drop in conversion. Retention does
  the same thing with a per-day denominator: day *k* is measured only over the machines
  that have actually had *k* days to come back.

## How the session works

- The password is compared in constant time, over SHA-256 digests so the operands are always
  the same length and nothing about the secret leaks through timing.
- The cookie is a signed assertion — `base64url(payload).base64url(HMAC-SHA256)` — not a
  lookup key. There is no session store; a tampered payload fails the signature check.
- `HttpOnly; Secure; SameSite=Lax; Path=/`, `Max-Age` one year. You sign in once per browser
  and it survives restarts.
- The payload carries a fingerprint of the password it was minted against, so
  **rotating `ADMIN_PASSWORD` signs everyone out** — that is the revocation story.
- Login attempts are capped at 5/min per IP. Unlike the ingest worker, which never reads the
  client IP at all, this one does — solely as a rate-limit key, never stored or logged.

## Deploy

Prereqs: the `getcodegraph.com` zone on the deploying Cloudflare account (the custom domain
auto-provisions DNS + cert), and the D1 database from `telemetry-worker/` already created.

```bash
cd telemetry-dashboard
npm install
npx wrangler login                      # once

npx wrangler secret put ADMIN_PASSWORD  # the shared password
npx wrangler secret put SESSION_SECRET  # cookie-signing key, e.g. `openssl rand -base64 48`

... (94 lines truncated)
</file>

<file path="telemetry-dashboard/tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "Bundler",
    "lib": ["ES2022"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noEmit": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "types": []
  },
  "include": ["src/**/*", "worker-configuration.d.ts"]
}
</file>

<file path="telemetry-worker/src/env.d.ts">
interface Env {
  ADMIN_TOKEN: string;
}
</file>

<file path="telemetry-worker/src/index.ts">
import { handleAdminRollup, retentionDays, runNightly } from './rollup';
⋮----
const infoText = (keepDays: number): string
⋮----
type JsonObject = Record<string, unknown>;
⋮----
type Sanitize = (v: unknown) => unknown;
⋮----
const oneOf =
(allowed: readonly string[]): Sanitize
⋮----
const matching =
(re: RegExp, maxLen: number): Sanitize
⋮----
const token = (maxLen: number): Sanitize
const label = (maxLen: number): Sanitize
⋮----
const tokenArray =
(maxItems: number, maxLen: number): Sanitize
⋮----
const nonNegInt =
(max: number): Sanitize
⋮----
interface StoredEvent {
  event: string;
  ts?: string;
  props: JsonObject;
}
⋮----
function clampTimestamp(v: unknown): string | undefined
⋮----
function sanitizeEvent(raw: unknown): StoredEvent | null
⋮----
const asText = (v: unknown): string | null
const asInt = (v: unknown): number | null
const asFlag = (v: unknown): number | null
⋮----
async function writeToD1(
  env: Env,
  machineId: string,
  common: JsonObject,
  batch: StoredEvent[],
): Promise<void>
⋮----
async fetch(request, env, ctx): Promise<Response>
⋮----
async scheduled(event, env): Promise<void>
</file>

<file path="telemetry-worker/src/rollup.ts">
export function utcDay(atMs: number): string
⋮----
export function isValidDay(day: string): boolean
⋮----
export function retentionDays(env: Env): number
⋮----
export function retentionCutoff(atMs: number, keepDays: number): string
⋮----
const prop = (name: string): string => `json_extract(e.props, '$.$
const quoted = (values: readonly string[]): string => values.map((v) => `'$
const onlyEvents = (...events: readonly string[]): string => ` AND e.event IN ($
⋮----
function dimStatement(dim: string, value: string, where = ''): string
⋮----
/**
 * One dimension unnested from a JSON array prop — one row per element, so an index
 * of a TypeScript+Go repo counts once under each language. `json_each` over a path
 * the props do not have yields no rows, which is exactly the wanted behaviour for
 * events that omit the array.
 */
function arrayDimStatement(dim: string, path: string, events: readonly string[]): string
⋮----
/**
 * Rebuilt from `machine_days`, not from `events`: that table is never purged, so this
 * number stays right for days whose raw rows are long gone. `prod` is already the
 * per-machine-day maximum the ingest path maintains (0 only if every event that
 * machine sent that day carried ci = 1).
 *
 * So this is also the one rollup that can still be rebuilt for a day whose raw events
 * are long gone.
 */
⋮----
// Envelope dimensions — every event type carries them.
⋮----
export interface DayResult {
  day: string;
  rows: number;
  pastRetention: boolean;
}
⋮----
export async function rollupDay(
  env: Env,
  day: string,
  opts: { cutoff: string; reset?: boolean },
): Promise<DayResult>
⋮----
export interface PurgeResult {
  cutoff: string;
  deleted: number;
  batches: number;
  capped: boolean;
}
⋮----
export async function purgeOldEvents(env: Env, cutoff: string): Promise<PurgeResult>
⋮----
export async function runNightly(env: Env, atMs: number): Promise<void>
⋮----
const json = (body: unknown, status = 200): Response
⋮----
async function tokenMatches(provided: string, expected: string): Promise<boolean>
⋮----
export async function handleAdminRollup(request: Request, env: Env, url: URL): Promise<Response>
⋮----
// Cap how fast the token can be guessed at. Only failures spend the budget, so a
// chunked backfill loop is never throttled. Best-effort and fails open like the
// ingest limiter — the token itself is the guard, this only slows a guesser down.
</file>

<file path="telemetry-worker/package.json">
{
  "name": "codegraph-telemetry-worker",
  "private": true,
  "description": "First-party ingest endpoint for codegraph's anonymous usage telemetry (telemetry.getcodegraph.com)",
  "scripts": {
    "dev": "wrangler dev",
    "deploy": "wrangler deploy",
    "types": "wrangler types",
    "check": "wrangler types && tsc --noEmit && wrangler deploy --dry-run",
    "smoke": "./scripts/smoke-ingest.sh",
    "smoke:rollup": "./scripts/smoke-rollup.sh",
    "smoke:cutover": "./scripts/smoke-cutover.sh",
    "db:migrate:local": "wrangler d1 migrations apply codegraph-telemetry --local",
    "db:migrate": "wrangler d1 migrations apply codegraph-telemetry --remote",
    "db:migrations": "wrangler d1 migrations list codegraph-telemetry --remote",
    "db:sql": "wrangler d1 execute codegraph-telemetry --remote --command"
  },
  "devDependencies": {
    "typescript": "^5.0.0",
    "wrangler": "^4.36.0"
  }
}
</file>

<file path="telemetry-worker/README.md">
# codegraph telemetry ingest worker

The first-party endpoint behind `telemetry.getcodegraph.com`. This directory is in the
public repo **on purpose**: it is the exact code that receives codegraph's anonymous usage
telemetry, so anyone can audit what is stored. The schema contract (every event, every
field, and everything that is never collected) is in
[`docs/design/telemetry.md`](../docs/design/telemetry.md).

What it does, in one breath: validates incoming batches against a strict allowlist (unknown
events dropped, unknown properties stripped), never reads or stores the client IP,
rate-limits per machine ID, and writes the survivors to our own D1 database off the response
path. A nightly cron rolls each finished day up into anonymous daily counts and deletes the
raw rows behind it. It makes no outbound requests — nothing is forwarded to a third-party
analytics vendor. It ships nowhere with the npm package — the engine's `files` allowlist
excludes it.

## Endpoint contract

- `POST /v1/events` — JSON body: envelope (`machine_id` UUID, `codegraph_version`, `os`,
  `arch`, `node_major`, `ci`, `schema_version`) + `events: [{event, ts?, props?}]`.
  Responds `204` when accepted (including events dropped by the allowlist), honest `4xx`
  for malformed/oversized/rate-limited requests. Clients treat every response as final —
  no retries.
- `GET /` — plain-text pointer to the docs and the off-switches.
- `POST /admin/rollup` — manual rollup trigger, see below. `404` unless `ADMIN_TOKEN` is set.

## Storage (Cloudflare D1)

Telemetry is stored in the `codegraph-telemetry` D1 database on the same account, bound as
`env.DB` — this database is the only place accepted events go. Each request's surviving
events are written in a single `batch()` (one implicit transaction) under `ctx.waitUntil`,
so the write is off the response path. It is deliberately **fail-silent**: a D1 error is
logged to Workers Logs (counts only, never the payload) and the client still gets its `204`,
because clients never retry — losing a datapoint beats losing availability. Alongside the
raw rows, the worker upserts `machine_days` and `machine_first_seen`; when a batch is emptied
by the allowlist, nothing at all is written, so those tables only ever describe stored events.

The complete schema is [`migrations/0001_init.sql`](migrations/0001_init.sql) —
checked in for the same reason this worker's source is public: it is the entire list of what
gets kept, with a comment on every column and on which dashboard chart each rollup table
serves. Shape: raw sanitized `events`, `daily_*` rollups recomputed nightly, and
`machine_days` / `machine_first_seen` for retention cohorts. The dashboard reads rollups; raw
events exist for drill-down and are purged past the retention window.

```bash
npm run db:migrate:local     # apply to the local .wrangler state (offline, no account needed)
npm run db:migrate           # apply to the remote codegraph-telemetry database
npm run db:migrations        # which migrations are applied remotely
npm run db:sql "select count(*) from events"
```

Both applies bootstrap from empty and are a no-op when already current. A schema change is a
new numbered file (`npx wrangler d1 migrations create codegraph-telemetry <name>`) — never an
edit to a migration that has been applied.

Volume, at ~97k accepted POSTs/day: ≈30M D1 row writes/month against the 50M included on
Workers Paid, plus roughly as much again once the purge reaches steady state — a delete bills
like an insert, and at steady state every row written is eventually deleted, so budget ≈48M.
D1 bills a row write per index touched on top of the table row, which is why `events` carries
only two indexes; dropping `events_machine_day` is the first lever if that gets tight. Storage
is the other constraint, and it is what sets the window: raw events grow ≈74 MB/day, so 90 days
lands at ≈6.7 GB against D1's 10 GB per-database cap, while 180 days would exceed it. Full
arithmetic and the remaining levers are in the migration's footer comment.

## Rollups & retention (nightly cron)

`src/rollup.ts` runs on a Cron Trigger at **00:30 UTC** and does two things.

**Rolls up** the day that just ended into `daily_machines`, `daily_event_counts` and
`daily_dim_counts`, then re-runs the two days before it — offline clients ship completed-day
rollups late, so a day keeps growing after it ends. The aggregation is one
`INSERT … SELECT … ON CONFLICT DO UPDATE` per table or dimension, so it happens inside D1 and
no event row crosses the wire. Every write overwrites the recomputed value rather than adding
to it: **re-running a day is a no-op, never a double count.** Two things the SQL is careful
about — a `usage_rollup` row is a counter the client pre-aggregated, so its `count` prop is
summed rather than the rows counted; and `index.languages` / `install.targets` are unnested
with `json_each`, one row per element. Adding a breakdown is a line in `ROLLUP_STATEMENTS`,
never a migration — that is what the generic `(dim, value)` shape buys.

**Purges** raw `events` older than `RETENTION_DAYS` (90, a var in `wrangler.jsonc`) in bounded
`DELETE` batches, and logs one line of counts. `machine_days` and `machine_first_seen` are
never purged — retention cohorts need the full history and they are two orders of magnitude
smaller. Rollups are kept forever, so shortening the window costs ad-hoc drill-back, never a
chart.

Backfill or repair without a redeploy, guarded by the `ADMIN_TOKEN` secret:

```bash
curl -X POST -H "x-admin-token: $ADMIN_TOKEN" \
  'https://telemetry.getcodegraph.com/admin/rollup?day=2026-07-27'          # one day
curl -X POST -H "x-admin-token: $ADMIN_TOKEN" \
  'https://telemetry.getcodegraph.com/admin/rollup?day=2026-07-27&days=14'  # the 14 days ending there
```

`&reset=1` drops the day's rollup rows before recomputing, for when the dimension list itself
changed and a value that no longer exists would otherwise linger. It is ignored past the
retention window, where it would delete rows and then find no events to rebuild them from —
the response says which days it refused. Keep manual ranges to a few days at production volume;
each day is a full scan of that day's events, and the request has a wall-clock budget.

... (155 lines truncated)
</file>

<file path="telemetry-worker/tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ES2022",
    "moduleResolution": "Bundler",
    "lib": ["ES2022"],
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noEmit": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "types": []
  },
  "include": ["src/**/*", "worker-configuration.d.ts"]
}
</file>

<file path="ui/src/components/entry/EntrySection.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { fileHref } from '../../lib/navigation';
  import type { EntryRow, EntrySection } from '../../lib/entry-model';
  interface Props {
    section: EntrySection;
    armed: string | null;
    onopen: (row: EntryRow) => void;
    onflow: (row: EntryRow) => void;
  }
  let { section, armed, onopen, onflow }: Props = $props();
</script>
<section class="sec" aria-labelledby={`entry-${section.id}`}>
  <div class="sec-h">
    <h3 id={`entry-${section.id}`}>{section.title}</h3>
    <span class="meta">{section.meta}</span>
  </div>
  <p class="note">{section.note}</p>
  {#each section.groups as group (group.path)}
    <div class="filegroup">
      <div class="fpath">
        {#if group.file}
          <a href={fileHref(group.file)} title={group.file}>{group.path}</a>
        {:else}
          <span title={group.path}>{group.path}</span>
        {/if}
        <b>{group.rows.length}</b>
      </div>
      {#each group.rows as row (row.id)}
        <div class="row" class:armed={armed === row.id} class:stub={!row.target}>
          <KindGlyph kind={row.kind} />
          <div class="body">
            <div class="line">
              {#if row.target}
                <button
                  type="button"
                  class="nm"
                  title={row.title}
                  data-entry-row={row.id}
                  onclick={() => onopen(row)}
                >
                  {#if row.method}<span class="verb">{row.method}</span>{/if}{row.name}
                </button>
              {:else}
                <span class="nm plain" title={row.title}>
                  {#if row.method}<span class="verb">{row.method}</span>{/if}{row.name}
                </span>
              {/if}
              {#if row.flowFrom}
                {@const label =
                  armed === null ? 'Flow ›' : armed === row.id ? 'Cancel' : '→ here'}
                <button
                  type="button"
                  class="chip"
                  title={armed === null
                    ? `Start a flow from ${row.flowFrom}`
                    : armed === row.id
                      ? 'Stop drawing a flow from here'
                      : `Draw the path that ends at ${row.flowFrom}`}
                  data-entry-flow={row.id}
                  onclick={() => onflow(row)}>{label}</button
                >
              {/if}
            </div>
            <div class="meta">{row.meta}</div>
          </div>
        </div>
      {/each}
    </div>
  {/each}
  {#if section.shown < section.total}
    <p class="note dim">
      Showing {section.shown} of {section.floor ? 'at least ' : ''}{section.total} — the rest are in
      the index, not on this list.
    </p>
  {/if}
</section>
<style>
  .sec {
    padding: 0 0 18px;
    border-bottom: 1px solid var(--rule-faint);
  }
  .sec:last-child {
    border-bottom: 0;
  }
  .sec-h {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 12px;
    padding: 14px 14px 2px;
  }
  .sec-h h3 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
  }
  .sec-h .meta {
    color: var(--ink-3);
    font-size: 11.5px;
... (97 lines truncated)
</file>

<file path="ui/src/components/file/CodeArcs.svelte">
<script lang="ts">
  import { hot } from '../../lib/focus.svelte';
  import { ARC_COLUMN, type FileArc } from '../../lib/filecode-model';
  interface Props {
    arcs: FileArc[];
    height: number;
    hoverLine: number | null;
    onfollow: (arc: FileArc) => void;
  }
  let { arcs, height, hoverLine, onfollow }: Props = $props();
  function isLit(arc: FileArc): boolean {
    return hot.is(arc.targetId) || arc.fromLine === hoverLine || arc.toLine === hoverLine;
  }
  function label(arc: FileArc): string {
    const direction = arc.toLine < arc.fromLine ? 'above' : 'below';
    return `line ${arc.fromLine} calls ${arc.targetName}, defined ${direction} at line ${arc.toLine}`;
  }
</script>
<svg
  class="arcs"
  width={ARC_COLUMN}
  {height}
  viewBox={`0 0 ${ARC_COLUMN} ${height}`}
  focusable="false"
  aria-hidden="true"
>
  {#each arcs as arc (arc.key)}
    <path
      class="arc"
      class:lit={isLit(arc)}
      class:uncertain={arc.uncertain}
      class:heur={arc.synthesized}
      d={arc.d}
    />
    <path
      class="hit"
      d={arc.d}
      role="button"
      tabindex="-1"
      onclick={() => onfollow(arc)}
      onkeydown={(e) => {
        if (e.key === 'Enter' || e.key === ' ') {
          e.preventDefault();
          onfollow(arc);
        }
      }}
      onmouseenter={() => hot.set(arc.targetId)}
      onmouseleave={() => hot.clear(arc.targetId)}
    >
      <title>{label(arc)}</title>
    </path>
  {/each}
</svg>
<style>
  .arcs {
    position: absolute;
    top: 0;
    left: 0;
    overflow: visible;
  }
  .arc {
    fill: none;
    stroke: var(--ink-4);
    stroke-width: 1;
    pointer-events: none;
  }
  .arc.uncertain {
    stroke-dasharray: 2 3;
  }
  .arc.heur {
    stroke: var(--ink-3);
    stroke-dasharray: 6 3;
  }
  .arc.lit {
    stroke: var(--accent);
    stroke-width: 1.5;
  }
  .hit {
    fill: none;
    stroke: transparent;
    stroke-width: 10;
    cursor: pointer;
  }
</style>
</file>

<file path="ui/src/components/file/FileCodeBlock.svelte">
<script lang="ts">
  import { tokenClass, type Token } from '../../lib/highlight';
  import { assignRefs, type LineRef } from '../../lib/symbol-model';
  import { lineTop } from '../../lib/filecode-model';
  import { hot } from '../../lib/focus.svelte';
  interface Props {
    first: number;
    last: number;
    tokensFor: (line: number) => Token[] | null;
    refs: Map<number, LineRef[]>;
    defNames: Map<number, string>;
    highlight: number | null;
    onfollow: (ref: LineRef) => void;
    onhoverline: (line: number | null) => void;
  }
  let { first, last, tokensFor, refs, defNames, highlight, onfollow, onhoverline }: Props =
    $props();
  interface Part {
    text: string;
    cls: string | null;
    ref: LineRef | null;
    def: boolean;
  }
  interface RenderedLine {
    n: number;
    top: number;
    parts: Part[] | null;
    port: 'sure' | 'unsure' | null;
    targets: string[];
  }
  let lines = $derived.by<RenderedLine[]>(() => {
    const out: RenderedLine[] = [];
    for (let n = first; n <= last; n++) {
      const lineRefs = refs.get(n) ?? [];
      const tokens = tokensFor(n);
      out.push({
        n,
        top: lineTop(n),
        parts: tokens ? toParts(tokens, assignRefs(tokens, lineRefs), defNames.get(n) ?? null) : null,
        port: portFor(lineRefs),
        targets: [...new Set(lineRefs.map((r) => r.targetId).filter((id): id is string => !!id))],
      });
    }
    return out;
  });
  function toParts(line: Token[], claimed: Map<number, LineRef>, definition: string | null): Part[] {
    return line.map((token, index) => {
      const ref = claimed.get(index) ?? null;
      return {
        text: token.text,
        cls: ref ? null : tokenClass(token.cls),
        ref,
        def:
          !ref &&
          definition !== null &&
          token.text === definition &&
          token.cls !== 'comment' &&
          token.cls !== 'string',
      };
    });
  }
  function portFor(lineRefs: readonly LineRef[]): 'sure' | 'unsure' | null {
    if (lineRefs.length === 0) return null;
    return lineRefs.some((r) => !r.uncertain && !r.outside) ? 'sure' : 'unsure';
  }
  function isHot(line: RenderedLine): boolean {
    return line.n === highlight || line.targets.some((id) => hot.is(id));
  }
</script>
<div class="code">
  {#each lines as line (line.n)}
    <div
      class="ln"
      class:hot={isHot(line)}
      style:top={`${line.top}px`}
      data-line={line.n}
      onmouseenter={() => onhoverline(line.n)}
      role="presentation"
    >
      <span class="no">{line.n}</span>
      <span class="tx"
        >{#if line.parts}{#each line.parts as part, i (i)}{#if part.ref && !part.ref.outside}{@const ref =
              part.ref}<span
              class="ref"
              class:uncertain={ref.uncertain}
              class:hot={hot.is(ref.targetId)}
              role="link"
              tabindex="0"
              title={ref.title}
              onclick={() => onfollow(ref)}
              onkeydown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onfollow(ref);
                }
              }}
              onmouseenter={() => hot.set(ref.targetId)}
              onmouseleave={() => hot.clear(ref.targetId)}>{part.text}</span
            >{:else if part.ref}<span class="ref stub" title={part.ref.title}>{part.text}</span
            >{:else if part.def}<span class="t-def">{part.text}</span
... (111 lines truncated)
</file>

<file path="ui/src/components/file/FileCodeOutline.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { OUTLINE_VIRTUAL_THRESHOLD, type OutlineEntryRow } from '../../lib/file-model';
  import { NAV_ROW_HEIGHT } from '../../lib/filecode-model';
  interface Props {
    rows: OutlineEntryRow[];
    total: number;
    truncated: boolean;
    currentId: string | null;
    ongo: (line: number, id: string) => void;
  }
  let { rows, total, truncated, currentId, ongo }: Props = $props();
  let listEl = $state<HTMLDivElement | null>(null);
  let scrollTop = $state(0);
  let viewport = $state(0);
  let virtual = $derived(rows.length > OUTLINE_VIRTUAL_THRESHOLD);
  let window_ = $derived.by(() => {
    if (!virtual) return { start: 0, end: rows.length, before: 0, after: 0 };
    const first = Math.floor(scrollTop / NAV_ROW_HEIGHT) - 8;
    const count = Math.ceil((viewport || 800) / NAV_ROW_HEIGHT) + 16;
    const start = Math.max(0, Math.min(rows.length - 1, first));
    const end = Math.max(start, Math.min(rows.length, start + count));
    return {
      start,
      end,
      before: start * NAV_ROW_HEIGHT,
      after: (rows.length - end) * NAV_ROW_HEIGHT,
    };
  });
  $effect(() => {
    const id = currentId;
    const el = listEl;
    if (!id || !el) return;
    const at = rows.findIndex((row) => row.entry.id === id);
    if (at < 0) return;
    const top = at * NAV_ROW_HEIGHT;
    const scroller = el.parentElement;
    if (!scroller) return;
    if (top < scroller.scrollTop) scroller.scrollTop = top - NAV_ROW_HEIGHT * 2;
    else if (top + NAV_ROW_HEIGHT > scroller.scrollTop + scroller.clientHeight) {
      scroller.scrollTop = top + NAV_ROW_HEIGHT * 3 - scroller.clientHeight;
    }
  });
  $effect(() => {
    const el = listEl?.parentElement;
    if (!el) return;
    const read = () => {
      scrollTop = el.scrollTop;
      viewport = el.clientHeight;
    };
    read();
    el.addEventListener('scroll', read, { passive: true });
    const observer = new ResizeObserver(read);
    observer.observe(el);
    return () => {
      el.removeEventListener('scroll', read);
      observer.disconnect();
    };
  });
</script>
<div class="navrail">
  <div class="navh">
    <span>Outline</span>
    <span class="dim">{total}</span>
  </div>
  <div class="navlist">
    <div bind:this={listEl}>
      {#if window_.before > 0}<div style:height={`${window_.before}px`}></div>{/if}
      {#each rows.slice(window_.start, window_.end) as row (row.entry.id)}
        <button
          type="button"
          class="nrow"
          class:dimmed={row.dimmed}
          class:current={row.entry.id === currentId}
          style:padding-left={`${6 + row.indent * 14}px`}
          title={`${row.entry.qualifiedName} — line ${row.entry.line}`}
          onclick={() => ongo(row.entry.line, row.entry.id)}
        >
          <KindGlyph kind={row.entry.kind} />
          <span class="nm">{row.entry.name}</span>
          <span class="ln">{row.entry.line}</span>
        </button>
      {/each}
      {#if window_.after > 0}<div style:height={`${window_.after}px`}></div>{/if}
    </div>
  </div>
  {#if truncated}
    <div class="note">Showing {rows.length} of {total} symbols.</div>
  {/if}
</div>
<style>
  .navrail {
    display: grid;
    grid-template-rows: auto minmax(0, 1fr) auto;
    height: 100%;
    border-right: 1px solid var(--rule-soft);
    background: var(--paper);
  }
  .navh {
    display: flex;
... (50 lines truncated)
</file>

<file path="ui/src/components/file/FileCodeRail.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { hot } from '../../lib/focus.svelte';
  import type { FileCallRow } from '../../lib/filecode-model';
  import type { WireNodeRef } from '../../lib/api';
  interface Props {
    rows: FileCallRow[];
    focalFile: string;
    focusId: string | null;
    onopen: (node: WireNodeRef) => void;
    onhover: (row: FileCallRow | null) => void;
  }
  let { rows, focalFile, focusId, onopen, onhover }: Props = $props();
  function title(row: FileCallRow): string {
    const node = row.call.relation.node;
    const where = row.lines.length > 0 ? ` · called from line ${row.lines.join(', ')}` : '';
    return `${node.qualifiedName} — ${node.file}:${node.line}${where}`;
  }
</script>
{#each rows as row (row.key)}
  {@const node = row.call.relation.node}
  <div
    class="rrow"
    class:hot={hot.is(node.id)}
    class:focused={focusId !== null && (row.ownerId === focusId || node.id === focusId)}
    class:uncertain={row.call.relation.uncertain}
    style:top={`${row.top}px`}
    data-target={node.id}
    role="button"
    tabindex="0"
    title={title(row)}
    onclick={() => onopen(node)}
    onkeydown={(e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        onopen(node);
      }
    }}
    onmouseenter={() => {
      hot.set(node.id);
      onhover(row);
    }}
    onmouseleave={() => {
      hot.clear(node.id);
      onhover(null);
    }}
  >
    <KindGlyph kind={node.kind} />
    <div class="body">
      <div class="nm">
        {node.name}{#if row.lines.length > 1}<span class="dim"> ×{row.lines.length}</span>{/if}
      </div>
      <div class="meta">
        <span>{node.file === focalFile ? 'same file' : node.file}</span>
        {#if row.words.length > 0}<span>{row.words.join(', ')}</span>{/if}
        {#if row.via}<span
            class="tag"
            title="A synthesized edge — dynamic dispatch the parser cannot see">via {row.via}</span
          >{/if}
      </div>
    </div>
  </div>
{/each}
<style>
  .rrow {
    position: absolute;
    right: 12px;
    left: 14px;
    display: grid;
    height: 34px;
    box-sizing: border-box;
    grid-template-columns: 16px 1fr;
    gap: 8px;
    align-items: center;
    padding: 0 6px;
    border: 1px solid transparent;
    background: var(--paper);
    cursor: pointer;
  }
  .rrow:hover {
    background: var(--press);
  }
  .rrow.focused {
    border-color: var(--rule-soft);
  }
  .rrow.hot {
    border-color: var(--accent-line);
    background: var(--accent-soft);
  }
  .body {
    min-width: 0;
  }
  .nm {
    overflow: hidden;
    font: 12.5px var(--mono);
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .rrow.uncertain .nm {
    color: var(--ink-2);
... (21 lines truncated)
</file>

<file path="ui/src/components/file/FileModeTabs.svelte">
<script lang="ts">
  import { fileHref } from '../../lib/navigation';
  interface Props {
    path: string;
    line: number | null;
    source: boolean;
  }
  let { path, line, source }: Props = $props();
</script>
<nav class="modes" aria-label="File view mode">
  <a
    class="mode"
    class:on={!source}
    href={fileHref(path, line ? { line } : {})}
    aria-current={!source ? 'page' : undefined}>Outline</a
  >
  <a
    class="mode"
    class:on={source}
    href={fileHref(path, { source: true, ...(line ? { line } : {}) })}
    aria-current={source ? 'page' : undefined}>Source</a
  >
</nav>
<style>
  .modes {
    display: flex;
    gap: 2px;
  }
  .mode {
    padding: 3px 10px;
    border: 1px solid var(--rule-soft);
    color: var(--ink-2);
    font-size: 12.5px;
    text-decoration: none;
  }
  .mode:hover {
    background: var(--press);
  }
  .mode.on {
    border-color: var(--ink);
    color: var(--ink);
  }
</style>
</file>

<file path="ui/src/components/file/FileOutline.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import type { WireNodeRef } from '../../lib/api';
  import {
    OUTLINE_ROW_HEIGHT,
    OUTLINE_VIRTUAL_THRESHOLD,
    type OutlineEntryRow,
  } from '../../lib/file-model';
  interface Props {
    rows: OutlineEntryRow[];
    total: number;
    truncated: boolean;
    scroller: HTMLElement | null;
    selected?: number;
    onopen: (node: WireNodeRef) => void;
    onhover?: (index: number) => void;
  }
  let { rows, total, truncated, scroller, selected = -1, onopen, onhover }: Props = $props();
  let listEl = $state<HTMLDivElement | null>(null);
  let scrollTop = $state(0);
  let viewport = $state(0);
  let virtual = $derived(rows.length > OUTLINE_VIRTUAL_THRESHOLD);
  let window_ = $derived.by(() => {
    if (!virtual) return { start: 0, end: rows.length, before: 0, after: 0 };
    const top = listEl ? listEl.offsetTop : 0;
    const first = Math.floor((scrollTop - top) / OUTLINE_ROW_HEIGHT) - 8;
    const count = Math.ceil((viewport || 800) / OUTLINE_ROW_HEIGHT) + 16;
    const start = Math.max(0, Math.min(rows.length - 1, first));
    const end = Math.max(start, Math.min(rows.length, start + count));
    return {
      start,
      end,
      before: start * OUTLINE_ROW_HEIGHT,
      after: (rows.length - end) * OUTLINE_ROW_HEIGHT,
    };
  });
  $effect(() => {
    if (selected < 0 || !scroller || !listEl) return;
    const rowTop = listEl.offsetTop + selected * OUTLINE_ROW_HEIGHT;
    const rowBottom = rowTop + OUTLINE_ROW_HEIGHT;
    if (rowTop < scroller.scrollTop) scroller.scrollTop = rowTop - OUTLINE_ROW_HEIGHT;
    else if (rowBottom > scroller.scrollTop + scroller.clientHeight) {
      scroller.scrollTop = rowBottom - scroller.clientHeight + OUTLINE_ROW_HEIGHT;
    }
  });
  $effect(() => {
    const el = scroller;
    if (!el) return;
    const read = () => {
      scrollTop = el.scrollTop;
      viewport = el.clientHeight;
    };
    read();
    el.addEventListener('scroll', read, { passive: true });
    const observer = new ResizeObserver(read);
    observer.observe(el);
    return () => {
      el.removeEventListener('scroll', read);
      observer.disconnect();
    };
  });
</script>
<div class="subh">
  <span>Outline</span>
  <span class="n">in source order</span>
  <span class="n count">{total}</span>
</div>
<div class="outline" bind:this={listEl}>
  {#if window_.before > 0}<div style:height={`${window_.before}px`}></div>{/if}
  {#each rows.slice(window_.start, window_.end) as row, offset (row.entry.id)}
    {@const index = window_.start + offset}
    <button
      type="button"
      class="orow"
      class:dimmed={row.dimmed}
      class:sel={index === selected}
      style:padding-left={`${4 + row.indent * 22}px`}
      onclick={() => onopen(row.entry)}
      onmouseenter={() => onhover?.(index)}
      title={`${row.entry.qualifiedName} — line ${row.entry.line}`}
    >
      <KindGlyph kind={row.entry.kind} />
      <span class="nm">{row.entry.name}</span>
      <span class="sig">{row.entry.signature ?? ''}</span>
      <span class="cnt">
        {row.entry.line}{#if row.entry.fanIn}&nbsp;· ← {row.entry.fanIn}{/if}{#if row.entry.fanOut}&nbsp;·
          → {row.entry.fanOut}{/if}
      </span>
    </button>
  {/each}
  {#if window_.after > 0}<div style:height={`${window_.after}px`}></div>{/if}
</div>
{#if rows.length === 0}
  <div class="note">
    Nothing was extracted from this file — it holds no symbols the graph
    recognises, only top-level code, or a language without an extractor.
  </div>
{/if}
{#if truncated}
  <div class="note">
... (70 lines truncated)
</file>

<file path="ui/src/components/file/FileRail.svelte">
<script lang="ts">
  import { fileHref } from '../../lib/navigation';
  import { plural } from '../../lib/symbol-model';
  import type { FileRailModel, FileRailRow } from '../../lib/file-model';
  interface Props {
    title: string;
    model: FileRailModel;
    emptyNote: string;
    side: 'left' | 'right';
    selected?: number;
    onhover?: (index: number) => void;
  }
  let { title, model, emptyNote, side, selected = -1, onhover }: Props = $props();
  function dirOf(path: string): string {
    const cut = path.lastIndexOf('/');
    return cut < 0 ? '' : path.slice(0, cut + 1);
  }
  function baseOf(path: string): string {
    return path.slice(path.lastIndexOf('/') + 1);
  }
  function rowTitle(row: FileRailRow): string {
    if (row.symbols.length === 0) return row.path;
    const names = row.symbols.map((s) => s.name).join(', ');
    const more = row.symbolCount > row.symbols.length ? ', …' : '';
    return `${row.path} — ${names}${more}`;
  }
</script>
<div class="rail" class:right={side === 'right'} aria-label={title}>
  <div class="rail-h">
    <span>{title} <span class="n">{model.total}</span></span>
  </div>
  {#if model.rows.length === 0}
    <div class="note">{emptyNote}</div>
  {/if}
  {#each model.rows as row, index (row.path)}
    <a
      class="filerow"
      class:test={row.test}
      class:sel={index === selected}
      href={fileHref(row.path)}
      title={rowTitle(row)}
      onmouseenter={() => onhover?.(index)}
    >
      <span class="p"><span class="dir">{dirOf(row.path)}</span><span class="base"
          >{baseOf(row.path)}</span
        ></span>
      {#if row.symbolCount > 0}
        <span class="n2">{row.symbolCount}</span>
      {/if}
    </a>
  {/each}
  {#if model.testCount > 0 && model.testCount < model.rows.length}
    <div class="note dim">
      {plural(model.testCount, 'test file')} at the end of the list.
    </div>
  {/if}
  {#if model.outside.length > 0}
    <div class="sub">
      Outside the index <span class="n">{model.outside.length}</span>
    </div>
    {#each model.outside as row (row.name)}
      <div class="filerow outside" title={`imported at line ${row.lines.join(', ')}`}>
        <span class="p"><span class="dir">{row.name}</span></span>
        {#if row.lines.length > 1}<span class="n2">×{row.lines.length}</span>{/if}
      </div>
    {/each}
    <div class="note dim">
      Packages and runtime modules — nothing was indexed for them, so this
      viewer cannot open them.
    </div>
  {/if}
</div>
<style>
  .rail {
    overflow: auto;
    height: 100%;
    border-right: 1px solid var(--rule-soft);
    background: var(--paper);
  }
  .rail.right {
    border-right: none;
    border-left: 1px solid var(--rule-soft);
  }
  .rail-h {
    position: sticky;
    top: 0;
    z-index: 2;
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    padding: 12px 14px 8px;
    border-bottom: 1px solid var(--rule-soft);
    background: var(--paper);
    font-weight: 600;
    font-size: 13px;
  }
  .rail-h .n,
  .sub .n {
    color: var(--ink-3);
    font-weight: 400;
... (62 lines truncated)
</file>

<file path="ui/src/components/flow/FlowCard.svelte">
<script lang="ts">
  import { Handle, Position } from '@xyflow/svelte';
  import KindGlyph from '../KindGlyph.svelte';
  import { tokenClass, tokensByLine, type Token } from '../../lib/highlight';
  import { assignRefs, basename, type LineRef } from '../../lib/symbol-model';
  import type { FlowCardLayout } from '../../lib/flow-model';
  interface Props {
    data: {
      card: FlowCardLayout;
      current: boolean;
      dimmed: boolean;
      onOpen: (card: FlowCardLayout) => void;
      onFollow: (card: FlowCardLayout) => void;
    };
  }
  let { data }: Props = $props();
  let card = $derived(data.card);
  let hop = $derived(card.hop);
  let source = $derived(hop.source);
  let refs = $derived.by<Map<number, LineRef[]>>(() => {
    const byLine = new Map<number, LineRef[]>();
    const ref = hop.callRef;
    if (!ref) return byLine;
    byLine.set(ref.line, [
      {
        ident: ref.name,
        col: ref.col,
        targetId: ref.targetId,
        uncertain: false,
        outside: false,
        title: ref.backwards
          ? `${hop.node.name} calls ${ref.name} here`
          : `calls ${ref.name}`,
      },
    ]);
    return byLine;
  });
  let tokens = $derived.by<Map<number, Token[]>>(() =>
    source?.lines ? tokensByLine(source.lines, source.from, source.highlight) : new Map()
  );
  interface Part {
    text: string;
    cls: string | null;
    ref: LineRef | null;
  }
  let rows = $derived.by(() => {
    if (!source?.lines) return [];
    return source.lines.map((text, offset) => {
      const n = source.from + offset;
      const lineTokens = tokens.get(n) ?? [{ cls: 'other' as const, text, col: 0 }];
      const claimed = assignRefs(lineTokens, refs.get(n) ?? []);
      return {
        n,
        call: n === hop.callRef?.line || n === card.stopLine,
        parts: lineTokens.map((token, index): Part => {
          const ref = claimed.get(index) ?? null;
          return { text: token.text, cls: ref ? null : tokenClass(token.cls), ref };
        }),
      };
    });
  });
</script>
<div
  class="card"
  class:cur={data.current}
  class:dim={data.dimmed}
  style={`width:${card.width}px;height:${card.height}px`}
>
  <Handle type="target" position={Position.Left} id="in" isConnectable={false} />
  <Handle type="source" position={Position.Right} id="out" isConnectable={false} />
  <button type="button" class="head" onclick={() => data.onOpen(card)}>
    <KindGlyph kind={hop.node.kind} />
    <span class="nm">{hop.node.name}</span>
    <span class="loc">{basename(hop.node.file)}:{hop.node.line}</span>
  </button>
  {#if rows.length > 0}
    <div class="code">
      {#each rows as row (row.n)}
        <div class="ln" class:call={row.call}>
          <span class="no">{row.n}</span>
          <span class="tx"
            >{#each row.parts as part, i (i)}{#if part.ref}<button
                  type="button"
                  class="ref"
                  title={part.ref.title}
                  onclick={() => data.onFollow(card)}>{part.text}</button
                >{:else if part.cls}<span class={part.cls}>{part.text}</span
                >{:else}{part.text}{/if}{/each}</span
          >
        </div>
      {/each}
    </div>
  {:else}
    <p class="nosource">
      {source?.drift
        ? 'Changed on disk after the last index sync — source is not shown.'
        : (source?.reason ?? 'Source outside this slice or this index.')}
    </p>
  {/if}
</div>
... (105 lines truncated)
</file>

<file path="ui/src/components/flow/FlowEndCap.svelte">
<script lang="ts">
  import { Handle, Position } from '@xyflow/svelte';
  import { endCapText, type FlowEndCapLayout } from '../../lib/flow-model';
  import { basename } from '../../lib/symbol-model';
  interface Props {
    data: {
      cap: FlowEndCapLayout;
      dimmed: boolean;
      onOpen: (nodeId: string) => void;
    };
  }
  let { data }: Props = $props();
  let cap = $derived(data.cap);
  let text = $derived(endCapText(cap.boundary));
</script>
<div
  class="endcap"
  class:dim={data.dimmed}
  style={`width:${cap.width}px;min-height:${cap.height}px`}
>
  <Handle type="target" position={Position.Left} id="in" isConnectable={false} />
  <p class="lead"><b>Where the graph stops.</b> {text.intro}</p>
  {#each text.sites as site, i (i)}
    <div class="site">
      <p class="form">{site.headline}</p>
      {#if site.key !== null}
        <p class="key">key <span class="mono">{site.key}</span></p>
      {/if}
      {#each site.notes as note (note)}
        <p class="soft">{note}</p>
      {/each}
      {#if site.candidateHeading !== null}
        <p class="soft">{site.candidateHeading}</p>
        {#each site.candidates as candidate (candidate.node.id)}
          <button type="button" class="row" onclick={() => data.onOpen(candidate.node.id)}>
            <span class="nm">{candidate.display}</span>
            <span class="at">{basename(candidate.node.file)}:{candidate.node.line}</span>
          </button>
        {/each}
      {:else if site.candidateNote !== null}
        <p class="soft">{site.candidateNote}</p>
      {/if}
    </div>
  {/each}
  {#if text.quiet !== null}
    <p class="soft block">{text.quiet}</p>
  {/if}
  {#if text.uncertainHeading !== null}
    <div class="block">
      <p class="soft">{text.uncertainHeading}</p>
      {#each text.uncertain as next (next.node.id)}
        <button type="button" class="row" onclick={() => data.onOpen(next.node.id)}>
          <span class="nm unsure">{next.node.name}</span>
          <span class="at">{next.confidence === null ? '' : next.confidence.toFixed(2)}</span>
        </button>
      {/each}
    </div>
  {/if}
  {#if text.further !== null}
    <p class="block">{text.further}</p>
  {/if}
  {#if text.missed !== null}
    <p class="block">{text.missed}</p>
  {/if}
</div>
<style>
  .endcap {
    box-sizing: border-box;
    padding: 12px;
    background: var(--paper);
    border: 1px dashed var(--rule-soft);
    color: var(--ink-2);
    font-size: 12px;
    line-height: 1.45;
    text-align: left;
  }
  .endcap.dim {
    opacity: 0.4;
  }
  .lead {
    margin: 0;
  }
  .lead b {
    color: var(--ink);
    font-weight: 600;
  }
  .site,
  .block {
    margin-top: 8px;
  }
  .endcap p {
    margin: 0;
  }
  .form {
    color: var(--ink);
  }
  .soft {
    color: var(--ink-3);
  }
  .key .mono,
... (36 lines truncated)
</file>

<file path="ui/src/components/flow/FlowLink.svelte">
<script lang="ts">
  import { BaseEdge, type EdgeProps } from '@xyflow/svelte';
  import type { FlowLinkLayout } from '../../lib/flow-model';
  let { sourceX, sourceY, targetX, targetY, data }: EdgeProps = $props();
  const d = $derived(data as unknown as { link: FlowLinkLayout; dimmed: boolean });
  const path = $derived.by(() => {
    if (Math.abs(sourceY - targetY) < 0.5) return `M${sourceX},${sourceY} L${targetX},${targetY}`;
    const midX = (sourceX + targetX) / 2;
    return `M${sourceX},${sourceY} C${midX},${sourceY} ${midX},${targetY} ${targetX},${targetY}`;
  });
  const head = $derived(
    `${targetX - 10},${targetY - 4} ${targetX - 2},${targetY} ${targetX - 10},${targetY + 4}`
  );
  const labelX = $derived((sourceX + targetX) / 2);
  const labelY = $derived((sourceY + targetY) / 2);
  const dashStyle = $derived(d.link.dash ? `stroke-dasharray:${d.link.dash}` : '');
  /** Stacked upwards from the line, so the last clause sits nearest it. */
  const above = $derived(d.link.labelLines);
</script>
<BaseEdge {path} class={`flink${d.dimmed ? ' dimmed' : ''}`} style={dashStyle} />
{#if !d.link.cap}
  <polygon class={`fhead${d.dimmed ? ' dimmed' : ''}`} points={head} />
{/if}
<g class={`flabel${d.dimmed ? ' dimmed' : ''}`}>
  <title>{d.link.label}{d.link.lineLabel ? ` (${d.link.lineLabel})` : ''}</title>
  {#each above as line, i (i)}
    <text x={labelX} y={labelY - 8 - (above.length - 1 - i) * 13} text-anchor="middle">{line}</text>
  {/each}
  {#if d.link.lineLabel}
    <text x={labelX} y={labelY + 17} text-anchor="middle">{d.link.lineLabel}</text>
  {/if}
</g>
<style>
  :global(.svelte-flow__edge-path.flink) {
    stroke: var(--ink-3);
    stroke-width: 1px;
    fill: none;
  }
  :global(.svelte-flow__edge-path.flink.dimmed) {
    stroke-opacity: 0.25;
  }
  .fhead {
    fill: var(--ink-3);
  }
  .fhead.dimmed {
    fill-opacity: 0.25;
  }
  .flabel text {
    fill: var(--ink-3);
    font: 11px var(--mono);
  }
  .flabel.dimmed text {
    fill-opacity: 0.25;
  }
</style>
</file>

<file path="ui/src/components/map/MapKey.svelte">
<script lang="ts">
  interface Props {
    minWeight: number;
    thinCount: number;
    declaredBasis: boolean;
    open: boolean;
    onToggle: (open: boolean) => void;
  }
  let { minWeight, thinCount, declaredBasis, open, onToggle }: Props = $props();
</script>
<div class="legend" class:open>
  <button class="legend-h" onclick={() => onToggle(!open)} aria-expanded={open}>
    Key <span class="dim">{open ? '▾' : '▸'}</span>
  </button>
  {#if open}
    <div class="legend-body">
      <div class="lrow">
        <span class="k-box mono">src/api</span>
        <span>A module — one directory, with the symbols and files in it</span>
      </div>
      <div class="lrow">
        <span class="k-box k-weight mono">src/db</span>
        <span>
          The bar along the bottom is how much leans on it — files elsewhere that reference
          straight into it, against the most depended-on box here. The count is on the box
        </span>
      </div>
      <div class="lrow">
        <svg width="44" height="12" aria-hidden="true"><path d="M2 6 H42" class="k-line" /></svg>
        <span>
          Depends on — the box above calls, imports, extends or names a type from the box below.
          Thicker is more references{declaredBasis
            ? ''
            : '; here the layering had too few imports to trust, so it used raw counts'}
        </span>
      </div>
      <div class="lrow">
        <svg width="44" height="12" aria-hidden="true"><path d="M2 6 H42" class="k-line k-back" /></svg>
        <span>
          Points back up — the lighter half of a mutual dependency, or a link with no import or
          declared type behind it. Drawn only while a module it touches is selected
        </span>
      </div>
      <div class="lrow">
        <span class="k-label">top / bottom</span>
        <span>
          A module sits one layer above everything it depends on, so entry points end up at the top
          and the foundations — which depend on nothing below — at the bottom
        </span>
      </div>
      <div class="lrow">
        <span class="k-box k-sel mono">src/api</span>
        <span>Selected: click a module to bring out its links and list its files; everything more than one hop away fades</span>
      </div>
      <div class="lrow">
        <span class="k-label">nothing depends on this</span>
        <span>No link in the index arrives here — a script, a workflow, an unreferenced corner</span>
      </div>
      <div class="lrow">
        <span class="k-box k-test mono">__tests__</span>
        <span>More than half its files are tests; off unless you turn tests on</span>
      </div>
      <div class="lrow">
        <span class="k-box k-gen mono">gen</span>
        <span>Every file in it is tool-generated — nobody wrote it and nobody edits it</span>
      </div>
      {#if thinCount > 0}
        <div class="lrow">
          <span class="k-label">{thinCount} hidden</span>
          <span>
            Links carrying fewer than {minWeight} references wait until you select a module they
            touch, so a weak coincidence never draws as a dependency
          </span>
        </div>
      {/if}
    </div>
  {/if}
</div>
<style>
  .legend {
    position: absolute;
    left: 12px;
    bottom: 12px;
    z-index: 4;
    max-width: 400px;
    border: 1px solid var(--rule);
    background: var(--paper);
    font-size: 11.5px;
    color: var(--ink-2);
  }
  .legend-h {
    display: block;
    width: 100%;
    border: 0;
    background: transparent;
    padding: 5px 10px;
    text-align: left;
    color: var(--ink);
    font: 600 12px var(--sans);
    cursor: pointer;
... (72 lines truncated)
</file>

<file path="ui/src/components/map/MapSidePanel.svelte">
<script lang="ts">
  import ExportButtons from '../ExportButtons.svelte';
  import { fileHref } from '../../lib/navigation';
  import { plural } from '../../lib/symbol-model';
  import type { WireMapLink, WireMapPayload } from '../../lib/api';
  import type { MapLayout } from '../../lib/map-model';
  interface Props {
    payload: WireMapPayload;
    layout: MapLayout;
    selected: string | null;
    includeTests: boolean;
    files: string[];
    onToggleTests: (value: boolean) => void;
    onSelectRoot: (root: string) => void;
    chosenDepth: number | null;
    onSelectDepth: (depth: number | null) => void;
    onSelect: (id: string | null) => void;
    buildSvg: (scale: number) => string;
    exportName: string;
  }
  let {
    payload,
    layout,
    selected,
    includeTests,
    files,
    onToggleTests,
    onSelectRoot,
    chosenDepth,
    onSelectDepth,
    onSelect,
    buildSvg,
    exportName,
  }: Props = $props();
  const DEPTHS = [1, 2, 3, 4] as const;
  function depthLabel(depth: number): string {
    return depth === 1 ? 'top-level folders' : `${depth} folders deep`;
  }
  const DASH = '\u2014';
  const selectedNode = $derived(
    selected === null ? null : (layout.nodes.find((n) => n.id === selected) ?? null)
  );
  const selectedModule = $derived(selectedNode?.module ?? null);
  const generatedFiles = $derived(new Set(selectedModule?.generatedFiles ?? []));
  const dependencies = $derived(
    selected === null
      ? []
      : layout.edges
          .filter((e) => e.source === selected)
          .map((e) => e.link)
          .sort((a, b) => b.count - a.count || a.target.localeCompare(b.target))
  );
  const dependents = $derived(
    selected === null
      ? []
      : layout.edges
          .filter((e) => e.target === selected)
          .map((e) => e.link)
          .sort((a, b) => b.count - a.count || a.source.localeCompare(b.source))
  );
  const thinCount = $derived(layout.edges.filter((e) => e.thin && !e.back).length);
</script>
<aside class="mapside">
  <h2>Architecture map</h2>
  <p>
    Derived from the graph, not drawn by hand: each module sits one layer above the modules it
    depends on, so reading top to bottom follows the dependency direction. Line weight is how many
    calls, imports and type references cross the link.
  </p>
  <ExportButtons build={buildSvg} filename={exportName} />
  <label class="field">
    <span>Showing</span>
    <select
      value={payload.root}
      onchange={(event) => onSelectRoot((event.currentTarget as HTMLSelectElement).value)}
    >
      {#each payload.roots as option (option.root)}
        <option value={option.root}>{option.label} · {option.files} files</option>
      {/each}
    </select>
  </label>
  <label class="field">
    <span>Grouping</span>
    <select
      value={chosenDepth === null ? 'auto' : String(chosenDepth)}
      onchange={(event) => {
        const value = (event.currentTarget as HTMLSelectElement).value;
        onSelectDepth(value === 'auto' ? null : Number(value));
      }}
    >
      <option value="auto">automatic {DASH} {depthLabel(payload.depth)}</option>
      {#each DEPTHS as option (option)}
        <option value={String(option)}>{depthLabel(option)}</option>
      {/each}
    </select>
  </label>
  <label class="toggle">
    <input
      type="checkbox"
      checked={includeTests}
... (314 lines truncated)
</file>

<file path="ui/src/components/map/ModuleEdge.svelte">
<script lang="ts">
  import { BaseEdge, type EdgeProps } from '@xyflow/svelte';
  import type { MapEdgeLayout } from '../../lib/map-model';
  let { sourceX, sourceY, targetX, targetY, data }: EdgeProps = $props();
  const d = $derived(
    data as unknown as {
      edge: MapEdgeLayout;
      hot: boolean;
      dimmed: boolean;
      onHover: (edge: MapEdgeLayout | null, event: MouseEvent | null) => void;
    }
  );
  const path = $derived.by(() => {
    const midY = (sourceY + targetY) / 2;
    return `M${sourceX},${sourceY} C${sourceX},${midY} ${targetX},${midY} ${targetX},${targetY}`;
  });
</script>
<BaseEdge
  {path}
  class={`medge${d.edge.back ? ' back' : ''}${d.hot ? ' hot' : ''}${d.dimmed ? ' dimmed' : ''}`}
  style={`stroke-width:${d.edge.width}px`}
/>
<path
  class="hit"
  d={path}
  role="presentation"
  onmousemove={(event) => d.onHover(d.edge, event)}
  onmouseleave={() => d.onHover(null, null)}
/>
<style>
  :global(.svelte-flow__edge-path.medge) {
    stroke: var(--ink);
    stroke-opacity: 0.28;
    fill: none;
  }
  :global(.svelte-flow__edge-path.medge.hot) {
    stroke-opacity: 0.95;
  }
  :global(.svelte-flow__edge-path.medge.dimmed) {
    stroke-opacity: 0.06;
  }
  :global(.svelte-flow__edge-path.medge.back) {
    stroke: var(--accent);
    stroke-opacity: 0.6;
    stroke-dasharray: 4 3;
  }
  .hit {
    stroke: transparent;
    stroke-width: 12;
    fill: none;
    pointer-events: stroke;
    cursor: crosshair;
  }
</style>
</file>

<file path="ui/src/components/map/ModuleNode.svelte">
<script lang="ts">
  import { Handle, Position, type NodeProps } from '@xyflow/svelte';
  import { moduleMetaLabel, type MapNodeLayout } from '../../lib/map-model';
  let { data }: NodeProps = $props();
  const node = $derived(
    data as unknown as {
      layout: MapNodeLayout;
      selected: boolean;
      dimmed: boolean;
      onSelect: (id: string) => void;
    }
  );
  const layout = $derived(node.layout);
  const module = $derived(layout.module);
  function portStyle(index: number, total: number): string {
    return `left:${((index + 1) / (total + 1)) * 100}%`;
  }
</script>
{#each layout.targetHandles as handle, i (handle)}
  <Handle
    type="target"
    id={`t:${handle}`}
    position={Position.Top}
    style={portStyle(i, layout.targetHandles.length)}
    isConnectable={false}
  />
{/each}
<button
  class="mnode"
  class:sel={node.selected}
  class:dimmed={node.dimmed}
  class:test={module.test}
  class:gen={layout.generated}
  style={`width:${layout.width}px;height:${layout.height}px`}
  onclick={() => node.onSelect(layout.id)}
  aria-pressed={node.selected}
  title={`${module.id} — ${module.symbols} symbols in ${module.files} file${
    module.files === 1 ? '' : 's'
  }${
    (module.dependents?.files ?? 0) > 0
      ? `. ${module.dependents.files} file${module.dependents.files === 1 ? '' : 's'} outside it, across ${module.dependents.modules} module${module.dependents.modules === 1 ? '' : 's'}, reference into it.`
      : ''
  }${layout.island ? '. Nothing in the index depends on it.' : ''}${
    layout.generated ? '. Every file in it is tool-generated.' : ''
  }`}
>
  <span class="name">{module.label || module.id}</span>
  <span class="count" class:island={layout.island}
    >{moduleMetaLabel(module, layout.island)}</span
  >
  {#if layout.weight > 0}
    <span class="weight" style={`width:${(layout.weight * 100).toFixed(1)}%`}></span>
  {/if}
</button>
{#each layout.sourceHandles as handle, i (handle)}
  <Handle
    type="source"
    id={`s:${handle}`}
    position={Position.Bottom}
    style={portStyle(i, layout.sourceHandles.length)}
    isConnectable={false}
  />
{/each}
<style>
  .mnode {
    position: relative;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 1px;
    box-sizing: border-box;
    padding: 0 9px;
    border: 1px solid var(--ink);
    border-radius: 0;
    background: var(--paper);
    text-align: left;
    cursor: pointer;
    font: inherit;
    color: var(--ink);
    transition: background 90ms linear;
  }
  .mnode:hover,
  .mnode.sel {
    border-width: 2px;
    padding: 0 8px;
    background: var(--press);
  }
  .mnode.dimmed {
    border-color: var(--ink-4);
    color: var(--ink-4);
  }
  .mnode.dimmed .count {
    color: var(--ink-4);
  }
  .count.island {
    color: var(--ink-2);
  }
  .mnode.gen {
    color: var(--ink-4);
    border-color: var(--rule-soft);
... (46 lines truncated)
</file>

<file path="ui/src/components/screens/ScreenEdge.svelte">
<script lang="ts">
  import { BaseEdge, EdgeLabel, type EdgeProps } from '@xyflow/svelte';
  import type { MapEdgeLayout } from '../../lib/map-model';
  import { pathOf, type Curve, type PillPlacement } from '../../lib/screens-model';
  let { data }: EdgeProps = $props();
  const d = $derived(
    data as unknown as {
      edge: MapEdgeLayout;
      info: { synthesized: boolean };
      curve: Curve;
      hot: boolean;
      soft: boolean;
      focus: boolean;
      dimmed: boolean;
      pill: PillPlacement | null;
      full: string | null;
      onHover: (edge: MapEdgeLayout | null, event: MouseEvent | null) => void;
    }
  );
  const path = $derived(pathOf(d.curve));
  const classes = $derived(
    `sedge${d.edge.back ? ' back' : ''}${d.info.synthesized ? ' synth' : ''}${d.hot ? ' hot' : ''}${
      d.soft ? ' soft' : ''
    }${d.focus ? ' focus' : ''}${d.dimmed ? ' dimmed' : ''}`
  );
</script>
<BaseEdge {path} class={classes} style={`stroke-width:${Math.min(3, d.edge.width)}px`} />
{#if d.pill !== null}
  <EdgeLabel
    x={d.pill.x}
    y={d.pill.y}
    transparent
    class="spill-anchor"
    onmousemove={(event) => d.onHover(d.edge, event)}
    onmouseleave={() => d.onHover(null, null)}
  >
    <span class="spill" class:hot={d.hot} class:focus={d.focus} class:full={d.full !== null}>
      {d.full ?? d.pill.text}
    </span>
  </EdgeLabel>
{/if}
<style>
  :global(.svelte-flow__edge-path.sedge) {
    stroke: var(--ink);
    stroke-opacity: 0.32;
    fill: none;
  }
  :global(.svelte-flow__edge-path.sedge.synth) {
    stroke-dasharray: 5 3;
  }
  :global(.svelte-flow__edge-path.sedge.back) {
    stroke: var(--accent);
    stroke-opacity: 0.6;
    stroke-dasharray: 4 3;
  }
  :global(.svelte-flow__edge-path.sedge.hot) {
    stroke-opacity: 0.95;
  }
  :global(.svelte-flow__edge-path.sedge.back.hot) {
    stroke-opacity: 0.85;
  }
  :global(.svelte-flow__edge-path.sedge.hot.soft) {
    stroke-opacity: 0.38;
  }
  :global(.svelte-flow__edge-path.sedge.focus) {
    stroke-opacity: 1;
  }
  :global(.svelte-flow__edge-path.sedge.dimmed) {
    stroke-opacity: 0.06;
  }
  :global(.svelte-flow__edge-label.spill-anchor) {
    padding: 0;
    line-height: 0;
    font-size: 0;
  }
  .spill {
    display: inline-block;
    box-sizing: border-box;
    height: 17px;
    padding: 0 5px;
    border: 1px solid var(--rule);
    background: var(--paper);
    color: var(--ink-2);
    font: 400 10.5px var(--mono);
    line-height: 15px;
    white-space: nowrap;
    cursor: crosshair;
  }
  .spill.hot {
    border-color: var(--ink-3);
    color: var(--ink);
  }
  .spill.focus {
    border-color: var(--ink);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
  }
  .spill.full {
    height: auto;
    max-width: 360px;
    padding: 2px 6px;
... (7 lines truncated)
</file>

<file path="ui/src/components/screens/ScreenNode.svelte">
<script lang="ts">
  import { Handle, Position, type NodeProps } from '@xyflow/svelte';
  import type { MapNodeLayout } from '../../lib/map-model';
  import type { ScreenNodeInfo } from '../../lib/screens-model';
  let { data }: NodeProps = $props();
  const node = $derived(
    data as unknown as {
      layout: MapNodeLayout;
      info: ScreenNodeInfo;
      selected: boolean;
      dimmed: boolean;
      onSelect: (id: string) => void;
      onOpen?: (id: string) => void;
    }
  );
  const layout = $derived(node.layout);
  const info = $derived(node.info);
  function portStyle(index: number, total: number): string {
    return `left:${((index + 1) / (total + 1)) * 100}%`;
  }
</script>
{#each layout.ports.top as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Top}
    style={portStyle(i, layout.ports.top.length)}
    isConnectable={false}
  />
{/each}
<button
  class="snode"
  class:sel={node.selected}
  class:dimmed={node.dimmed}
  class:origin={info.origin}
  class:entry={info.entry}
  class:unreached={info.unreached}
  style={`width:${layout.width}px;height:${layout.height}px`}
  onclick={() => node.onSelect(info.id)}
  ondblclickcapture={(e) => {
    e.stopPropagation();
    node.onOpen?.(info.id);
  }}
  aria-pressed={node.selected}
  title={(info.origin
    ? `${info.label} — navigates, but no screen reaches it within the walk. In ${info.sub}.`
    : `${info.label} — rendered by ${info.sub}${info.entry ? '. The entry screen.' : ''}${
        info.unreached ? '. No transition in the graph reaches it from the entry.' : ''
      }`) + (node.onOpen ? ' Double-click for what happens here.' : '')}
>
  <span class="name">{#if info.entry}<span class="mark" aria-hidden="true">●</span>{/if}{info.label}</span>
  <span class="sub">{info.sub}</span>
</button>
{#each layout.ports.bottom as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Bottom}
    style={portStyle(i, layout.ports.bottom.length)}
    isConnectable={false}
  />
{/each}
<style>
  .snode {
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 1px;
    box-sizing: border-box;
    padding: 0 9px;
    border: 1px solid var(--ink);
    border-radius: 0;
    background: var(--paper);
    text-align: left;
    cursor: pointer;
    font: inherit;
    color: var(--ink);
    transition: background 90ms linear;
  }
  .snode:hover,
  .snode.sel {
    border-width: 2px;
    padding: 0 8px;
    background: var(--press);
  }
  .snode.dimmed {
    border-color: var(--ink-4);
    color: var(--ink-4);
  }
  .snode.dimmed .sub {
    color: var(--ink-4);
  }
  .snode.origin {
    border-style: dashed;
    border-color: var(--ink-3);
  }
  .snode.unreached {
    border-color: var(--ink-4);
    color: var(--ink-2);
  }
... (27 lines truncated)
</file>

<file path="ui/src/components/steps/DecisionCaption.svelte">
<script lang="ts">
  import type { NodeProps } from '@xyflow/svelte';
  import { joinTokens, whenTokens } from '../../lib/conditions';
  let { data }: NodeProps = $props();
  const caption = $derived(data as unknown as { label: string; width: number; dimmed: boolean });
  const tokens = $derived(whenTokens(caption.label.replace(/\?$/, '')));
  const plain = $derived(tokens.length === 0 || joinTokens(tokens) !== caption.label.replace(/\?$/, ''));
</script>
<div class="dcap" class:dimmed={caption.dimmed} style={`width:${caption.width}px`} title={caption.label}>
  {#if plain}{caption.label}{:else}{#each tokens as t, i (i)}{#if i > 0}{' '}{/if}{#if t.kw}<b class="kw">{t.text}</b
      >{:else}{t.text}{/if}{/each}?{/if}
</div>
<style>
  .dcap {
    box-sizing: border-box;
    font: 400 10.5px/14px var(--mono);
    color: var(--ink-2);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: center;
    pointer-events: none;
    user-select: none;
  }
  .dcap.dimmed {
    color: var(--ink-4);
  }
  .kw {
    font-weight: 600;
  }
</style>
</file>

<file path="ui/src/components/steps/ForkPoint.svelte">
<script lang="ts">
  import { Handle, Position, type NodeProps } from '@xyflow/svelte';
  import type { MapNodeLayout } from '../../lib/map-model';
  import type { StepForkInfo } from '../../lib/steps-model';
  import { joinTokens, whenTokens } from '../../lib/conditions';
  import { EDGE_LABEL_MAX } from '../../lib/screens-model';
  let { data }: NodeProps = $props();
  const node = $derived(data as unknown as { layout: MapNodeLayout; fork: StepForkInfo; dimmed: boolean });
  const layout = $derived(node.layout);
  const tokens = $derived(whenTokens(node.fork.on));
  const plain = $derived(tokens.length === 0 || joinTokens(tokens).length > EDGE_LABEL_MAX);
  function portStyle(index: number, total: number): string {
    return `left:${((index + 1) / (total + 1)) * 100}%`;
  }
</script>
{#each layout.ports.top as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Top}
    style={portStyle(i, layout.ports.top.length)}
    isConnectable={false}
  />
{/each}
<div
  class="fpoint"
  class:dimmed={node.dimmed}
  style={`width:${layout.width}px;height:${layout.height}px`}
  title={node.fork.on
    ? `${node.fork.on} — the code forks here; each line out is one arm.`
    : 'The code forks here; each line out is one arm.'}
>
  <span class="q"
    >{#if plain}{node.fork.label}{:else}{#each tokens as t, i (i)}{#if i > 0}{' '}{/if}{#if t.kw}<b class="kw"
            >{t.text}</b
          >{:else}{t.text}{/if}{/each}?{/if}</span
  >
</div>
{#each layout.ports.bottom as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Bottom}
    style={portStyle(i, layout.ports.bottom.length)}
    isConnectable={false}
  />
{/each}
<style>
  .fpoint {
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    padding: 0 9px;
    border: 1px solid var(--ink-2);
    background: var(--paper);
    color: var(--ink);
    user-select: none;
  }
  .fpoint.dimmed {
    border-color: var(--ink-4);
    color: var(--ink-4);
  }
  .q {
    font: 400 12px var(--mono);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
  }
  .kw {
    font-weight: 600;
  }
</style>
</file>

<file path="ui/src/components/steps/RegionCaption.svelte">
<script lang="ts">
  import type { NodeProps } from '@xyflow/svelte';
  let { data }: NodeProps = $props();
  const caption = $derived(data as unknown as { label: string; width: number });
</script>
<div class="rcap" style={`width:${caption.width}px`}>{caption.label}</div>
<style>
  .rcap {
    box-sizing: border-box;
    padding-bottom: 4px;
    border-bottom: 1px solid var(--rule-soft);
    font: 500 11px/16px var(--mono);
    color: var(--ink-3);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    pointer-events: none;
    user-select: none;
  }
</style>
</file>

<file path="ui/src/components/steps/StepBox.svelte">
<script lang="ts">
  import type { MapNodeLayout } from '../../lib/map-model';
  import { kindWord, type ProjectKind, type StepNodeInfo } from '../../lib/steps-model';
  interface Props {
    info: StepNodeInfo;
    project: ProjectKind;
    selected: boolean;
    dimmed: boolean;
    size?: Pick<MapNodeLayout, 'width' | 'height'> | null;
    note?: string;
    onSelect: (id: string) => void;
    onStart?: (id: string) => void;
  }
  let { info, project, selected, dimmed, size = null, note = '', onSelect, onStart }: Props = $props();
  const step = $derived(info.step);
  const cutNote = $derived.by(() => {
    switch (step.cut) {
      case 'depth':
        return ' More happens past the depth of this picture — start here to see it.';
      case 'fan-out':
        return ' It reaches more than the walk follows from one node.';
      case 'folded':
        return ' The walk folded as much plumbing as it allows from one step.';
      case 'steps':
        return ' The picture reached its size limit here.';
      case 'screen':
        return ` Another ${kindWord('screen', project, step)} — a chapter of its own. Start here to see what happens on it.`;
      case 'component':
        return ' The event lands in a component of another screen — a picture of its own. Start here to see it.';
      default:
        return '';
    }
  });
</script>
<button
  class={`snode k-${step.kind}`}
  class:sel={selected}
  class:dimmed
  class:anchor={step.anchor}
  class:rail={size === null}
  style={size === null ? undefined : `width:${size.width}px;height:${size.height}px`}
  onclick={() => onSelect(info.id)}
  ondblclickcapture={(e) => {
    // The flow canvas zooms on a double-click that reaches its pane; a
    // double-click on a box is a navigation, not a zoom — stop it here,
    // at the target, before it bubbles. The pane's own double-click keeps zooming.
    e.stopPropagation();
    onStart?.(info.id);
  }}
  aria-pressed={selected}
  title={`${info.label} — ${step.anchor ? 'where this picture starts; ' : ''}${kindWord(step.kind, project, step)}. ${info.sub}.${note ? ` ${note}` : ''}${cutNote}${onStart && !step.anchor ? ' Double-click to start here.' : ''}`}
>
  <span class="name"
    >{#if step.anchor}<span class="mark" aria-hidden="true">●</span>{/if}{info.label}{#if step.cut !== null}<span
        class="more"
        aria-hidden="true"> …</span
      >{/if}</span
  >
  <span class="sub">{info.sub}</span>
</button>
<style>
  .snode {
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 1px;
    box-sizing: border-box;
    padding: 0 9px;
    border: 1px solid var(--ink);
    border-radius: 0;
    background: var(--paper);
    text-align: left;
    cursor: pointer;
    font: inherit;
    color: var(--ink);
    transition: background 90ms linear;
  }
  .snode.rail {
    align-items: flex-start;
    padding: 5px 9px;
    max-width: 100%;
  }
  .snode:hover,
  .snode.sel {
    border-width: 2px;
    padding: 0 8px;
  }
  .snode.rail:hover,
  .snode.rail.sel {
    padding: 4px 8px;
  }
  .snode:hover,
  .snode.sel {
    background: var(--press);
  }
  .snode.dimmed {
    border-color: var(--ink-4);
    color: var(--ink-4);
  }
  .snode.dimmed .sub {
... (61 lines truncated)
</file>

<file path="ui/src/components/steps/StepNode.svelte">
<script lang="ts">
  import { Handle, Position, type NodeProps } from '@xyflow/svelte';
  import StepBox from './StepBox.svelte';
  import type { MapNodeLayout } from '../../lib/map-model';
  import type { ProjectKind, StepNodeInfo } from '../../lib/steps-model';
  let { data }: NodeProps = $props();
  const node = $derived(
    data as unknown as {
      layout: MapNodeLayout;
      info: StepNodeInfo;
      project: ProjectKind;
      selected: boolean;
      dimmed: boolean;
      onSelect: (id: string) => void;
      onStart?: (id: string) => void;
    }
  );
  const layout = $derived(node.layout);
  function portStyle(index: number, total: number): string {
    return `left:${((index + 1) / (total + 1)) * 100}%`;
  }
</script>
{#each layout.ports.top as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Top}
    style={portStyle(i, layout.ports.top.length)}
    isConnectable={false}
  />
{/each}
<StepBox
  info={node.info}
  project={node.project}
  selected={node.selected}
  dimmed={node.dimmed}
  size={layout}
  onSelect={node.onSelect}
  onStart={node.onStart}
/>
{#each layout.ports.bottom as port, i (`${port.type}:${port.id}`)}
  <Handle
    type={port.type}
    id={`${port.type === 'source' ? 's' : 't'}:${port.id}`}
    position={Position.Bottom}
    style={portStyle(i, layout.ports.bottom.length)}
    isConnectable={false}
  />
{/each}
</file>

<file path="ui/src/components/steps/StepsKey.svelte">
<script lang="ts">
  import { kindWord, type ProjectKind } from '../../lib/steps-model';
  interface Props {
    project: ProjectKind;
    order: boolean;
    regions?: boolean;
    flow: boolean;
    open: boolean;
    onToggle: (open: boolean) => void;
  }
  let { project, order, regions = false, flow, open, onToggle }: Props = $props();
</script>
<div class="legend" class:open class:flow>
  <button class="legend-h" onclick={() => onToggle(!open)} aria-expanded={open}>
    Key <span class="dim">{open ? '▾' : '▸'}</span>
  </button>
  {#if open}
    <div class="legend-body">
      <div class="lrow">
        <span class="k-box k-anchor mono"><span class="mark">●</span>start</span>
        <span
          >{order
            ? 'Where the picture starts; below it, what it does in the code’s own order'
            : regions
              ? 'Where the picture starts; below it, the parts of the ' + kindWord('screen', project) + ', each with what happens there'
              : 'Where the picture starts; each row down is one more step away'}</span
        >
      </div>
      {#if regions && !order}
        <div class="lrow">
          <span class="k-cap mono">Name</span>
          <span
            >A region — the component that owns the boxes under its rule, a box above what it sets in motion. One line from
            the start into each region stands in for the {kindWord('screen', project)}'s whole fan-out; every other line
            draws where it leads</span
          >
        </div>
        <div class="lrow">
          <span class="k-label">no line</span>
          <span
            >A box nothing points at is the region's own doing — run on render or mount, or from a binding written inline.
            Select it and its line from the {kindWord('screen', project)} lights, with what fires it</span
          >
        </div>
      {/if}
      {#if !order}
        <div class="lrow">
          <span class="k-label mono">→ name</span>
          <span
            >What a box leads to, or what reaches it (←), when the two are too far apart for a line to be followed — said
            in words under the box rather than drawn across the picture. Select the box and every one of its real lines
            draws</span
          >
        </div>
      {/if}
      {#if project === 'api'}
        <div class="lrow">
          <span class="k-box mono">POST /x</span>
          <span>An endpoint — its verb and path — or a handler: a function a request, a job, an event or a schedule fires; its line says which</span>
        </div>
        <div class="lrow">
          <span class="k-box k-cross mono">⇢ fn</span>
          <span>The code crosses a tier: a call into another service or a job put on a queue (⇢), or a job, an event, a message arriving (⇠)</span>
        </div>
        <div class="lrow">
          <span class="k-box k-store mono">set</span>
          <span>A data call — a function in a store or state file</span>
        </div>
        <div class="lrow">
          <span class="k-box k-effect mono">db</span>
          <span>A call that leaves the index: the database, the response, a queue, email, payments, a cache, auth, the network</span>
        </div>
      {:else if project === 'web'}
        <div class="lrow">
          <span class="k-box mono">/path</span>
          <span>A page, an endpoint, or a handler — a function an event, a request or a page load fires; its line says which</span>
        </div>
        <div class="lrow">
          <span class="k-box k-cross mono">⇢ fn</span>
          <span>The code crosses to the server (⇢ a request, a server action) or comes back from it (⇠ a push, a stream)</span>
        </div>
        <div class="lrow">
          <span class="k-box k-store mono">set</span>
          <span>A store action — a function in a store file</span>
        </div>
        <div class="lrow">
          <span class="k-box k-effect mono">api</span>
          <span>A call that leaves the index: the network, the database, the response, storage, a queue, email</span>
        </div>
      {:else}
        <div class="lrow">
          <span class="k-box mono">/path</span>
          <span>A screen, or a handler — a function fired from a tap, an option, a listener; its line says the event</span>
        </div>
        <div class="lrow">
          <span class="k-box k-cross mono">⇢ fn</span>
          <span>The code crosses into native (⇢ a bridge call) or comes back from it (⇠ an event)</span>
        </div>
        <div class="lrow">
          <span class="k-box k-store mono">set</span>
... (160 lines truncated)
</file>

<file path="ui/src/components/steps/StepStubs.svelte">
<script lang="ts">
  import type { NodeProps } from '@xyflow/svelte';
  import type { StepStub } from '../../lib/steps-model';
  const MAX = 3;
  let { data }: NodeProps = $props();
  const node = $derived(data as unknown as { stubs: StepStub[]; width: number; dimmed: boolean });
  const stubs = $derived(node.stubs);
  const width = $derived(node.width);
  const dimmed = $derived(node.dimmed);
  const shown = $derived(stubs.slice(0, MAX));
  const rest = $derived(stubs.length - shown.length);
  const restTitle = $derived(
    stubs
      .slice(MAX)
      .map((s) => `${s.dir === 'out' ? 'leads to' : 'arrives from'} ${s.label}`)
      .join('\n')
  );
</script>
<div class="stubs" class:dimmed style={`width:${width}px`} aria-hidden="true">
  {#each shown as stub (stub.edge + stub.dir)}
    <span class="stub" title={`${stub.dir === 'out' ? 'Leads to' : 'Arrives from'} ${stub.label} — too far across the picture to draw as a line. Click the box to draw it.`}>
      <span class="arrow">{stub.dir === 'out' ? '→' : '←'}</span>{stub.label}
    </span>
  {/each}
  {#if rest > 0}
    <span class="stub more" title={restTitle}>+{rest} more</span>
  {/if}
</div>
<style>
  .stubs {
    display: flex;
    flex-direction: column;
    gap: 1px;
    padding-top: 3px;
    box-sizing: border-box;
    pointer-events: none;
    font-size: 10.5px;
    line-height: 13px;
    color: var(--ink-3);
  }
  .stubs.dimmed {
    opacity: 0.25;
  }
  .stub {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-family: var(--mono);
    pointer-events: auto;
  }
  .arrow {
    display: inline-block;
    width: 11px;
    color: var(--ink-4);
  }
  .more {
    color: var(--ink-4);
  }
</style>
</file>

<file path="ui/src/components/symbol/BlastStrip.svelte">
<script lang="ts">
  import { fileHref } from '../../lib/navigation';
  import { plural } from '../../lib/symbol-model';
  import type { WireBlastScale, WireBlastSummary } from '../../lib/api';
  interface Props {
    blast: WireBlastSummary;
    scale: WireBlastScale | null;
    testCalls: number;
    testFiles: number;
  }
  let { blast, scale, testCalls, testFiles }: Props = $props();
  let maxDirect = $derived(Math.max(1, scale?.maxDirect ?? 0, blast.direct));
  let maxWithin = $derived(Math.max(1, scale?.maxWithinHops ?? 0, blast.withinHops));
  const share = (value: number, max: number): number =>
    value <= 0 ? 0 : Math.max(0.5, Math.min(100, (100 * value) / max));
</script>
<div class="blast">
  <div class="bh">
    <b>Blast radius</b>
    <span class="stat"><strong>{blast.direct}</strong> direct dependent{blast.direct === 1 ? '' : 's'}</span>
    <span class="stat"><strong>{blast.withinHops}</strong> within {blast.hops} hops</span>
    <span class="stat"><strong>{blast.files}</strong> file{blast.files === 1 ? '' : 's'}</span>
    <span class="stat"><strong>{blast.testFiles}</strong> test file{blast.testFiles === 1 ? '' : 's'}</span>
    {#if blast.routes > 0}
      <span class="stat"><strong>{blast.routes}</strong> route{blast.routes === 1 ? '' : 's'}</span>
    {/if}
  </div>
  <div
    class="bar"
    title={`Scaled to the widest radius in the index: ${maxWithin} symbols within ${blast.hops} hops.`}
  >
    <i style:width={`${share(blast.withinHops, maxWithin)}%`}></i>
    <i class="direct" style:width={`${share(blast.direct, maxDirect)}%`}></i>
  </div>
  <div class="legend">
    dark: direct dependents · light: within {blast.hops} hops — scaled to the widest radius in the
    index{#if scale?.estimated}{' '}<span class="dim"
        >(measured across its {scale.sampled} most-depended-on symbols)</span
      >{/if}
  </div>
  {#if blast.topFiles.length > 0}
    <details>
      <summary>What would need re-checking if this changed</summary>
      <div class="body">
        {#each blast.topFiles as entry (entry.file)}
          <div class="fp">
            <a href={fileHref(entry.file)} class:test={entry.test}>{entry.file}</a>
            <b>{entry.symbols}</b>
          </div>
        {/each}
        {#if blast.files > blast.topFiles.length}
          <div class="fp dim">+{blast.files - blast.topFiles.length} more files</div>
        {/if}
        {#if testCalls > 0}
          <div class="note">
            plus {plural(testCalls, 'call')} from {plural(testFiles, 'test file')} — the tests that
            would catch a regression.
          </div>
        {/if}
      </div>
    </details>
  {/if}
</div>
<style>
  .blast {
    margin-top: 22px;
    padding-top: 10px;
    border-top: 1px solid var(--rule);
  }
  .bh {
    display: flex;
    flex-wrap: wrap;
    align-items: baseline;
    gap: 6px 14px;
  }
  .bh b {
    font-weight: 600;
  }
  .stat {
    color: var(--ink-2);
    font-size: 12.5px;
  }
  .stat strong {
    color: var(--ink);
    font-weight: 600;
    font-variant-numeric: tabular-nums;
  }
  .bar {
    position: relative;
    max-width: 420px;
    height: 6px;
    margin-top: 8px;
    background: var(--press);
  }
  .bar i {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    background: var(--ink-2);
... (59 lines truncated)
</file>

<file path="ui/src/components/symbol/CalleeRail.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { hot, railFocus } from '../../lib/focus.svelte';
  import { plural, type CalleeRailModel, type CalleeRow } from '../../lib/symbol-model';
  import type { WireNodeRef } from '../../lib/api';
  interface Props {
    model: CalleeRailModel;
    tops: number[];
    foldTop: number;
    noteTop: number;
    placed: boolean;
    focalFile: string;
    originId: string | null;
    emptyReason: string;
    onstepDown: (node: WireNodeRef) => void;
  }
  let { model, tops, foldTop, noteTop, placed, focalFile, originId, emptyReason, onstepDown }: Props =
    $props();
  function rowTitle(row: CalleeRow): string {
    return `${row.relation.node.qualifiedName} — ${row.relation.node.file}:${row.relation.node.line}`;
  }
</script>
<div class="rail-h" data-rail-header>
  <span>Calls <span class="n">{model.rows.length}</span></span>
  <span class="hint">step down →</span>
</div>
{#each model.rows as row, i (row.relation.node.id)}
  {@const node = row.relation.node}
  <div
    class="rrow"
    class:origin={node.id === originId}
    class:hot={hot.is(node.id)}
    class:sel={railFocus.at('right', i)}
    class:unplaced={!placed}
    style:top={`${tops[i] ?? 0}px`}
    data-target={node.id}
    role="button"
    tabindex="0"
    title={rowTitle(row)}
    onclick={() => onstepDown(node)}
    onkeydown={(e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        onstepDown(node);
      }
    }}
    onmouseenter={() => hot.set(node.id)}
    onmouseleave={() => hot.clear(node.id)}
  >
    <KindGlyph kind={node.kind} />
    <div class="body">
      <div class="nm">
        {node.name}{#if row.lines.length > 1}<span class="dim"> ×{row.lines.length}</span>{/if}
      </div>
      <div class="meta">
        <span>{node.file === focalFile ? 'same file' : node.file}</span>
        {#if row.words.length > 0}<span>{row.words.join(', ')}</span>{/if}
        {#if row.relation.hub}<span class="tag">hub · {row.relation.fanIn}</span>{/if}
        {#if row.via}<span class="tag" title="A synthesized edge — dynamic dispatch the parser cannot see"
            >via {row.via}</span
          >{/if}
        {#each row.when as w (w)}<span class="tag when" title="The call runs only under this condition — read from the source as it is now"
            >when {w}</span
          >{/each}
      </div>
    </div>
  </div>
{/each}
{#if model.uncertain.length > 0}
  <details class="rfold" class:unplaced={!placed} data-rail-fold style:top={`${foldTop}px`}>
    <summary>
      Uncertain <span class="dim"
        >· {model.uncertain.length} name-only match{model.uncertain.length === 1 ? '' : 'es'},
        confidence &lt; 0.6</span
      >
    </summary>
    <div class="fold-body">
      {#each model.uncertain as row (row.relation.node.id)}
        {@const node = row.relation.node}
        <div
          class="rrow static uncertain"
          class:hot={hot.is(node.id)}
          data-target={node.id}
          role="button"
          tabindex="0"
          title={rowTitle(row)}
          onclick={() => onstepDown(node)}
          onkeydown={(e) => {
            if (e.key === 'Enter' || e.key === ' ') {
              e.preventDefault();
              onstepDown(node);
            }
          }}
          onmouseenter={() => hot.set(node.id)}
          onmouseleave={() => hot.clear(node.id)}
        >
          <KindGlyph kind={node.kind} />
          <div class="body">
            <div class="nm">{node.name}</div>
            <div class="meta">
... (147 lines truncated)
</file>

<file path="ui/src/components/symbol/CallersRail.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { fileHref } from '../../lib/navigation';
  import { hot, railFocus } from '../../lib/focus.svelte';
  import { basename, plural, type CallerRailModel, type CallerRow } from '../../lib/symbol-model';
  import type { WireNodeRef } from '../../lib/api';
  interface Props {
    model: CallerRailModel;
    originId: string | null;
    exported: boolean;
    onstepUp: (node: WireNodeRef, line?: number) => void;
  }
  let { model, originId, exported, onstepUp }: Props = $props();
  function rowName(node: WireNodeRef): string {
    return node.kind === 'file' ? `${basename(node.file)} (top level)` : node.name;
  }
  function rowTitle(row: CallerRow): string {
    return `${row.relation.node.qualifiedName} — ${row.relation.node.file}:${row.relation.node.line}`;
  }
  function indexOf(groupIndex: number, rowIndex: number): number {
    let base = 0;
    for (let i = 0; i < groupIndex; i++) base += model.groups[i]?.rows.length ?? 0;
    return base + rowIndex;
  }
</script>
<div class="rail-h">
  <span>Called by <span class="n">{model.total}</span></span>
  <span class="hint">← step up</span>
</div>
{#if model.total === 0}
  <div class="note">
    Nothing in the graph calls or references this symbol{exported
      ? ' — it is exported, so callers may live outside the index (or it is an entry point).'
      : '.'}
  </div>
{/if}
{#each model.groups as group, groupIndex (group.file)}
  <div class="filegroup">
    <div class="fpath">
      <a href={fileHref(group.file)} title={group.file}>{group.same ? 'same file' : group.file}</a>
      <b>{group.rows.length}</b>
    </div>
    {#each group.rows as row, rowIndex (row.relation.node.id)}
      {@const node = row.relation.node}
      {@const isOrigin = node.id === originId}
      <div
        class="row"
        class:origin={isOrigin}
        class:sel={railFocus.at('left', indexOf(groupIndex, rowIndex))}
        data-target={node.id}
        role="button"
        tabindex="0"
        title={rowTitle(row)}
        onclick={() => onstepUp(node)}
        onkeydown={(e) => {
          if (e.key === 'Enter' || e.key === ' ') {
            e.preventDefault();
            onstepUp(node);
          }
        }}
        onmouseenter={() => hot.set(node.id)}
        onmouseleave={() => hot.clear(node.id)}
      >
        <KindGlyph kind={node.kind} />
        <div>
          <div class="nm">{rowName(node)}</div>
          <div class="meta">
            {#if row.words.length > 0}<span class="kindlbl">{row.words.join(', ')}</span>{/if}
            {#each row.when as w (w)}<span class="tag when" title="The call runs only under this condition — read from the source as it is now"
                >when {w}</span
              >{/each}
            {#each row.lines as line (line)}
              <button
                type="button"
                class="chip"
                title={`Open ${node.name} at line ${line}`}
                onclick={(e) => {
                  e.stopPropagation();
                  onstepUp(node, line);
                }}>:{line}</button
              >
            {/each}
            {#if row.via}<span class="kindlbl">via {row.via}</span>{/if}
            {#if isOrigin}<span class="kindlbl">you came from here</span>{/if}
          </div>
        </div>
      </div>
    {/each}
  </div>
{/each}
{#if model.tests.rows.length > 0}
  <details class="fold">
    <summary>
      Tests <span class="dim"
        >· {plural(model.tests.calls, 'call')} from {plural(model.tests.files.length, 'file')}</span
      >
    </summary>
    <div class="body">
      {#each model.tests.rows as row (row.relation.node.id)}
        {@const node = row.relation.node}
... (215 lines truncated)
</file>

<file path="ui/src/components/symbol/Connectors.svelte">
<script lang="ts">
  import { hot } from '../../lib/focus.svelte';
  import type { Connector } from '../../lib/symbol-model';
  interface Props {
    connectors: Connector[];
    width: number;
    height: number;
  }
  let { connectors, width, height }: Props = $props();
</script>
<svg
  class="overlay"
  {width}
  {height}
  viewBox={`0 0 ${width} ${height}`}
  aria-hidden="true"
  focusable="false"
>
  {#each connectors as connector, i (`${connector.targetId}:${i}`)}
    <path
      d={connector.d}
      class:uncertain={connector.uncertain}
      class:heur={connector.heuristic}
      class:origin={connector.origin}
      class:hot={hot.is(connector.targetId)}
    />
  {/each}
</svg>
<style>
  .overlay {
    position: absolute;
    inset: 0;
    overflow: visible;
    pointer-events: none;
  }
  path {
    fill: none;
    stroke: var(--ink-4);
    stroke-width: 1;
  }
  path.uncertain {
    stroke-dasharray: 2 3;
  }
  path.heur {
    stroke: var(--ink-3);
    stroke-dasharray: 6 3;
  }
  path.origin {
    stroke: var(--accent);
  }
  path.hot {
    stroke: var(--accent);
    stroke-width: 1.5;
  }
</style>
</file>

<file path="ui/src/components/symbol/MembersOutline.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import type { WireNodeRef, WireOverride } from '../../lib/api';
  import type { OutlineRow } from '../../lib/symbol-model';
  interface Props {
    rows: OutlineRow[];
    total: number;
    truncated: boolean;
    onopen: (node: WireNodeRef) => void;
  }
  let { rows, total, truncated, onopen }: Props = $props();
  function overrideTitle(o: WireOverride): string {
    return o.relation === 'implements'
      ? `Declares a member ${o.baseTypeName} requires — matched by name.`
      : `Redeclares a member of ${o.baseTypeName} — matched by name.`;
  }
</script>
<div class="subh">
  <span>Members</span>
  <span class="n">{total}</span>
</div>
<div class="outline">
  {#each rows as row (row.member.id)}
    <button
      type="button"
      class="orow"
      class:nested={row.nested}
      class:dimmed={row.dimmed}
      onclick={() => onopen(row.member)}
      title={`${row.member.qualifiedName} — ${row.member.file}:${row.member.line}`}
    >
      <KindGlyph kind={row.member.kind} />
      <span class="nm">{row.member.name}</span>
      <span class="sig">
        {#if row.member.overrides}
          <span class="ovr" title={overrideTitle(row.member.overrides)}>
            {row.member.overrides.relation === 'implements' ? 'satisfies' : 'overrides'}
            {row.member.overrides.baseTypeName}
          </span>
        {/if}{row.member.signature ?? ''}</span>
      <span class="cnt">
        {#if row.member.fanIn}← {row.member.fanIn}{/if}{#if row.member.fanIn && row.member.fanOut}&nbsp;
        {/if}{#if row.member.fanOut}→ {row.member.fanOut}{/if}
      </span>
    </button>
  {/each}
</div>
{#if truncated}
  <div class="note">
    Showing {rows.length} of {total} members — open the file to see the rest.
  </div>
{/if}
<style>
  .subh {
    display: flex;
    align-items: baseline;
    gap: 8px;
    margin: 18px 0 4px;
    font-weight: 600;
    font-size: 13px;
  }
  .subh .n {
    color: var(--ink-3);
    font-weight: 400;
  }
  .outline {
    border-top: 1px solid var(--rule);
  }
  .orow {
    display: grid;
    grid-template-columns: 16px minmax(160px, auto) 1fr auto;
    gap: 10px;
    align-items: baseline;
    width: 100%;
    padding: 6px 4px;
    border-bottom: 1px solid var(--rule-faint);
    text-align: left;
  }
  .orow:hover {
    background: var(--press);
  }
  .orow.nested {
    padding-left: 22px;
  }
  .nm {
    font: 12.5px var(--mono);
  }
  .orow.dimmed .nm {
    color: var(--ink-3);
  }
  .ovr {
    margin-right: 6px;
    padding: 0 4px;
    border: 1px solid var(--rule-soft);
    color: var(--ink-2);
    font: 10.5px var(--mono);
    white-space: nowrap;
  }
  .sig {
    overflow: hidden;
... (18 lines truncated)
</file>

<file path="ui/src/components/symbol/SourceBlock.svelte">
<script lang="ts">
  import { tokenClass, type Token } from '../../lib/highlight';
  import { assignRefs, type CodeBlock, type LineRef } from '../../lib/symbol-model';
  import { hot } from '../../lib/focus.svelte';
  interface Props {
    block: CodeBlock;
    tokens: Map<number, Token[]>;
    refs: Map<number, LineRef[]>;
    defLine: number;
    defName: string;
    highlight: number | null;
    onfollow: (ref: LineRef) => void;
  }
  let { block, tokens, refs, defLine, defName, highlight, onfollow }: Props = $props();
  interface Part {
    text: string;
    cls: string | null;
    ref: LineRef | null;
    def: boolean;
  }
  interface RenderedLine {
    n: number;
    parts: Part[];
    port: 'sure' | 'unsure' | null;
    targets: string[];
  }
  interface Chunk {
    gapBefore: number;
    lines: RenderedLine[];
  }
  let chunks = $derived.by<Chunk[]>(() =>
    block.windows.map((window, windowIndex) => ({
      gapBefore: windowIndex === 0 ? 0 : (block.gapsAfter[windowIndex - 1] ?? 0),
      lines: window.lines.map((text, offset) => {
        const n = window.start + offset;
        const lineTokens = tokens.get(n) ?? [{ cls: 'other' as const, text, col: 0 }];
        const lineRefs = refs.get(n) ?? [];
        const claimed = assignRefs(lineTokens, lineRefs);
        return {
          n,
          parts: toParts(lineTokens, claimed, n === defLine ? defName : null),
          port: portFor(lineRefs),
          targets: [...new Set(lineRefs.map((r) => r.targetId).filter((id): id is string => !!id))],
        };
      }),
    }))
  );
  function toParts(line: Token[], claimed: Map<number, LineRef>, definition: string | null): Part[] {
    return line.map((token, index) => {
      const ref = claimed.get(index) ?? null;
      return {
        text: token.text,
        cls: ref ? null : tokenClass(token.cls),
        ref,
        def:
          !ref &&
          definition !== null &&
          token.text === definition &&
          token.cls !== 'comment' &&
          token.cls !== 'string',
      };
    });
  }
  function portFor(lineRefs: readonly LineRef[]): 'sure' | 'unsure' | null {
    if (lineRefs.length === 0) return null;
    return lineRefs.some((r) => !r.uncertain && !r.outside) ? 'sure' : 'unsure';
  }
  function isHot(line: RenderedLine): boolean {
    return line.n === highlight || line.targets.some((id) => hot.is(id));
  }
</script>
<div class="code">
  {#each chunks as chunk (chunk.lines[0]?.n ?? -1)}
    {#if chunk.gapBefore > 0}
      <div class="gap">⋯ {chunk.gapBefore} lines without calls</div>
    {/if}
    {#each chunk.lines as line (line.n)}
      <div class="ln" class:hot={isHot(line)} data-line={line.n}>
        <span class="no">{line.n}</span>
        <span class="tx"
          >{#each line.parts as part, i (i)}{#if part.ref && !part.ref.outside}{@const ref = part.ref}<span
                class="ref"
                class:uncertain={ref.uncertain}
                class:hot={hot.is(ref.targetId)}
                role="link"
                tabindex="0"
                title={ref.title}
                onclick={() => onfollow(ref)}
                onkeydown={(e) => {
                  if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    onfollow(ref);
                  }
                }}
                onmouseenter={() => hot.set(ref.targetId)}
                onmouseleave={() => hot.clear(ref.targetId)}>{part.text}</span
              >{:else if part.ref}<span class="ref stub" title={part.ref.title}>{part.text}</span
              >{:else if part.def}<span class="t-def">{part.text}</span
              >{:else if part.cls}<span class={part.cls}>{part.text}</span
              >{:else}{part.text}{/if}{/each}</span
... (115 lines truncated)
</file>

<file path="ui/src/components/symbol/SymbolHeader.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import { fileHref } from '../../lib/navigation';
  import { kindPhrase, plural } from '../../lib/symbol-model';
  import type {
    WireNodeDetail,
    WireNodeRef,
    WireRelation,
    WireSymbolPayload,
  } from '../../lib/api';
  interface Props {
    payload: WireSymbolPayload;
    onopen: (node: WireNodeRef) => void;
    relationChips?: boolean;
  }
  let { payload, onopen, relationChips = true }: Props = $props();
  let node = $derived<WireNodeDetail>(payload.node);
  let tests = $derived(payload.tests);
  let supertypes = $derived(
    relationChips
      ? payload.outgoing.items.filter((r) =>
          r.edgeKinds.some((k) => k === 'extends' || k === 'implements')
        )
      : []
  );
  let subtypes = $derived(
    relationChips
      ? payload.incoming.items.filter((r) =>
          r.edgeKinds.some((k) => k === 'extends' || k === 'implements')
        )
      : []
  );
  const TYPE_CHIP_LIMIT = 12;
  let typeChips = $derived(payload.typesUsed.slice(0, TYPE_CHIP_LIMIT));
  function relationWord(relation: WireRelation): string {
    return relation.edgeKinds.includes('implements') ? 'implements' : 'extends';
  }
  let testBadge = $derived.by(() => {
    if (tests.reached) {
      return {
        warn: false,
        text: `Reached by tests · ${plural(tests.fileCount, 'file')} within ${tests.hopsSearched} hop${tests.hopsSearched === 1 ? '' : 's'}`,
        title: tests.files.join(', '),
      };
    }
    return {
      warn: true,
      text: tests.exhaustive
        ? `No test reaches this within ${tests.hopsSearched} caller hops`
        : 'No test calls this directly',
      title: tests.exhaustive
        ? 'No test file reaches this symbol within the caller hops searched.'
        : 'The caller search ran out of budget — only direct callers were checked.',
    };
  });
</script>
<div class="card-h">
  <KindGlyph kind={node.kind} titled />
  <h1>{node.name}</h1>
  <span class="kindword">{kindPhrase(node)}</span>
  <span class="loc mono">
    <a href={fileHref(node.file, { line: node.line })}>{node.file}</a>:{node.line}–{node.endLine}
    · {plural(node.lines, 'line')}
  </span>
</div>
{#if payload.ancestors.length > 0}
  <div class="parents mono">
    in {#each payload.ancestors as ancestor, i (ancestor.id)}{#if i > 0}<span class="sep"> › </span
        >{/if}<button type="button" onclick={() => onopen(ancestor)}>{ancestor.name}</button
      >{/each}
  </div>
{/if}
<div class="badges">
  {#if node.exported}<span class="badge">exported</span>{/if}
  {#if payload.counts.hub}
    <span class="badge hub" title="Changing this reaches a lot of the repo">
      hub · {plural(payload.counts.callers, 'caller')}
    </span>
  {/if}
  <span class="badge" class:warn={testBadge.warn} title={testBadge.title}>
    <span class="sw"></span>{testBadge.text}
  </span>
</div>
{#if node.signature}
  <div class="sig">{node.name}{node.signature}</div>
{/if}
{#if node.docstring}
  <div class="doc">{node.docstring}</div>
{/if}
{#if supertypes.length > 0 || subtypes.length > 0 || typeChips.length > 0}
  <div class="rel">
    {#if supertypes.length > 0}
      <span>
        {#each supertypes as relation (relation.node.id)}
          {relationWord(relation)}
          <button type="button" class="chip" onclick={() => onopen(relation.node)}>
            {relation.node.name}
          </button>
        {/each}
      </span>
... (140 lines truncated)
</file>

<file path="ui/src/components/symbol/TypeHierarchy.svelte">
<script lang="ts">
  import KindGlyph from '../KindGlyph.svelte';
  import type { WireHierarchy, WireNodeDetail, WireNodeRef } from '../../lib/api';
  import {
    buildHierarchyModel,
    connectorPath,
    visibleHierarchy,
    HIER_ROW_H,
  } from '../../lib/hierarchy-model';
  interface Props {
    hierarchy: WireHierarchy;
    focus: WireNodeDetail;
    onopen: (node: WireNodeRef) => void;
  }
  let { hierarchy, focus, onopen }: Props = $props();
  let expanded = $state(false);
  let model = $derived(buildHierarchyModel(hierarchy, focus));
  let view = $derived(visibleHierarchy(model, expanded));
  $effect(() => {
    focus.id;
    expanded = false;
  });
  let counts = $derived(
    [
      hierarchy.ancestors.total > 0
        ? `${hierarchy.ancestors.total} above`
        : '',
      hierarchy.direct > 0 ? `${hierarchy.descendants.total} below` : '',
    ]
      .filter(Boolean)
      .join(' · ')
  );
  function title(row: (typeof view.rows)[number]): string {
    const where = `${row.node.file}:${row.node.line}`;
    if (!row.entry) return `${row.node.qualifiedName} — ${where}`;
    const wiring = row.entry.synthesized
      ? ` — matched by ${row.entry.via ?? 'the resolver'}${row.entry.registeredAt ? ` at ${row.entry.registeredAt}` : ''}`
      : '';
    return `${row.node.qualifiedName} — ${where}${wiring}`;
  }
</script>
<div class="subh">
  <span>Type hierarchy</span>
  <span class="n">{counts}</span>
  <span class="hint">supertypes above · subtypes below</span>
</div>
{#if model.headline}
  <p class="headline">{model.headline}</p>
{/if}
<div class="tree">
 <div class="canvas" style:height={`${view.height}px`}>
  <svg class="wires" width="100%" height={view.height} aria-hidden="true">
    {#each view.connectors as c, i (i)}
      <path
        d={connectorPath(c)}
        class:dashed={c.relation === 'implements'}
        class:synth={c.synthesized}
      />
    {/each}
  </svg>
  {#each view.rows as row (row.node.id + row.side)}
    {#if row.side === 'focus'}
      <div
        class="row focus"
        style:top={`${row.index * HIER_ROW_H}px`}
        style:padding-left={`${row.indent + 18}px`}
      >
        <KindGlyph kind={row.node.kind} />
        <span class="nm">{row.node.name}</span>
      </div>
    {:else}
      <button
        type="button"
        class="row"
        style:top={`${row.index * HIER_ROW_H}px`}
        style:padding-left={`${row.indent + 18}px`}
        onclick={() => onopen(row.node)}
        title={title(row)}
      >
        <KindGlyph kind={row.node.kind} />
        <span class="nm">{row.node.name}</span>
        <span class="word">{row.word}</span>
        {#if row.entry?.synthesized}
          <span class="pill" title={row.entry.registeredAt ?? ''}>
            via {row.entry.via ?? 'resolver'}
          </span>
        {/if}
        {#if row.entry && row.entry.hiddenSubtypes > 0}
          <span class="pill">+{row.entry.hiddenSubtypes} below</span>
        {/if}
        <span class="file">{row.node.file === focus.file ? 'same file' : row.node.file}</span>
      </button>
    {/if}
  {/each}
 </div>
</div>
{#if model.foldFrom !== null}
  <button type="button" class="fold" onclick={() => (expanded = !expanded)}>
    {expanded ? 'Fold' : `+${model.foldCount} more ${model.foldNoun}`}
  </button>
... (118 lines truncated)
</file>

<file path="ui/src/components/CodegraphUi.svelte">
<script lang="ts">
  import { untrack, type Snippet } from 'svelte';
  import { setGraphAdapter, type GraphAdapter } from '../lib/adapter';
  import { setNavigationDriver, type NavigationDriver } from '../lib/navigation';
  interface Props {
    adapter?: GraphAdapter | null;
    nav?: NavigationDriver | null;
    theme?: 'auto' | 'light' | 'dark';
    fill?: boolean;
    children?: Snippet;
  }
  let { adapter = null, nav = null, theme = 'auto', fill = true, children }: Props = $props();
  setGraphAdapter(untrack(() => adapter));
  setNavigationDriver(untrack(() => nav));
</script>
<div class="codegraph-ui" class:fill data-theme={theme === 'auto' ? undefined : theme}>
  {@render children?.()}
</div>
<style>
  .codegraph-ui {
    background: var(--paper);
    color: var(--ink);
    font-family: var(--sans);
    font-size: 13px;
    line-height: 1.45;
  }
  .fill {
    display: flex;
    flex-direction: column;
    height: 100%;
    min-height: 0;
  }
  .fill > :global(*) {
    flex: 1;
    min-height: 0;
  }
</style>
</file>

<file path="ui/src/components/DriftBanner.svelte">
<script lang="ts">
  import type { Snippet } from 'svelte';
  interface Props {
    file: string;
    children: Snippet;
  }
  let { file, children }: Props = $props();
</script>
<div class="drift" role="status">
  <span class="glyph" aria-hidden="true">⚠</span>
  <span class="body"><code>{file}</code> changed on disk after the last index sync — {@render children()}</span>
</div>
<style>
  .drift {
    display: grid;
    grid-template-columns: 16px 1fr;
    gap: 6px;
    align-items: start;
    padding: 8px 12px;
    border: 1px solid var(--rule-soft);
    background: var(--paper-2);
    color: var(--ink-2);
    font-size: 12.5px;
    line-height: 1.5;
  }
  .glyph {
    color: var(--ink-3);
    font-size: 12px;
    line-height: 1.55;
  }
  .body :global(code) {
    font-family: var(--mono);
    font-size: 12px;
    color: var(--ink);
  }
  .body :global(button) {
    background: none;
    border: 0;
    padding: 0;
    color: var(--accent);
    font: inherit;
    cursor: pointer;
    text-decoration: underline;
    text-decoration-color: var(--accent-line);
    text-underline-offset: 3px;
  }
  .body :global(a) {
    color: var(--accent);
    text-decoration: underline;
    text-decoration-color: var(--accent-line);
    text-underline-offset: 3px;
  }
</style>
</file>

<file path="ui/src/components/ExportButtons.svelte">
<script lang="ts">
  import { copyPngToClipboard, downloadSvg, svgToPng, PNG_SCALE } from '../lib/export-image';
  import { toast } from '../lib/toast.svelte';
  interface Props {
    build: (scale: number) => string;
    filename: string;
    disabled?: boolean;
  }
  let { build, filename, disabled = false }: Props = $props();
  let busy = $state(false);
  async function copyImage(): Promise<void> {
    if (busy) return;
    busy = true;
    try {
      const where = await copyPngToClipboard(
        () => svgToPng(build(PNG_SCALE)),
        `${filename}.png`
      );
      toast.show(
        where === 'copied'
          ? 'Image copied · paste it into a comment'
          : 'Clipboard unavailable · image saved instead'
      );
    } catch (error) {
      toast.show(error instanceof Error ? error.message : 'The image could not be made.');
    } finally {
      busy = false;
    }
  }
  function saveSvg(): void {
    try {
      downloadSvg(build(1), `${filename}.svg`);
      toast.show('SVG saved');
    } catch (error) {
      toast.show(error instanceof Error ? error.message : 'The file could not be saved.');
    }
  }
</script>
<div class="exp">
  <button type="button" onclick={copyImage} disabled={disabled || busy}>
    {busy ? 'Rendering…' : 'Copy image'}
  </button>
  <button type="button" onclick={saveSvg} {disabled}>Download SVG</button>
</div>
<style>
  .exp {
    display: flex;
    flex: 0 0 auto;
    margin-left: auto;
    gap: 6px;
  }
  .exp button {
    padding: 3px 8px;
    background: var(--paper-2);
    border: 1px solid var(--rule-soft);
    border-radius: 0;
    color: var(--ink-2);
    cursor: pointer;
    font: 12.5px var(--sans);
    white-space: nowrap;
  }
  .exp button:hover:not(:disabled) {
    background: var(--press);
    border-color: var(--ink-3);
    color: var(--ink);
  }
  .exp button:disabled {
    color: var(--ink-4);
    cursor: default;
  }
  .exp button:focus-visible {
    outline: 2px solid var(--accent);
    outline-offset: 1px;
  }
</style>
</file>

<file path="ui/src/components/KindGlyph.svelte">
<script lang="ts">
  import { kindLetter, kindWord, FILLED_KINDS } from '../lib/kinds';
  interface Props {
    kind: string | null | undefined;
    titled?: boolean;
  }
  let { kind, titled = false }: Props = $props();
  let letter = $derived(kind ? kindLetter(kind) : '');
  let filled = $derived(kind ? FILLED_KINDS.has(kind) : false);
  let dashed = $derived(kind === 'file');
</script>
<span
  class="k"
  class:filled
  class:dashed
  class:wide={letter.length > 1}
  title={titled ? kindWord(kind) : undefined}
  aria-hidden={titled ? undefined : 'true'}
>{letter}</span>
<style>
  .k {
    display: inline-flex;
    width: 16px;
    height: 16px;
    flex: 0 0 auto;
    align-items: center;
    justify-content: center;
    border: 1px solid var(--ink-3);
    color: var(--ink-2);
    font: 500 9.5px var(--mono);
    line-height: 1;
    user-select: none;
  }
  .k.filled {
    background: var(--press);
  }
  .k.dashed {
    border-style: dashed;
  }
  .k.wide {
    font-size: 8.5px;
    letter-spacing: -0.02em;
  }
</style>
</file>

<file path="ui/src/components/PalettePanel.svelte">
<script lang="ts">
  import PaletteRows from './PaletteRows.svelte';
  import { palette } from '../lib/palette.svelte';
  import type { PaletteItem } from '../lib/search-model';
  interface Props {
    onpick: (item: PaletteItem) => void;
  }
  let { onpick }: Props = $props();
  let panel: HTMLDivElement | null = $state(null);
  let view = $derived(palette.view);
  $effect(() => {
    const index = palette.selected;
    if (!panel) return;
    const row = panel.querySelector(`[data-palette-row="${index}"]`);
    row?.scrollIntoView({ block: 'nearest' });
  });
</script>
<div class="panel" bind:this={panel} id="palette-panel" role="listbox" aria-label="Search results">
  {#if view.hint}
    <p class="hint">{view.hint}</p>
  {/if}
  <PaletteRows
    palette={view}
    selected={palette.selected}
    rowRole="option"
    {onpick}
    onhover={(index) => palette.select(index)}
  />
  {#if palette.failure}
    <p class="note">{palette.failure}</p>
  {:else if palette.pending && view.items.length === 0}
    <p class="note">Searching…</p>
  {:else if view.empty}
    <p class="note">{view.empty}</p>
  {/if}
</div>
<style>
  .panel {
    position: absolute;
    z-index: 40;
    top: 32px;
    right: 0;
    left: 0;
    max-height: 420px;
    overflow: auto;
    background: var(--paper);
    border: 1px solid var(--ink);
  }
  .hint {
    margin: 0;
    padding: 8px 10px;
    border-bottom: 1px solid var(--rule-faint);
    background: var(--paper-2);
    color: var(--ink-2);
    font-size: 12px;
  }
  .note {
    margin: 0;
    padding: 8px 10px;
    color: var(--ink-3);
    font-size: 12px;
  }
</style>
</file>

<file path="ui/src/components/PaletteRows.svelte">
<script lang="ts">
  import KindGlyph from './KindGlyph.svelte';
  import type { Palette, PaletteItem } from '../lib/search-model';
  interface Props {
    palette: Palette;
    selected?: number;
    rowRole?: 'option' | undefined;
    idPrefix?: string;
    onpick: (item: PaletteItem) => void;
    onhover?: (index: number) => void;
  }
  let {
    palette,
    selected = -1,
    rowRole = undefined,
    idPrefix = 'palette-row',
    onpick,
    onhover,
  }: Props = $props();
  function flatIndex(sectionIndex: number, rowIndex: number): number {
    let base = 0;
    for (let i = 0; i < sectionIndex; i += 1) base += palette.sections[i]?.items.length ?? 0;
    return base + rowIndex;
  }
</script>
{#each palette.sections as section, s (section.title)}
  <div class="head">
    <span class="head-title">{section.title}</span>
    {#if section.note}<span class="head-note">{section.note}</span>{/if}
  </div>
  {#each section.items as item, r (item.id)}
    {@const index = flatIndex(s, r)}
    <button
      type="button"
      class="row"
      class:sel={index === selected}
      data-palette-row={index}
      id={`${idPrefix}-${index}`}
      role={rowRole}
      aria-selected={rowRole ? index === selected : undefined}
      onmousedown={(event) => {
        event.preventDefault();
        onpick(item);
      }}
      onmouseenter={() => onhover?.(index)}
    >
      {#if item.type === 'route'}
        <KindGlyph kind="route" />
        <span class="mid">
          <span class="nm">{item.url}</span>
          <span class="sig">{item.handler}</span>
        </span>
      {:else if item.type === 'flow'}
        <KindGlyph kind="route" />
        <span class="mid">
          <span class="nm">{item.name}</span>
        </span>
      {:else if item.type === 'entry'}
        <KindGlyph kind={item.row.kind} />
        <span class="mid" title={item.row.title}>
          <span class="nm">{item.name}</span>
          {#if item.meta}<span class="sig">{item.meta}</span>{/if}
        </span>
      {:else}
        <KindGlyph kind={item.node.kind} />
        <span class="mid" title={item.node.generated ? `${item.name} — tool-generated` : undefined}>
          <span class="nm" class:gen={item.node.generated}>{item.name}</span>
          {#if item.meta}<span class="sig">{item.meta}</span>{/if}
        </span>
      {/if}
      <span class="loc">{item.location}</span>
    </button>
  {/each}
{/each}
<style>
  .head {
    display: flex;
    align-items: baseline;
    gap: 8px;
    padding: 6px 10px 4px;
    border-bottom: 1px solid var(--rule-faint);
    color: var(--ink-3);
    font-size: 12px;
  }
  .head-note {
    overflow: hidden;
    color: var(--ink-4);
    font-size: 11.5px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .row {
    display: grid;
    width: 100%;
    align-items: baseline;
    padding: 6px 10px;
    border-bottom: 1px solid var(--rule-faint);
    color: var(--ink);
    gap: 10px;
    grid-template-columns: 18px 1fr auto;
... (35 lines truncated)
</file>

<file path="ui/src/components/SavedTrails.svelte">
<script lang="ts">
  import KindGlyph from './KindGlyph.svelte';
  import { symbolHref, navigate } from '../lib/navigation';
  import { trails } from '../lib/trails.svelte';
  import { trail } from '../lib/trail.svelte';
  import { decodeTrail } from '../lib/trail-codec';
  import {
    isOpenable,
    trailDecay,
    trailExport,
    trailMeta,
    trailOpens,
    trailTitle,
  } from '../lib/trails-model';
  import type { WireTrail } from '../lib/api';
  interface Props {
    title?: string;
    hideWhenEmpty?: boolean;
  }
  let { title = 'Saved trails', hideWhenEmpty = true }: Props = $props();
  $effect(() => {
    void trails.ensure();
  });
  let confirming = $state<string | null>(null);
  let list = $derived(trails.list);
  function open(saved: WireTrail) {
    if (!isOpenable(saved)) return;
    const hops = decodeTrail(saved.encoded);
    trail.clear();
    const resolved = saved.hops.filter((hop) => hop.id !== null);
    for (const hop of hops) {
      const known = resolved.find((h) => h.id === hop.id);
      trail.push({ id: hop.id, name: known?.name ?? null, kind: known?.kind ?? null, dir: hop.dir });
    }
    navigate(symbolHref(saved.openId as string, { trail: saved.encoded as string }));
  }
  async function remove(saved: WireTrail) {
    if (confirming !== saved.id) {
      confirming = saved.id;
      return;
    }
    confirming = null;
    await trails.remove(saved.id);
  }
  function download(saved: WireTrail) {
    const blob = new Blob([trailExport(saved)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `${saved.id}.json`;
    link.click();
    URL.revokeObjectURL(url);
  }
</script>
{#if !(hideWhenEmpty && list.length === 0 && trails.failure === null)}
  <section class="trails" aria-label={title}>
    <div class="head">
      <h3>{title}</h3>
      {#if trails.directory}
        <span class="where">{trails.directory}</span>
      {/if}
    </div>
    {#if trails.failure}
      <p class="msg err">{trails.failure}</p>
    {:else if !trails.settled}
      <p class="msg">Reading saved trails…</p>
    {:else if list.length === 0}
      <p class="msg">
        No saved trails yet. Walk a path through the code, then press
        <strong>Save trail</strong> on the trail bar to keep it.
        {#if trails.readOnlyReason}
          <br />{trails.readOnlyReason}
        {/if}
      </p>
    {:else}
      <div class="rows">
        {#each list as saved (saved.id)}
          {@const decay = trailDecay(saved)}
          {@const opens = trailOpens(saved)}
          <div class="row" class:dead={!isOpenable(saved)}>
            <button
              type="button"
              class="pick"
              title={trailTitle(saved)}
              disabled={!isOpenable(saved)}
              onclick={() => open(saved)}
            >
              <KindGlyph kind={saved.hops[0]?.kind ?? null} />
              <span class="mid">
                <span class="nm">{saved.name}</span>
                {#if saved.note}<span class="note">{saved.note}</span>{/if}
              </span>
              <span class="meta">{trailMeta(saved)}</span>
            </button>
            <div class="acts">
              <button type="button" class="act" onclick={() => download(saved)}>Export</button>
              {#if trails.canSave}
                <button
                  type="button"
                  class="act"
... (136 lines truncated)
</file>

<file path="ui/src/components/SearchPalette.svelte">
<script lang="ts">
  import PalettePanel from './PalettePanel.svelte';
  import { palette } from '../lib/palette.svelte';
  import type { PaletteItem } from '../lib/search-model';
  import { fileHref, flowHref, navigate } from '../lib/navigation';
  import { openEntryTarget, walkTo } from '../lib/walk';
  interface Props {
    placeholder?: string;
    label?: string;
    onpick?: (item: PaletteItem) => void;
  }
  let {
    placeholder = 'Search a symbol or file, or ask “how does execute reach getFile” — press / to focus',
    label = 'Search symbols and files',
    onpick,
  }: Props = $props();
  let input: HTMLInputElement | null = $state(null);
  let box: HTMLDivElement | null = $state(null);
  export function focus(): void {
    input?.focus();
    input?.select();
    palette.show();
  }
  export function pick(item: PaletteItem): void {
    palette.reset();
    input?.blur();
    if (onpick) {
      onpick(item);
      return;
    }
    if (item.type === 'flow') {
      navigate(flowHref({ from: item.from, to: item.to }));
      return;
    }
    if (item.type === 'entry') {
      if (item.row.target) openEntryTarget(item.row.target);
      return;
    }
    const id = item.type === 'route' ? item.nodeId : item.id;
    if (!id) return;
    if (item.type === 'symbol' && item.node.kind === 'file') {
      navigate(fileHref(item.node.file));
      return;
    }
    walkTo(
      item.type === 'route'
        ? { id, name: item.handler, kind: null }
        : { id, name: item.node.name, kind: item.node.kind },
      'start'
    );
  }
  function onkeydown(event: KeyboardEvent) {
    if (event.key === 'Escape') {
      event.preventDefault();
      palette.hide();
      input?.blur();
      return;
    }
    if (!palette.open) {
      if (event.key !== 'Tab') palette.show();
      return;
    }
    switch (event.key) {
      case 'ArrowDown':
        event.preventDefault();
        palette.move(1);
        break;
      case 'ArrowUp':
        event.preventDefault();
        palette.move(-1);
        break;
      case 'Enter': {
        event.preventDefault();
        const item = palette.selectedItem;
        if (item) pick(item);
        break;
      }
    }
  }
  function onpointerdown(event: PointerEvent) {
    if (!palette.open) return;
    const target = event.target;
    if (target instanceof Node && box?.contains(target)) return;
    palette.hide();
  }
</script>
<svelte:window {onpointerdown} />
<div class="search" role="search" bind:this={box}>
  <input
    bind:this={input}
    bind:value={palette.query}
    {onkeydown}
    onfocus={() => palette.show()}
    id="q"
    type="search"
    autocomplete="off"
    spellcheck="false"
    {placeholder}
    aria-label={label}
    role="combobox"
... (33 lines truncated)
</file>

<file path="ui/src/components/Toast.svelte">
<script lang="ts">
  import { toast } from '../lib/toast.svelte';
</script>
<div class="live-region" aria-live="polite">
  {#if toast.message}
    <div class="toast">{toast.message}</div>
  {/if}
</div>
<style>
  .toast {
    position: fixed;
    left: 50%;
    bottom: 22px;
    transform: translateX(-50%);
    background: var(--ink);
    color: var(--paper);
    padding: 8px 14px;
    font-size: 12.5px;
    line-height: 1.4;
    max-width: 70ch;
    z-index: 50;
    animation: rise 140ms ease-out;
  }
  @keyframes rise {
    from {
      opacity: 0;
      transform: translate(-50%, 6px);
    }
    to {
      opacity: 1;
      transform: translate(-50%, 0);
    }
  }
  @media (prefers-reduced-motion: reduce) {
    .toast {
      animation: none;
    }
  }
</style>
</file>

<file path="ui/src/components/TopBar.svelte">
<script lang="ts">
  import { router, mapHref, flowHref, entryHref, screensHref, stepsHref, deadHref, symbolHref } from '../lib/router.svelte';
  import { trail } from '../lib/trail.svelte';
  import SearchPalette from './SearchPalette.svelte';
  import { live } from '../lib/live.svelte';
  interface Props {
    project?: string | null;
    stats?: string | null;
    showScreens?: boolean;
  }
  let { project = null, stats = null, showScreens = false }: Props = $props();
  let search: SearchPalette | null = $state(null);
  let view = $derived(router.route.view);
  let symbolTabHref = $derived.by(() => {
    const route = router.route;
    if (route.view === 'symbol' && route.id !== null) return symbolHref(route.id);
    const current = trail.current;
    return symbolHref(current ? current.id : null);
  });
  export function focusSearch(): void {
    search?.focus();
  }
  let liveNote = $derived.by(() => {
    if (live.degraded !== null) {
      return {
        text: 'Live updates off',
        title: `${live.degraded} This page no longer refreshes itself — reload it after a sync.`,
      };
    }
    if (live.stopped) {
      return {
        text: 'Not live',
        title:
          'Lost the connection to codegraph ui and stopped retrying. Focus this tab to try again, or reload the page.',
      };
    }
    return null;
  });
</script>
<header class="topbar">
  <a class="brand" href="#/" aria-label="CodeGraph home">
    <span class="brand-mark" aria-hidden="true"></span>
    <span class="brand-name">CodeGraph</span>
    <span class="brand-sub">ui</span>
  </a>
  <nav class="views" aria-label="Views">
    {#if showScreens}<a href={screensHref()} class:active={view === 'screens' || view === 'home'}>Screens</a>{/if}
    <a href={stepsHref()} class:active={view === 'steps'}>Steps</a>
    <a href={entryHref()} class:active={view === 'entry'}>Entry points</a>
    <a href={mapHref()} class:active={view === 'map'}>Map</a>
    <a href={symbolTabHref} class:active={view === 'symbol' || (view === 'home' && !showScreens)}>Symbol</a>
    <a href={flowHref()} class:active={view === 'flow'}>Flow</a>
    <a href={deadHref()} class:active={view === 'dead'}>Dead code</a>
  </nav>
  <SearchPalette bind:this={search} />
  <div class="project" title="Indexed project">
    {#if liveNote}<span class="offline" title={liveNote.title}>{liveNote.text}</span>{/if}
    {#if project}<span class="mono">{project}</span>{/if}
    {#if stats}<span class="dim">{stats}</span>{/if}
  </div>
</header>
<style>
  .topbar {
    display: grid;
    grid-template-columns: auto auto 1fr auto;
    align-items: center;
    gap: 22px;
    padding: 0 18px;
    background: var(--paper);
    border-bottom: 1px solid var(--rule);
    position: relative;
    z-index: 30;
  }
  .brand {
    display: flex;
    align-items: baseline;
    gap: 8px;
  }
  .brand-mark {
    display: inline-block;
    width: 10px;
    height: 10px;
    align-self: center;
    border: 1.5px solid var(--ink);
    background: var(--paper);
  }
  .brand-name {
    font-weight: 600;
    font-size: 14px;
    letter-spacing: -0.01em;
  }
  .brand-sub {
    color: var(--ink-3);
    font-size: 12px;
  }
  .views {
    display: flex;
    gap: 2px;
  }
  .views a {
... (32 lines truncated)
</file>

<file path="ui/src/components/TrailBar.svelte">
<script lang="ts">
  import KindGlyph from './KindGlyph.svelte';
  import { trail, hopLabel, encodeTrail } from '../lib/trail.svelte';
  import { navigate, symbolHref, flowHref } from '../lib/navigation';
  import { trails } from '../lib/trails.svelte';
  import { replacedTrail, trailNameProblem } from '../lib/trails-model';
  import { toast } from '../lib/toast.svelte';
  const MAX_NAME = 120;
  let hops = $derived(trail.hops);
  let naming = $state(false);
  let name = $state('');
  let nameInput: HTMLInputElement | null = $state(null);
  // The list is wanted before Save is pressed, not after: it decides whether
  // this name would REPLACE something, which the form has to say beforehand.
  $effect(() => {
    if (naming) void trails.ensure();
  });
  let problem = $derived(trailNameProblem(name, MAX_NAME));
  let replaces = $derived(naming ? replacedTrail(name, trails.list) : null);
  function openForm() {
    trails.clearFailure();
    naming = true;
    // The last hop is the thing the reader is looking at, so it is the most
    // likely name for the walk that got there — offered, not imposed.
    name = trail.current?.name ?? '';
    queueMicrotask(() => {
      nameInput?.focus();
      nameInput?.select();
    });
  }
  function closeForm() {
    naming = false;
    name = '';
  }
  async function submit(event: Event) {
    event.preventDefault();
    if (problem || trails.busy) return;
    const replacing = replaces !== null;
    const saved = await trails.save(name, '', hops);
    if (saved === null) return; // the reason is on `trails.failure`, shown below
    toast.show(replacing ? `Trail replaced · ${name.trim()}` : `Trail saved · ${name.trim()}`);
    closeForm();
  }
  function onkeydown(event: KeyboardEvent) {
    if (event.key === 'Escape') {
      event.preventDefault();
      event.stopPropagation();
      closeForm();
    }
  }
  function step(index: number) {
    const hop = hops[index];
    if (!hop) return;
    trail.truncateTo(index);
    navigate(symbolHref(hop.id, { trail: encodeTrail(trail.hops) }));
  }
  function readAsFlow() {
    navigate(flowHref({ trail: encodeTrail(hops) }));
  }
  function clear() {
    const here = trail.current;
    trail.clear();
    if (!here) {
      navigate('#/');
      return;
    }
    trail.push({ id: here.id, name: here.name, kind: here.kind, dir: 'start' });
    navigate(symbolHref(here.id, { trail: encodeTrail(trail.hops) }), { replace: true });
  }
</script>
<div class="trailwrap">
<div class="trailbar">
  <span class="label">Trail</span>
  {#if hops.length === 0}
    <span class="empty"
      >Step into a call on the right, or up to a caller on the left — the trail records the
      path.</span
    >
  {:else}
    {#each hops as hop, i (hop.id)}
      {#if i > 0}
        <span
          class="hop-arrow"
          class:up={hop.dir === 'up'}
          title={hop.dir === 'up'
            ? 'stepped up to a caller'
            : hop.dir === 'down'
              ? 'stepped down into a call'
              : 'jumped here'}
          aria-hidden="true"
        >
          {hop.dir === 'up' ? '←' : hop.dir === 'down' ? '→' : '·'}
        </span>
      {/if}
      <button
        type="button"
        class="hop"
        class:cur={i === hops.length - 1}
        aria-current={i === hops.length - 1 ? 'true' : undefined}
        onclick={() => step(i)}
... (169 lines truncated)
</file>

<file path="ui/src/views/DeadCodeView.svelte">
<script lang="ts">
  import KindGlyph from '../components/KindGlyph.svelte';
  import { fetchDeadCode, ApiFailure, type WireDeadCode, type WireDeadCodeRow } from '../lib/api';
  import { deadHref, fileHref, navigate, symbolHref } from '../lib/navigation';
  import { live } from '../lib/live.svelte';
  import {
    DEAD_CODE_CAVEAT,
    deadCodeHeadline,
    deadCodeRowMeta,
    deadCodeScale,
    emptyMessage,
    exclusionPhrases,
    groupMeta,
  } from '../lib/deadcode-model';
  interface Props {
    exported?: boolean;
  }
  let { exported = false }: Props = $props();
  let payload = $state<WireDeadCode | null>(null);
  let failure = $state<string | null>(null);
  let loading = $state(true);
  $effect(() => {
    const includeExported = exported;
    void live.indexTick;
    const controller = new AbortController();
    loading = true;
    failure = null;
    fetchDeadCode({ includeExported }, controller.signal)
      .then((next) => {
        payload = next;
        loading = false;
      })
      .catch((error: unknown) => {
        if (controller.signal.aborted) return;
        failure = error instanceof ApiFailure ? error.message : 'The list could not be read.';
        loading = false;
      });
    return () => controller.abort();
  });
  let headline = $derived(deadCodeHeadline(payload));
  let scale = $derived(deadCodeScale(payload));
  let phrases = $derived(exclusionPhrases(payload));
  function open(row: WireDeadCodeRow): void {
    navigate(symbolHref(row.id, { line: row.line }));
  }
</script>
<div class="scroll">
  <div class="head">
    <h2>Dead code</h2>
    <p>
      Symbols no import, call or reference in this index reaches, largest first. Everything below
      is what the graph can see; the notes under the list are what it cannot.
    </p>
  </div>
  <div class="bar">
    <p class="caveat">{DEAD_CODE_CAVEAT}</p>
    <a
      class="toggle"
      class:on={exported}
      href={deadHref({ exported: !exported })}
      title={exported
        ? 'Back to symbols nothing outside this repository could import either'
        : 'Also list symbols something outside this repository could import — the index cannot check those'}
      onclick={(event) => {
        event.preventDefault();
        navigate(deadHref({ exported: !exported }));
      }}>{exported ? 'Including exported' : 'Internal only'}</a
    >
  </div>
  {#if failure}
    <p class="state">Could not read the list — {failure}</p>
  {:else if loading && payload === null}
    <p class="state">Reading the graph…</p>
  {:else if payload}
    {#if exported}
      <p class="warn">
        Exported symbols are on this list. Nothing in this repository references them, but anything
        outside it can — a published package, another service, a script. Read each one before you
        believe it.
      </p>
    {/if}
    {#if payload.groups.length === 0}
      <p class="state">{emptyMessage(payload)}</p>
    {:else}
      <p class="headline">{headline}</p>
      <div class="groups">
        {#each payload.groups as group (group.file)}
          <div class="filegroup" class:gen={group.generated}>
            <div class="fpath">
              <a href={fileHref(group.file)} title={group.file}>{group.file}</a>
              <b>{groupMeta(group)}</b>
            </div>
            {#each group.rows as row (row.id)}
              <div class="row">
                <KindGlyph kind={row.kind} />
                <div class="body">
                  <div class="line">
                    <button
                      type="button"
                      class="nm"
... (267 lines truncated)
</file>

<file path="ui/src/views/EntryView.svelte">
<script lang="ts">
  import EntrySection from '../components/entry/EntrySection.svelte';
  import SavedTrails from '../components/SavedTrails.svelte';
  import { palette } from '../lib/palette.svelte';
  import { buildEntryPanel, flowPair, type EntryRow } from '../lib/entry-model';
  import { flowHref, navigate } from '../lib/navigation';
  import { openEntryTarget } from '../lib/walk';
  interface Props {
    project?: string | null;
  }
  let { project = null }: Props = $props();
  $effect(() => {
    void palette.ensureEntries();
  });
  let panel = $derived(buildEntryPanel(palette.entries));
  let armed = $state<{ id: string; name: string } | null>(null);
  let reaches = $state('');
  let input: HTMLInputElement | null = $state(null);
  // A refetch (the index moved) can retire the armed row. Dropping the arming
  // is the honest response: the symbol it named may not be there any more.
  $effect(() => {
    const id = armed?.id;
    if (id && !panel.rows.some((row) => row.id === id)) armed = null;
  });
  function open(row: EntryRow): void {
    openEntryTarget(row.target);
  }
  function draw(from: string, to: string): void {
    const pair = flowPair(from, to);
    if (!pair) return;
    armed = null;
    reaches = '';
    navigate(flowHref(pair));
  }
  function onflow(row: EntryRow): void {
    if (!row.flowFrom) return;
    if (armed === null) {
      armed = { id: row.id, name: row.flowFrom };
      reaches = '';
      // The input is the faster path for anyone who already knows the other
      // end; focusing it costs nothing to anyone who would rather click a row.
      queueMicrotask(() => input?.focus());
      return;
    }
    if (armed.id === row.id) {
      armed = null;
      return;
    }
    draw(armed.name, row.flowFrom);
  }
  function onkeydown(event: KeyboardEvent): void {
    if (event.key === 'Escape') {
      event.preventDefault();
      armed = null;
    }
  }
</script>
<div class="scroll">
  <div class="head">
    <h2>Entry points</h2>
    <p>
      Where a flow starts{project ? ` in ${project}` : ''} — every list below is read out of the
      graph, not guessed from a filename. Open a row to read the code, or use
      <span class="chiplike">Flow ›</span> to draw the path from it to a second symbol.
    </p>
  </div>
  {#if armed}
    <div class="arming" role="group" aria-label="Draw a flow">
      <span class="from">{armed.name}</span>
      <span class="arrow" aria-hidden="true">→</span>
      <input
        bind:this={input}
        bind:value={reaches}
        {onkeydown}
        type="text"
        autocomplete="off"
        spellcheck="false"
        placeholder="a symbol it reaches"
        aria-label={`The symbol ${armed.name} should reach`}
        onkeypress={(event) => {
          if (event.key === 'Enter' && armed) draw(armed.name, reaches);
        }}
      />
      <button
        type="button"
        class="go"
        disabled={flowPair(armed.name, reaches) === null}
        onclick={() => armed && draw(armed.name, reaches)}>Draw the flow</button
      >
      <button type="button" class="cancel" onclick={() => (armed = null)}>Cancel</button>
      <span class="hint">or pick the other end with <span class="chiplike">→ here</span></span>
    </div>
  {/if}
  <div class="saved">
    <SavedTrails hideWhenEmpty={false} />
  </div>
  {#if palette.entriesFailure}
    <p class="state">Could not read the entry points — {palette.entriesFailure}</p>
  {:else if !palette.entriesSettled}
    <p class="state">Reading the graph…</p>
... (108 lines truncated)
</file>

<file path="ui/src/views/FileCodeView.svelte">
<script lang="ts">
  import { untrack } from 'svelte';
  import CodeArcs from '../components/file/CodeArcs.svelte';
  import Connectors from '../components/symbol/Connectors.svelte';
  import FileCodeBlock from '../components/file/FileCodeBlock.svelte';
  import FileCodeOutline from '../components/file/FileCodeOutline.svelte';
  import FileCodeRail from '../components/file/FileCodeRail.svelte';
  import FileModeTabs from '../components/file/FileModeTabs.svelte';
  import KindGlyph from '../components/KindGlyph.svelte';
  import DriftBanner from '../components/DriftBanner.svelte';
  import {
    ApiFailure,
    fetchFileCode,
    fetchSource,
    type WireFileCodePayload,
    type WireNodeRef,
  } from '../lib/api';
  import { tokensByLine, type Token } from '../lib/highlight';
  import { hot } from '../lib/focus.svelte';
  import { basename, formatBytes, type OutlineEntryRow } from '../lib/file-model';
  import {
    ARC_CROWD_LIMIT,
    arcSummary,
    arcsInRange,
    buildFileArcs,
    buildFileCallRows,
    buildFileRefs,
    documentHeight,
    lineAtOffset,
    lineCentre,
    lineTop,
    ownerAt,
    pageFor,
    pagesForRange,
    railHeight,
    rowsInRange,
    visibleArcs,
    visibleLines,
    type FileArc,
    type FileCallRow,
  } from '../lib/filecode-model';
  import { liveRefresh } from '../lib/live.svelte';
  import { plural, synthesizedBy, type Connector, type LineRef } from '../lib/symbol-model';
  import { walkTo } from '../lib/walk';
  interface Props {
    path: string;
    line: number | null;
  }
  let { path, line }: Props = $props();
  let payload = $state<WireFileCodePayload | null>(null);
  let failure = $state<ApiFailure | null>(null);
  let loading = $state(true);
  let tokens = $state(new Map<number, Token[]>());
  let loadedPages = new Set<number>();
  let inflightPages = new Set<number>();
  let pageError = $state<string | null>(null);
  let pageController: AbortController | null = null;
  $effect(() => {
    const wanted = path;
    const controller = new AbortController();
    untrack(() => load(wanted, controller.signal));
    return () => controller.abort();
  });
  let liveController: AbortController | null = null;
  liveRefresh(
    () => payload?.file.path ?? path,
    () => {
      const wanted = path;
      liveController?.abort();
      liveController = new AbortController();
      void load(wanted, liveController.signal, true);
    }
  );
  async function load(file: string, signal: AbortSignal, quiet = false): Promise<void> {
    if (!quiet) {
      loading = true;
      failure = null;
      payload = null;
      landed = null;
      hoverLine = null;
      hoverFocus = null;
      highlight = null;
      if (stageEl) stageEl.scrollTop = 0;
    }
    tokens = new Map();
    loadedPages = new Set();
    inflightPages = new Set();
    pageError = null;
    pageController?.abort();
    pageController = new AbortController();
    try {
      const next = await fetchFileCode(file, signal);
      if (signal.aborted) return;
      payload = next;
      failure = null;
    } catch (cause) {
      if (signal.aborted) return;
      failure =
        cause instanceof ApiFailure
          ? cause
... (427 lines truncated)
</file>

<file path="ui/src/views/FileView.svelte">
<script lang="ts">
  import { tick, untrack } from 'svelte';
  import FileOutline from '../components/file/FileOutline.svelte';
  import FileRail from '../components/file/FileRail.svelte';
  import FileModeTabs from '../components/file/FileModeTabs.svelte';
  import KindGlyph from '../components/KindGlyph.svelte';
  import DriftBanner from '../components/DriftBanner.svelte';
  import { ApiFailure, fetchFile, type WireFilePayload, type WireNodeRef } from '../lib/api';
  import {
    basename,
    buildFileOutline,
    buildFileRail,
    fileMetaLine,
  } from '../lib/file-model';
  import { fileHref, navigate } from '../lib/navigation';
  import { liveRefresh } from '../lib/live.svelte';
  import { plural } from '../lib/symbol-model';
  import { walkTo } from '../lib/walk';
  interface Props {
    path: string;
    line: number | null;
  }
  let { path, line }: Props = $props();
  let payload = $state<WireFilePayload | null>(null);
  let failure = $state<ApiFailure | null>(null);
  let loading = $state(true);
  let centerEl = $state<HTMLElement | null>(null);
  let landed: string | null = null;
  $effect(() => {
    const wanted = path;
    const controller = new AbortController();
    untrack(() => load(wanted, controller.signal));
    return () => controller.abort();
  });
  let liveController: AbortController | null = null;
  liveRefresh(
    () => payload?.file.path ?? path,
    () => {
      const wanted = path;
      liveController?.abort();
      liveController = new AbortController();
      void load(wanted, liveController.signal, true);
    }
  );
  async function load(file: string, signal: AbortSignal, quiet = false): Promise<void> {
    if (!quiet) {
      loading = true;
      failure = null;
      payload = null;
      pane = 'outline';
      index = -1;
      landed = null;
    }
    try {
      const next = await fetchFile(file, signal);
      if (signal.aborted) return;
      payload = next;
      failure = null;
    } catch (cause) {
      if (signal.aborted) return;
      failure =
        cause instanceof ApiFailure
          ? cause
          : new ApiFailure(0, 'error', cause instanceof Error ? cause.message : String(cause), null);
    } finally {
      if (!signal.aborted) loading = false;
    }
  }
  let outline = $derived(payload ? buildFileOutline(payload) : []);
  let importedBy = $derived(
    payload ? buildFileRail(payload.dependents, payload.importedBy.items) : null
  );
  let imports = $derived(
    payload
      ? buildFileRail(payload.dependencies, payload.imports.items, payload.unresolvedImports)
      : null
  );
  function open(node: WireNodeRef | { id: string; name: string; kind: string }): void {
    walkTo({ id: node.id, name: node.name, kind: node.kind }, 'start');
  }
  function openFileNode(): void {
    const file = payload?.file;
    if (!file?.id) return;
    walkTo({ id: file.id, name: basename(file.path), kind: 'file' }, 'start');
  }
  type Pane = 'left' | 'outline' | 'right';
  const PANES: Pane[] = ['left', 'outline', 'right'];
  let pane = $state<Pane>('outline');
  let index = $state(-1);
  function paneLength(which: Pane): number {
    if (which === 'left') return importedBy?.rows.length ?? 0;
    if (which === 'right') return imports?.rows.length ?? 0;
    return outline.length;
  }
  function follow(): void {
    if (index < 0) return;
    if (pane === 'outline') {
      const row = outline[index];
      if (row) open(row.entry);
      return;
... (251 lines truncated)
</file>

<file path="ui/src/views/FlowView.svelte">
<script lang="ts">
  import { SvelteFlow, Controls, type Node, type Edge } from '@xyflow/svelte';
  import '@xyflow/svelte/dist/style.css';
  import FlowCard from '../components/flow/FlowCard.svelte';
  import FlowLink from '../components/flow/FlowLink.svelte';
  import FlowEndCap from '../components/flow/FlowEndCap.svelte';
  import ExportButtons from '../components/ExportButtons.svelte';
  import { exportFilename, flowSvg } from '../lib/export-svg';
  import { fetchFlow, type WireFlow, type WireFlowPayload } from '../lib/api';
  import { live } from '../lib/live.svelte';
  import { navigate, symbolHref } from '../lib/navigation';
  import { trail, encodeTrail, type TrailHop } from '../lib/trail.svelte';
  import { decodeTrail } from '../lib/trail-codec';
  import { buildFlowLayout, type FlowCardLayout, type FlowLayout } from '../lib/flow-model';
  import { basename } from '../lib/symbol-model';
  interface Props {
    from: string | null;
    to: string | null;
    symbols: string | null;
    trailParam: string | null;
  }
  let { from, to, symbols, trailParam }: Props = $props();
  let payload = $state<WireFlowPayload | null>(null);
  let error = $state<string | null>(null);
  let loading = $state(true);
  let picked = $state<string | null>(null);
  let showAll = $state(false);
  const ALL = 'all-paths';
  const START_VIEWPORT = { x: 0, y: 0, zoom: 1 };
  const nodeTypes = { flow: FlowCard, cap: FlowEndCap };
  const edgeTypes = { flow: FlowLink };
  const trailHops = $derived<TrailHop[]>(trailParam ? decodeTrail(trailParam) : []);
  $effect(() => {
    const spec = trailParam
      ? { trail: trailHops.map((h) => `${h.dir === 'start' ? 's' : h.dir === 'up' ? 'u' : 'd'}${h.id}`) }
      : symbols
        ? { symbols }
        : { from: from ?? '', to: to ?? '' };
    if (!trailParam && !symbols && !(from && to)) {
      payload = null;
      loading = false;
      error = null;
      return;
    }
    // Re-run when the index moves: a path is a walk over edges that a sync can
    // add, remove or re-route, and a strip drawn from the previous graph would
    // disagree with `codegraph_explore` about the same question.
    void live.indexTick;
    const controller = new AbortController();
    loading = true;
    error = null;
    const keep = picked;
    fetchFlow(spec, controller.signal)
      .then((next) => {
        payload = next;
        // A refresh keeps the reader's chosen path when it survived the sync.
        picked = next.flows.some((f) => f.id === keep) ? keep : (next.flows[0]?.id ?? null);
        loading = false;
      })
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        error = err instanceof Error ? err.message : String(err);
        loading = false;
      });
    return () => controller.abort();
  });
  const flows = $derived<WireFlow[]>(payload?.flows ?? []);
  const shown = $derived<WireFlow[]>(
    showAll ? flows : flows.filter((f) => f.id === picked).slice(0, 1)
  );
  const layout = $derived<FlowLayout | null>(
    shown.length === 0 ? null : buildFlowLayout(showAll ? flows : shown, picked)
  );
  const activeFlow = $derived(flows.find((f) => f.id === picked) ?? flows[0] ?? null);
  const nodes = $derived.by<Node[]>(() => {
    if (layout === null) return [];
    const caps: Node[] = layout.endCaps.map((cap) => ({
      id: cap.id,
      type: 'cap',
      position: { x: cap.x, y: cap.y },
      draggable: false,
      selectable: false,
      connectable: false,
      data: {
        cap,
        dimmed: showAll && picked !== null && !cap.flows.includes(picked),
        onOpen: openNode,
      },
    }));
    return [
      ...caps,
      ...layout.cards.map((card) => ({
        id: card.id,
        type: 'flow',
        position: { x: card.x, y: card.y },
        draggable: false,
        selectable: false,
        connectable: false,
        data: {
          card,
... (280 lines truncated)
</file>

<file path="ui/src/views/HomeView.svelte">
<script lang="ts">
  import PaletteRows from '../components/PaletteRows.svelte';
  import SavedTrails from '../components/SavedTrails.svelte';
  import { palette } from '../lib/palette.svelte';
  import { buildEntryPalette, type PaletteItem } from '../lib/search-model';
  import { entryHref, fileHref, flowHref, navigate } from '../lib/navigation';
  import { openEntryTarget, walkTo } from '../lib/walk';
  interface Props {
    project?: string | null;
  }
  let { project = null }: Props = $props();
  $effect(() => {
    void palette.ensureEntries();
  });
  let entries = $derived(buildEntryPalette(palette.entries));
  function pick(item: PaletteItem) {
    if (item.type === 'flow') {
      navigate(flowHref({ from: item.from, to: item.to }));
      return;
    }
    if (item.type === 'entry') {
      openEntryTarget(item.row.target);
      return;
    }
    const id = item.type === 'route' ? item.nodeId : item.id;
    if (!id) return;
    if (item.type === 'symbol' && item.node.kind === 'file') {
      navigate(fileHref(item.node.file));
      return;
    }
    walkTo(
      item.type === 'route'
        ? { id, name: item.handler, kind: null }
        : { id, name: item.node.name, kind: item.node.kind },
      'start'
    );
  }
</script>
<div class="scroll">
  <div class="emptystate">
    <h2>Nothing selected</h2>
    <p>
      Search for a symbol or a file to start reading{project ? ` in ${project}` : ''}. Press
      <code>/</code> to focus the search box.
    </p>
    <p>
      Every symbol you open shows who calls it on the left, its verbatim source in the middle, and
      what it calls on the right — each callee lined up with the line that makes the call.
    </p>
  </div>
  <div class="saved">
    <SavedTrails />
  </div>
  {#if entries.sections.length > 0}
    <section class="entries" aria-label="Where to start">
      <div class="entries-h">
        <h3>Where to start</h3>
        <a href={entryHref()}>All entry points ›</a>
      </div>
      <div class="rows">
        <PaletteRows palette={entries} onpick={pick} />
      </div>
    </section>
  {/if}
</div>
<style>
  .scroll {
    height: 100%;
    overflow: auto;
  }
  .scroll :global(.emptystate) {
    padding-bottom: 8px;
  }
  .saved {
    max-width: 800px;
    padding: 8px 40px 0;
  }
  .entries {
    max-width: 720px;
    padding: 8px 40px 48px;
  }
  .entries-h {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 8px;
  }
  .entries h3 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
  }
  .entries-h a {
    color: var(--ink-2);
    font-size: 12px;
  }
  .entries-h a:hover {
    color: var(--ink);
    text-decoration: underline;
... (6 lines truncated)
</file>

<file path="ui/src/views/MapView.svelte">
<script lang="ts">
  import { SvelteFlow, Controls, ViewportPortal, type Node, type Edge } from '@xyflow/svelte';
  import '@xyflow/svelte/dist/style.css';
  import ModuleNode from '../components/map/ModuleNode.svelte';
  import ModuleEdge from '../components/map/ModuleEdge.svelte';
  import MapSidePanel from '../components/map/MapSidePanel.svelte';
  import MapKey from '../components/map/MapKey.svelte';
  import { exportFilename, mapSvg } from '../lib/export-svg';
  import { fetchMap, type WireMapPayload } from '../lib/api';
  import { live } from '../lib/live.svelte';
  import { mapHref, navigate } from '../lib/navigation';
  import {
    buildMapLayout,
    isEdgeVisible,
    type MapEdgeLayout,
    type MapLayout,
  } from '../lib/map-model';
  interface Props {
    root: string | null;
    depth: number | null;
    tests: boolean;
  }
  let { root, depth, tests }: Props = $props();
  let payload = $state<WireMapPayload | null>(null);
  let error = $state<string | null>(null);
  let loading = $state(true);
  let selected = $state<string | null>(null);
  let hovered = $state<{ edge: MapEdgeLayout; x: number; y: number } | null>(null);
  let stage = $state<HTMLDivElement | null>(null);
  const FIT = { fitViewOptions: { padding: 0.12, maxZoom: 1, minZoom: 0.45 } };
  const LEGEND_KEY = 'codegraph-ui:map-legend';
  let legendOpen = $state(readLegendOpen());
  function readLegendOpen(): boolean {
    try {
      return localStorage.getItem(LEGEND_KEY) !== 'closed';
    } catch {
      return true;
    }
  }
  $effect(() => {
    try {
      localStorage.setItem(LEGEND_KEY, legendOpen ? 'open' : 'closed');
    } catch {
    }
  });
  const nodeTypes = { module: ModuleNode };
  const edgeTypes = { module: ModuleEdge };
  $effect(() => {
    const wantRoot = root;
    const wantDepth = depth;
    void live.indexTick;
    const controller = new AbortController();
    loading = true;
    error = null;
    fetchMap({ root: wantRoot, depth: wantDepth ?? undefined }, controller.signal)
      .then((next) => {
        payload = next;
        loading = false;
      })
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        error = err instanceof Error ? err.message : String(err);
        loading = false;
      });
    return () => controller.abort();
  });
  const layout = $derived<MapLayout | null>(
    payload === null ? null : buildMapLayout(payload, { includeTests: tests })
  );
  const neighbours = $derived.by(() => {
    if (layout === null || selected === null) return null;
    const set = new Set<string>([selected]);
    for (const edge of layout.edges) {
      if (edge.source === selected) set.add(edge.target);
      if (edge.target === selected) set.add(edge.source);
    }
    return set;
  });
  const nodes = $derived.by<Node[]>(() => {
    if (layout === null) return [];
    return layout.nodes.map((node) => ({
      id: node.id,
      type: 'module',
      position: { x: node.x, y: node.y },
      draggable: false,
      selectable: false,
      connectable: false,
      data: {
        layout: node,
        selected: selected === node.id,
        dimmed: neighbours !== null && !neighbours.has(node.id),
        onSelect: (id: string) => {
          selected = selected === id ? null : id;
          hovered = null;
        },
      },
    }));
  });
  const edges = $derived.by<Edge[]>(() => {
    if (layout === null) return [];
... (277 lines truncated)
</file>

<file path="ui/src/views/NotFoundView.svelte">
<script lang="ts">
  interface Props {
    path: string;
  }
  let { path }: Props = $props();
</script>
<div class="scroll">
  <div class="emptystate">
    <h2>No such view</h2>
    <p>
      <span class="mono">#{path}</span> does not match a view. Try
      <a class="mono link" href="#/">the start</a>.
    </p>
  </div>
</div>
<style>
  .scroll {
    height: 100%;
    overflow: auto;
  }
  .link {
    color: var(--accent);
    text-decoration: underline;
    text-decoration-color: var(--accent-line);
    text-underline-offset: 3px;
  }
</style>
</file>

<file path="ui/src/views/ScreensView.svelte">
<script lang="ts">
  import { SvelteFlow, Controls, type Node, type Edge, type Viewport } from '@xyflow/svelte';
  import '@xyflow/svelte/dist/style.css';
  import ScreenNode from '../components/screens/ScreenNode.svelte';
  import ScreenEdge from '../components/screens/ScreenEdge.svelte';
  import KindGlyph from '../components/KindGlyph.svelte';
  import { fetchScreens, type WireScreensPayload, type WireScreenLink } from '../lib/api';
  import { live } from '../lib/live.svelte';
  import { symbolHref, fileHref, navigate, stepsHref } from '../lib/navigation';
  import { isEdgeVisible, type MapEdgeLayout } from '../lib/map-model';
  import { commonTokens, conditionTokens, restTokens, scenarios, whenWords, type WordToken } from '../lib/conditions';
  import {
    buildScreensModel,
    hoverPill,
    nearestEdge,
    neighbourhood,
    pairId,
    placeLabels,
    viaText,
    type ScreensModel,
  } from '../lib/screens-model';
  let payload = $state<WireScreensPayload | null>(null);
  let error = $state<string | null>(null);
  let loading = $state(true);
  let selected = $state<string | null>(null);
  let hovered = $state<{ edge: MapEdgeLayout; x: number; y: number } | null>(null);
  let panelHot = $state<{ edge: string; link: WireScreenLink } | null>(null);
  let stage = $state<HTMLDivElement | null>(null);
  let viewport = $state<Viewport | undefined>(undefined);
  const HOVER_REACH = 10;
  const LEGEND_KEY = 'codegraph-ui:screens-legend';
  let legendOpen = $state(readLegendOpen());
  function readLegendOpen(): boolean {
    try {
      return localStorage.getItem(LEGEND_KEY) !== 'closed';
    } catch {
      return true;
    }
  }
  $effect(() => {
    try {
      localStorage.setItem(LEGEND_KEY, legendOpen ? 'open' : 'closed');
    } catch {
    }
  });
  const FIT = { fitViewOptions: { padding: 0.1, maxZoom: 1, minZoom: 0.4 } };
  const DOUBLE_CLICK_MS = 400;
  let lastClick: { id: string; at: number } | null = null;
  const nodeTypes = { screen: ScreenNode };
  const edgeTypes = { screen: ScreenEdge };
  $effect(() => {
    void live.indexTick;
    const controller = new AbortController();
    loading = true;
    error = null;
    fetchScreens(controller.signal)
      .then((next) => {
        payload = next;
        loading = false;
      })
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        error = err instanceof Error ? err.message : String(err);
        loading = false;
      });
    return () => controller.abort();
  });
  const model = $derived<ScreensModel | null>(
    payload === null || !payload.routed ? null : buildScreensModel(payload)
  );
  const neighbours = $derived.by(() => {
    if (model === null || selected === null) return null;
    const set = new Set<string>([selected]);
    for (const edge of model.layout.edges) {
      if (edge.source === selected) set.add(edge.target);
      if (edge.target === selected) set.add(edge.source);
    }
    return set;
  });
  const pills = $derived(model === null ? null : placeLabels(model, selected));
  const focusId = $derived(hovered?.edge.id ?? panelHot?.edge ?? null);
  const focusPill = $derived.by(() => {
    if (model === null || focusId === null || pills?.pills.has(focusId)) return null;
    const full = panelHot?.edge === focusId ? fullText(panelHot.link) : undefined;
    return hoverPill(model, focusId, selected, full, pills ?? undefined);
  });
  const nodes = $derived.by<Node[]>(() => {
    if (model === null) return [];
    return model.layout.nodes.map((node) => ({
      id: node.id,
      type: 'screen',
      position: { x: node.x, y: node.y },
      draggable: false,
      selectable: false,
      connectable: false,
      data: {
        layout: node,
        info: model.nodes.get(node.id)!,
        selected: selected === node.id,
        dimmed: neighbours !== null && !neighbours.has(node.id),
... (607 lines truncated)
</file>

<file path="ui/src/views/StepsView.svelte">
<script lang="ts">
  import { SvelteFlow, Controls, type Node, type Edge, type Viewport } from '@xyflow/svelte';
  import '@xyflow/svelte/dist/style.css';
  import StepNode from '../components/steps/StepNode.svelte';
  import StepStubs from '../components/steps/StepStubs.svelte';
  import ForkPoint from '../components/steps/ForkPoint.svelte';
  import DecisionCaption from '../components/steps/DecisionCaption.svelte';
  import RegionCaption from '../components/steps/RegionCaption.svelte';
  import StepsKey from '../components/steps/StepsKey.svelte';
  import ScreenEdge from '../components/screens/ScreenEdge.svelte';
  import KindGlyph from '../components/KindGlyph.svelte';
  import {
    canDrawSteps,
    fetchRoutes,
    fetchScreens,
    fetchSteps,
    type WireRoute,
    type WireScreen,
    type WireStepLink,
    type WireStepsPayload,
  } from '../lib/api';
  import { live } from '../lib/live.svelte';
  import { fileHref, flowHref, navigate, stepsHref, symbolHref } from '../lib/navigation';
  import type { MapEdgeLayout } from '../lib/map-model';
  import { hoverPill, nearestEdge, placeLabels } from '../lib/screens-model';
  import { commonTokens, conditionTokens, restTokens, scenarios, whenWords, type WordToken } from '../lib/conditions';
  import {
    buildStepsModel,
    kindWord,
    kindWords,
    selectionReach,
    stepEdgeVisible,
    stepNeighbourhood,
    stepPairId,
    stepViaText,
    triggerWords,
    type StepsModel,
  } from '../lib/steps-model';
  import { buildOrderModel } from '../lib/program-model';
  interface Props {
    anchor: string | null;
    symbol: string | null;
    depth: number | null;
    through: boolean;
    reading: 'order' | 'tree' | null;
  }
  let { anchor, symbol, depth, through, reading }: Props = $props();
  let payload = $state<WireStepsPayload | null>(null);
  let error = $state<string | null>(null);
  let loading = $state(true);
  let selected = $state<string | null>(null);
  let hovered = $state<{ edge: MapEdgeLayout; x: number; y: number } | null>(null);
  let panelHot = $state<{ edge: string; link: WireStepLink } | null>(null);
  let stage = $state<HTMLDivElement | null>(null);
  let viewport = $state<Viewport | undefined>(undefined);
  const HOVER_REACH = 10;
  let screens = $state<WireScreen[] | null>(null);
  let routes = $state<WireRoute[] | null>(null);
  const chooser = $derived.by<'screens' | 'routes' | 'none' | null>(() => {
    if (screens === null) return null;
    if (screens.length > 0) return 'screens';
    if (routes === null) return null;
    return routes.length > 0 ? 'routes' : 'none';
  });
  function routeGroups(list: WireRoute[]): Array<{ file: string; entries: WireRoute[] }> {
    const byFile = new Map<string, WireRoute[]>();
    for (const r of list) {
      const group = byFile.get(r.routeFile) ?? [];
      group.push(r);
      byFile.set(r.routeFile, group);
    }
    return [...byFile]
      .map(([file, entries]) => ({ file, entries: [...entries].sort((a, b) => a.routeLine - b.routeLine) }))
      .sort((a, b) => b.entries.length - a.entries.length || a.file.localeCompare(b.file));
  }
  const LEGEND_KEY = 'codegraph-ui:steps-legend';
  let legendOpen = $state(readLegendOpen());
  function readLegendOpen(): boolean {
    try {
      return localStorage.getItem(LEGEND_KEY) !== 'closed';
    } catch {
      return true;
    }
  }
  $effect(() => {
    try {
      localStorage.setItem(LEGEND_KEY, legendOpen ? 'open' : 'closed');
    } catch {
    }
  });
  const nodeTypes = { step: StepNode, region: RegionCaption, fork: ForkPoint, decision: DecisionCaption, stubs: StepStubs };
  const DOUBLE_CLICK_MS = 400;
  let lastClick: { id: string; at: number } | null = null;
  function startHere(id: string): boolean {
    const step = model?.nodes.get(id)?.step;
    if (!step || !step.node || step.anchor) return false;
    navigate(stepsHref({ anchor: step.node.id }));
    return true;
  }
  const edgeTypes = { screen: ScreenEdge };
... (938 lines truncated)
</file>

<file path="ui/src/views/SymbolView.svelte">
<script lang="ts">
  import { tick, untrack } from 'svelte';
  import CalleeRail from '../components/symbol/CalleeRail.svelte';
  import CallersRail from '../components/symbol/CallersRail.svelte';
  import Connectors from '../components/symbol/Connectors.svelte';
  import BlastStrip from '../components/symbol/BlastStrip.svelte';
  import MembersOutline from '../components/symbol/MembersOutline.svelte';
  import TypeHierarchy from '../components/symbol/TypeHierarchy.svelte';
  import SourceBlock from '../components/symbol/SourceBlock.svelte';
  import SymbolHeader from '../components/symbol/SymbolHeader.svelte';
  import DriftBanner from '../components/DriftBanner.svelte';
  import {
    ApiFailure,
    fetchFile,
    fetchSource,
    fetchSymbol,
    type WireNodeDetail,
    type WireNodeRef,
    type WireSource,
    type WireSymbolPayload,
  } from '../lib/api';
  import { tokensByLine, type Token } from '../lib/highlight';
  import { hot, railFocus } from '../lib/focus.svelte';
  import { project } from '../lib/project.svelte';
  import {
    buildCalleeRail,
    buildCallerRail,
    buildCodeBlock,
    buildOutline,
    graphCallLines,
    refsByLine,
    showsBody,
    synthesizedBy,
    type Connector,
    type LineRef,
  } from '../lib/symbol-model';
  import { encodeTrail, trail } from '../lib/trail.svelte';
  import { liveRefresh } from '../lib/live.svelte';
  import { fileHref, navigate, symbolHref } from '../lib/navigation';
  import { arrivedFrom, walkTo } from '../lib/walk';
  interface Props {
    id: string;
    line: number | null;
  }
  let { id, line }: Props = $props();
  const ROW_HEIGHT = 34;
  const ROW_GAP = 6;
  const RAIL_HEADER_FALLBACK = 38;
  const DRIFT_INLINE_MAX_LINES = 400;
  const EMPTY_REFS: Map<number, LineRef[]> = new Map();
  let payload = $state<WireSymbolPayload | null>(null);
  let source = $state<WireSource | null>(null);
  let failure = $state<ApiFailure | null>(null);
  let loading = $state(true);
  let innerEl = $state<HTMLDivElement | null>(null);
  let centerEl = $state<HTMLElement | null>(null);
  let railEl = $state<HTMLElement | null>(null);
  let leftRailEl = $state<HTMLElement | null>(null);
  let tops = $state<number[]>([]);
  let foldTop = $state(0);
  let noteTop = $state(0);
  let stageMinHeight = $state(0);
  let connectors = $state<Connector[]>([]);
  let overlay = $state({ width: 0, height: 0 });
  let placed = $state(false);
  $effect(() => {
    const wanted = id;
    const controller = new AbortController();
    untrack(() => load(wanted, controller.signal));
    return () => controller.abort();
  });
  let liveController: AbortController | null = null;
  liveRefresh(
    () => payload?.node.file ?? null,
    () => {
      const wanted = id;
      liveController?.abort();
      liveController = new AbortController();
      void load(wanted, liveController.signal, true);
    }
  );
  async function load(nodeId: string, signal: AbortSignal, quiet = false): Promise<void> {
    if (!quiet) {
      loading = true;
      failure = null;
      payload = null;
      source = null;
      railFocus.reset();
      hot.set(null);
      placed = false;
    }
    void project.ensure();
    let node: WireSymbolPayload;
    try {
      node = await fetchSymbol(nodeId, signal);
    } catch (cause) {
      if (signal.aborted) return;
      if (quiet && asFailure(cause).code === 'not-found' && payload !== null) {
        const moved = await refind(payload.node, signal);
        if (signal.aborted) return;
... (407 lines truncated)
</file>

<file path="ui/src/App.svelte">
<script lang="ts">
  import { untrack } from 'svelte';
  import TopBar from './components/TopBar.svelte';
  import TrailBar from './components/TrailBar.svelte';
  import HomeView from './views/HomeView.svelte';
  import SymbolView from './views/SymbolView.svelte';
  import FileView from './views/FileView.svelte';
  import FileCodeView from './views/FileCodeView.svelte';
  import MapView from './views/MapView.svelte';
  import ScreensView from './views/ScreensView.svelte';
  import StepsView from './views/StepsView.svelte';
  import FlowView from './views/FlowView.svelte';
  import EntryView from './views/EntryView.svelte';
  import DeadCodeView from './views/DeadCodeView.svelte';
  import NotFoundView from './views/NotFoundView.svelte';
  import Toast from './components/Toast.svelte';
  import {
    router,
    navigate,
    back,
    mapHref,
    flowHref,
    entryHref,
    screensHref,
    deadHref,
  } from './lib/router.svelte';
  import { palette } from './lib/palette.svelte';
  import { trail, resolveTrailNames } from './lib/trail.svelte';
  import { trails } from './lib/trails.svelte';
  import { project } from './lib/project.svelte';
  import { live } from './lib/live.svelte';
  import { toast } from './lib/toast.svelte';
  $effect(() => {
    void project.ensure();
  });
  $effect(() => {
    live.start();
  });
  let seenIndexTick = live.indexTick;
  $effect(() => {
    const tick = live.indexTick;
    untrack(() => {
      if (tick === seenIndexTick) return;
      seenIndexTick = tick;
      void project.reload();
      void palette.reloadEntries();
      void trails.reload();
      toast.show('Index updated · reloaded');
    });
  });
  let topbar: TopBar | null = $state(null);
  let route = $derived(router.route);
  let hasScreens = $derived((project.stats?.graph.edgesByKind.navigates ?? 0) > 0);
  $effect(() => {
    const current = router.route;
    const encoded = router.params.get('t');
    untrack(() => {
      trail.hydrate(encoded);
      if (current.view === 'symbol' && current.id !== null && trail.current?.id !== current.id) {
        trail.push({ id: current.id });
      }
    });
  });
  $effect(() => {
    void trail.hops.length;
    void resolveTrailNames();
  });
  function isTypingTarget(target: EventTarget | null): boolean {
    if (!(target instanceof HTMLElement)) return false;
    return (
      target.isContentEditable ||
      target instanceof HTMLInputElement ||
      target instanceof HTMLTextAreaElement ||
      target instanceof HTMLSelectElement
    );
  }
  function onkeydown(event: KeyboardEvent) {
    if (event.defaultPrevented) return;
    if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
      event.preventDefault();
      topbar?.focusSearch();
      return;
    }
    if (event.metaKey || event.ctrlKey || event.altKey) return;
    if (isTypingTarget(event.target)) return;
    switch (event.key) {
      case '/':
        event.preventDefault();
        topbar?.focusSearch();
        break;
      case 'm':
        event.preventDefault();
        navigate(mapHref());
        break;
      case 'f':
        event.preventDefault();
        navigate(flowHref());
        break;
      case 'e':
        event.preventDefault();
... (59 lines truncated)
</file>

<file path="ui/src/index.ts">

</file>

<file path="ui/src/main.ts">
import { mount } from 'svelte';
import App from './App.svelte';
</file>

<file path="ui/index.html">
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="color-scheme" content="light dark" />
    <title>CodeGraph</title>
    <link rel="icon" href="data:," />
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.ts"></script>
  </body>
</html>
</file>

<file path="ui/package.json">
{
  "name": "@colbymchenry/codegraph-ui",
  "private": true,
  "version": "1.6.1",
  "type": "module",
  "description": "The CodeGraph reader as Svelte components: Symbol view, Flow strip and architecture Map behind one data adapter.",
  "keywords": [
    "codegraph",
    "svelte",
    "code-intelligence",
    "knowledge-graph"
  ],
  "repository": {
    "type": "git",
    "url": "git+https://github.com/colbymchenry/codegraph.git",
    "directory": "ui"
  },
  "license": "MIT",
  "files": [
    "dist",
    "README.md"
  ],
  "svelte": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "sideEffects": [
    "**/*.css"
  ],
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "svelte": "./dist/index.js",
      "default": "./dist/index.js"
    },
    "./theme.css": "./dist/lib/theme.css",
    "./package.json": "./package.json"
  },
  "scripts": {
    "build": "vite build",
    "build:lib": "node ../scripts/sync-ui-version.mjs && svelte-package -i src -o dist && node ../scripts/check-ui-package.mjs",
    "dev": "vite",
    "preview": "vite preview",
    "check": "svelte-check --tsconfig ./tsconfig.json"
  },
  "peerDependencies": {
    "svelte": "^5.25.0"
  },
  "dependencies": {
    "@xyflow/svelte": "^1.6.5"
  },
  "devDependencies": {
    "@fontsource-variable/archivo": "^5.3.0",
    "@fontsource/ibm-plex-mono": "^5.3.0",
    "@sveltejs/package": "^2.5.8",
    "@sveltejs/vite-plugin-svelte": "^6.2.4",
    "svelte": "^5.56.10",
    "svelte-check": "^4.7.6",
    "typescript": "^5.0.0",
    "vite": "^7.3.6"
  }
}
</file>

<file path="ui/README.md">
# ui/ — the `codegraph ui` viewer, and `@colbymchenry/codegraph-ui`

One source tree, two builds.

- **The app** — the browser reader for an indexed project: Svelte 5 + Vite,
  built as static files into `../dist/viewer` and served by the CLI over
  loopback.
- **The library** — the same components, packaged with `svelte-package` into
  `dist/` as `@colbymchenry/codegraph-ui`, so a host (CodeGraph Pro) renders
  the Symbol view, the Flow strip and the Map over its **own** graph reads.

They are one tree on purpose. A forked component is a second answer to the same
question about the same graph, and sooner or later the two get quoted against
each other in a review.

An npm workspace of the engine, so `npm ci` at the repo root installs the
toolchain for both.

Design spec (every token, size and measurement):
`../docs/design/codegraph-ui-design-spec.md`.

## Build

```bash
npm run build          # from the repo root: tsc -> copy-assets -> this app
npm run build:ui       # just the app, plus the dist assertion
npm run build:lib      # the LIBRARY: svelte-package -> ui/dist, plus its checks
npm run dev -w ui      # Vite dev server on 127.0.0.1:5174
npm run check -w ui    # svelte-check
```

`build:lib` is deliberately not part of `npm run build`: the CLI does not need
it, and a release that fails because a component library would not compile is a
release that failed for the wrong reason.

`npm run build` emits **`dist/viewer/`** (`index.html` + hashed assets).
`scripts/check-ui-build.mjs` then asserts the tree is complete, so a broken UI
build fails the release instead of shipping a CLI that serves a 404. The same
check runs again in `scripts/build-bundle.sh` (after the bundle stage copies
`dist`) and in `scripts/pack-npm.sh` (after each archive is unpacked).

### Why `dist/viewer` and not `dist/ui`

`src/ui/` is the engine's **terminal** UI (shimmer progress and its worker) and
tsc compiles it to `dist/ui/`. Pointing Vite there deletes those modules — the
CLI then dies at startup with `Cannot find module '../ui/shimmer-progress'` —
and would also leave the static server handing out compiled engine internals.
`check-ui-build.mjs` re-asserts the compiled engine is intact after every UI
build so that mistake cannot land twice.

## `@colbymchenry/codegraph-ui`

```svelte
<script lang="ts">
  import { CodegraphUi, SymbolView, FlowStrip, ArchitectureMap }
    from '@colbymchenry/codegraph-ui';
  import '@colbymchenry/codegraph-ui/theme.css';
</script>

<CodegraphUi adapter={myAdapter} nav={myNavigation}>
  <SymbolView id={symbolId} line={null} />
</CodegraphUi>
```

Exports: `SymbolView`, `FlowStrip`, `ArchitectureMap`, `FileView`,
`FileSourceView`, `EntryPointsView`, `DeadCodeView`, `TypeHierarchy`, `TrailBar`,
`SavedTrails`, `SearchPalette`, `PalettePanel`, `PaletteRows`, `DriftBanner`,
`KindGlyph`, `ExportButtons`, `CodegraphUi` — plus every pure model function the screens are
built from (`buildCalleeRail`, `buildFlowLayout`, `buildMapLayout`,
`buildHierarchyModel`, `tokensByLine`, …) and the `Wire*` types an adapter
answers in.

`TypeHierarchy` is the one screen that takes its data as a prop rather than
asking the adapter: it is part of `SymbolView`'s payload (`/api/node`'s
`hierarchy`), so a host that already holds a `WireSymbolPayload` can render the
tree on its own without a second read.

### The adapter is the only way data arrives

```ts
interface GraphAdapter {
  stats(signal?): Promise<WireStats>;
  search(query, opts?, signal?): Promise<WireSearch>;
  node(id, signal?): Promise<WireSymbolPayload>;
  nodes(ids, signal?): Promise<WireNodeRefs>;
  source(request, signal?): Promise<WireSource>;
  file(path, signal?): Promise<WireFilePayload>;
  fileCode(path, signal?): Promise<WireFileCodePayload>;
  flow(request, signal?): Promise<WireFlowPayload>;
  map(request?, signal?): Promise<WireMapPayload>;
  routes(request?, signal?): Promise<WireRoutes>;
  entryPoints(request?, signal?): Promise<WireEntryPoints>;
  deadCode(request?, signal?): Promise<WireDeadCode>;
  trails(signal?): Promise<WireTrails>;

  // The only mutating pair, and the only optional methods besides `events`.
  saveTrail?(request, signal?): Promise<WireTrails>;
  deleteTrail?(id, signal?): Promise<WireTrails>;
  events?(handlers): () => void;   // optional: the live channel
}
... (295 lines truncated)
</file>

<file path="ui/svelte.config.js">

</file>

<file path="ui/tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "bundler",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "types": ["vite/client"],
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noUncheckedIndexedAccess": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "allowJs": true,
    "checkJs": true,
    "noEmit": true
  },
  "include": ["src/**/*.ts", "src/**/*.svelte", "vite.config.ts", "svelte.config.js"]
}
</file>

<file path="ui/vite.config.ts">
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
</file>

<file path="AGENTS.md">
# AGENTS.md

Canonical project guidance for coding agents working in this repository (Codex/Astra, Claude Code via `@AGENTS.md`, Cursor, etc.).

**Codex size note:** root `AGENTS.md` is intentionally kept near ~35 KiB (critical build/test/arch/retrieval rules retained). Longer validation methodology + the Excalidraw worked example live in `docs/AGENTS.md`. This environment sets `project_doc_max_bytes = 49152` so root (and root+`docs/` when cwd is under `docs/`) are not silently truncated at the 32 KiB default.

## Project Overview

CodeGraph is a local-first code intelligence library + CLI + MCP server. It parses any supported codebase with tree-sitter, stores symbols/edges/files in SQLite (FTS5), and exposes a knowledge graph to AI agents (Claude Code, Cursor, Codex CLI, opencode) over MCP. Per-project data lives in `.codegraph/`. Extraction is deterministic — derived from AST, not LLM-summarized.

Distributed as `@colbymchenry/codegraph` on npm; same binary serves as installer, indexer, and MCP server.

## Build, Test, Run

```bash
npm run build           # tsc + copy schema.sql and *.wasm + build the viewer into dist/; chmods dist/bin/codegraph.js
npm run build:lib       # the viewer's components as @colbymchenry/codegraph-ui (ui/dist) — NOT part of `build`
npm run dev             # tsc --watch
npm run clean           # rm -rf dist

npm test                # vitest run (all)
npm run test:watch
npm run test:eval       # only __tests__/evaluation/
npm run eval            # build then run __tests__/evaluation/runner.ts via tsx

npm run cli             # build then run the local dist binary

# Single test file / pattern
npx vitest run __tests__/installer-targets.test.ts
npx vitest run __tests__/extraction.test.ts -t "TypeScript"
```

`copy-assets` (called from `build`) copies `src/db/schema.sql` and all `src/extraction/wasm/*.wasm` files into `dist/`. **Any new SQL or grammar wasm must be copied or it won't ship.**

One other build step writes into `dist/` and is subject to the same rule: `build:ui` builds the
browser viewer into `dist/viewer/` (never `dist/ui/` — that's the terminal ui).
`scripts/check-ui-build.mjs` asserts both `dist/viewer/` and the copied grammars in
`dist/extraction/wasm/` after every build and inside every release archive — the viewer's syntax
highlighting reads a file with the same grammar the engine indexed it with, so a missing wasm is an
unhighlighted screen as well as an extraction gap.

`npm run build:lib` is separate and does NOT run as part of `npm run build`: it compiles the same
`ui/src` tree a second way, with `svelte-package`, into `ui/dist` — the `@colbymchenry/codegraph-ui`
component library the Pro app imports (task CG-61). `scripts/check-ui-package.mjs` then prunes the
standalone app's shell out of it, resolves the extensionless import specifiers `svelte-package`
leaves behind, and asserts the seam: nothing outside `lib/adapter.js` may reach the network. The
package is **prepared, not published** — `ui/package.json` carries `"private": true` deliberately,
and `scripts/pack-npm.sh` only packs a tarball when `CODEGRAPH_PACK_UI=1`.

Tests run as **two vitest projects** (`vitest.workspace.mts`): `engine` (node) and `ui` (jsdom, the
Svelte plugin, `resolve.conditions: ['browser']`) for the single `__tests__/ui-package.test.ts`.
`npm test` still runs both. The split is not cosmetic — `browser` is a package-resolution
condition, and applied globally it hands the engine's suites the browser builds of
`web-tree-sitter` and friends. The root config (`vitest.config.mts`, `.mts` because the plugin is
ESM-only and the repo is CJS) is the shared base; note that a workspace project **concatenates**
the base's `include` with its own, which is why the `ui` project does not `extends` it.

Node engines: `>=20.0.0 <25.0.0`. There is a hard exit on Node 25.x and below 20 (see `src/bin/node-version-check.ts`).

## Architecture

### Layered pipeline

```
files → ExtractionOrchestrator (tree-sitter) → DB (nodes/edges/files)
              ↓
       ReferenceResolver (imports, name-matching, framework patterns)
              ↓
       GraphQueryManager / GraphTraverser (callers, callees, impact)
              ↓
       ContextBuilder (markdown/JSON for AI consumption)
```

The public API surface is `src/index.ts` — the `CodeGraph` class wires all the layers and re-exports types. Library users only touch this file; the MCP server and CLI also drive it.

### Module layout

- `src/index.ts` — `CodeGraph` class: `init`/`open`/`close`, `indexAll`, `sync`, `searchNodes`, `getCallers`/`getCallees`, `getImpactRadius`, `buildContext`, `watch`/`unwatch`.
- `src/db/` — `DatabaseConnection`, `QueryBuilder` (prepared statements), `schema.sql`, `sqlite-adapter.ts`. Backed by Node's built-in **`node:sqlite`** (`DatabaseSync`) — real SQLite with WAL + FTS5, exposed through a thin better-sqlite3-shaped adapter. The bundled runtime always ships Node ≥22.5, so `node:sqlite` is always available: **no native build step and no wasm fallback**. (Running from source needs Node ≥22.5.) `codegraph status` reports the live backend (`node-sqlite`, the sole backend).
- `src/extraction/` — `ExtractionOrchestrator`, tree-sitter wrappers, per-language extractors under `languages/` (one file per language), plus standalone extractors for non-tree-sitter formats (`svelte-extractor.ts`, `vue-extractor.ts`, `liquid-extractor.ts`, `dfm-extractor.ts` for Delphi). `parse-worker.ts` runs heavy parsing off the main thread.
- `src/resolution/` — `ReferenceResolver` orchestrates `import-resolver.ts` (with `path-aliases.ts` for tsconfig path aliases + cargo workspace member globs), `name-matcher.ts`, and `frameworks/` (Express, Laravel, Rails, FastAPI, Django, Flask, Spring, Gin, Axum, ASP.NET, Vapor, React Router, Next.js — `nextjs.ts`: pages and `route.ts` handlers from files, `router.push` / `redirect` / `NextResponse.redirect` as `navigates` edges, with `next-router-synthesizer.ts` for `<Link href>` — Expo Router, SvelteKit, Vue/Nuxt, Cargo workspaces). Frameworks emit `route` nodes and `references` edges. `callback-synthesizer.ts` holds the whole-graph synthesis passes (`SYNTH_PASSES`, merged in registry order — first-seen wins a duplicate pair) with the language gates; `tier-synthesizer.ts` is the cross-tier pass (a client's literal `fetch`/`axios` path onto its own route, a queue job onto its consumer, a bus / socket event onto its handler — `channel`, `tier`, `registeredAt` on every edge; registered before the in-process emitter pass so its more specific edge wins); `synth-utils.ts` has the helpers they share (`enclosingFn`, `enclosingValue`, `makeLineAt`). Express's `postExtract` composes `app.use('/prefix', router)` mounts onto a mounted file's route names, idempotently (the original path stays in `qualifiedName`).
- `src/graph/` — `GraphTraverser` (BFS/DFS, impact radius, path finding) and `GraphQueryManager` (high-level queries), plus the shared query-time derivations more than one surface renders: `named-symbol-flow.ts` (the one path finder, behind `codegraph_explore`'s Flow section and the viewer's Flow strip), `dynamic-boundary-report.ts` (where the graph stops), `type-hierarchy.ts` (ancestors/subtypes and the implementation count explore prints and the viewer draws),
  `dead-code.ts` (unreferenced symbols, and every reason a candidate is NOT claimed). A derivation that two callers render must live here, not in `ToolHandler` — two derivations eventually disagree.
- `src/context/` — `ContextBuilder` + formatter for markdown/JSON output.
- `src/search/` — full-text query parser and helpers for FTS5.
- `src/sync/` — `FileWatcher` (native FSEvents/inotify/RDCW) with debounce + filter, and git-hook helpers.
- `src/mcp/` — MCP server (`MCPServer`, `tools.ts`, `transport.ts`). `server-instructions.ts` is what the server returns in the MCP `initialize` response — keep it in sync with the user-facing tool guidance.
- `src/installer/` — see below.
- `src/bin/codegraph.ts` — CLI (commander). Subcommands: `install`, `init`, `uninit`, `index`, `sync`, `status`, `query`, `files`, `context`, `affected`, `serve --mcp`.
- `src/ui/` — terminal UI (shimmer progress, worker).
- `src/ui-server/` -- read-only JSON API for the `codegraph ui` browser viewer (`api/`: `node`, `flow`, `map`, `screens`, `steps`, `deadcode`, `trails`, `program`, ...) plus static server; Svelte viewer lives in `ui/` (see `docs/design/codegraph-ui-design-spec.md`). `screens`/`steps`/`program` share one fold (`via`/`when` via `graph/branch-guards.ts`); `api/effects.ts` curates calls that leave the index; `api/route-roots.ts` names where a route's code starts. Derivations rendered by more than one surface belong in `src/graph/`, not `ToolHandler`.
  **Not released yet:** `codegraph ui` / `web` are refused (and hidden from `--help`) unless `CODEGRAPH_UI=1` is set — `src/bin/viewer-gate.ts`. Viewer changelog entries wait in `docs/viewer-launch-changelog.md`, not under `[Unreleased]`. At launch: delete the gate, move those entries back, drop the "not released yet" notes from `site/`.

### NodeKind / EdgeKind

Defined in `src/types.ts`. Both extractors and resolvers must use these exact strings.

- **NodeKind**: `file`, `module`, `class`, `struct`, `interface`, `trait`, `protocol`, `function`, `method`, `property`, `field`, `variable`, `constant`, `enum`, `enum_member`, `type_alias`, `namespace`, `parameter`, `import`, `export`, `route`, `component`, `union`.
- **EdgeKind**: `contains`, `calls`, `imports`, `exports`, `extends`, `implements`, `references`, `type_of`, `returns`, `instantiates`, `overrides`, `decorates`.

... (188 lines truncated)
</file>

<file path="BUNDLING.md">
# Distribution: self-contained bundles

CodeGraph ships a **vendored Node runtime** alongside the app. Because Node 22.5+
has a built-in real SQLite (`node:sqlite`, with WAL + FTS5), bundling Node means:

- **No native build** — `better-sqlite3` is gone, so there are zero native addons
  to compile or rebuild.
- **No wasm fallback** — and therefore no more `database is locked` (issue #238).
- **No Node-version dependence** — the app always runs on the bundled Node,
  whatever the user has (or doesn't have) installed.

## What's in a bundle

Built by [`scripts/build-bundle.sh`](scripts/build-bundle.sh) — one archive per
platform, identical recipe (only the Node download differs):

```
codegraph-<target>/
  node | node.exe          # official Node runtime for <target>
  lib/
    dist/                  # compiled app (+ tree-sitter .wasm grammars, schema.sql)
    node_modules/          # production deps only (pure JS / wasm — portable)
  bin/
    codegraph | codegraph.cmd   # launcher → runs the bundled Node with the app
```

Targets: `darwin-arm64`, `darwin-x64`, `linux-x64`, `linux-arm64`, `win32-x64`,
`win32-arm64`. Unix targets produce `.tar.gz` (shell launcher); Windows produces
`.zip` (`node.exe` + a `.cmd` launcher).

```bash
scripts/build-bundle.sh linux-x64            # -> release/codegraph-linux-x64.tar.gz
scripts/build-bundle.sh win32-x64            # -> release/codegraph-win32-x64.zip
```

Because dropping better-sqlite3 left **zero native addons**, building a bundle is
pure file-packaging — **any** target builds on **any** OS (the whole matrix builds
on one Linux runner). Cross-compilation isn't a concern; only *run-testing* a
bundle needs the target platform (or emulation, e.g. `docker run --platform
linux/amd64`).

## Install channels (all deliver the same bundle)

1. **`curl | sh`** ([`install.sh`](install.sh)) — no Node required; ideal for a
   fresh Linux VPS over SSH. Detects os/arch, pulls the archive from GitHub
   Releases, symlinks `codegraph` onto PATH. Re-run to upgrade; `--uninstall` to
   remove.
2. **npm** ([`scripts/npm-shim.js`](scripts/npm-shim.js)) — preserves
   `npm i -g @colbymchenry/codegraph`. The main package is a tiny shim; the
   bundles ship as per-platform `optionalDependencies`
   (`@colbymchenry/codegraph-<target>` with `os`/`cpu`), so npm installs only the
   matching one. The shim — run by the user's Node — execs the bundle, so the
   real work runs on the bundled Node 24. Works even on old Node. On Windows it
   invokes the bundled `node.exe` against the app entry directly (not the `.cmd`
   launcher) — modern Node throws `EINVAL` when asked to spawn a `.cmd`/`.bat`.
3. **Windows** ([`install.ps1`](install.ps1)) — `irm … | iex`; same flow as
   install.sh (detect arch, pull the `.zip` from Releases, add to PATH).
4. **Homebrew / Scoop** — TODO (tap + cask pointing at the Release archives).

## Release pipeline

[`.github/workflows/release.yml`](.github/workflows/release.yml) — manually
triggered. Reads the version from `package.json`, builds every platform bundle on
one runner, creates the GitHub Release (notes from `CHANGELOG.md`), and publishes
the npm shim + per-platform packages. Requires the `NPM_TOKEN` repo secret.

Still TODO:
- **Code signing** — the main gap for "download & run": macOS Gatekeeper needs a
  Developer ID + notarization; Windows needs Authenticode. Homebrew softens the
  macOS case (handles quarantine).
- Retire the now-vestigial Node-version gate in `src/bin/codegraph.ts` — the
  bundle always runs Node 24, and the npm shim does no tree-sitter work.
- Re-wire `npm uninstall` cleanup (the agent-config `preuninstall`) through the
  shim — the generated main package doesn't carry it.
</file>

<file path="CHANGELOG.md">
# Changelog

All notable changes to CodeGraph are documented here. Each entry also ships as
a [GitHub Release](https://github.com/colbymchenry/codegraph/releases) tagged
`vX.Y.Z`, which is where most people will look.

Each release opens with a short **Highlights** list — the handful of things most
users will notice — followed by the full notes.

This project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/)
and adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixes

- A Python module member used through the imported module, like `generic.ObjectEditView` after `from netbox.views import generic`, `serializers.ValidationError` or `utils.assert_deserialize(…)`, now also follows the package's re-exports to its definition. Before, netbox's view classes lost their `generic.*` base classes, and mealie's test helpers called through `utils.` went unresolved.
- A Python name imported from a package now follows the package's re-exports to where it's defined. That covers both `from .users import *` and `from .tokens import Token` in its `__init__.py`. Before, httpx's own tests' `httpx.Client(…)` and `httpx.URL(…)`, pytest's `pytest.raises(…)` and `pytest.param(…)`, and netbox's `from users.models import User` went unresolved or to a same-named class elsewhere, such as a test's `User` or an Alembic migration's copy of a model.
- In NestJS projects, the provider naming convention (`…Service`, `…Controller`, …) now picks a class only from the reference's own file. Another file's provider is reached through its import, or by ordinary name matching that prefers the nearest declaration. Before, the convention's preference for `*.service.ts` files sent Nest's own specs' `TransientService` and `TestService` to same-named classes in unrelated sample apps.
- In Astro projects, the component-name convention now applies only inside `.astro` files, where components are used. Before, a TypeScript type with a component's name was linked to that component: astrowind's `image?: Image` and `callToAction?: CallToAction` in its type declarations, and starlight's Playwright `page: Page` in its tests.
- In JavaScript and TypeScript, the Express conventions for middleware (`validate…`, `auth`, `logger`, …), controllers and services now pick only the calling file's own declaration. Another file's is reached only through an `import` or `require`. Before, SvelteKit's remote functions linked `validate(arg)` to its config loader's `validate` in another package, and Express's examples linked `logger('dev')` to one example's `logger`.
- An Objective-C class that conforms to a protocol of its own name now links to that protocol instead of to itself. Swift's naming conventions for views, models and controllers also no longer apply to Objective-C code. Before, every one of SDWebImage's `@interface SDDiskCache : NSObject <SDDiskCache>`-style classes implemented itself.
- In Solidity, a call to an overloaded function now reaches the overload whose parameter count it fits, as in the other languages with overloading. Before, OpenZeppelin's `_checkRole(role, _msgSender())` inside the one-argument `_checkRole(bytes32 role)` was linked to itself.
- In JavaScript and TypeScript, the React conventions for hooks (`use…`) and contexts (`…Context`, `…Provider`) now pick only from the reference's own file. Another file's hook or context is reached only through an import. An optional call like `onSuccess?.(…)` now gets the same scope rules as a plain call. Before, trpc's WebSocket adapter's `createContext?.(…)` option linked to an example app's `createContext`, zod's `schemas.ParseContext` linked to the v3 copy instead of v4's, and bulletproof-react's apps linked `useUser()` to one another's.
- In R, a call like `c(1, 2)` is no longer linked to a data variable that happens to share a base function's name, since R skips non-function bindings when it looks up a call. Before, ggplot2's facet tests bound `c <- data_frame(b = 3)`, and every `c(…)` call in those files pointed at that data frame. Functions built by a factory, like ggplot2's `geom_point <- make_constructor(…)`, still resolve.
- In Swift, a call to an overloaded method now reaches the overload whose argument labels it spells, with defaulted parameters optional. Before, only the argument count was compared. Alamofire's `self.tableView(tableView, numberOfRowsInSection:)` inside another `tableView` overload linked to itself, and `cancel(optionallyProducingResumeData:)` linked to `cancel(producingResumeData:)`.
- A Dart `extension on X { … }` with no name is no longer mistaken for the type `X`, and its members are reachable only inside the file that declares it, as in Dart. Before, bloc's linter linked analyzer's `Token` and Dart's `Uri` to small extension blocks, and every flutter_test `find.text(…)` call linked to a `text` getter on another example's `TaskStatus`.
- In Java, a bare type name now resolves only to a type in reach. That is a type in the same package, one imported by name or with `.*`, or a nested type used from inside its owner, from a subclass (anonymous classes included), or written through its owner as in `Outer.Inner`. A constructor no longer stands in for its class, and an enum constant is reached by bare name only inside its enum, in a `case` label, or through a static import. Before, retrofit's `new Retrofit.Builder()` linked to `RequestFactory.Builder`, halo's micrometer `Counter` to its own `Counter` class, and jsoup's `java.lang.Class<?>` to a nested selector class.
- In PHP, an unqualified class name now resolves to the current namespace's class or the one a `use` imports, as PHP does. If the imported class comes from a library, it resolves to nothing in the project. Before, koel's form requests linked `extends Request` to whichever `Request` class was indexed first, and BookStack's controllers linked `Request $request` (Laravel's, by import) to BookStack's own `Request` subclass.
- A call in C code is no longer linked to a C++ class's method, since C has no methods and can't call one. Before, redis's POSIX `read(fd, buf, n)` calls and hiredis's `c->funcs->read(…)` function pointer pointed at a Qt adapter's `read` method.
- In Go, a name written through an imported package from outside the module, like `context.Context`, `http.ResponseWriter` or testify's `require.Contains`, is no longer linked to a project symbol of that name. Before, fiber's `context.Context` parameters pointed at a method `Stream.Context`, its `require.Contains(…)` assertions at an extractor's `Contains`, and gin's `http.ResponseWriter` at its own `ResponseWriter` interface.
- Bare calls in Gradle Kotlin scripts (`build.gradle.kts`), like `plugins { }`, `dependencies { }` or `api(…)`, are no longer linked to a method or property of one of the project's own classes. Build logic's extension functions on Gradle's types still resolve. Before, nowinandroid's build scripts pointed every `plugins { }` and `dependencies { }` block at its build logic's `Graph` class, and every `api(…)` at a lint registry's `api` property.
- In Rust, `Self::Error` in a signature now resolves to the enclosing impl's or trait's own associated type. A path through a generic parameter, like `V::Value`, no longer resolves to an unrelated struct of that name. Before, serde's `Self::Error` signatures pointed at its one `struct Error`, and axum's `Self::Error` at `axum-core`'s error type.
- In Scala, a package object's member now resolves only where it is in scope: in its own package, the packages under it, or a file that imports through that package. Before, cats' laws resolved `Eq`, `Order` and `Monoid` to the `algebra` package object's aliases rather than the `cats` package object's, and sttp's akka tests reached a zio package object's `whenRequestMatches`.
- A type that extends another type of the same name now links to that other type instead of to itself. When the source spells out the qualifier, that qualifier picks between same-named candidates. Before, cats' `trait BigDecimalInstances extends cats.kernel.instances.BigDecimalInstances` and every `trait AllOps … with Functor.AllOps[…]` pointed back at the declaring trait, and Newtonsoft.Json's `JsonConverter<T> : JsonConverter` extended itself.
- In pytest tests, a parameter now takes the class its fixture returns, so a call on it reaches that class's method. If the class comes from a library, the call no longer reaches the project's only method of that name. Fixtures a `conftest.py` pulls in with `from … import *` or `pytest_plugins` now count as in reach. Before, flask's `runner.invoke(…)` on click's `CliRunner()` linked to the project's `FlaskCliRunner.invoke`, and `@app.get(…)` on a `Flask(…)` fixture linked to an unrelated `get`.
- What a Svelte component's instance `<script>` or a Vue component's `<script setup>` declares is now private to that component. Only a Svelte `<script module>`, a plain Vue `<script>`, or a type a `<script setup>` exports can be reached from another file. Before, shadcn-svelte's `<Item.Root>` linked to a `type Item` that one example component declares for itself, and halo's `isActive` imported from its editor core linked to a tab component's local value.
- In JavaScript and TypeScript, a name the calling function binds itself, as a parameter or a plain `var`/`let`/`const` above the reference, now means that local instead of a same-named function elsewhere in the file. Before, every lodash helper's `object` parameter linked to a `function object() {}` declared inside `runInContext`, and zod's `new Class(…)` linked to an unrelated `Class` when `Class` was the function's parameter. Destructured hook results like `const { t } = useI18n()` still link to the function they come from.
- Framework name conventions for Django, FastAPI, Flask, ASP.NET, Gin, SwiftUI and Vapor now only pick a class the reference can see. Examples of these conventions are "a `…View` is a view", "a `…Service` is a service" and "a capitalized name is a model". The pick starts from the reference's own file and then its package, and never takes a class declared inside some function or nested in another file's class. Before, Django REST framework's tests linked each file's own `MockView` and `Serializer` to another file's, and netbox's tests linked `TestForm()` to a form declared inside a different test function.
- In Rust projects, a struct, handler or service name no longer resolves to an item declared inside some function body, and a file's own item comes before any other crate's. Before, axum's examples' `Uri` linked to a `struct Uri` declared inside a routing test, tokio's runtime `Handle` linked to `tokio-test`'s, and ripgrep's `Glob { … }` in globset linked to the CLI flags' `Glob`.
- A method that calls a same-named method on another expression's result is no longer linked to itself in any language. Examples are Scala's `requestToArmeria(request).execute()` inside `execute()`, Rust's `self.0.into_route(state)` inside `into_route()`, and Kotlin's `this@Buffer.write(…)` from an inner object. A value whose initializer chain calls a same-named method, like sttp's `val response = basicRequest.get(…).response(…)`, no longer links to itself either.
- In Spring projects, a class name now resolves to the one in the reference's own file or package before any guess by folder convention. A class nested inside another file's class is never reached by its bare name. Before, every MyBatis `Example` class's `new Criteria()` in mall linked to the first `Example`'s nested `Criteria`, and halo's Lombok `@Builder` linked to a nested `Builder` class elsewhere.
- A method that hands its call on to another object is no longer linked to itself. In TypeScript and JavaScript, a call through `this.<field>` or `window.<x>` counts as recursion only when the field is declared as the method's own class. A guess from a receiver's name alone never lands on the calling method. Before, BookStack's `toggle()` doing `this.container.classList.toggle('open')`, `listen()` doing `window.$events.listen(…)`, and `FileStorage::delete` doing `$storage->delete($path)` each pointed at themselves.
- C# names now follow the language's scopes. A block `namespace X { … }` qualifies only the types inside it, so a type declared after the block, or in a file's second namespace, is no longer filed under the first. A namespace written inside another is `Outer.Inner`. A `using` links to the project's namespace instead of another file's `using` of the same name. A `global using` applies only within its own project. A nested type is reachable by bare name only from inside its owner or a type deriving from it, including through another partial part. Before, serilog's `Guard` was filed under `JetBrains.Annotations`, its tests' `Some.InformationEvent()` went to the performance tests' `Some`, and AutoMapper's same-file `new Source()` could reach another test class's nested `Source`.
- A function or name passed as a value now resolves to what is in scope where it's written. A function nested inside another function is only reachable from inside it. In Python, a parameter or local of the same name is that local. A pytest fixture is a test's parameter only in its own module or under its `conftest.py`. Before, httpx's `self._build_auth(auth)` linked to an `auth` a test defines inside another function, and `auth_flow(self, request)` handing `request` on linked to the package's `request()` function.
- In Python, an attribute passed as a value through an object nothing types, like netbox's `device=self.parent.device`, is no longer linked to the project's only method of that name when the object isn't named after the method's class. Before, netbox's model-field reads went to a GraphQL filter's `device` method, and healthchecks' `check.last_ping` went to a notification transport's.
- In Scala, a kind-projector placeholder in a type, like `Align[Either[A, *]]`, is no longer linked to an operator method named `*`. A symbolic name in a type, like cats' `F ~> G`, now resolves only to a type.
- C# type names now follow namespaces. A type is in reach from its own namespace or one nested inside it, or through a `using` of its namespace. Also counted: a project-wide `global using`, the project's `<Using>` entries, the SDK's implicit usings, or an alias that names it. Before, Newtonsoft's `async Task` tests linked `Task` to a test class of that name in another namespace, and AutoMapper's DTOs linked to another namespace's `BaseEntity`.
- Rust type and function names now follow Rust's scoping. A name from another file counts only when a `use` brings it in (or a `*` glob over its module). One imported from outside the project, like `use std::task::{Context, Poll}` or `use futures::Stream`, means that outside item. A path names its module: `io::Result` isn't an unrelated `Result` alias elsewhere, and `std::io::Error` is std's. On tokio, over 1,200 `io::Result` and 600 `Context` references had been landing on private project types.
- In Java, C#, Kotlin, Swift, Scala, Dart and VB.NET, a call now reaches the overload whose parameters fit its arguments, not whichever same-named overload was indexed first. For example, `HashCodeBuilder.reflectionHashCode(this)` now reaches the one-argument overload with varargs, not a three-parameter one. Each overload's callers are now its own.
- A method that calls another overload of itself now links to that overload rather than to itself. An example is `toInstant(instant)` returning `toInstant(instant, Instant.EPOCH)`. The fuller overload now lists its convenience overloads among its callers, so its impact includes them. This applies to Java, C#, Kotlin, Swift, C++, Scala, Dart and VB.NET. Real recursion is unchanged.
- In a project with a React front end, the React rules for hooks (`use…`) and contexts (`…Context`, `…Provider`) no longer apply to backend code. In halo, a Spring app with a React UI, Java imports such as `SecurityContext` and `ObjectProvider` had been handled as React contexts.
- In a project with a Vue front end, the backend's calls no longer land on Vue components. mealie's Python `QueryFilterBuilder(…)` had been linking to the `QueryFilterBuilder.vue` component. The Vue rules (compiler macros, Nuxt auto-imports, components by name) now apply only to the app's scripts.
- Production code no longer links to a same-named symbol inside a test suite, since tests aren't built into the program. Before, typeorm's `Record<string, …>` types reached a test entity called `Record`, and okhttp's sample `@Override` annotations reached a test's nested `Override` class. Test-support code a project ships, such as a `testing/` folder or a `*-test` module, stays in reach.
- A Dart call like `ext.endsWith(".avi")` or `map.putIfAbsent(…)` on a value whose type isn't known now counts as Dart's own String, List or Map method. It no longer lands on a project method of the same name. A Dart extension is also matched by the type it extends, not by its own name, so getx's `ext.endsWith` on a String stopped reaching `extension RxStringExt on Rx<String>`.
- Kotlin calls inside a DSL lambda now reach the lambda's own receiver. That receiver comes from the function the lambda is passed to, even through a typealias like koin's `Definition<T> = Scope.(…) -> T`. It also wins over other types the project uses as lambda receivers elsewhere. On koin, over 2,000 `get()` calls in `single { … }` now reach `Scope.get` instead of `Koin.get`; on Exposed, `varchar(…)` inside a table object reaches `Table.varchar`; on kotlinx.coroutines, `launch { }` reaches `CoroutineScope.launch`.
- A Swift call on a property declared with a type, like Kingfisher's `var cache: ImageCache!` or `self.storage.write(…)`, now reaches that type's method or one it inherits. It no longer lands on a subclass override in a test, or on another type's method of the same name.
- Calls in your own JavaScript no longer link to a same-named function inside a vendored minified script, like a `*.min.js` or a bundle made of a few enormous lines. Those names are mangled. In healthchecks, every jQuery `$(…)` call had gone to a one-letter helper inside `bootstrap-native.min.js`.
- A Swift call on a value built on the spot, like `JSONDecoder().decode(…)` or `Realm().create(…)`, now resolves to that type's method, or to one it inherits. It no longer lands on some other type's method of the same name: Vapor's `JSONDecoder().decode` calls had gone to a request's private container.
- A bare Lua call like `ipairs(t)`, `error("…")` or busted's `setup()` now means Lua's own function unless the file defines one. It no longer lands on a table method of the same name: telescope's `ipairs` calls had gone to a linked list's `ipairs`, and kong's `error` calls to its response module. A function's own alias of a host table member, like `local get_query = kong.request.get_query`, is now followed as well.
- A C++ call into a macro-opened namespace, like `fmt::format("{}", x)`, now picks the overload its arguments fit. Before, the first overload indexed won: fmt's 1,400 `fmt::format` calls all reached the `text_style` overload in `color.h`. A narrow string literal now fits a narrow format string, a wide `L"…"` fits the wide overload, and the argument count has to fit too.
- Calls inside an inline route handler now keep their receivers, so they resolve like any other method call. Before, Hono's `app.get('/', (c) => c.text('Hello'))` linked the route to the one other `text` method in the project, its client's `ClientResponse.text`; that happened in over 400 routes. A call like `userService.lookup(id)` reaches the service it names.
- A Scala chained call like `xs.map { … }` no longer lands on an object that happens to be named `map`, as with cats' `alleycats.std.map` and its `syntax`/`instances` objects. A type or object in a chain is only matched when the receiver names what holds it, as in `sttp.client4.Response(…)`.
- A Python call to a name the function or module binds itself now means that local value, not a same-named function in another file. In Django REST Framework's tests, `view = SomeView.as_view()` followed by `view(request)` had pointed at one test file's `def view`. The same goes for a parameter or a `for`/`with … as` target. A pytest fixture a test takes as a parameter is still the fixture.
- A method call on a variable is no longer guessed to be a test double's method just because the double has the only method of that name. That covered classes named `Mocked…`, `Fake…`, `Stub…` or `Dummy…`: django-allauth's `resp.json()` calls had all gone to its `MockedResponse`. A test that names the double still calls it.
- Kotlin imports now decide what a name means, as Java imports already do. `import java.net.Proxy` or `import org.mockito.Mockito.mock` no longer links to a same-named project symbol, and a member the file declares itself still comes first. An `import x.Foo` picks the right one of several same-named classes: on okhttp, `MockResponse.Builder()` and `Request.Builder()` now reach their classes. A renaming import like `import …internal.unsafeFlow as flow` means the function it names.
- In Java, a class you import from outside your project now owns its name. After `import java.lang.reflect.Field;` the file's `Field` no longer links to a project class that happens to share the name. In gson that was a test's nested `Field` class; in jsoup's W3C converter it was jsoup's own `Document` and `Element`. A static import like `import static org.mockito.Mockito.verify;` is covered the same way.
- Java enum constants and Kotlin enum entries with a body of their own now have their methods in the graph. Examples are `PLUS { int apply(…) { … } }` and `NewBuffer { override fun pipe() … }`. Before, those methods were missing and every call inside them was dropped. jsoup's HTML tokenizer and tree builder are written this way, so over 2,000 of their calls were invisible. Re-index to pick this up.
- Scala calls no longer land on another test's local value. A `val f` written inside one `test("…") { }` block was being picked for a lambda parameter `f` in another suite, and even for `f(…)` in cats' core library. A package import like `import cats.syntax.all._` no longer puts every class's members in scope. Members that really are in scope now resolve: those of an imported package object's parent types (`import sttp.client4._` gives `SttpApi`'s `multipart`), and of the file's own package object.
- A barrel's `export * as core from './core'` now exports only `core`, not everything in `./core`. In zod, `z.string()` and `z.number()` had been landing on same-named regex constants deep in its core module instead of the schema functions. Calls through `import * as ns` also find members a barrel forwards by name (`export { safeParse } from '../core'`). They follow a namespace path like `z.coerce.number()` too.
- JavaScript calls through CommonJS `require` bindings now reach the right function. `var express = require('../')` follows `module.exports` through an `index.js` to the function it exports, and every binding in a `var a = require('x'), b = require('y')` list is read. `require('./utils').setCharset` means that module's `setCharset` rather than its first export, and a call to a package from outside the project (`supertest`, `node:assert`) is no longer an edge to the local variable. On express, over 700 `express()` calls now reach `createApplication`.
- Lua calls made through a `local` alias now reach the function it names. That covers `local splitn = require("kong.tools.string").splitn`, a module member such as `utils.select_listener`, and a function a module exports under another name (`return { check = check_phase }`). Aliases of Lua's own functions, such as `local type = type` or `local fmt = string.format`, no longer show up as calls into your project. On Kong that is over 1,000 calls that now reach their real function, and about 5,000 fewer dead-end edges.
- React Router links and `navigate(…)` calls written through a route-config object, like bulletproof-react's `paths.app.discussion.getHref(id)`, now reach the route they open. A `<Link>` with an arrow-function attribute before its `to`, such as `onMouseEnter={() => …}`, is read too.
- C++ classes written around macros and preprocessor conditionals now keep their members. These include an access specifier spelled as a macro (`JSON_PRIVATE_UNLESS_TESTED:`), an attribute macro after a template head or a doc comment, and an `#if` in the middle of a declaration, such as inside a constructor's initializer list. The first branch of a mid-declaration `#if` is the one indexed. nlohmann/json's `basic_json` class used to be lost whole and now has its roughly 390 members. Files with a parse error dropped on redis, curl, pybind11 and leveldb, and no file got worse. Re-index after upgrading.
- Kotlin files using newer syntax now keep their classes intact. That covers `when` guard conditions (`is X if cond ->`), `..<` ranges, multi-dollar strings (`$$"…"`) and nullable receivers in function types (`T?.() -> R`). Before, the class around such code could come out as a scatter of loose functions. On Exposed, files with a parse error dropped from 65 to 43, and on kotlinx.coroutines from 50 to 46. Re-index after upgrading.
- A call through a class name, like `THorse.Get(…)`, `MyView.as_view()` or `ColorChoices.values()`, now reaches the class method that class inherits. The inheritance is read from the class declarations themselves, in Pascal, Python, Ruby, PHP, TypeScript/JavaScript and the Java family. Before, such a call was resolved by guessing from the name. On Horse, `THorse.Get('/ping', …)` used to land on a route-group interface's `Get` 120 times. Re-index after upgrading.
- In Objective-C, `[super init]` and other messages to `super` now reach the superclass's method, never the sending class's own override. This also works where the index lost the `@implementation`'s range. On SDWebImage, `NSObject` subclasses' `[super init]` used to land on `SDDiskCache`'s `init`, and `[self class]` in tests on a proxy class's `class`. On AFNetworking, a serializer's `[super encodeWithCoder:]` now reaches its superclass. Re-index after upgrading.
- In Solidity, a call with no receiver now reaches a function of the contract around it or of one it inherits. On OpenZeppelin, `_msgSender()` in contracts built on `Context` used to land on `ERC2771Context`'s override 83 times. In Erlang, a call to another module's function now follows the file's `-import(Mod, [f/N])`. On cowboy, `-import(req_SUITE, [do_get/3])` calls used to land on another suite's `do_get/3`. A bare call with no such import no longer links to some other module. Re-index after upgrading.
- Calls on a library's own types and modules no longer land on a project method that happens to share the name. In Rust, `Vec::new()`, `String::from(…)` and module paths like `task::spawn(…)` stay the standard library's. A later link of a multi-line Rust or Go chain now counts as a chained call, named after the chain's first line. In Go, `w.Header().Get(…)` is net/http's. In R, a plain call like `range(x)` is a function, not an object's method. In JavaScript, `response.text()` / `.json()` is fetch's. On tokio, `task::spawn(…)` used to land on `TaskTracker::spawn` 300 times. On ggplot2, `range(…)` used to land on a coordinate system's `range` method. Re-index after upgrading.
- In C and C++, a qualified name like `fmt::format` now reaches a declaration inside a namespace the library opens with a macro, like fmt's `FMT_BEGIN_NAMESPACE`, pybind11's `PYBIND11_NAMESPACE_BEGIN(…)` or rapidjson's and spdlog's `…_NAMESPACE_BEGIN`. It also works through a namespace alias like `namespace py = pybind11;`. On fmt, 1,728 `fmt::format(…)` calls used to link to nothing, and so did about 1,400 `py::…` calls on pybind11.
- A method guessed from a receiver's name no longer lands on a request handler the web framework dispatches to, such as a Django or DRF view's `post` / `get` or a controller's `update` / `destroy`. It also no longer lands on a test double the calling file never mentions. On django-allauth, tests' `client.post(…)` used to land on a `ClientRegistrationView` 425 times. On mealie, `response.json()` used to land on a test's `_FakeHTTPResponse` 424 times. In Python, `site = Site.objects.create(…)` now makes `site` a `Site`, so `site.save()` reaches the model's own `save`. Re-index after upgrading.
- Kotlin infix calls, like `Users.id eq id1` or koin's `single { … } bind MyApi::class`, are now recorded as calls to the infix function. Before, they had no callers at all. On Exposed, `eq` now shows over a thousand callers. Bit operations on numbers (`x and 0xff`, `h shr 8`) are left to Kotlin's own operators, even where the project defines a same-named extension. Re-index after upgrading.
- Kotlin code using an infix function whose name starts with `e`, like Exposed's `Users.id eq id1`, now parses cleanly. Before, the rest of such a line was a parse error, and in a file with many of them the whole class around it could be lost. On Exposed, files with a parse error dropped from 229 to 71. Re-index after upgrading.
- In Kotlin, a call with no receiver now reaches a method of another class only when that class is in reach. That means a class, an anonymous `object : Base()` or an extension function's receiver around the call, what those inherit, or the receiver of a DSL lambda (koin's `single { get() }` runs on a `Scope`, Exposed's `withTables { … }` on a transaction). An object member the file imports is in reach too. Kotlin's own `error(…)`, `require(x >= 0) { … }` and `check(…)` no longer land on a project class's method of that name. On koin, `module { … }` in one test used to land on another test class's private `module` over 260 times, and inside a lambda `get()` landed on the wrong class's `get`. Re-index after upgrading.
- In C#, Java and Kotlin, a call through a field, property or parameter now lands on the method of the type it is declared with. That includes a type inherited from a base class with its type argument filled in, a generic or `for`-each declaration, a C# `using` alias, and a type parameter's bound. A call no longer falls back to a guess at some project class's same-named method, and a type from outside the project gives no link. On Newtonsoft.Json, `_innerWriter.WriteValue(…)` inside a writer wrapper used to land on the wrapper's own `WriteValue`, and a `TextWriter`'s `Write(…)` on a test writer's. On commons-lang, a `DateFormat` field's `parse(…)` used to land on the project's `DateParser` 284 times.
- C# members of an interface are now public and types declared without a modifier are now internal, as the language defines. A call on an interface-typed field now reaches the interface's method, where it used to find nothing. A guess from a receiver's name now weighs only the owner type's own name, not its namespace. Standard .NET names like `ToString`, `Add` and `Write` need a receiver named after the owner. In every language, a guess from production code no longer lands on a mock or helper defined in a test suite. Re-index after upgrading.
- In Swift, a call written with no receiver, or through `self.` or `super.`, now reaches only a member of the type around it or of what that type inherits or conforms to, and the nearest override wins. A standard-library name later in a chain (`axis.entries.removeAll()`, `names.contains(x)`) no longer lands on a project type's method, unless the receiver or the call's argument label points to it. On Charts, `min(a, b)` and `max(a, b)` used to land on a range type's `min` field and a `Sequence` extension, and `super.init(…)` on an Objective-C demo's `init` over 170 times. A global in a playground or a test target is no longer linked from the main code. Re-index after upgrading.
- A call on a variable declared with a type from outside the project (`List<String> list`, `var sb = new StringBuilder()`, `signer = TimestampSigner()`) no longer lands on a project type's method with the same name. On gson, `list.add(…)` used to land on a project list wrapper; on commons-lang, `s.length()` and `buffer.append(…)` on project classes. In Python, a keyword argument inside a call (`prefix=IPNetwork(…)`) is no longer taken for an assignment to that name.
- Kotlin classes whose primary constructor sits on the line after the class name, before a supertype list (`expect open class ByteString` / `internal constructor(…) : Comparable<ByteString>`, common in Kotlin Multiplatform code), no longer lose their members to loose functions. A call later in a chain to a Kotlin standard-library function (`apply`, `let`, `toString`, `map`, `contains`…) no longer lands on a project type's same-named method. On okhttp, `.apply { … }` used to land on `ConnectionSpec.apply`. Re-index after upgrading.
- In Rust and Go, a call later in a chain, like `sym.filename().map(…)` or `c.Flags().String(…)`, no longer lands on the project's own method of that name when the name is a standard-library one (`unwrap`, `clone`, `map`, `iter`, Go's `String` or `Error`). A plain call like `get(handler)` or `drop(x)` never lands on a method. On tokio, `.map(…)` on an `Option` used to land on `MutexGuard::map`; on axum, the router's `get(handler)` on a cookie jar's `get`; on ripgrep, `.clone()` on an error type.
- A call on a type from outside the project, like `Integer.valueOf(…)`, `Arrays.asList(…)`, `Object.assign(…)` or Delphi's `Exception.Create(…)`, no longer lands on the project's own method with that name. On commons-lang, `Integer.valueOf` used to land on `StringUtils.valueOf` over 800 times. Go's exported variables and Pascal's capitalized parameters and locals are not mistaken for type names.
- Imports through a tsconfig or jsconfig path alias now use the config nearest the importing file, so each app in a monorepo resolves its own `@/…` or `~/…` alias. On bulletproof-react and trpc's examples, those imports used to fail or land in a different app.
- React Router data-router routes are named by their full path: nested `children` paths are joined to their parent's, `path: paths.app.root.path` constants are read, and `lazy: () => import('./routes/x')` routes link to the module's component. A guard wrapper like `<ProtectedRoute>` no longer stands in for the page. On bulletproof-react, every route now has its real path and page.
- In JavaScript, TypeScript and Vue, a call through a name destructured from a composable or custom hook, like `const { getDefaultActivityRoute } = useDefaultActivity()` or `const { t } = useI18n()`, now reaches the function the hook returns. These calls used to resolve to nothing. mealie, elk, halo and excalidraw each gained dozens to over a hundred such links.
- In JavaScript and TypeScript, a module's top-level function, variable or type that the module doesn't export is no longer linked from other files. Every form of export still counts: the `export` keyword, `export { … }` lists, `export default`, and a default-exported object. On typeorm, test fixtures' local `ColumnMetadata` used to capture `import { ColumnMetadata } from "typeorm"`; on sveltekit, an unexported `resolve` collected other files' `resolve(…)` calls; on zod, a local `z` collected the `zod` package imports.
- Flow-typed JavaScript files (those with `@flow` in their header comment) are now parsed like TypeScript, so type annotations like `render(): React.Node` no longer cut classes short. This mostly affects React Native code: on React Native's own libraries the graph gained over 8,000 links, and component classes keep their methods. Files without the pragma are unchanged. Re-index after upgrading.
- In Scala, a call reached by its name alone now stays in reach. A name that the enclosing function binds as a parameter or local (`f(true)` for `f: A => B`) is that local. A call later in a chain, like `fa.iterator.map(…)`, reaches only a member of what its receiver is named after. A plain call reaches only the enclosing class and its supertypes (an anonymous subclass's base included), a companion, or an imported object. On cats, parameter calls like `f(a)` used to land on a case class's field `f` over 400 times, and chained `.map(…)` on one ops class's `map`.
- A link made by a framework or bridge resolver now records which one made it (`metadata.framework`, such as `swift-objc-bridge` or `react-native-bridge`), as the README describes. Before, only synthesized event and view channels were named.
- ASP.NET apps built with FastEndpoints now have their routes: each endpoint class's `Get(…)` / `Post(…)` in `Configure()` becomes a route linked to its own `HandleAsync` / `ExecuteAsync`, including paths kept in a request class's `Route` constant. ardalis/CleanArchitecture went from no routes to 24. Minimal API routes written without a leading slash (`app.MapGet("api/todos", …)`) are now named `/api/todos`.
- Vapor routes whose handler is a trailing closure (`app.get("hello") { req in … }`), WebSocket routes (`app.webSocket("chat") { … }`) and `routes.on(.POST, "x", use: handler)` registrations are now found. Only routes with a `use:` handler were read before: the Swift Package Index server went from 13 routes to 34, and a WebSocket-only chat server from none to one.
... (1142 lines truncated)
</file>

<file path="CLAUDE.md">
# CLAUDE.md

Claude Code project guidance for this repository.

Primary instructions live in the canonical agent guide — import it:

@AGENTS.md

## Claude-only notes

- Prefer the repo-root `AGENTS.md` as the source of truth for build/test/architecture/house rules. Edit that file (not this wrapper) when guidance changes.
- Claude Code can `@`-import nested guides too (e.g. `@docs/AGENTS.md`) when working on design/eval docs; Codex loads nested `AGENTS.md` automatically when the session cwd is under that directory.
- Do not reintroduce a duplicated `## CodeGraph` MCP tool-guidance block here — `src/mcp/server-instructions.ts` is the single source of truth (issue #529); the installer strips legacy marker blocks on upgrade.
</file>

<file path="install.ps1">
# CodeGraph standalone installer for Windows (PowerShell).
#
# Downloads a self-contained bundle (a vendored Node runtime + the app) from
# GitHub Releases. No Node.js, no build tools required.
#
#   irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex
#
# Upgrade with `codegraph upgrade` (or just re-run this). To uninstall: remove
# $env:LOCALAPPDATA\codegraph and drop its \current\bin entry from your user PATH.
#
# Environment:
#   CODEGRAPH_VERSION      release tag to install (default: latest)
#   CODEGRAPH_INSTALL_DIR  install location (default: %LOCALAPPDATA%\codegraph)

$ErrorActionPreference = 'Stop'
$repo = 'colbymchenry/codegraph'
$installDir = if ($env:CODEGRAPH_INSTALL_DIR) { $env:CODEGRAPH_INSTALL_DIR } else { Join-Path $env:LOCALAPPDATA 'codegraph' }

# 1. Detect architecture -> target matching the release archives.
$arch = if ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture -eq 'Arm64') { 'arm64' } else { 'x64' }
$target = "win32-$arch"

# 2. Resolve the version (latest release unless pinned).
$version = $env:CODEGRAPH_VERSION
if (-not $version) {
  $version = (Invoke-RestMethod "https://api.github.com/repos/$repo/releases/latest").tag_name
}
if (-not $version) { throw "codegraph: could not resolve latest version; set CODEGRAPH_VERSION." }

# 3. Download + extract the bundle into a stable 'current' dir (overwritten on upgrade).
$url = "https://github.com/$repo/releases/download/$version/codegraph-$target.zip"
Write-Host "Installing CodeGraph $version ($target)..."
$tmp = Join-Path $env:TEMP ("cg-" + [guid]::NewGuid().ToString())
New-Item -ItemType Directory -Force -Path $tmp | Out-Null
$zip = Join-Path $tmp 'cg.zip'
Invoke-WebRequest -Uri $url -OutFile $zip

$dest = Join-Path $installDir 'current'
if (Test-Path $dest) { Remove-Item -Recurse -Force $dest }
New-Item -ItemType Directory -Force -Path $dest | Out-Null
Expand-Archive -Path $zip -DestinationPath $dest -Force
# Archives contain a top-level codegraph-<target>\ dir; flatten it.
$inner = Join-Path $dest "codegraph-$target"
if (Test-Path $inner) {
  Get-ChildItem -Force $inner | Move-Item -Destination $dest -Force
  Remove-Item -Recurse -Force $inner
}
Remove-Item -Recurse -Force $tmp

# 4. Put the launcher dir on the user's PATH.
$binDir = Join-Path $dest 'bin'
$userPath = [Environment]::GetEnvironmentVariable('Path', 'User')
if (($userPath -split ';') -notcontains $binDir) {
  [Environment]::SetEnvironmentVariable('Path', "$binDir;$userPath", 'User')
  Write-Host "Added $binDir to your PATH (restart your terminal to pick it up)."
}

Write-Host "Installed to $dest"

# 5. Warn if a different codegraph earlier on PATH will shadow this install.
# Most often a stale `npm i -g @colbymchenry/codegraph`, whose launcher keeps
# running its own version-pinned bundle — so `codegraph --version` disagrees
# with what we just installed (issue #1071). Check both the persisted PATH a
# fresh shell sees (Machine + User) and this session's PATH (catches dirs a
# shell profile injects, e.g. conda / npm).
$expected = Join-Path $binDir 'codegraph.cmd'
function Find-FirstCodegraph([string]$pathStr) {
  foreach ($dir in ($pathStr -split ';')) {
    if (-not $dir) { continue }
    foreach ($leaf in @('codegraph.cmd', 'codegraph.exe', 'codegraph.bat', 'codegraph.ps1')) {
      $cand = Join-Path $dir $leaf
      if (Test-Path -LiteralPath $cand) { return $cand }
    }
  }
  return $null
}
$machinePath = [Environment]::GetEnvironmentVariable('Path', 'Machine')
$freshPath = ((@($machinePath, [Environment]::GetEnvironmentVariable('Path', 'User')) | Where-Object { $_ }) -join ';')
$shadow = $null
foreach ($winner in @((Find-FirstCodegraph $env:Path), (Find-FirstCodegraph $freshPath))) {
  if ($winner -and ($winner -ne $expected)) { $shadow = $winner; break }
}
if ($shadow) {
  Write-Warning "Another codegraph is earlier on your PATH and will run instead of this install:"
  Write-Warning "  $shadow"
  Write-Warning "  (this install: $expected)"
  Write-Warning "If 'codegraph --version' shows an unexpected version, remove the other copy"
  Write-Warning "(e.g. 'npm rm -g @colbymchenry/codegraph') or put '$binDir' first on your PATH."
}

Write-Host "Run: codegraph --help"
</file>

<file path="install.sh">
set -eu
REPO="colbymchenry/codegraph"
INSTALL_DIR="${CODEGRAPH_INSTALL_DIR:-$HOME/.codegraph}"
BIN_DIR="${CODEGRAPH_BIN_DIR:-$HOME/.local/bin}"
if [ "${1:-}" = "--uninstall" ]; then
  rm -f "$BIN_DIR/codegraph"
  rm -rf "$INSTALL_DIR"
  echo "CodeGraph uninstalled (removed $INSTALL_DIR and $BIN_DIR/codegraph)."
  exit 0
fi
os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Darwin) os="darwin" ;;
  Linux)  os="linux" ;;
  MINGW*|MSYS*|CYGWIN*)
    echo "codegraph: on Windows, open PowerShell and run:" >&2
    echo "  irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex" >&2
    exit 1
    ;;
  *) echo "codegraph: unsupported OS '$os'." >&2; exit 1 ;;
esac
case "$arch" in
  arm64|aarch64) arch="arm64" ;;
  x86_64|amd64)  arch="x64" ;;
  *) echo "codegraph: unsupported architecture '$arch'." >&2; exit 1 ;;
esac
target="${os}-${arch}"
version="${CODEGRAPH_VERSION:-}"
if [ -z "$version" ]; then
  version="$(curl -fsSLI -o /dev/null -w '%{url_effective}' "https://github.com/$REPO/releases/latest" \
    | sed -n 's#.*/releases/tag/##p')"
fi
if [ -z "$version" ]; then
  version="$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" \
    | sed -n 's/.*"tag_name": *"\([^"]*\)".*/\1/p' | head -n1)"
fi
[ -n "$version" ] || { echo "codegraph: could not resolve latest version; set CODEGRAPH_VERSION (e.g. CODEGRAPH_VERSION=v0.9.4)." >&2; exit 1; }
case "$version" in v*) ;; *) version="v$version" ;; esac
url="https://github.com/$REPO/releases/download/$version/codegraph-${target}.tar.gz"
echo "Installing CodeGraph $version ($target)..."
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
curl -fsSL "$url" -o "$tmp/cg.tar.gz" || { echo "codegraph: download failed: $url" >&2; exit 1; }
dest="$INSTALL_DIR/versions/$version"
rm -rf "$dest"
mkdir -p "$dest"
tar -xzf "$tmp/cg.tar.gz" -C "$dest" --strip-components=1
mkdir -p "$BIN_DIR"
ln -sf "$dest/bin/codegraph" "$BIN_DIR/codegraph"
ln -sfn "$dest" "$INSTALL_DIR/current"
echo "Installed to $dest"
echo "Linked     $BIN_DIR/codegraph"
pruned=0
if [ -d "$INSTALL_DIR/versions" ]; then
  for d in "$INSTALL_DIR/versions"/*; do
    [ -d "$d" ] || continue
    if [ "$d" != "$dest" ]; then
      if rm -rf "$d"; then
        pruned=$((pruned + 1))
      fi
    fi
  done
fi
if [ "$pruned" -gt 0 ]; then
  echo "Removed    $pruned older version(s)"
fi
on_path=0
winner=""
oldifs="$IFS"; IFS=:
for dir in $PATH; do
  [ -n "$dir" ] || continue
  if [ "$dir" = "$BIN_DIR" ]; then on_path=1; fi
  if [ -z "$winner" ] && [ -x "$dir/codegraph" ] && [ ! -d "$dir/codegraph" ]; then
    winner="$dir/codegraph"
  fi
done
IFS="$oldifs"
if [ "$on_path" -eq 0 ]; then
  echo ""
  echo "$BIN_DIR is not on your PATH. Add it:"
  echo "  export PATH=\"$BIN_DIR:\$PATH\""
elif [ -n "$winner" ] && [ "$winner" != "$BIN_DIR/codegraph" ]; then
  echo ""
  echo "Warning: another codegraph is earlier on your PATH and will run instead:"
  echo "  $winner"
  echo "  (this install: $BIN_DIR/codegraph)"
  echo "If 'codegraph --version' shows an unexpected version, remove the other copy"
  echo "(e.g. 'npm rm -g @colbymchenry/codegraph') or put $BIN_DIR first on PATH."
fi
echo ""
echo "Done. Run: codegraph --help"
</file>

<file path="LICENSE">
MIT License

Copyright (c) 2026 Colby Mchenry

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</file>

<file path="package.json">
{
  "name": "@colbymchenry/codegraph",
  "version": "1.6.1",
  "description": "Supercharge AI coding agents with semantic code intelligence — surgical context, fewer tool calls, faster answers. 100% local.",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/colbymchenry/codegraph.git"
  },
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "bin": {
    "codegraph": "./dist/bin/codegraph.js"
  },
  "files": [
    "dist",
    "scripts",
    "README.md"
  ],
  "workspaces": [
    "ui"
  ],
  "scripts": {
    "build": "tsc && npm run copy-assets && npm run build:ui && node -e \"require('fs').chmodSync('dist/bin/codegraph.js', 0o755)\"",
    "build:ui": "npm run build --workspace ui && node scripts/check-ui-build.mjs",
    "build:lib": "npm run build:lib --workspace ui",
    "preuninstall": "node dist/bin/uninstall.js",
    "copy-assets": "node -e \"const fs=require('fs');fs.mkdirSync('dist/db',{recursive:true});fs.copyFileSync('src/db/schema.sql','dist/db/schema.sql');fs.mkdirSync('dist/extraction/wasm',{recursive:true});fs.readdirSync('src/extraction/wasm').filter(f=>f.endsWith('.wasm')).forEach(f=>fs.copyFileSync('src/extraction/wasm/'+f,'dist/extraction/wasm/'+f))\"",
    "dev": "tsc --watch",
    "build:kernel": "bash scripts/build-kernel.sh",
    "cli": "npm run build && node dist/bin/codegraph.js",
    "test": "vitest run",
    "test:watch": "vitest",
    "test:eval": "vitest run __tests__/evaluation/",
    "eval": "npm run build && npx tsx __tests__/evaluation/runner.ts",
    "clean": "node -e \"const fs=require('fs');fs.rmSync('dist',{recursive:true,force:true})\""
  },
  "keywords": [
    "code-intelligence",
    "knowledge-graph",
    "static-analysis"
  ],
  "author": "",
  "license": "MIT",
  "dependencies": {
    "@clack/prompts": "^1.3.0",
    "commander": "^14.0.2",
    "fast-string-width": "^3.0.2",
    "fast-wrap-ansi": "^0.2.0",
    "ignore": "^7.0.5",
    "jsonc-parser": "^3.3.1",
    "picomatch": "^4.0.3",
    "sisteransi": "^1.0.5",
    "tree-sitter-wasms": "^0.1.11",
    "web-tree-sitter": "^0.25.3"
  },
  "devDependencies": {
    "@sveltejs/vite-plugin-svelte": "^4.0.4",
    "@types/better-sqlite3": "^7.6.0",
    "@types/node": "^20.19.30",
    "@types/picomatch": "^4.0.2",
    "jsdom": "^25.0.1",
    "typescript": "^5.0.0",
    "vitest": "^2.1.9"
  },
  "engines": {
    "node": ">=20.0.0 <25.0.0"
  }
}
</file>

<file path="README.md">
<div align="center">

# CodeGraph

Already installed? Run `codegraph upgrade`

Follow [@getcodegraph](https://x.com/getcodegraph) on X for updates.

### Supercharge Claude Code, Cursor, Codex, OpenCode, Hermes Agent, Gemini, Antigravity, Kiro, and GitHub Copilot with Semantic Code Intelligence

**The fastest complete code graph · surgical context · built for how agents actually work · 100% local**

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/colbymchenry/codegraph/main/assets/rust-logo-dark.svg?v=1">
  <img src="https://raw.githubusercontent.com/colbymchenry/codegraph/main/assets/rust-logo.svg?v=1" height="30" alt="Rust" align="center">
</picture>&nbsp; **Kernel powered by Rust**

### [Documentation & Website →](https://colbymchenry.github.io/codegraph/)

[![npm version](https://img.shields.io/npm/v/@colbymchenry/codegraph.svg)](https://www.npmjs.com/package/@colbymchenry/codegraph)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Self-contained](https://img.shields.io/badge/Node.js-bundled%20%C2%B7%20none%20required-brightgreen.svg)](https://nodejs.org/)
[![npm provenance](https://img.shields.io/badge/npm-provenance-brightgreen.svg)](#verified-releases)
[![Attested builds](https://img.shields.io/badge/releases-signed%20%26%20attested-brightgreen.svg)](#verified-releases)

[![Windows](https://img.shields.io/badge/Windows-supported-blue.svg)](#supported-platforms)
[![macOS](https://img.shields.io/badge/macOS-supported-blue.svg)](#supported-platforms)
[![Linux](https://img.shields.io/badge/Linux-supported-blue.svg)](#supported-platforms)

[![Claude Code](https://img.shields.io/badge/Claude_Code-supported-blueviolet.svg)](#supported-agents)
[![Cursor](https://img.shields.io/badge/Cursor-supported-blueviolet.svg)](#supported-agents)
[![Codex](https://img.shields.io/badge/Codex-supported-blueviolet.svg)](#supported-agents)
[![opencode](https://img.shields.io/badge/opencode-supported-blueviolet.svg)](#supported-agents)
[![Hermes Agent](https://img.shields.io/badge/Hermes_Agent-supported-blueviolet.svg)](#supported-agents)
[![Gemini](https://img.shields.io/badge/Gemini-supported-blueviolet.svg)](#supported-agents)
[![Antigravity](https://img.shields.io/badge/Antigravity-supported-blueviolet.svg)](#supported-agents)
[![Kiro](https://img.shields.io/badge/Kiro-supported-blueviolet.svg)](#supported-agents)
[![GitHub Copilot](https://img.shields.io/badge/GitHub_Copilot-supported-blueviolet.svg)](#supported-agents)

<br>

**The CodeGraph platform is coming** — for every PR, know exactly what to test, what could break, which flows are affected, and whether business logic is compromised.

<a href="https://getcodegraph.com"><img alt="Join the waitlist for early beta access" src="https://raw.githubusercontent.com/colbymchenry/codegraph/main/assets/waitlist.svg?v=2" height="52"></a>

<sub>Get <b>early beta access</b> to the hosted product · <a href="https://getcodegraph.com">getcodegraph.com</a></sub>

</div>

## Contents

- [Get Started](#get-started)
- [Language Support](#language-support)
- [Why CodeGraph?](#why-codegraph)
- [Key Features](#key-features)
- [Framework-aware Routes](#framework-aware-routes)
- [Mixed iOS / React Native / Expo bridging](#mixed-ios--react-native--expo-bridging)
- [Quick Start](#quick-start)
- [How It Works](#how-it-works)
- [CLI Reference](#cli-reference)
- [MCP Tools](#mcp-tools)
- [Library Usage](#library-usage)
- [Configuration](#configuration)
- [Telemetry](#telemetry)
- [Verified releases](#verified-releases)
- [Supported Platforms](#supported-platforms)
- [Supported Agents](#supported-agents)
- [Supported Languages](#supported-languages)
- [Measured cross-file coverage](#measured-cross-file-coverage)
- [Troubleshooting](#troubleshooting)
- [License](#license)

## Get Started

### 1. Install the CLI

**No Node.js required** — one command grabs the right build for your OS:

```bash
# macOS / Linux
curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh

# Windows (PowerShell)
irm https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.ps1 | iex
```

<details>
<summary><b>Already have Node? Use npm instead (works on any version)</b></summary>

```bash
npm i -g @colbymchenry/codegraph
```

<sub>CodeGraph bundles its own runtime — nothing to compile, no native build, works the same everywhere. The installer puts `codegraph` on your PATH but **doesn't change your current shell** — open a new terminal before the next step so the command resolves.</sub>

<sub>**Upgrade any time** with `codegraph upgrade` — it detects how you installed (bundle, npm, or npx) and updates in place. Add `--check` to see if an update is available, or `codegraph upgrade <version>` to pin one.</sub>

</details>

### 2. Wire up your agent(s)
... (813 lines truncated)
</file>

<file path="TELEMETRY.md">
# Telemetry

CodeGraph collects a small set of **anonymous usage statistics** — which commands and
tools get used, which languages get indexed, which agents drive usage — so we can tell
which of the 20+ languages and 8 agent integrations deserve the most work. This page is
the complete list of what is collected. If a field isn't on this page, it isn't collected;
the ingest endpoint enforces this list as an allowlist and is itself
[public, auditable code](telemetry-worker/) in this repository.

## Turning it off

Any of these works, permanently:

```bash
codegraph telemetry off        # stores your choice (and deletes any unsent data)
```

```bash
export CODEGRAPH_TELEMETRY=0   # per-shell / per-CI override
export DO_NOT_TRACK=1          # the cross-tool standard — always honored
```

`codegraph telemetry status` shows the current state, what decided it, and your machine ID.
The interactive installer (`codegraph install`) asks up front with a visible default-on
toggle and never re-asks. If you never saw the installer (e.g. `npx` straight into `init`),
a one-line notice is printed to stderr before the first time anything is sent.

Off means off: when disabled, CodeGraph records nothing, opens no connection to the
telemetry endpoint, and sends no "opted out" ping. Running processes recheck the stored
choice before recording, persisting, and each send. Turning it off removes the local
identity and unsent queues (including claimed queues); turning it back on creates a new
identity. An HTTP request already started cannot be recalled, but opt-out prevents later
request chunks and prevents its unsent data from being requeued.

Environment overrides still apply: `CODEGRAPH_TELEMETRY=1` explicitly forces telemetry
on for that process even when the stored choice is off; `DO_NOT_TRACK=1` takes precedence.

Separately from telemetry, the MCP server checks GitHub for a newer release in the
background (at most once a day) so it can tell you an update exists — it fetches a
version number and sends nothing about you or your machine. `DO_NOT_TRACK=1` disables
this check too; to turn off only the update check, use `CODEGRAPH_NO_UPDATE_CHECK=1`.

## What is collected

Every payload carries this envelope:

| field | example | notes |
|---|---|---|
| `machine_id` | `b3a8c1…` | random UUID minted on first send — derived from nothing |
| `codegraph_version` | `0.9.9` | |
| `os` / `arch` | `darwin` / `arm64` | platform identifiers only |
| `node_major` | `22` | major version only |
| `ci` | `false` | whether the `CI` env var was set |
| `schema_version` | `2` | bumped when this page changes (v2 dropped the `index` event's `sqlite_backend` field) |

And one of four events:

- **`install`** — when `codegraph install` configures agents: which agents
  (`["claude","cursor",…]`), global vs project-local, and whether it was a fresh install,
  an upgrade, or a re-run.
- **`index`** — when a full index completes: the **language names** present (e.g.
  `["typescript","go"]`), the file count as a **coarse bucket** (`<100`, `100-1k`,
  `1k-10k`, `10k+`), and the duration as a bucket (`<10s`, `10-60s`, `1-5m`, `5m+`).
- **`usage_rollup`** — one line per day per tool: the tool or CLI command **name** (e.g.
  `codegraph_explore`, `init`), how many times it ran, how many errored, and — for MCP
  tools — the connecting agent's name and version from the MCP handshake (e.g.
  `Claude Code 2.1`). The Claude Code prompt hook also counts its **gate decision**
  (fired fully, fired as a hint, or did nothing — fixed counter names like
  `prompt-hook-gate-medium-segment`); the prompt itself is never read, stored, or sent.
- **`uninstall`** — when `codegraph uninstall`/`uninit` runs: which agents were removed.

Usage is **aggregated locally into daily totals** before anything is sent — there is no
per-call event stream, and nothing is sent in real time.

### The browser viewer sends nothing

`codegraph ui` (the local viewer) has no telemetry of its own. The server it starts
makes no outbound connections at all, and the page in your browser talks only to that
server on `127.0.0.1`: nothing about the symbols you open, the searches you type, or the
path you walk leaves your machine, and none of it is recorded anywhere. The only thing
telemetry ever learns about the viewer is what it learns about every command: that a
command named `ui` was run, once, on a day, in the daily `usage_rollup` above. The
command never triggers a send of its own, and `codegraph telemetry off`,
`CODEGRAPH_TELEMETRY=0`, or `DO_NOT_TRACK=1` switches off even that count, as it does
everything else on this page.

## What is never collected

- **No source code.** No file paths, file names, directory names, repository names or
  URLs, symbol names, search queries, or anything else derived from the contents of an
  indexed project.
- **No IP addresses.** The ingest endpoint never reads, logs, or stores the client IP —
  and there is no analytics vendor downstream that could. No geolocation.
- **No fingerprinting.** The machine ID is a random UUID stored in
  `~/.codegraph/telemetry.json` — delete that file (or run `codegraph telemetry off`,
  then `on`) and the old ID is gone forever, with no way to reconnect it.
- **No personal data.** No usernames, hostnames, emails, or environment variables.

## How it travels

... (30 lines truncated)
</file>

<file path="tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs",
    "lib": ["ES2022"],
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "paths": {
      "web-tree-sitter": ["./src/web-tree-sitter.d.ts"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "__tests__"]
}
</file>

<file path="vitest.config.mts">
import { defineConfig } from 'vitest/config';
import { WASM_RUNTIME_FLAGS } from './src/extraction/wasm-runtime-flags';
⋮----
/**
 * The SHARED base. `vitest.workspace.mts` extends it twice — once for the
 * engine's node-environment suites and once for the viewer package's jsdom
 * one — so the environment, the plugins and the module-resolution conditions
 * a browser test needs cannot leak into the other 200-odd suites.
 */
⋮----
// Suites that spawn the built CLI need a current dist/ (#1879).
⋮----
/**
     * Several MCP integration tests (mcp-daemon, mcp-initialize, mcp-ppid-watchdog,
     * mcp-roots) spawn `dist/bin/codegraph.js serve --mcp` with `process.execPath`
     * and rely on the child inheriting `process.env`. On a Node >= 25 dev machine
     * the CLI's hard-block (src/bin/codegraph.ts) would otherwise exit the child
     * before it ever responds, so every spawn-based test times out — see #478.
     *
     * Setting the override here keeps the CLI's runtime guard intact for end
     * users (it's still enforced when `codegraph` is invoked directly) while
     * letting the test suite run on whatever Node the contributor happens to
     * have installed. CI on Node 22/23 is unaffected — the guard doesn't fire
     * there, so the variable is a no-op.
     */
⋮----
/**
       * The suite spawns real CLI/MCP processes; without this they would write
       * telemetry state into the contributor's real ~/.codegraph and count test
       * tool calls as real usage. The telemetry unit tests are unaffected —
       * they inject their own `env` via the Telemetry constructor.
       */
⋮----
/**
     * The same V8 flags every real launch path passes (the bundled launcher,
     * the CLI's self re-exec, refresh-launcher): keep tree-sitter grammar
     * compilation on the Liftoff baseline tier. Without them a pool worker
     * runs the grammars on the turboshaft optimizing tier, and once enough
     * parses have warmed a grammar function up, its background tier-up job
     * exhausts a compiler Zone and aborts the worker — `Fatal process out of
     * memory: Zone`, surfaced by vitest only as "Worker exited unexpectedly"
     * with the rest of the file's tests silently unrun (#1779; the product-side
     * story is in wasm-runtime-flags.ts, #293/#298). On Node 24 with a
     * 660-test extraction suite this reproduced on every run at the same test.
     * V8 flags are process-global, so the parse worker threads a test spawns
     * are covered too.
     */
</file>

<file path="vitest.workspace.mts">
import { svelte, vitePreprocess } from '@sveltejs/vite-plugin-svelte';
import { defineWorkspace } from 'vitest/config';
⋮----
/**
 * Two projects, one command (`npm test` still runs everything).
 *
 * The split exists because of exactly one suite. `ui-package.test.ts` mounts
 * `@colbymchenry/codegraph-ui`'s components against a mock adapter (task
 * CG-61), and to do that it needs three things the engine's suites must never
 * see:
 *
 *   - the **Svelte plugin**, to compile `.svelte` and `.svelte.ts` modules;
 *   - **jsdom**, because a component without a document is not a render;
 *   - `resolve.conditions: ['browser']`, so `svelte` resolves to its client
 *     build rather than its server one (`mount()` throws on the server).
 *
 * That last one is why this is a workspace rather than one config with a
 * couple of extra fields. `browser` is a package-resolution condition, not a
 * test setting: applied globally it would also hand the engine's suites the
 * browser builds of `web-tree-sitter` and friends, and the failures that
 * causes look nothing like their cause.
 *
 * The engine project `extends` the shared base, so the env vars and Node guard
 * in `vitest.config.mts` still apply to every engine test. The ui project does
 * not — see the note on it.
 */
⋮----
// Deliberately NOT `extends`: a workspace project CONCATENATES the base's
// `include` with its own, so extending here would run all 200-odd engine
// suites a second time inside jsdom (and two of them fail there, for
// reasons that have nothing to do with anything). This project stands
// alone, and it needs none of the base's spawn-related env anyway.
⋮----
// The same preprocessor `ui/svelte.config.js` builds with, so the test
// compiles what the package ships.
⋮----
// `@xyflow/svelte` ships uncompiled `.svelte` files, so it has to go
// through the plugin above rather than be externalised to Node,
// which has no idea what a `.svelte` file is.
</file>

</files>
