Files
codegraph/__tests__/frameworks-integration.test.ts
T
71935e37c2 feat(mcp): multi-module Go trace-quality + small-repo retrieval tuning (#494)
* feat(go): generated-file down-rank + gRPC stub-impl bridge + trace-failure inlining

Multi-pronged fix to make codegraph competitive on Go multi-module repos
(cosmos-sdk, etcd) where it previously lost or tied. Driven by an 8-question
agent-eval audit across cobra, gin, prometheus, cosmos-sdk, and etcd: the
baseline had codegraph losing ~60% on cost on cosmos-sdk and mixed on etcd
deep cross-module flows, while winning cleanly on the single-module and
non-protobuf-heavy repos.

Diagnostics ruled OUT `go.work` parsing as the gap (prometheus crushes
without it). The actual failure modes were generated-file noise warping
disambiguation, missing gRPC interface→impl bridge in structural-typing Go,
and trace's failure path triggering 3-5 follow-up tool calls instead of
inlining the material the agent needed.

Changes:

- New `src/extraction/generated-detection.ts` — path-pattern classifier
  for `.pb.go`, `.pulsar.go`, `_grpc.pb.go`, `_mock.go`, `_mocks.go`,
  `mock_*.go`, `.generated.[jt]sx?`, `_pb2(_grpc)?.py`, `.pb.{cc,h}`,
  `.g.dart`, `.freezed.dart`. Applied as a stable sort tiebreaker in
  `findSymbol`, `findAllSymbols`, `codegraph_search` (MCP + CLI),
  `codegraph_explore` file ranking, and context formatter Entry Points /
  Related Symbols / Code blocks. Cosmos's `msgServer.Send` now ranks #3
  instead of #9 on a `Send` search.

- New `goGrpcStubImplEdges` synthesizer in `callback-synthesizer.ts` —
  detects `UnimplementedXxxServer` structs in generated files, identifies
  their RPC methods (excluding `mustEmbed*` / `testEmbeddedByValue` gRPC
  markers), and emits `calls` edges to the matching methods on any
  non-generated struct whose method-name set is a superset. Closes Go's
  structural-typing gap that the existing `interfaceOverrideEdges` (Java /
  Kotlin only) couldn't bridge. 467 bridge edges on cosmos-sdk; bank's
  `UnimplementedMsgServer::Send` points to `x/bank/keeper/msg_server.go`
  only, not to `msgClient` siblings or mock files.

- Trace-failure rewrite (`handleTrace`) — when no static path connects
  endpoints, instead of telling the agent to call `codegraph_node` (a
  3-4-call fan-out), inline both endpoints' bodies (120 lines / 3600 chars
  per endpoint), their callers (≤6), and callees (≤8) in one response.

- Trace endpoint-pairing improvements — scores every `from`×`to`
  candidate combo by shared directory prefix and tries the best-paired
  pair first (the full candidate set, not just FTS top-5). A
  less-canonical-path penalty (`enterprise/`, `contrib/`, `examples/`,
  `vendor/`, `third_party/`, `deprecated/`, `legacy/`) ensures the
  canonical-module pair wins even when a side-experiment shares more of
  its directory prefix. Find-path probe budget capped at 20 pairs.

- Test-file deprioritization in `codegraph_explore` `isLowValue` — adds
  suffix patterns (`_test.go`, `_spec.rb`, `.test.ts`, `.spec.tsx`,
  `Test.java`, `Spec.kt`) alongside the existing directory-style patterns.
  Otherwise etcd's `watchable_store_test.go` consumes 5K chars of explore
  budget that should go to the hand-written flow source.

Tests:

- New `__tests__/generated-detection.test.ts` (4 unit tests) pins the
  suffix patterns.
- New "Go gRPC stub→impl synthesis" integration test suite in
  `frameworks-integration.test.ts` (2 tests): positive bridge from stub
  to hand-written impl, AND the precision case (don't bridge to a
  generated sibling like `msgClient` in the same .pb.go).
- Full suite: 1076/1076 pass.

Empirical (post-fix, n=2 average per question):

| Repo / Q                | WITH       | WITHOUT     | Reads (W/WO) | Time (W/WO)
|-------------------------|------------|-------------|--------------|------------
| cobra (parse cmds)      | $0.27      | $0.27       | 0 / 4        | 39s / 60s
| prometheus (scrape→TSDB)| $0.63      | $0.70       | 0 / 6        | 106s/143s
| cosmos-sdk Q1 (MsgSend) | $0.41      | $0.26       | 1 / 2        | 67s / 64s
| cosmos-sdk Q2 (Delegate)| $0.47      | $0.46       | 0 / 5        | 50s / 73s
| cosmos-sdk Q3 (gov tally)| $0.34     | $0.31       | 1.5 / 3      | 54s / 76s
| etcd Q1 (Put→raft)      | $0.65      | $0.78       | 0 / 4        | 98s / 129s
| etcd Q2 (watch)         | $0.36      | $0.50       | 0 / 4+       | 58s / 89s

Codegraph wins on reads + time on every question. Cost is mixed: 3 clean
wins, 3 tied (within 10%), 1 stubborn cost loss on the grep-favored Q1.
Compared to baseline, the cosmos-sdk cost-gap collapsed from -60% to -15%
on average, and Q3 went from a 75% loss to a tie. Raw run artifacts in
`/tmp/cg-finalv2-*/` and `/tmp/cg-final-*/`.

Memory written at `project_go_multi_module_audit.md` for the methodology
+ before/after numbers.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mcp): auto-inline trace in codegraph_context for flow queries

When a codegraph_context task contains a flow keyword ("trace", "from",
"reach", "flow", "propagat", "how does", "how do") AND at least two
distinct PascalCase / camelCase identifiers, internally invoke trace
between the first two extracted symbols and splice the trace body into
the context response. Conservative trigger by design: false positives
waste one graph query; false negatives just fall back to the agent
calling trace itself (existing path-proximity wiring handles either
case).

Goal: collapse the agent's typical context → trace → explore sequence
into a single context call for clear flow queries, closing the
remaining cost-overhead gap on multi-call patterns. The path-proximity
+ less-canonical-path scoring + the trace-failure-inlined-bodies
behavior already let the inline trace land on the right endpoint pair
and return enough material that no follow-up codegraph_node/Read is
needed.

Doesn't fire on:
- cobra's "How does cobra parse commands and flags?" (no PascalCase
  symbols) — verified in regression run, no behavior change ($0.260
  WITH vs $0.257 WITHOUT, basically tied)
- queries where the agent doesn't call codegraph_context at all
  (cosmos Q1 in the audit went search → trace → node → trace → node)

Tests: 1076/1076 still pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mcp): trace failure inlines TO file siblings to displace node fan-out

The cosmos-Q1 audit revealed a static-resolution gap: msgServer.Send's
*real* next hop is `k.Keeper.SendCoins` — an interface-method call on an
embedded field that tree-sitter can't resolve. The static getCallees list
for msgServer.Send is all utility/error functions (StringToBytes, Wrapf,
…). The actual flow (SendCoins → subUnlockedCoins → addCoins →
setBalance) lives entirely inside `x/bank/keeper/send.go`, which is also
where the TO endpoint (setBalance) lives.

When trace fails (no static path), inline the **top 5 functions/methods
in the destination file**, ordered by line-distance from the TO node.
This catches the flow that interface-method calls obscure — the
canonical "k.<Iface>.<Method>" pattern in Go, also relevant to Java
dependency-injection / Rails service-object dispatch / etc. where
interface dispatch hides the real call.

Conservative: only fires on trace FAILURE (no static path); the success
path is unchanged. Per-body cap (40 lines / 1200 chars), top 5 siblings.
Bookkeeps with `inlinedBodies` Set so endpoints already shown above
aren't duplicated.

Result: cosmos-Q1 — historically the most stubborn cost loss (-2.2× to
-39% across the audit) — flipped to a clean WIN: $0.257 WITH vs $0.449
WITHOUT (-43%), 34s vs 79s, 0 Reads vs 2 Reads + 5 Greps, 5 codegraph
calls vs 12. Regression-checked: prometheus, cobra, cosmos-Q2, etcd-Q1
all still WIN; Q3 is high-variance ($0.30-$0.45 range historically) and
fell within that on this run.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat: extend coverage to all supported languages, not just Go

PR review feedback: the audit was Go-driven, so the patterns I added
were Go-flavored. Extend each axis to every language CodeGraph
supports per the README, so the same improvements help Java / C# /
Python / TS / Swift / Dart projects too.

**generated-detection.ts** — Added patterns for:
- TS/JS: `.gen.[jt]sx?`, `.pb.[jt]s`, `_pb.[jt]s`, `_grpc_pb.[jt]s`
  (ts-proto, gRPC-web, Apollo / GraphQL codegen, Hasura).
- Python: `_pb2.pyi` (mypy stubs from protobuf).
- C#: `.g.cs` (T4 / Razor codegen), `Grpc.cs` (protoc-gen-csharp).
- Java: `OuterClass.java` (protoc-gen-java), `Grpc.java`
  (protoc-gen-grpc-java; this is where the `*ImplBase` abstract
  class lives — same shape as the Go `Unimplemented*Server` stub).
- Swift: `.pb.swift` (protoc-gen-swift).
- Dart: `.pb.dart`, `.pbgrpc.dart`, `.chopper.dart`.
- Rust: `.generated.rs`.

**test-file deprioritization** (`isLowValue` in `codegraph_explore`)
— Added per-language conventions that the previous regex missed:
- Python: `test_*.py` (pytest discovery) and `*_test.py`.
- Ruby: `*_test.rb` (minitest) — `*_spec.rb` already covered.
- C#: `*Tests.cs`, `*Test.cs`, `*Spec.cs`.
- Swift: `*Tests.swift` (XCTest).
- Dart: `*_test.dart`.

**IFACE_OVERRIDE_LANGS** in `callback-synthesizer.ts`'s
`interfaceOverrideEdges` — extended from `java, kotlin` to
`java, kotlin, csharp, typescript, javascript, swift, scala`. Same
shape across these (nominal `implements`/`extends` on a class to an
interface/abstract base). Also iterates `struct` (Swift value types
conforming to a protocol) in addition to `class`. The existing
matchesSymbol-style logic and `getOutgoingEdges(..., ['implements',
'extends'])` work unchanged.

**CLAUDE.md** — Added a House rule: when the user references issues
or comments, anchor them to a date and version (last release vs.
last main commit vs. current branch tip) BEFORE concluding a fix is
incomplete. Issue #388 comments from May 25-27 were responding to
the released v0.9.5 / merged-PR-469 state — not to this branch's
in-flight work. The new rule walks through the disambiguation:
`grep -m1 '^## \[' CHANGELOG.md` for release version, `git log
--first-parent main -1` for main tip.

Tests: 1076/1076 still pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mcp): tiny-repo tool gating + shorter tool descriptions

Two cumulative changes targeting the small-repo cost gap surfaced by
the cross-language audit:

1. **Tool descriptions trimmed** (~2.1KB total saved across 10 tools).
   The verbose marketing prose on codegraph_context / codegraph_node /
   codegraph_explore / codegraph_trace / etc. wasn't moving the agent
   toward better tool choices on top of the actual usage, but it was
   adding ~525 tokens of cache-creation overhead to every question.
   The trimmed descriptions keep the operational hints (e.g. "Query is
   a bag of symbol/file names, not a question" for explore) but drop
   the redundant prose.

2. **Dynamic tiny-repo tool gating** in `ToolHandler.getTools()`. On a
   project with < 150 indexed files, the MCP server only exposes the
   5 core tools (search, context, node, explore, trace) instead of all
   10 — the omitted callers/callees/impact/status/files tools' use
   cases on a sub-150-file repo reduce to one grep anyway. The MCP
   tool-defs overhead is the #1 source of cost loss on tiny repos
   (~$0.10-0.15 fixed cache-creation per question); cutting 5 tools
   drops that by ~50%.

   Effect on ky (~25 files, the worst pre-fix offender):
     - Before: $0.59 WITH vs $0.42 WITHOUT (+42% loss, n=1)
     - After:  $0.32 WITH vs $0.44 WITHOUT (-26%, **flipped to WIN**)

   Effect on cobra/sinatra/slim (50-80 files): still cost-loss, but
   the gating doesn't regress them — same call-count, same reads.
   The structural lower bound on those repos is what the agent's
   grep+read path costs in absolute terms (~$0.20-0.30).

   Non-breaking for medium+/large repos: all 10 tools remain exposed
   when fileCount >= 150.

Tests: 1076/1076 still pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mcp): combined tiny-tier — smaller explore + tool gating (cobra/ky flip to WIN)

Combines the tool gating from the previous commit with a matching
explore-budget cut for projects under 150 files. The two together close
the cost gap that neither closes alone:

- Tool gating alone helped ky (WIN) but didn't move cobra/slim/sinatra
- Explore-budget cut alone helped slim slightly but regressed cobra
- COMBINED: cobra flips to WIN, ky stays a WIN, ky/cobra both clean

`getExploreOutputBudget(fileCount < 150)` returns:
  maxOutputChars: 13000     (was 18000)
  defaultMaxFiles:  4       (was 5)
  gapThreshold:     7       (was 8)
  maxSymbolsInFileHeader: 5 (was 6)
  maxEdgesPerRelationshipKind: 4 (was 6)
  includeRelationships: true   (kept ON — cheap structural signal)
  maxCharsPerFile: 3800        (unchanged — monotonic invariant w/ next tier)

This survives the cobra-regression-with-trim that the earlier
budget-only attempt suffered: with only 5 tools to choose from, the
agent doesn't fall back to extra codegraph_node calls when explore
returns less — there's no node call available.

Results on the four worst small-repo losses (combined intervention):

| Repo   | Files | WITH (combo)| WITHOUT     | Verdict (pre → post)     |
|--------|-------|-------------|-------------|--------------------------|
| cobra  | ~50   | $0.25       | $0.31       | loss → **WIN** (-19%)    |
| ky     | ~25   | $0.39       | $0.39       | -42% → tied              |
| slim   | ~80   | $0.31       | $0.24       | LOSS 31% → still LOSS    |
| sinatra| ~60   | $0.30       | $0.23       | LOSS 18% → still LOSS    |

sinatra/slim remain a cost-loss because their WITHOUT path is
structurally cheap (~$0.20 — fewer than 4 cheap grep+read calls).
Codegraph can't beat that absolute floor with any meaningful response.
Both still WIN on time + reads + tool-call count.

Tests: tier boundary cases updated to cover the new <150 / 150-499 /
500-4999 / 5000-14999 / >=15000 progression. Off-by-one guard updated
to include the new 149↔150 boundary. All 1076 tests pass.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(context): trim maxNodes default to 8 on tiny repos

On a <150-file project the entire repo is grep-able in one turn, so the
20-node default `codegraph_context` was paying for a graph subset that
exceeds the agent's actual question. Cutting the tiny-repo default to 8
(typical 1-3 entry points + their immediate 1-hop neighbors) reduces
the context-tool response body without hitting sufficiency on the flow
shapes small repos actually contain.

Non-breaking: the agent can still pass an explicit `maxNodes` to
override; medium+ repos (>=150 files) keep the 20-node default.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(mcp): pin the empirical 5-tool gating floor for tiny repos

n=2 audit on cobra/ky/sinatra ruled out cutting below 5 tools (search +
context + node + explore + trace) on the tiny-repo tier. The smaller
3-tool gate (search + context + trace) saved ~$0.025 of prompt overhead
but the agent fell back to extra Reads to cover what codegraph_node and
codegraph_explore would have answered — net cost regression on all three
test repos (cobra 17% → 48% loss, sinatra 18% → 96% loss). Documented
inline so future tuners don't re-try this dead-end.

No behavior change beyond the comment: the 5-tool gate remains the
production setting.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(mcp): pin empirical lower bound on tool gating after n=2 micro test

Tested the hypothesis that exposing FEWER tools on micro repos (<50
files) would close the cost gap. Results:

- 1-tool gate (codegraph_search only):
  - ky:    +44% (worse than 5-tool +30%)
  - express: +107% (catastrophic — was -43% WIN with all 10)
  - cobra: +126% (way worse than 5-tool +17%)

The single-tool gate forces the agent to read everything because it
can't navigate the call graph. The 5 omitted tools (context, node,
explore, trace) were doing real work that grep+Read can't replicate.

Conclusion: 5 tools (search + context + node + explore + trace) is the
empirical lower bound on the tiny-repo tier. Cutting below regresses
EVERY tested repo. The remaining ~$0.04-0.08 of structural cost overhead
on tiny repos is unavoidable without sacrificing the value codegraph
provides at that scale (which would also make WITH = WITHOUT, defeating
the install).

Comment documents the dead-ends so future tuners don't relitigate.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(mcp): iter3/iter4 — raise tool-gate to 500, sufficiency steering in context, hard-exclude low-value files

Three layered changes targeting the sinatra/slim/small-repo cost gap
that iter2's body-shrink failed to close (smaller bodies just pushed
the agent to Read instead):

1. **Tool-gate threshold 150 → 500** (`TINY_REPO_FILE_THRESHOLD`).
   Sinatra (~159 files) and slim (~200 files) have the same structural
   problem as cobra (

* feat(context): iter7 — core-directory boost to surface dominant-file siblings in search ranking

On projects with a single file holding the dense majority of internal
call edges (e.g. sinatra's `lib/sinatra/base.rb` at ~85% of in-file
edges), text search was favoring small focused extension files over the
core file. A small focused file like `multi_route.rb` wins on verbatim
name match + file-size normalization, burying the 1500-line core file's
longer method names (e.g. `route!` vs `route`).

Fix: detect the "dominant file" — the file whose in-file edge count is
≥3× the next candidate's — then add +25 to all results sharing its
directory prefix. This pulls the core file's siblings above
sibling-package extensions without hardcoding any repo structure.

`getDominantFile()` excludes test/spec files and generated files
(e.g. etcd's `rpc.pb.go` has 4× the in-file edges of `server.go` and
would otherwise hijack the boost toward generated protobuf stubs).
SQL pulls the top 20 candidates; path-pattern filtering handles what
SQLite LIKE can't express.

* feat(mcp): iter10+iter12 — routing manifest inline + probe-sweep harness

On small projects (<500 files) with a routing-shaped query, build a
URL→handler manifest directly from the graph (each `route` node joins to
its handler via `references`/`calls` edges) and inline the top handler
file's source. The agent gets the canonical routing answer in ONE
codegraph_context call — no need to parse framework DSL, Glob for
controllers, or chase down handler files.

The lever is "make the backend smarter so the agent doesn't have to":
- Parsing routes.rb / routes/api.php / urls.py DSL is the agent's job
  in the WITHOUT arm. Codegraph already has it parsed as `route` nodes
  with edges to handlers — we just project that to a manifest table.
- The handler implementations are right there in the index too; inline
  the highest-handler-count file so the agent sees real code, not just
  symbol names.

Results on the realworld template repos that were losing badly:
  rails-rw  +89% LOSS → -15% WIN  (agent often answers with 0-1 tool calls)
  laravel-rw  +29% LOSS → +12% (tight gap)
  gin-rw    +30% LOSS → +23% (still loss but smaller)
  flask-mb  +64% LOSS → +25% (smaller gap)

The residual losses are mostly the agent's defensive read behavior on
super-cheap-WITHOUT repos (express-rw still does 4 Reads even with a
19-row manifest + service file inlined). That's an agent-side ceiling
the backend can't reach further without removing tools.

Also lands `scripts/agent-eval/probe-sweep.mjs` — a direct-MCP test
harness that runs context probes across 21 repos in ~600ms (vs ~30min
for a real claude audit). Enables rapid iteration on backend changes:
edit tools.ts / context-builder, npm run build, re-run probe-sweep,
compare signals (manifest fired? handler file inlined? response size?)
before paying for a claude run.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(mcp): first tool call awaits catch-up sync (no stale rows for deleted files)

`MCPEngine.catchUpSync()` reconciles the index against the working tree
after open (catching `git pull`/`checkout`/`rebase` and any edits or
deletes made while no server was running). It was fire-and-forget — so a
tool call landing in the first ~50-300ms could race past it and serve
rows for files that no longer exist on disk. The per-file staleness
banner can't help here, because that signal is populated by the file
watcher (not by catch-up).

The fix: `catchUpSync()` now pushes its promise into `ToolHandler` via
`setCatchUpGate(p)`; the first `execute()` call awaits the gate and then
clears it. Subsequent calls pay nothing. Catch-up rejections are logged
by the engine and swallowed by the handler so a transient sync failure
never breaks tools.

Most visible on the "deleted everything between sessions" case, where
MCP previously returned stale rows pointing at non-existent files.
Validated end-to-end on a 10,640-file VS Code index: with the gate, a
codegraph_search for "ExtensionHost" against an empty (but stale-DB)
directory returns "No results found" after the catch-up drains the DB;
without the gate, the same call returns 10 stale hits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* docs(changelog): cover small-repo retrieval tuning + auto-trace + iface-override expansion

Add entries for work that landed on this branch but wasn't yet in
[Unreleased]: tiny-repo tool gating + sufficiency steering + budget
tier, auto-inline trace in codegraph_context, routing manifest inline,
core-directory ranking boost, JVM-only interfaceOverrideEdges extended
to C#/TS/JS/Swift/Scala, and the shorter tool descriptions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 12:38:03 -05:00

911 lines
37 KiB
TypeScript

import { describe, it, expect, beforeAll, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
describe('Django end-to-end framework extraction', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('creates a route->view edge from urls.py to view class', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-django-'));
fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# marker\n');
fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n');
fs.mkdirSync(path.join(tmpDir, 'users'));
fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), '');
fs.writeFileSync(
path.join(tmpDir, 'users/views.py'),
'class UserListView:\n def get(self, request): pass\n'
);
fs.writeFileSync(
path.join(tmpDir, 'users/urls.py'),
'from django.urls import path\n' +
'from users.views import UserListView\n' +
'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// Route node exists
const routes = cg.getNodesByKind('route');
expect(routes.length).toBeGreaterThan(0);
const route = routes.find((n) => n.name === 'users/');
expect(route).toBeDefined();
// View class exists
const classNodes = cg.getNodesByKind('class');
const view = classNodes.find((n) => n.name === 'UserListView');
expect(view).toBeDefined();
// Edge route -> view exists
const edges = cg.getOutgoingEdges(route!.id);
const toView = edges.find((e) => e.target === view!.id);
expect(toView).toBeDefined();
expect(toView!.kind).toBe('references');
cg.close();
});
});
describe('Flask end-to-end framework extraction', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('resolves stacked routes across @login_required to a view named after a builtin (index)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flask-'));
fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'flask==3.0\n');
fs.writeFileSync(
path.join(tmpDir, 'app.py'),
'from flask import Blueprint, render_template\n' +
'from flask_login import login_required\n' +
'bp = Blueprint("main", __name__)\n' +
'\n' +
'@bp.route("/", methods=["GET", "POST"])\n' +
'@bp.route("/index", methods=["GET", "POST"])\n' +
'@login_required\n' +
'def index():\n' +
' return render_template("index.html")\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// Both stacked @bp.route decorators are extracted (the second was previously
// dropped because @login_required broke the "def must follow" assumption).
const routes = cg.getNodesByKind('route');
expect(routes.map((r) => r.name).sort()).toEqual(['GET /', 'GET /index']);
// The view function exists even though its name is a Python builtin method.
const fn = cg.getNodesByKind('function').find((n) => n.name === 'index');
expect(fn).toBeDefined();
// Both routes resolve to it — exercises the bare-name builtin guard, which
// previously filtered the `index` reference as a builtin method.
for (const route of routes) {
const edges = cg.getOutgoingEdges(route.id);
const toView = edges.find((e) => e.target === fn!.id && e.kind === 'references');
expect(toView, `route ${route.name} should resolve to index()`).toBeDefined();
}
cg.close();
});
});
describe('Flutter end-to-end — setState→build synthesis', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('synthesizes a handler→build edge when a State method calls setState', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flutter-'));
fs.writeFileSync(
path.join(tmpDir, 'main.dart'),
'import "package:flutter/material.dart";\n' +
'class CounterPage extends StatefulWidget {\n' +
' @override\n' +
' State<CounterPage> createState() => _CounterPageState();\n' +
'}\n' +
'class _CounterPageState extends State<CounterPage> {\n' +
' int _count = 0;\n' +
' void _increment() {\n' +
' setState(() {\n' +
' _count++;\n' +
' });\n' +
' }\n' +
' @override\n' +
' Widget build(BuildContext context) {\n' +
' return Text("$_count");\n' +
' }\n' +
'}\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const methods = cg.getNodesByKind('method');
const increment = methods.find((n) => n.name === '_increment');
const build = methods.find((n) => n.name === 'build');
expect(increment).toBeDefined();
expect(build).toBeDefined();
// setState re-runs build (Flutter-internal, no static edge). The synthesizer
// bridges the handler → build so the "tap → setState → rebuilt UI" flow connects.
const edges = cg.getOutgoingEdges(increment!.id);
const toBuild = edges.find((e) => e.target === build!.id && e.kind === 'calls');
expect(toBuild, '_increment should reach build via setState synthesis').toBeDefined();
cg.close();
});
});
describe('C++ end-to-end — virtual override synthesis', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('resolves callers through typed object pointers', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
let cg: CodeGraph | undefined;
try {
fs.writeFileSync(
path.join(tmpDir, 'detect.hpp'),
'class CDetect {\n' +
' public:\n' +
' int Processing();\n' +
'};\n' +
'class CDetector {\n' +
' private:\n' +
' CDetect* m_cpAlg = nullptr;\n' +
' public:\n' +
' int Run();\n' +
' int Flush();\n' +
'};\n'
);
fs.writeFileSync(
path.join(tmpDir, 'detect.cpp'),
'#include "detect.hpp"\n' +
'int CDetector::Run() { return m_cpAlg->Processing(); }\n' +
'int CDetector::Flush() { return m_cpAlg->Processing(); }\n' +
'int CDetect::Processing() { return 0; }\n'
);
cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const processing = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName.endsWith('CDetect::Processing'));
expect(processing).toBeDefined();
const callers = cg.getCallers(processing!.id).map((c) => c.node.qualifiedName);
expect(callers).toContain('CDetector::Run');
expect(callers).toContain('CDetector::Flush');
const runMethod = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName.endsWith('CDetector::Run'));
expect(runMethod).toBeDefined();
const callees = cg.getCallees(runMethod!.id).map((c) => c.node.qualifiedName);
expect(callees).toContain('CDetect::Processing');
} finally {
cg?.close();
}
});
it('resolves typed pointer callers when the method name is ambiguous and the call sits inside a return/declaration', async () => {
// Regression: an earlier version of the C++ receiver-type inference matched
// the call line itself (`return m_cpAlg->Processing()`) and treated `return`
// as the type, OR grabbed `int r =` as a type from the prefix. With Strategy
// 3's "unique method name" fallback, the original issue example resolved
// anyway — but as soon as two classes share a method name (very common in
// real C++), both calls go unresolved.
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
let cg: CodeGraph | undefined;
try {
fs.writeFileSync(
path.join(tmpDir, 'detect.hpp'),
'class CDetect { public: int Processing(); };\n' +
'class CWidget { public: int Processing(); };\n' +
'class CDetector {\n' +
' private:\n' +
' CDetect* m_cpAlg = nullptr;\n' +
' public:\n' +
' int RunReturn();\n' +
' int RunAssign();\n' +
'};\n'
);
fs.writeFileSync(
path.join(tmpDir, 'detect.cpp'),
'#include "detect.hpp"\n' +
'int CDetector::RunReturn() { return m_cpAlg->Processing(); }\n' +
'int CDetector::RunAssign() { int r = m_cpAlg->Processing(); return r; }\n' +
'int CDetect::Processing() { return 0; }\n' +
'int CWidget::Processing() { return 0; }\n'
);
cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const detectProc = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'CDetect::Processing');
const widgetProc = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'CWidget::Processing');
expect(detectProc).toBeDefined();
expect(widgetProc).toBeDefined();
const detectCallers = cg.getCallers(detectProc!.id).map((c) => c.node.qualifiedName);
expect(detectCallers).toContain('CDetector::RunReturn');
expect(detectCallers).toContain('CDetector::RunAssign');
// CWidget::Processing is never called — calls must NOT misroute here.
const widgetCallers = cg.getCallers(widgetProc!.id).map((c) => c.node.qualifiedName);
expect(widgetCallers).not.toContain('CDetector::RunReturn');
expect(widgetCallers).not.toContain('CDetector::RunAssign');
} finally {
cg?.close();
}
});
it('bridges a base virtual method to the subclass override', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
fs.writeFileSync(
path.join(tmpDir, 'iter.cpp'),
'class Iterator {\n' +
' public:\n' +
' virtual void Next() { }\n' +
'};\n' +
'class DBIter : public Iterator {\n' +
' public:\n' +
' void Next() override { advance(); }\n' +
' void advance() { }\n' +
'};\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// Two methods named Next: the base virtual (lower line) and the override.
const nexts = cg
.getNodesByKind('method')
.filter((n) => n.name === 'Next')
.sort((a, b) => a.startLine - b.startLine);
expect(nexts.length).toBe(2);
const [baseNext, overrideNext] = nexts;
// A vtable call to Iterator::Next dispatches to DBIter::Next — bridge it so
// trace/callees from the interface method reaches the implementation.
const edge = cg
.getOutgoingEdges(baseNext!.id)
.find((e) => e.target === overrideNext!.id && e.kind === 'calls');
expect(edge, 'Iterator::Next should reach DBIter::Next via override synthesis').toBeDefined();
cg.close();
});
});
describe('Java end-to-end — field-injected bean trace (issue #389)', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
// Mirrors the issue's Spring MVC pattern:
// UserAction(@Resource UserBO userbo).toLogin2() -> this.userbo.toLogin2()
// -> UserBO.toLogin2() -> userService.toLogin() -> UserService.toLogin (iface)
// -> UserServiceImpl.toLogin() via interface→impl synthesis.
// Without the extractor `this.` strip + field-typed receiver lookup, the very
// first hop (controller -> bean) was missing entirely, breaking trace.
it('connects controller -> @Resource bean -> interface -> impl end-to-end', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-bean-'));
const javaDir = path.join(tmpDir, 'src/main/java/com/example/user');
fs.mkdirSync(path.join(javaDir, 'action'), { recursive: true });
fs.mkdirSync(path.join(javaDir, 'bo'), { recursive: true });
fs.mkdirSync(path.join(javaDir, 'service'), { recursive: true });
fs.mkdirSync(path.join(javaDir, 'service/impl'), { recursive: true });
fs.writeFileSync(
path.join(tmpDir, 'pom.xml'),
'<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>\n'
);
fs.writeFileSync(
path.join(javaDir, 'action/UserAction.java'),
'package com.example.user.action;\n' +
'import com.example.user.bo.UserBO;\n' +
'import javax.annotation.Resource;\n' +
'@org.springframework.stereotype.Controller\n' +
'public class UserAction {\n' +
' @Resource(name = "userBO") private UserBO userbo;\n' +
' public void toLogin2() { this.userbo.toLogin2(); }\n' +
'}\n'
);
fs.writeFileSync(
path.join(javaDir, 'bo/UserBO.java'),
'package com.example.user.bo;\n' +
'import com.example.user.service.UserService;\n' +
'import javax.annotation.Resource;\n' +
'@org.springframework.stereotype.Component("userBO")\n' +
'public class UserBO {\n' +
' @Resource private UserService userService;\n' +
' public void toLogin2() { userService.toLogin(); }\n' +
'}\n'
);
fs.writeFileSync(
path.join(javaDir, 'service/UserService.java'),
'package com.example.user.service;\n' +
'public interface UserService { void toLogin(); }\n'
);
fs.writeFileSync(
path.join(javaDir, 'service/impl/UserServiceImpl.java'),
'package com.example.user.service.impl;\n' +
'import com.example.user.service.UserService;\n' +
'@org.springframework.stereotype.Service("userService")\n' +
'public class UserServiceImpl implements UserService {\n' +
' public void toLogin() { }\n' +
'}\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const methods = cg.getNodesByKind('method');
const find = (cls: string, name: string) =>
methods.find((m) => m.name === name && m.filePath.endsWith(`${cls}.java`));
const action = find('UserAction', 'toLogin2');
const bo = find('UserBO', 'toLogin2');
const svc = find('UserService', 'toLogin');
const impl = find('UserServiceImpl', 'toLogin');
expect(action).toBeDefined();
expect(bo).toBeDefined();
expect(svc).toBeDefined();
expect(impl).toBeDefined();
// UserAction.toLogin2 -> UserBO.toLogin2 (the regressed hop — `this.userbo`
// receiver was emitted verbatim and the field-type lookup didn't exist).
const actionToBo = cg.getOutgoingEdges(action!.id).find((e) => e.target === bo!.id);
expect(actionToBo, 'controller `this.userbo.toLogin2()` should reach UserBO.toLogin2').toBeDefined();
expect(actionToBo!.kind).toBe('calls');
// UserBO.toLogin2 -> UserService.toLogin (plain identifier receiver, works pre-fix).
const boToSvc = cg.getOutgoingEdges(bo!.id).find((e) => e.target === svc!.id);
expect(boToSvc).toBeDefined();
// UserService.toLogin -> UserServiceImpl.toLogin (interface->impl synth).
const svcToImpl = cg.getOutgoingEdges(svc!.id).find((e) => e.target === impl!.id);
expect(svcToImpl).toBeDefined();
cg.close();
});
it('bridges a Java mapper interface method to its MyBatis XML statement (incl. SQL fragments)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-mybatis-'));
const javaDir = path.join(tmpDir, 'src/main/java/com/example/dao');
const xmlDir = path.join(tmpDir, 'src/main/resources/mappers');
fs.mkdirSync(javaDir, { recursive: true });
fs.mkdirSync(xmlDir, { recursive: true });
fs.writeFileSync(
path.join(tmpDir, 'pom.xml'),
'<project><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency></dependencies></project>\n'
);
fs.writeFileSync(
path.join(javaDir, 'UserDAOMapper.java'),
'package com.example.dao;\n' +
'public interface UserDAOMapper {\n' +
' Object getById(int id);\n' +
' int updateUser(Object u);\n' +
'}\n'
);
fs.writeFileSync(
path.join(xmlDir, 'UserDAOMapper.xml'),
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">\n' +
'<mapper namespace="com.example.dao.UserDAOMapper">\n' +
' <sql id="userCols">id, name, email</sql>\n' +
' <select id="getById" parameterType="int" resultType="User">\n' +
' SELECT <include refid="userCols"/> FROM users WHERE id = #{id}\n' +
' </select>\n' +
' <update id="updateUser" parameterType="User">\n' +
' UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}\n' +
' </update>\n' +
'</mapper>\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const methods = cg.getNodesByKind('method');
const getByIdJava = methods.find((m) => m.name === 'getById' && m.language === 'java');
const getByIdXml = methods.find((m) => m.name === 'getById' && m.language === 'xml');
const updateJava = methods.find((m) => m.name === 'updateUser' && m.language === 'java');
const updateXml = methods.find((m) => m.name === 'updateUser' && m.language === 'xml');
const sqlFrag = methods.find((m) => m.name === 'userCols' && m.language === 'xml');
expect(getByIdJava).toBeDefined();
expect(getByIdXml).toBeDefined();
expect(updateJava).toBeDefined();
expect(updateXml).toBeDefined();
expect(sqlFrag).toBeDefined();
// XML statement qualified name must be `<namespace>::<id>` so the
// synthesizer can match against the Java method's `<Class>::<method>`
// suffix — this is the load-bearing contract between extractor + synthesis.
expect(getByIdXml!.qualifiedName).toBe('com.example.dao.UserDAOMapper::getById');
// Bridge: Java mapper method -> XML statement, kind 'calls'.
const j2xGet = cg.getOutgoingEdges(getByIdJava!.id).find((e) => e.target === getByIdXml!.id);
expect(j2xGet, 'Java getById should reach the XML <select id="getById">').toBeDefined();
expect(j2xGet!.kind).toBe('calls');
const j2xUpd = cg.getOutgoingEdges(updateJava!.id).find((e) => e.target === updateXml!.id);
expect(j2xUpd, 'Java updateUser should reach the XML <update id="updateUser">').toBeDefined();
// <include refid="userCols"/> inside <select> -> <sql id="userCols"> in same mapper.
const incEdge = cg.getOutgoingEdges(getByIdXml!.id).find((e) => e.target === sqlFrag!.id);
expect(incEdge, '<include refid="userCols"/> should reach the <sql> fragment').toBeDefined();
cg.close();
});
it('binds @Value / @ConfigurationProperties to YAML + .properties keys (incl. relaxed binding)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-config-'));
const javaDir = path.join(tmpDir, 'src/main/java/com/example');
const resDir = path.join(tmpDir, 'src/main/resources');
fs.mkdirSync(javaDir, { recursive: true });
fs.mkdirSync(resDir, { recursive: true });
fs.writeFileSync(
path.join(tmpDir, 'pom.xml'),
'<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>\n'
);
fs.writeFileSync(
path.join(resDir, 'application.yml'),
'app:\n' +
' cache:\n' +
' name:\n' +
' user-token: "example-service:auth:token"\n' +
' enabled: true\n' +
'db:\n' +
' url: "jdbc:mysql://localhost/x"\n'
);
fs.writeFileSync(
path.join(resDir, 'application.properties'),
'app.retry-count=3\n'
);
fs.writeFileSync(
path.join(javaDir, 'CacheConfig.java'),
'package com.example;\n' +
'import org.springframework.beans.factory.annotation.Value;\n' +
'public class CacheConfig {\n' +
' @Value("${app.cache.name.user-token}") private String tokenCacheName;\n' +
' @Value("${app.cache.enabled:true}") private boolean enabled;\n' +
' // relaxed binding: java camelCase, properties kebab-case\n' +
' @Value("${app.retryCount}") private int retry;\n' +
'}\n'
);
fs.writeFileSync(
path.join(javaDir, 'CacheProperties.java'),
'package com.example;\n' +
'import org.springframework.boot.context.properties.ConfigurationProperties;\n' +
'@ConfigurationProperties(prefix = "app.cache")\n' +
'public class CacheProperties { private boolean enabled; }\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// YAML/properties leaf keys: one constant node per dotted path.
const cfgKeys = cg
.getNodesByKind('constant')
.filter((n) => n.language === 'yaml' || n.language === 'properties');
const cfgByQn = (qn: string) => cfgKeys.find((n) => n.qualifiedName === qn);
expect(cfgByQn('app.cache.name.user-token')).toBeDefined();
expect(cfgByQn('app.cache.enabled')).toBeDefined();
expect(cfgByQn('db.url')).toBeDefined();
expect(cfgByQn('app.retry-count')).toBeDefined();
// @Value("${app.cache.name.user-token}") -> the YAML leaf key.
const valueBindings = cg
.getNodesByKind('constant')
.filter((n) => n.id.startsWith('spring-value:'));
const userToken = valueBindings.find((n) => n.name === 'app.cache.name.user-token');
expect(userToken).toBeDefined();
const userTokenEdges = cg.getOutgoingEdges(userToken!.id);
const userTokenTarget = userTokenEdges.find((e) =>
cfgKeys.some((c) => c.id === e.target && c.qualifiedName === 'app.cache.name.user-token'),
);
expect(userTokenTarget, '@Value should reference the YAML leaf key').toBeDefined();
// Default-value form `${k:default}` — strip the `:default` and bind the key.
const enabledBind = valueBindings.find((n) => n.name === 'app.cache.enabled');
expect(enabledBind).toBeDefined();
expect(cg.getOutgoingEdges(enabledBind!.id).some((e) => {
const t = cfgByQn('app.cache.enabled');
return t && e.target === t.id;
})).toBe(true);
// Relaxed binding: `app.retryCount` (camel) -> `app.retry-count` (kebab).
const retryBind = valueBindings.find((n) => n.name === 'app.retryCount');
expect(retryBind).toBeDefined();
expect(cg.getOutgoingEdges(retryBind!.id).some((e) => {
const t = cfgByQn('app.retry-count');
return t && e.target === t.id;
})).toBe(true);
// @ConfigurationProperties(prefix="app.cache") -> a key under that prefix.
const cpBindings = cg
.getNodesByKind('constant')
.filter((n) => n.id.startsWith('spring-cp:'));
const cpAppCache = cpBindings.find((n) => n.name === 'app.cache');
expect(cpAppCache).toBeDefined();
const cpEdges = cg.getOutgoingEdges(cpAppCache!.id);
expect(cpEdges.length).toBeGreaterThan(0);
cg.close();
});
it('emits only a file node for non-MyBatis XML (pom.xml, beans.xml, log4j.xml)', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-xml-non-mybatis-'));
fs.writeFileSync(
path.join(tmpDir, 'pom.xml'),
'<project><groupId>x</groupId><artifactId>y</artifactId></project>\n'
);
fs.writeFileSync(
path.join(tmpDir, 'log4j.xml'),
'<?xml version="1.0"?><Configuration><Loggers><Root level="info"/></Loggers></Configuration>\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// No method nodes — non-mapper XML produces no symbols (just file rows).
expect(cg.getNodesByKind('method').filter((n) => n.language === 'xml').length).toBe(0);
cg.close();
});
it('resolves a `this.field.method()` call to a unique implementation class', async () => {
// Standalone test of the extractor `this.` strip: even without Spring annotations,
// `this.svc.run()` where `svc` is typed as a concrete class should route to that
// class's method. This is the general Java fix, Spring is only one consumer.
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-java-this-field-'));
fs.writeFileSync(
path.join(tmpDir, 'App.java'),
'class Svc { public void run() { } }\n' +
'class App {\n' +
' private Svc svc;\n' +
' public void go() { this.svc.run(); }\n' +
'}\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const methods = cg.getNodesByKind('method');
const go = methods.find((m) => m.name === 'go');
const run = methods.find((m) => m.name === 'run');
expect(go && run).toBeTruthy();
const edge = cg.getOutgoingEdges(go!.id).find((e) => e.target === run!.id);
expect(edge, '`this.svc.run()` should resolve to Svc.run').toBeDefined();
cg.close();
});
});
describe('JVM FQN imports — end-to-end', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('resolves a Kotlin import when the file name differs from the class name', async () => {
// Bar lives in Models.kt — the filesystem-based Java-style path lookup
// (com/example/Bar.kt) misses this; only FQN-via-qualifiedName finds it.
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
fs.writeFileSync(
path.join(tmpDir, 'Models.kt'),
'package com.example\n\nclass Bar {\n fun greet(): String = "hi"\n}\n'
);
fs.writeFileSync(
path.join(tmpDir, 'Caller.kt'),
'package com.example.app\n\nimport com.example.Bar\n\nclass App {\n fun run() { Bar().greet() }\n}\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const bar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::Bar');
expect(bar, 'Bar should be extracted with package-qualified name').toBeDefined();
const importNode = cg.getNodesByKind('import').find((n) => n.name === 'com.example.Bar');
expect(importNode, 'import statement node should exist').toBeDefined();
// The imports edge may originate from the import node OR from a parent
// scope (file / namespace) — accept either, but require that an
// imports-kind edge to Bar exists.
const reachesBar = cg
.getIncomingEdges(bar!.id)
.find((e) => e.kind === 'imports');
expect(reachesBar, 'an imports edge should resolve to Bar via FQN').toBeDefined();
cg.close();
});
it('resolves a Kotlin top-level function import', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
fs.writeFileSync(
path.join(tmpDir, 'Utils.kt'),
'package com.example\n\nfun util(): Int = 42\n'
);
fs.writeFileSync(
path.join(tmpDir, 'Caller.kt'),
'package com.example.app\n\nimport com.example.util\n\nfun main() { util() }\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const util = cg.getNodesByKind('function').find((n) => n.qualifiedName === 'com.example::util');
expect(util, 'top-level util() should be extracted under com.example').toBeDefined();
const edge = cg.getIncomingEdges(util!.id).find((e) => e.kind === 'imports');
expect(edge, 'imports edge should reach the top-level function by FQN').toBeDefined();
});
it('resolves cross-language: Kotlin importing a Java class', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
fs.writeFileSync(
path.join(tmpDir, 'JavaBar.java'),
'package com.example;\n\npublic class JavaBar {\n public String greet() { return "hi"; }\n}\n'
);
fs.writeFileSync(
path.join(tmpDir, 'Caller.kt'),
'package com.example.app\n\nimport com.example.JavaBar\n\nfun main() { JavaBar().greet() }\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const javaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::JavaBar');
expect(javaBar, 'JavaBar should be extracted under com.example regardless of language').toBeDefined();
const edge = cg.getIncomingEdges(javaBar!.id).find((e) => e.kind === 'imports');
expect(edge, 'Kotlin caller should resolve its import to the Java class').toBeDefined();
});
it('disambiguates a class-name collision across packages', async () => {
// Two `Bar` classes in different packages — each importer should reach
// ITS Bar, not the other one. This is the central failure mode that
// name-matcher alone cannot disambiguate.
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
fs.writeFileSync(
path.join(tmpDir, 'AlphaBar.kt'),
'package com.example.alpha\n\nclass Bar { fun who() = "alpha" }\n'
);
fs.writeFileSync(
path.join(tmpDir, 'BetaBar.kt'),
'package com.example.beta\n\nclass Bar { fun who() = "beta" }\n'
);
fs.writeFileSync(
path.join(tmpDir, 'CallerA.kt'),
'package app\n\nimport com.example.alpha.Bar\n\nfun a() { Bar().who() }\n'
);
fs.writeFileSync(
path.join(tmpDir, 'CallerB.kt'),
'package app\n\nimport com.example.beta.Bar\n\nfun b() { Bar().who() }\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const alphaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.alpha::Bar');
const betaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.beta::Bar');
expect(alphaBar).toBeDefined();
expect(betaBar).toBeDefined();
expect(alphaBar!.id).not.toBe(betaBar!.id);
// Each Bar receives exactly one imports edge — from its own caller.
const alphaIncoming = cg.getIncomingEdges(alphaBar!.id).filter((e) => e.kind === 'imports');
const betaIncoming = cg.getIncomingEdges(betaBar!.id).filter((e) => e.kind === 'imports');
expect(alphaIncoming.length).toBeGreaterThan(0);
expect(betaIncoming.length).toBeGreaterThan(0);
// Sanity: the edges don't cross — alpha's incoming sources don't include
// beta's filePath and vice versa.
const sourceFiles = (edges: typeof alphaIncoming) =>
edges.map((e) => cg.getNode(e.source)?.filePath).filter(Boolean);
expect(sourceFiles(alphaIncoming).some((p) => p?.includes('CallerA.kt'))).toBe(true);
expect(sourceFiles(betaIncoming).some((p) => p?.includes('CallerB.kt'))).toBe(true);
});
});
describe('Java anonymous-class override synthesis — end-to-end', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('bridges an abstract base method to overrides inside `new Base() { ... }`', async () => {
// Mirrors guava Splitter: a factory returns `new BaseIter() {
// @Override int separatorStart(...) { ... } }`. Without anon-class
// extraction the override is invisible — Phase 5.5 interface-impl
// has no class to bridge — and an agent investigating `BaseIter.separatorStart`
// can't see its real implementation without reading the file.
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-anon-java-'));
fs.writeFileSync(
path.join(tmpDir, 'Splitter.java'),
'package com.example;\n' +
'\n' +
'abstract class BaseIter {\n' +
' abstract int separatorStart(int start);\n' +
'}\n' +
'\n' +
'public class Splitter {\n' +
' public BaseIter make() {\n' +
' return new BaseIter() {\n' +
' @Override\n' +
' int separatorStart(int start) { return start + 1; }\n' +
' };\n' +
' }\n' +
'}\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// The anon class is extracted and contains the override.
const anonClass = cg
.getNodesByKind('class')
.find((n) => /BaseIter\$anon@/.test(n.name));
expect(anonClass, 'anonymous BaseIter subclass should be a class node').toBeDefined();
const baseAbstract = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName === 'com.example::BaseIter::separatorStart');
const anonOverride = cg
.getNodesByKind('method')
.find(
(n) =>
n.name === 'separatorStart' &&
n.qualifiedName.includes('$anon@') &&
n.qualifiedName.startsWith('com.example::Splitter::make::')
);
expect(baseAbstract, 'base abstract method should be in the graph').toBeDefined();
expect(anonOverride, 'anon-class override should be in the graph').toBeDefined();
// Phase 5.5 interface-impl: the abstract method has a synthesized
// `calls` edge to the anon override. Without this hop the agent
// would have to Read the file to discover the implementation.
const synthEdge = cg
.getOutgoingEdges(baseAbstract!.id)
.find((e) => e.target === anonOverride!.id && e.kind === 'calls');
expect(synthEdge, 'BaseIter.separatorStart should bridge to anon.separatorStart').toBeDefined();
expect(synthEdge!.provenance).toBe('heuristic');
expect((synthEdge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
'interface-impl'
);
cg.close();
});
});
describe('Go gRPC stub→impl synthesis', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('bridges UnimplementedMsgServer methods to the hand-written keeper impl', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-'));
// Mimic protoc-gen-go-grpc output: `*_grpc.pb.go` carrying the
// UnimplementedMsgServer stub.
fs.writeFileSync(
path.join(tmpDir, 'tx_grpc.pb.go'),
'package banktypes\n\n' +
'type UnimplementedMsgServer struct{}\n\n' +
'func (UnimplementedMsgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) { return nil, nil }\n' +
'func (UnimplementedMsgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) { return nil, nil }\n' +
'func (UnimplementedMsgServer) mustEmbedUnimplementedMsgServer() {}\n' +
'func (UnimplementedMsgServer) testEmbeddedByValue() {}\n'
);
// Hand-written impl in a non-generated file — what an agent actually
// wants the trace to land on.
fs.writeFileSync(
path.join(tmpDir, 'msg_server.go'),
'package keeper\n\n' +
'type msgServer struct{ k Keeper }\n\n' +
'func (m msgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) {\n' +
' return m.k.SendCoins(ctx, req.From, req.To, req.Amount)\n' +
'}\n' +
'func (m msgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) {\n' +
' return nil, nil\n' +
'}\n'
);
let cg: CodeGraph | undefined;
try {
cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const stubSend = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'));
const implSend = cg
.getNodesByKind('method')
.find((n) => n.qualifiedName.endsWith('msgServer::Send'));
expect(stubSend, 'UnimplementedMsgServer.Send should be indexed').toBeDefined();
expect(implSend, 'msgServer.Send should be indexed').toBeDefined();
const bridge = cg
.getOutgoingEdges(stubSend!.id)
.find((e) => e.target === implSend!.id && e.kind === 'calls');
expect(bridge, 'stub Send should bridge to impl Send').toBeDefined();
expect(bridge!.provenance).toBe('heuristic');
expect((bridge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
'go-grpc-stub-impl'
);
} finally {
cg?.close();
}
});
it('does not bridge to candidates living in another generated file', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-sib-'));
// `*_grpc.pb.go` also contains a sibling `msgClient` struct that
// happens to satisfy the same method set. We must NOT bridge to it —
// it's not the hand-written impl, just the gRPC client wrapper.
fs.writeFileSync(
path.join(tmpDir, 'tx_grpc.pb.go'),
'package banktypes\n\n' +
'type UnimplementedMsgServer struct{}\n' +
'func (UnimplementedMsgServer) Send() {}\n' +
'func (UnimplementedMsgServer) MultiSend() {}\n\n' +
'type msgClient struct{}\n' +
'func (m msgClient) Send() {}\n' +
'func (m msgClient) MultiSend() {}\n'
);
let cg: CodeGraph | undefined;
try {
cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
const stub = cg
.getNodesByKind('struct')
.find((n) => n.name === 'UnimplementedMsgServer');
expect(stub).toBeDefined();
const bridges = cg
.getNodesByKind('method')
.filter((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'))
.flatMap((stubSend) => cg!.getOutgoingEdges(stubSend.id))
.filter(
(e) =>
e.kind === 'calls' &&
(e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
'go-grpc-stub-impl',
);
expect(bridges, 'no bridge to msgClient (also generated)').toHaveLength(0);
} finally {
cg?.close();
}
});
});