* fix(analyze): enforce parse-worker heap caps under an inherited heap flag
V8 reads --max-old-space-size and --max-semi-space-size when it creates
an isolate, and the process-wide values override a Worker's
resourceLimits. Under the analyze respawn's flags every parser worker
therefore ran with the main heap limit instead of its own cap, and with
a 384 MiB young generation.
The default parser-worker factory now spawns through a process-wide
lease that clears both flags while workers start and restores them when
the last starting worker reports online, posts its first message, or
exits. A synchronous restore right after new Worker() races the isolate
creation on the worker thread, so the lease waits for those events.
Initial spawns, startup retries and replacements all use this factory.
The plan cleared only the old-space flag; measuring showed the
semi-space flag also overrides the worker's young generation (a 512 MiB
worker reported 896 MiB instead of 560 MiB), so the lease clears both.
Admission is unchanged here and still reserves at least the main heap
per worker, which over-reserves safely; the next commit charges each
worker its own cap.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): charge each parse worker its own heap cap in resource admission
Admission assumed every parser worker inherits the main heap limit, so it
charged each worker max(mainHeap, workerHeap) + 128 MiB, divided the main
heap by (requiredWorkers + 1), and also capped it at 35% of the total. In
a 10 GiB / 4-CPU container that admitted a 2639 MiB main heap, and on a
4-CPU host it admitted one parse worker at every size from 4 to 32 GiB.
The parser pool now enforces each worker's cap (previous commit), so a
worker is charged its own heap plus the 128 MiB native allowance. The
main heap holds the analysis peak and is sized first: it takes what the
pools, headroom and required workers leave, capped at 16384 MiB and at
an unpinned runtime limit. Automatic workers fill the remainder up to
the CPU count. The rejection minimum uses the same inequality.
4 CPUs, 200 MiB supervisor, no model (main / workers / worker heap):
4 GiB: 957 / 1 / 958 -> 1403 / 1 / 512
10 GiB: 2639 / 1 / 2639 -> 4206 / 1 / 1072
16 GiB: 4300 / 1 / 4300 -> 6850 / 3 / 512
A sweep over RAM, CPUs, explicit totals, heaps, workers, models and
supervisor sizes finds no newly rejected request, no smaller main heap
and no reservation above the total. isConstrainedPdgBuild is unchanged;
the measured 6 GiB / one-worker PDG envelope stays constrained.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): key the constrained PDG write guard on requested workers
isConstrainedPdgBuild serializes LadybugDB COPY/FTS and limits malloc
arenas for the measured 6 GiB, single-worker PDG configuration. It read
the admitted parser worker count. Since admission now charges workers
their own cap, an explicit small budget such as
--pdg --resource-budget 6144 --memory-budget 2048 on 4 CPUs fits three
workers and silently dropped the guard, although the graph write it
protects runs after the parser workers exit and its memory is the same.
The budget now carries the worker count the operator requested (the
explicit --workers value, or 1 when automatic) and the guard reads it.
Predicate sweep over 544,320 requests (158,826 admitted by every
version), pdg on, against upstream/main: 0 configurations lose the
guard; 1,920 gain it (explicit budgets where upstream/main fitted more
than one automatic worker), which only makes their COPY serial. The 416
configurations the previous commit had turned off are all constrained
again. Explicit --workers N > 1 stays unconstrained.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(analyze): describe enforced parser-worker heap caps
Parser workers used to run with the main heap limit by accident; they now
run at their admitted cap, 512 MiB on common hosts. Say so in MIGRATION.md
and next to --max-file-size in the README: files above roughly 2 MB or
large explicit sub-batches can exceed the cap, the file is quarantined,
and GITNEXUS_WORKER_HEAP_MB raises it.
Also fix two stale sentences: the RUNBOOK still said each worker reserves
at least the --memory-budget allocation, and the README named one heap
flag where the pool clears both --max-old-space-size and
--max-semi-space-size.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): cover a parser worker dying at its enforced heap cap
With caps now enforced, an oversized job ending in
ERR_WORKER_OUT_OF_MEMORY is an expected outcome, and no test drove a
worker past its cap. The new case runs a pool of one 512 MiB worker
under --max-old-space-size=3000 and has it allocate up to 1 GiB on one
file. It asserts that dispatch resolves, the log names the cap and
GITNEXUS_WORKER_HEAP_MB, the file is quarantined and counted in stats,
the slot respawns, and the files around it are still parsed.
On upstream/main the worker inherits the main limit, so the same file
parses, nothing is quarantined and the case fails on the missing hint.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): derive the respawned main heap from the mocked host
Three heap-respawn tests pinned the main heap the old admission rule
gave the mocked 16 GiB host (4300 MiB, respawned as
--max-old-space-size=3916). Admission now sizes the main heap first:
75% of RAM (12288 MiB) minus headroom, supervisor, graph pool, vector
pool and embedding queues, which gives 6858 MiB and an old space of
6858 - 3 x 128 = 6474 MiB.
The tests now compute that value from the same host constants instead
of a literal, and pin the supervisor's RSS below its 192 MiB floor: the
main heap now depends on the measured supervisor reservation, which
otherwise varies with the test process.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* perf(analyze): start community workers through the heap lease
Node shares one built-in code cache between a process's isolates and
accepts an entry only under the V8 flag hash it was compiled with. The
parser-worker heap lease clears the inherited heap flags while a worker
starts, so that worker recompiles the built-ins its startup needs and
stores them under the cleared hash. The Leiden worker, created after
the flags were restored, then rejected those entries and recompiled
again: about 14 ms on the analyze-resume incremental scenario, where
the CI benchmark measured a ~0.7% slowdown.
The graphology and icebug workers now start through the same lease, so
their startup reuses the parser worker's entries and their later loads
the main isolate's. They pass inheritedWorkerResourceLimits(), the old
space and three semi-spaces the inherited flags give, so their heap is
unchanged.
CPU profiles of three incremental pairs (16 GiB / 4 CPUs simulated),
built-in compile time added per worker vs the base revision: Leiden
+13.8 ms before, +0.1 ms after; the parser worker's startup recompile
(+11 ms) remains. Clearing the flags once without restoring was also
measured and moved the cost into the parser worker instead (+24.7 ms).
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* Keep allocator defaults for multi-worker PDG parsing (#4045)
Apply the two-arena default only for a single admitted parser worker. Keep each worker's young generation inside its reservation, reuse its startup options, and share quoted numeric heap-flag parsing with CLI admission.
Cover allocator selection, real worker caps and reentrant startup events. Document community and loader heaps outside admission.
Validation: six incremental-index tests failed during a full run stopped early. All six passed in isolated reruns on the original and updated revisions.
* perf(analyze): lease community workers only after a parser worker did
Starting a worker under the cleared heap flags pays a one-time
recompile of the built-ins its startup needs, because Node's shared
built-in code cache is keyed by the V8 flag hash. Routing the community
workers through the lease saves that cost only when a parser worker has
already started under the cleared flags. With a warm parse cache, as in
`analyze --force` on an unchanged repository, no parser worker starts,
so the leased Leiden worker became the first to recompile: 6-file
repository, 20 runs each, Leiden spawn to result median 47.5 ms on the
base revision, 71.0 ms with the lease, 49.0 ms with this change.
spawnWithInheritedHeap() now takes the lease, with
inheritedWorkerResourceLimits(), only after a parser worker has used
the cleared flags in this process, and otherwise spawns plainly under
the inherited flags as before. The parser-worker path is unchanged.
Also restore the caveat that a Worker created in the analysis process
without these helpers while a lease is open gets V8's default heap.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): keep two allocator arenas when several PDG parser workers fit
The constrained PDG guard starts the first analyze child, which runs the
parser pool and then the graph writer, with MALLOC_ARENA_MAX=2 on Linux
with glibc. a7691f8cd limited that to one admitted parser worker. Two
measurements disagree only on what they measured: four workers on 210
TypeScript files parsed in 14.36-17.90 s with allocator defaults and
19.44-20.15 s with two arenas (parse time only); three workers on a Kotlin
repository of 2,448 files in an 8 GiB, 4-CPU container parsed in 30-34 s at
a ~3,050 MiB cgroup peak with two arenas, and in ~27 s at ~3,530 MiB with
defaults. The guard exists for the memory, so two arenas apply again
whenever it does. An operator's MALLOC_ARENA_MAX or glibc.malloc.arena_max
still wins.
The respawn test now runs the Linux branch on every host and covers an
automatic multi-worker admission, --workers 1, and an operator override.
The benchmark note carries both measurement sets.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): read every heap-flag spelling V8 and Node accept in the shared reader
lib/node-size-flag.ts is the one reader for heap flags in CLI admission and
the worker lease. It only knew `--name`, so `-max-old-space-size=3000` (V8
accepts one leading dash) pinned the heap unseen, and a signed or
space-padded size (`=+3000`, `= 3000`) was skipped although V8 applies it.
The reader now accepts one or two leading dashes, reads sizes like strtoull,
ignores a value V8 rejects as out of bounds (V8 keeps the earlier one), and
reports a value V8 accepts but JavaScript cannot hold exactly as NaN. New
helpers read an option's raw value (for the percentage flag) and a V8
boolean flag with both `--no-` and `--no` negation (for frozen flags), all
by argument so an `--eval` source or a `--title` value is never a flag, plus
process-level variants in which a command-line value wins over NODE_OPTIONS
even when it is zero.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): derive inherited worker heaps from the live main heap, by argument
The lease read heap flags from `process.execArgv.join(' ')` and treated a
command-line zero as absent, and it restored the main isolate's whole limit
as old space under the percentage flag. On Node 22 that let an `--eval`
source naming the percentage flag grow a later worker from 1,072 to
1,120 MiB, a valid title `--title 'worker --max-old-space-size=2000'` shrink
it from 4,144 to 2,048 MiB, command-line zeros over NODE_OPTIONS 2000/64
leave it at 2,192 instead of 4,144 MiB, and a 12.5% pin with a 64 MiB
semi-space change an ordinary worker's heap between before and after
parsing. `--max-heap-size` was never cleared, so a capped worker kept it, and
under `--freeze-flags-after-init` the first flag write aborted V8.
`inheritedHeap()` now reads the flags argument by argument through the
shared reader (command line over NODE_OPTIONS, zero included) and checks them
against the main isolate's live `heap_size_limit`, which is old space plus a
three-semi-space young generation. When they agree, the lease clears and
restores old space, semi-space and `--max-heap-size` as read, and
community-style workers get the main isolate's old space and young
generation from the live limit. When they disagree, or a heap flag is set
under frozen flags, the lease is skipped before any flag write and admission
charges every parser worker the main heap (`workerHeapCapEnforced: false`).
The percentage's old space follows Node's own formula, checked by the live
limit. The released-once guard for reentrant startup events is kept.
Subprocess tests in test/integration/worker-heap-flags.test.ts reproduce
each case with real flags from execArgv and NODE_OPTIONS, including that a
fresh ordinary worker gets the same heap before and after parsing.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): pin the host-resources wiring of worker-cap enforceability
Replacing `workerHeapCapEnforceable()` with `true` in
`resolveHostAnalysisResources` left every unit test green; only a
subprocess test against a built dist caught it. A unit test now drives the
predicate both ways and checks that an unenforced cap charges each worker
the main heap, and that an explicit `workerHeapCapEnforced` still wins.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(analyze): let a command-line zero hide a NODE_OPTIONS heap pin in the CLI
Node applies the command line after NODE_OPTIONS, so
`node --max-old-space-size=0` runs at V8's default even when NODE_OPTIONS
pins a size. Manual admission and the budget decision already read the
process value with the command line first; the manual-heap check and
ensureHeap's ambient pin did not: under `--max-old-space-size=0` with a
large NODE_OPTIONS pin, analyze took the heap as pinned by the operator and
skipped its own sizing, or warned about a pin that was not in effect.
Both now take a NODE_OPTIONS pin only when the command line sets no
`--max-old-space-size` of its own.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* docs(analyze): name the heap-flag changes the worker-cap lease cannot see
A preload can change heap flags after startup without leaving anything the
live-limit check contradicts (`v8.setFlagsFromString`, or deleting
NODE_OPTIONS), and a module-hooks thread that a preload's `module.register()`
starts in a leased worker gets V8's default heap: Node takes no
`resourceLimits` for it. Neither is fixable from the lease; the module doc
and the README worker-cap paragraph now say so in one sentence each.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): restore process.platform without a non-null assertion
The arena test added a no-non-null-assertion lint warning when it saved the
platform descriptor; fall back to an empty descriptor instead.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* test(analyze): verify worker heap defaults across host sizes (#4045)
Compare ignored and reset heap flags against a clean Node subprocess. Pin the page-size input in the respawn fixture and exercise a real process title whose value starts with a dash.
* test: clarify heap reset and worker recovery coverage
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
91 KiB
Architecture — GitNexus
Monorepo: CLI/MCP (gitnexus/) + browser UI (gitnexus-web/).
Repository layout
| Path | Role |
|---|---|
gitnexus/ |
npm package gitnexus: CLI, MCP server (stdio), HTTP API, ingestion pipeline, LadybugDB graph, embeddings. |
gitnexus-web/ |
Vite + React thin client: graph explorer + AI chat. All queries via gitnexus serve HTTP API. |
gitnexus-shared/ |
Shared TypeScript types and constants (consumed by CLI and Web). |
.claude/, gitnexus-claude-plugin/, gitnexus-cursor-integration/ |
Agent skills and plugin metadata. |
eval/ |
Evaluation harnesses for benchmarking tool usage. |
.github/ |
CI workflows + composite actions (setup-gitnexus/, setup-gitnexus-web/). |
End-to-end flow: index → graph → tools
-
Ingestion —
analyze.ts→runFullAnalysis(run-analyze.ts) →runPipelineFromRepo(pipeline.ts). The default DAG of 19 phases builds aKnowledgeGraphin memory, then loads into LadybugDB under.gitnexus/. Repo registered in~/.gitnexus/registry.jsonfor MCP discovery. -
Persistence —
repo-manager.ts(paths, registry, LadybugDB cleanup).lbug-adapter.ts(graph load, queries, embedding batches). -
Query layer — three interfaces to the same backend:
- MCP (stdio):
mcp.ts→LocalBackend→ tools (tools.ts) + resources (resources.ts) - HTTP bridge:
serve.ts→ Express (api.ts,mcp-http.ts) for web UI - CLI direct:
gitnexus query|context|impact|cypherintool.ts
- MCP (stdio):
-
Staleness —
core/git-staleness.tscompares indexedlastCommittoHEADand classifies the result ascurrent,behind,divergedorunknown. The MCP read tools andserverepo routes usecore/staleness-status.tsto format the result. MCPlist_reposskips Git checks and reportsunknownduring discovery.
MCP tools
| Tool | Purpose |
|---|---|
list_repos |
Discover indexed repos |
query |
Hybrid BM25 + vector search over the graph |
cypher |
Ad hoc Cypher against the schema |
context |
Callers, callees, processes for one symbol |
impact |
Blast radius (upstream/downstream) with risk summary |
detect_changes |
Map git diffs to affected symbols and processes |
rename |
Semantic rename: previews by default (dry_run omitted/true), applies with dry_run: false and the preview's plan_token |
api_impact |
Pre-change impact report for an API route handler |
trace |
Shortest directed path between two symbols (call + class-member edges); group-aware (repo: "@<group>") for cross-repo traces |
route_map |
API route → handler → consumer mappings |
tool_map |
MCP/RPC tool definitions and handlers |
shape_check |
Response shape vs consumer property access mismatches |
explain |
Persisted taint findings (source→sink data flows) — needs analyze --pdg |
pdg_query |
Control/data dependence — CDG (mode: controls) / REACHING_DEF (mode: flows) — needs analyze --pdg |
group_list |
List repo groups or details for one group |
group_sync |
Rebuild group Contract Registry (contracts.json) and bridge graph |
query, context, and impact are group-aware: pass repo: "@<groupName>" (or "@<groupName>/<memberPath>" to scope to one member) plus optional service: "<monorepo/path>". Group-mode query merges per-repo results via Reciprocal Rank Fusion; group-mode impact runs the local walk in the chosen member and fans out across boundaries via the Contract Bridge (gitnexus/src/core/group/cross-impact.ts). trace is also group-aware via repo: "@<groupName>" — but, unlike the others, it resolves from/to across all members (a @<groupName>/<memberPath> suffix is advisory for trace, not a scope); pass from_uid/to_uid to disambiguate a symbol name that occurs in more than one member.
Group-mode trace (gitnexus/src/core/group/cross-trace.ts) stitches a path that crosses repositories: it resolves from/to across all members, and when they live in different repos it joins the home-repo segment to the target-repo segment over a single ContractLink boundary (an HTTP consumer→provider link, joined on Contract.symbolUid), reported as a CONTRACT_LINK hop in crossings[]. The crossing is clamped to one boundary (MAX_SUPPORTED_CROSS_DEPTH, shared with cross-impact); deeper crossDepth is reported via notes[]. With pdg: true (experimental, opt-in), each boundary-adjacent segment is enriched with its intra-procedural REACHING_DEF data-flow when that repo was indexed with --pdg (reusing the same anchored flows query as pdg_query); data flow never crosses the repo boundary, and a missing PDG layer degrades to call-level hops with a note. Two stores meet only at the symbolUid grain — the per-repo PDG/call graph and the group bridge — so this is the documented join; full cross-program (SDG-like) data flow across the boundary remains deferred (see docs/plans/2026-06-18-002-feat-unified-pdg-impact-evaluation-plan.md). The previously-planned group_query, group_context, group_impact, group_contracts, group_status MCP tools are intentionally not introduced — group-level state is exposed via resources instead:
| Resource URI | Purpose |
|---|---|
gitnexus://group/{name}/contracts |
Contract Registry (provider/consumer rows + cross-links) |
gitnexus://group/{name}/status |
Per-member index + Contract Registry staleness |
Where to change what
| Concern | Start in |
|---|---|
| CLI commands/flags | src/cli/ (index.ts, per-command modules) |
| Parsing/graph construction | src/core/ingestion/pipeline-phases/ + pipeline.ts |
| Graph schema/DB | src/core/lbug/ (schema.ts, lbug-adapter.ts) |
| MCP tools/resources | src/mcp/server.ts, tools.ts, resources.ts |
Cross-repo groups (sync, contracts, @<group> routing) |
src/core/group/ (service.ts, cross-impact.ts, sync.ts, bridge-db.ts) |
| Search ranking | src/core/search/ (BM25, hybrid fusion) |
| Embeddings | src/core/embeddings/ + src/core/run-analyze.ts |
| Wiki generation | src/core/wiki/ |
| Language support | src/core/ingestion/languages/ + tree-sitter-queries.ts + gitnexus-shared/src/languages.ts |
| Import resolution | src/core/ingestion/scope-resolution/pipeline/run.ts + per-language ScopeResolver.resolveImportTarget hooks (which files an import can reach) and optional ScopeResolver.onDemandImportTargets (which wildcard targets become persisted IMPORTS edges) |
| Call resolution/inheritance/MRO | src/core/ingestion/scope-resolution/ (pipeline, passes, graph-bridge) |
| Type extraction | src/core/ingestion/type-extractors/ |
| Worker pool | src/core/ingestion/workers/ |
| Web UI | gitnexus-web/src/ |
| CI | .github/workflows/*.yml, .github/actions/ |
Paths above are relative to
gitnexus/unless they start withgitnexus-web/or.github/.
Pipeline Phase DAG
19 default phases are defined in gitnexus/src/core/ingestion/pipeline-phases/, each with explicit deps and typed output. --pdg adds taintSummaries and callSummaries (21 total).
scan → structure → [springConfig, markdown, cobol] → parse → [routes, tools, orm]
→ crossFile → scopeResolution → [springAutoConfiguration, springAop]
→ pruneLocalSymbols → mro → springAopInheritance → di → communities → processes
| Phase | File | Deps | Output |
|---|---|---|---|
scan |
scan.ts |
(root) | File paths + sizes |
structure |
structure.ts |
scan |
File/Folder nodes, CONTAINS edges, allPathSet |
springConfig |
spring-config.ts |
structure |
Spring configuration-property nodes and metadata |
markdown |
markdown.ts |
structure |
Section nodes, cross-link edges from .md/.mdx |
cobol |
cobol.ts |
structure |
COBOL program/paragraph/section nodes (regex, no tree-sitter) |
parse |
parse.ts + parse-impl.ts |
structure, markdown, cobol |
Symbol nodes, IMPORTS/CALLS/EXTENDS edges, extracted routes/tools/ORM queries |
routes |
routes.ts |
parse |
Route nodes + HANDLES_ROUTE edges (Next.js, Expo, PHP, decorators, and JS/TS static route sources — see below) |
tools |
tools.ts |
parse |
Tool nodes + HANDLES_TOOL edges |
orm |
orm.ts |
parse |
QUERIES edges (Prisma, Supabase) |
crossFile |
cross-file.ts + cross-file-impl.ts |
parse, routes, tools, orm |
Cross-file type propagation in topological import order |
scopeResolution |
scope-resolution/pipeline/phase.ts |
parse, crossFile, structure |
Binding/reference + inheritance edges; disposes BindingAccumulator |
springAutoConfiguration |
spring-auto-configuration.ts |
structure, scopeResolution |
DECLARES and CONDITIONAL_ON metadata for Spring configuration candidates |
springAop |
spring-aop.ts |
scopeResolution |
Direct declarative/advice ADVISED_BY edges and pointcut evidence |
pruneLocalSymbols |
prune-local-symbols.ts |
scopeResolution |
Drops inert block-local Const/Variable/Static nodes (only a File→DEFINES edge) post-resolution |
mro |
mro.ts |
crossFile, scopeResolution, pruneLocalSymbols, structure |
METHOD_OVERRIDES + METHOD_IMPLEMENTS edges |
springAopInheritance |
spring-aop.ts |
springAop, mro |
Propagates declarative behavior through class/interface inheritance decisions |
di |
di.ts |
mro |
INJECTS edges from consumer Classes, factory Methods, or AST-captured programmatic lookup callables to provider Classes/declaration CodeElements (framework-neutral DI resolution; per-language matchers registered in di-extractors/) |
communities |
communities.ts |
mro, pruneLocalSymbols, structure |
Community nodes + MEMBER_OF edges (Leiden algorithm) |
processes |
processes.ts |
communities, routes, tools, pruneLocalSymbols, structure |
Process nodes + STEP_IN_PROCESS edges |
Non-phase files in the same directory: parse-impl.ts, cross-file-impl.ts (implementation), wildcard-synthesis.ts (whole-module import expansion), types.ts, runner.ts, index.ts.
Incremental resolution groups
LanguageProvider.incrementalResolutionGroup(filePath) groups files whose
resolution can change together even without a persisted import edge. Java uses
one workspace-wide group because a chained call can depend on an unmentioned
type in another directory. Edits, additions and deletions make every group member
and its importers candidates for rewriting.
After resolution, incremental/file-row-digests.ts compares each candidate's
graph rows with the digest recorded in index metadata at its last write. Only
changed candidates join the write set; missing digests conservatively require a
rewrite. This preserves incremental/full parity without making every Java body
edit rewrite the whole language. Grouping affects invalidation, not name visibility.
DAG runner
runner.ts — static phase graph, no plugins, compile-time type safety.
-
Validation — Kahn's topological sort. Rejects on: duplicate names, missing deps, cycles (DFS traces the concrete cycle path, e.g.,
A -> B -> C -> A, plus count of transitively blocked dependents). -
Execution — sequential in topological order. Each phase receives:
ctx: PipelineContext— shared mutableKnowledgeGraph,repoPath, progress callback, optionsdeps: ReadonlyMap<string, PhaseResult>— declared deps only (runner filters the results map to prevent hidden coupling)
-
Error handling — wraps phase errors with the phase name, emits terminal
errorprogress event, swallows progress handler errors to preserve the original cause. -
Timing — per-phase
durationMsinPhaseResult, dev-mode console logging.
Design patterns:
- Single graph accumulator — all phases mutate the same
KnowledgeGraphinctx; the graph is the primary output. - Typed phase access —
getPhaseOutput<T>(deps, 'name')for type-safe upstream results. - Binding accumulator lifecycle — created in
parse, disposed bycrossFile(infinally). No other phase should take ownership. - Skippable phases —
skipGraphPhasesomits MRO/di/communities/processes (faster tests);pruneLocalSymbolsstill runs (it is graph cleanup, not analysis).skipWorkersis no longer a sequential escape hatch — it (like--workers 0/GITNEXUS_WORKER_POOL_SIZE=0) is rejected with an actionable error, since the worker pool is the sole parse path (§ Chunked parse-and-resolve). - Local-symbol pruning —
pruneLocalSymbolsremoves inert block-local value symbols after scope resolution has consumed them. Opt out per-call withPipelineOptions.keepLocalValueSymbolsor globally with theGITNEXUS_KEEP_LOCAL_VALUE_SYMBOLSenv var.
How to add a new phase
- Create
pipeline-phases/my-phase.tswith aPipelinePhase<MyOutput>(name, deps, execute) - Export from
pipeline-phases/index.ts - Add to
buildPhaseList()inpipeline.ts
import type { PipelinePhase, PhaseResult } from './types.js';
import { getPhaseOutput } from './types.js';
import type { ParseOutput } from './parse.js';
export interface MyPhaseOutput {
/* ... */
}
export const myPhase: PipelinePhase<MyPhaseOutput> = {
name: 'myPhase',
deps: ['parse'],
async execute(ctx, deps) {
const { allPaths } = getPhaseOutput<ParseOutput>(deps, 'parse');
// ... write to ctx.graph ...
return {
/* typed output */
};
},
};
Where routes come from
route-extractors/ holds five independent ways a route can be discovered, all
converging on the routes phase's (method, url) registry:
| Source | Shape | Examples |
|---|---|---|
| Filesystem convention | path → URL, no parsing | Next.js app/, Expo, PHP |
| Single-file framework route | isRouteFile + worker extraction |
Laravel routes/*.php |
| Cross-file framework route | discoverRootRouteFiles + extractRoutes |
Django urlpatterns |
| AST-level route in a normal file | extractDecoratorRoutes |
Spring, FastAPI, NestJS (@Controller + @Get/@Post/…; URLs are controller-relative — setGlobalPrefix and URI versioning live in the bootstrap file and are not applied), JS/TS dispatch guards and static data route tables |
| Cross-file AST route facts | extractRouteFacts + resolveRouteFacts |
Express apps/routers and their mount paths; directly proven Hono registrations |
The AST-level route hook is the one whose name undersells it. A route is DECLARED by a
decorator, but it can also be inferred from a raw node:http server's own
dispatch — if (req.method === 'GET' && pathname === '/api/x') is a route with
a path, a verb and a handler, and nothing else in the pipeline could see it.
route-extractors/dispatch-guard.ts reads that shape; the transport, dedup and
handler resolution are shared with decorator routes, and
ExtractedDecoratorRoute.source carries the provenance difference through to
the HANDLES_ROUTE edge.
JS/TS data route tables share that transport when a route-named array contains
direct object literals with static path, method, and handler fields and a
same-scope for...of dispatcher positively compares the path and method before
directly invoking the handler. Dynamic values, computed keys, spreads,
inline/called handlers, unknown verbs, and ambiguous handler bindings are
suppressed. Bare import aliases and single-level member handlers are attributed
only through declared import and owner provenance; an unproven receiver never
falls back to a global name guess.
That extractor is deliberately precision-weighted: route_map presents its
output as fact, so a startsWith namespace test, a bare pathname === '/'
without a verb, and any regex it cannot translate exactly are all dropped rather
than guessed at. A missing route is a coverage limit; an invented one is a lie.
Express app.get(RegExp, handler) registrations are likewise omitted: a regex
matcher does not have one finite URL to use as a Route node key.
Express app.use(path, middleware) does not itself create a Route node. When
both receivers are proven Express instances, mounting a router joins the literal
prefix to its registered paths before handler selection. Nested and repeated
mounts, literal path arrays, and middleware arrays share this composition.
Express receiver facts reuse the existing AST and ParsedFile lexical identities.
They follow explicit ESM/CommonJS imports and exports through the configured
ScopeResolver, including stable aliases and barrels. An object named app or
router is not evidence; type-only imports, shadowed bindings, conflicting writes,
and unproven factories do not establish a receiver. Directly proven Hono verb
registrations remain supported, without applying Express mounting semantics.
A registration whose receiver, literal path or mounted router is a parameter of a
named function (mountSSEProgress(app, '/p', jobs) → app.get(routePath, …))
resolves through each call site of that function, once per site and in the
helper's file. This is one hop only: a site argument that is itself a parameter,
an unproven argument, or a reassigned parameter establishes nothing, and a helper
with no recorded call site is read as written, so an unknown mount path still
suppresses its router's standalone paths.
Fetch-wrapper facts use the same lexical identities. The shared resolver in
route-extractors/fetch-wrapper-index.ts names no language, but it applies
ECMAScript ResolveExport rules to the re-export facts it receives: only
providers whose modules link that way implement the re-export hook. A file that
passes a route's URL to a callee not proven to be a wrapper is counted on the
Route as unverifiedConsumers (proven consumers and the route's own file
excluded), and api_impact then reports its consumer count as a lower bound.
A FETCHES edge is file-level. Its reason also names the callables whose spans
contain the request sites (|via:<id>, under the same containment rule as the
R3-6 sink set). api_impact follows their CALLS edges one level up and lists
those callers as indirectConsumers, apart from the direct count and outside
the risk level: they never mention the URL, so no edge of their own could reach
the route. An index built before this attribution carries no such list.
An inline Express handler resolves to the anonymous Function node the capture
layer names by position, so its Route carries a handlerSymbolId. In a file
with several routes, response keys come from that handler's lines rather than
the whole file (middleware stays file-level), and flows link only where they
start at that handler.
A standalone router retains its local paths. A known dynamic mount suppresses that fallback, while independently proven static mounts remain available. Cycles terminate, and exceeding the expansion budget omits the affected mount component rather than publishing a partial set of paths. Per-file facts are cached, but cross-file paths are recomputed each run. Group HTTP contracts use the same resolver and composition, including in source-only mode.
Dispatch-guard inference also ignores stored route.routePath metadata:
comparing a recorded route name with a literal does not prove that the request
path is being dispatched.
Two rules there need more than one comparison to decide, and are worth knowing about before changing either:
- Same-file constant folding.
pathname === `${basePath}/rules`is common enough that refusing it loses whole route modules — and loses them invisibly, since a module with unfoldable paths and a module with no routes produce the same empty answer. Folding is same-file, string literals only, one alias hop, and refuses on ambiguity (a name declared twice with different values is dropped, never guessed). - Whole-repo reconciliation (
reconcileDispatchGuardRoutes, applied in the routes phase). A split route table — one module listing every path it recognises so the dispatcher can 404 early, handlers in others — otherwise lists every route twice, once verb-less with the table as its "handler". It applies to dispatch-guard routes only: a framework route with no verb is method-agnostic by declaration, which is a fact, not a weaker observation.
Semantic model
SemanticModel is the active declaration store used by the ingestion pipeline.
Its symbols, types, methods and fields registries supply symbol and
owner-oriented lookups. Scope resolution consumes this model; it does not replace
it with a second symbol store.
Type facts and resolution responsibilities
| Layer | Responsibility |
|---|---|
LanguageProvider and parse workers |
Extract declarations, type annotations, imports and reference facts using language-owned rules. |
TypeEnvironment (type-env.ts) |
Collect temporary per-file hints used by extraction and exported-type metadata. |
ParsedFile |
Carry declarations, scopes, imports, type bindings and reference sites into workspace resolution. |
SemanticModel |
Keep authoritative declaration registries and member ownership. |
ScopeResolver and shared passes |
Apply language rules, visibility, type propagation, receiver folding and dispatch to emit graph edges. |
Language providers + parse workers
├── symbol registration ───────► SemanticModel
├── scope/type/reference facts ► ParsedFile
└── TypeEnv hints ─────────────► extraction / exported-type metadata
SemanticModel + ParsedFile + ScopeResolver hooks
└──► finalize scopes/imports → propagate types → resolve → emit graph edges
Type handling occurs during both extraction and resolution. The worker builds
TypeEnv without a global model or imported-binding inputs. Only file-scope
TypeEnv bindings are serialized into BindingAccumulator for exported-type
metadata enrichment; function-local maps are not a second workspace resolver.
The current crossFile phase only disposes that accumulator. The legacy
cross-file call re-resolution and call-resolution DAG were removed in #942.
ParsedFile (gitnexus-shared/src/scope-resolution/parsed-file.ts) is the per-file
artifact the scope-resolution pipeline consumes. Passes must reuse it rather
than build parallel parse representations. If a provider needs additional AST
facts, it can reuse the orchestrator's treeCache; ordinary worker-pool runs
consume serialized facts because native Trees cannot cross MessageChannels.
WorkspaceResolutionIndex supplies derived scope and return-fact lookups, such as
classScopeByDefId and moduleScopeByFile. These caches complement the model's
authoritative declaration registries.
Write and read lifecycle
- Parsing calls
model.symbols.add, which registers declarations with the appropriate type, method or field registry. - The per-language scope pipeline populates ownership and calls
reconcileOwnershipto register corrections before reference resolution. - The orchestrator narrows the model to the read-only
SemanticModelinterface for downstream resolution passes.finalizeScopeModelreturns the scope/index bundle that the orchestrator consumes directly.
The bundle's imports field is an ImportVisibility (gitnexus-shared,
scope-resolution/import-visibility.ts), the only way to ask what a scope
imports. A reader that needs every file a scope reaches asks reaches,
membership or forEachTarget; a reader that picks an import by name,
definition or kind uses edgesAt. How finalize stores imports is not visible to
either, so no reader can hold a collection that omits part of what a scope
reaches.
This read-only model handle restricts registry writes. It does not freeze every
scope map: imported-return propagation and precise call-result binding deliberately
refine Scope.typeBindings in ordered passes. Graph-query MCP and HTTP endpoints read the
persisted graph/index rather than a live parse-time model handle.
The model also exports optional scopes / attachScopeIndexes APIs. No production
attachment call is present in the reviewed source, so callers must not assume
model.scopes is populated. Similarly, the shared resolveTypeRef helper is
exported and unit-tested, while current registry lookup resolves receiver owners
directly. These are API-audit candidates, not reasons to label the whole model or
typing layer obsolete.
reconcileOwnership is an active compatibility pass for providers whose parse-time
owner differs from their scope-resolution owner. The dev validator
validateOwnershipParity reports drift under
NODE_ENV !== 'production' && VALIDATE_SEMANTIC_MODEL !== '0'. Retiring reconciliation
requires provider ownership parity first.
See Type Resolution System for execution details and Type Resolution Roadmap for planned work and acceptance criteria.
Scope-Resolution Pipeline (RFC #909 Ring 3)
The shared scope-resolution pipeline handles ordinary source-language references
using ParsedFile, SemanticModel and provider hooks. It emits resolved calls,
accesses, value uses and inheritance edges. Register a ScopeResolver in
SCOPE_RESOLVERS to participate; the old per-language migration flag and parallel
call-resolution DAG were removed in RING4-1 #942.
Method extraction still supplies graph properties and overload identity; scope
extraction builds the declaration metadata used by resolution. Their repeated
node-only signature callbacks share facts through memoizeDeclarationFact
(ingestion/method-extractors/declaration-facts.ts). Each callback owns a WeakMap
from the immutable parse tree to native node IDs, so separate traversal wrappers
reuse one result without retaining old trees. Parameter facts are read-only;
providers can map syntax wrappers to the same declaration identity. Each consumer
keeps its own arity/type normalization. Owner-dependent flags and file-dependent
receiver rules remain separate. The cache stays inside parser isolates; serialized
graph/ParsedFile payloads and the persistent parse-cache format remain unchanged.
A provider can explicitly restrict its edge mode. COBOL currently uses
callable-flow-only: its established processor retains structural CALLS/IMPORTS,
and scope resolution contributes procedure-pointer calls. Registration alone is
not a claim that every language feature uses identical resolution rules.
Shared code does not name languages. When a language needs an extension point that does not exist yet, it is added as an optional LanguageProvider hook that no other language has to implement (R's postParse and resolveMemberOwnerNode; see the hook table below).
Pipeline stages
ParsedFile[] (extractParsedFile per file)
│ finalizeScopeModel (+ provider hooks)
▼
ScopeResolutionIndexes
│ resolveReferenceSites (via MethodRegistry.lookup)
▼
ReferenceIndex
│ emitReceiverBoundCalls ── FIRST
│ emitFreeCallFallback ── THEN
│ emitReferencesViaLookup ── uses handledSites + deferred-site skip set
│ emitPropertyDispatchCalls ── registration USES + conservative CALLS
│ emitCallableValueFlow ── assigned/passed callable invocation CALLS
│ emitImportedValueReferences ── cross-file value reads via finalized imports
│ emitUniqueNamePropertyAccesses ── LAST-RESORT property reads by name,
│ narrowed same-file → direct-import, refusing to choose otherwise
│ emitImportEdges
▼
KnowledgeGraph (IMPORTS / CALLS / ACCESSES / INHERITS / USES)
Orchestrator: runScopeResolution(input, provider) in scope-resolution/pipeline/run.ts.
Pipeline phase: scopeResolutionPhase in scope-resolution/pipeline/phase.ts — iterates the registered SCOPE_RESOLVERS over the worker-serialized ParsedFiles. (Per-language emitScopeCaptures hooks may reuse a cached Tree via the orchestrator's treeCache, but in worker-pool runs that cache is empty — Trees can't cross MessageChannels — so they consume the pre-extracted ParsedFile instead; § Performance notes.)
Semantic rename
rename plans through the graph-backed planner in mcp/local/rename/graph-rename.ts; dry_run (omitted or true) stops after planning and returns a single-use plan_token. Public apply requires that token with dry_run: false, validates the captured repository, declaration inventory, stable symbol identity, source-file set, source hashes and approved physical paths, and executes exactly the captured edits without replanning. The process-local cache retains edited-file snapshots and targets, hash/target evidence for unedited semantic sources, and an immutable provider-resolution configuration value, with a 15-minute lifetime and bounded plan-count and memory budgets. Provider-owned fresh configuration hooks bypass workspace memoization; configuration semantics are checked at capability validation and once after staging, before the first installation, independently of edited-file count. Source bytes and approved targets are checked before each replacement. These cooperative-workspace checks are not an atomic filesystem snapshot. An unedited source aliasing an edited target blocks preview. In MCP read-only mode the same tool is listed preview-only and any other dry_run is rejected before backend dispatch (mcp/read-only-policy.ts). The selected graph declaration must match the current source. Each language's LanguageProvider.rename supplies original-source name spans, spelling rules, declaration families, and syntax-specific rewrites. Embedded and standalone providers retain their own parsing strategy; shared planning does not classify language syntax or invoke compiler/language-service APIs.
The planner runs the existing scope-resolution pipeline before and after the proposed edits. An opt-in source-binding observer records the declaration selected for a written name, separately from runtime dispatch expansion. Provider capture metadata travels with each parsed file, so both passes retain ordinary import and ownership evidence. Provider-proven declaration families use the existing inheritance, implementation, and declaration relationships. Re-resolution checks edited references, untouched bindings, collisions, and changes in those families.
Application validates all captured source snapshots before each per-file replacement, then rechecks that destination immediately before installing it. Validation and replacement are separate filesystem operations; the operation is neither an atomic compare-and-swap nor a multi-file transaction. Unsupported or ambiguous source constructs produce an explicit blocked result. Coverage is limited to the indexed workspace and the provider's available semantic evidence; dynamic names and external consumers are not silently treated as resolved.
Callable-value flow
First-class callable values use a language-neutral inclusion analysis in passes/callable-value-flow.ts. Providers recognize their own syntax and emit JSON-safe CallableFlowSite facts (seed, copy, alias, address, load, store, formal, argument, and invoke) into ParsedFile; shared ingestion never branches on a language name. These always-on facts cross workers and the durable parse store. Changes to their producers or shared contracts automatically change the base parser identity used by both caches.
The emit stage defers only invocation sites proven to reference a flow cell. Ordinary receiver/free/reference passes still resolve direct callees first and record exact callee IDs by file/line/column. Property dispatch then runs before callable flow because a property-dispatched wrapper call can seed actual-to-formal propagation. The callable solver consumes those direct targets, propagates callable sets through lexical cells and formals, and emits CALLS at the real indirect invocation site with reason callable-value-flow (confidence 0.8 for a singleton, 0.7 for a bounded multi-target set).
The solver is flow-insensitive but bounded: dependency-indexed work items rerun only when a cell they read changes; target/address sets cap at 32; a hostile fact graph has a finite work budget; overflow or budget exhaustion emits no partial CALLS and produces a structured warning. Lexical shadowing is function/block aware, invocation/constructor results are not reinterpreted as callable designators, and overload selection uses provider-supplied signature metadata. C/C++ additionally associate visible prototypes with unique definitions so actual-to-formal flow crosses translation units; the provider-owned hasFileLocalCallableLinkage hook prevents static declarations or definitions from leaking across files. C++ member-function pointers preserve parameter/cv shape, keep non-virtual targets exact, and expand virtual targets through MethodDispatchIndex/MRO.
Property-key dispatch remains a separate conservative fallback. Its per-key fan-out cap is 32; capped keys synthesize no partial calls and are reported at warning level with language, skipped-key count, dropped key names (bounded), and cap; the count also travels in RunScopeResolutionStats.propertyDispatchSkippedKeys.
Interface-dispatch fan-out walks the subtype closure of the receiver's interface and is generic-instantiation aware (#2912): a call through IValidator<string> must not reach an implementor of IValidator<int>, which shares its declaration and therefore its subtype list. Each heritage clause's arguments reach resolution by one of three routes — read off the @reference.inherits anchor's own spelling where that anchor spans the whole base (most languages, no query change), through the @reference.type-arguments sub-tag where the anchor is the bare name and moving it would renumber inheritance edge ids (Rust impl T<A> for S, Dart extends), or on a heritage MARKER payload for clauses that never become reference sites (Dart implements/with). Whichever pass emits the edge records the pair through one sink: preEmitInheritanceEdges for heritage clauses, ScopeResolver.emitHeritageEdges for the rest.
The walk then carries a substitution: a subtype's own type parameters bind to the receiver's arguments, so class Wrapper<T> : IValidator<T> stays reachable from every instantiation while class IntValidator : IValidator<int> is pruned from the string one. Receiver arguments come from the declared type (Case 4), a class-level field's declared type (Case 6), or — for a compound receiver such as this._repo — the spelling the compound fold typed that position from, reported back through recordReceiverType and accepted only when it names the class the fold returned.
The filter prunes only on positive evidence: an unknown instantiation on either side, an argument list whose arity does not line up, a name that may be a type variable the language's captures never recorded, or an unresolved spelling whose simple name matches all keep the target. A type parameter of the declaration ENCLOSING either side is recognised as such and never compared — void Run<T>(IValidator<T> v) writes a receiver with no known instantiation, so it keeps the unfiltered fan-out. That recognition is what generic METHODS now carry @declaration.type-parameters for in C#, Java and Kotlin (TypeScript already did): without it an unbounded T grounds to nothing and a bounded one grounds to its BOUND, and both compare unequal to an implementor's concrete argument. Languages that capture neither type arguments nor type parameters therefore emit exactly the pre-#2912 fan-out. The fan-out cap (32, GITNEXUS_MAX_INTERFACE_DISPATCH_FANOUT) and its skipped-target reporting are unchanged and apply after filtering. Note the fan-out itself still fires only for a receiver whose folded type is an Interface symbol, so a Rust Trait or a Dart abstract Class receiver emits no secondary targets to filter in the first place.
Standalone (regex-based) providers such as COBOL participate via ScopeResolver.scopeResolutionEdgeMode: 'callable-flow-only': runScopeResolution runs for them, but every ordinary emission path — heritage, interface implementations, receiver-bound, free-call fallback, reference/import edges, post-resolution hooks — is gated off, so their legacy phase (e.g. cobolPhase) remains the sole owner of structural edges and the callable solver's CALLS are purely additive. A callable-flow-only provider whose files emitted no callable facts exits early, before finalize, keeping the opt-in proportional to source scanning.
Receiver chains and the drop census (#2766)
A compound receiver (svc.getUser().address.save()) is captured as a compact string on ReferenceSite.receiverChain. utils/receiver-chain-codec.ts is the ONE encoder/decoder — capture emitters, the scope-resolution fold, and the durable ParsedFile store all import it rather than hand-rolling the format.
Wire format is v2: 2|<base>|<step>|<step>…, one-character version prefix, then base-first steps, each a one-character kind sigil plus the member name (c = call, f = field). a (await) and i (index) are name-free and encode as a bare sigil — an awaited call's name already lives on its c step, and a subscript key is a value, not a lookup-able identifier. The version went 1 → 2 when those two kinds were added, and a decoder REFUSES a foreign version rather than decoding the prefix it understands: a chain missing its await/index hop decodes cleanly as a different, shorter chain and would type the receiver against the wrong member. The format is unescaped (| and ~ cannot occur in an identifier), so an unencodable name is refused rather than escaped, and the payload is capped at MAX_RECEIVER_CHAIN_BYTES / MAX_CHAIN_DEPTH steps. These strings live in both parse stores. Codec and capture changes automatically invalidate their caches through the base parser identity; the explicit receiver-chain wire version and foreign-version rejection still govern decoding.
Receivers the resolver could not type are not silently dropped. Each records a ResolutionOutcome (scope-resolution/resolution-outcome.ts) carrying the receiver's shape (classifyReceiverShape: chain-call / chain-field / chain-mixed / chain-unwrap / no-chain — the bench censuses these) and its origin (in-program / external / unknown). scope-resolution/unresolved-receivers.ts aggregates them per member name into the index-persisted unresolvedReceiverMembers summary, keeping in-program and external counts under separate keys. Only in-program drops make a count short: an external-rooted call (System.out.println, fetch(...)) has no in-graph node an edge could have reached, so it is reported but does not hedge. impact / context read that summary and publish epistemic: 'exact' | 'lower-bound', prose boundaries, and the machine-readable causes split (EpistemicCauses in mcp/local/local-backend.ts).
Python's provider classifies attribute reads and assignment targets separately; augmented assignments produce both read and write references. Constructor assignments on a proven instance receiver also create Property nodes without requiring a value type annotation. Annotation-only targets do not assign a value. These rules follow the Python attribute-reference and assignment semantics.
Property references declined across language boundaries are recorded in crossLanguageProperties. Both context and upstream impact on an affected property report epistemic: 'lower-bound', with the explanation in boundaries and unresolved, and the definition languages in anchorLanguages. This evidence does not fabricate cross-language edges and does not qualify a downstream walk.
Java overload selection and missing call edges (#3789)
Java resolves an overload family through provider hooks before the shared passes
prune candidates by owner or conversion rank. The provider gathers eligible
members across the receiver's compile-time hierarchy, removes overridden
signatures, and applies the JLS 15.12.2 phases in order: strict invocation, loose
invocation, then variable arity. Within the first applicable phase it compares
parameter types pairwise for specificity. Boxing, primitive widening, arrays,
null, and concrete invariant generic arguments retain their distinct meanings.
Lexically scoped argument facts travel in Java's existing captureSideChannel,
so parse workers and durable cache replay make the same decisions.
Static imports use accessible overload families; an explicit import shadows only
the same signature from an on-demand import. Enum constant bodies and implicit
record accessors reuse the provider's existing synthetic identities. Field,
hierarchy, and subtype walks memoize shared ancestors while preserving cycle and
depth bounds.
The provider models a bounded set of qualified JDK type relationships and
Arrays.asList / Collections.singletonList calls. These factories are poly
expressions: their type arguments depend on the candidate's parameter type.
Source declarations and lexical shadowing take precedence over these summaries.
Unsupported generic inference, unavailable argument types, and incomplete
inherited inventories leave an overload unresolved. A complete original family
containing only one declaration may retain the existing unique-member inference
for opaque arguments; this exception does not apply to a family narrowed to one
candidate. Runtime implementation dispatch follows the selected signature.
It preserves the original receiver's subtype bound and excludes static and private
methods from virtual dispatch.
Captures also retain callable-owned return annotations and structural identities
for var initializers. The shared passes keep the selected compile-time method
separate from runtime dispatch targets, then propagate owned return types to
untyped assignments and revisit waiting receiver calls through a dependency
queue. Sequential assignments have no expression-depth cutoff. Unresolved producers
cannot restore an earlier name-based return guess. Generic implementation
signatures substitute a whole formal type parameter only when concrete source
heritage proves its binding; unsupported substitutions remain unknown.
Suppressed overload calls record graph identities for their candidate methods,
declaring owners, and caller. unresolved-overloads.ts reconciles decisions per
call site and resolution phase and persists a bounded unresolvedOverloads
receipt, including an explicit complete-empty receipt. impact and context
report matching omitted sites through causes.overloadResolution and
epistemic: 'lower-bound'; possible callers never become ordinary CALLS
edges or inflate known caller counts. Impact checks the nodes whose neighbors
were actually expanded before pagination, using candidate identities upstream
and caller identities downstream. Missing, malformed, or capped receipts retain
an uncertainty boundary. Re-analyze with the current build (--force when
repairing metadata) to replace a legacy receipt.
Optional CFG/PDG emission (--pdg, #2081–#2086)
On a --pdg run providers build control-flow graphs through LanguageProvider.cfgVisitor (Tree-sitter ASTs) or collectSourceCfgs (standalone source processing). Every supported language supplies one of these hooks; Vue covers executable scripts. AST visitors run in the parse worker, while source-backed providers run during fresh scope extraction. Both produce plain ParsedFile.cfgSideChannel data. Scope-resolution emits the program-dependence layers inside Phase 4 of runScopeResolution, while the disk-backed ParsedFile store is still live. The store is cleared after that phase, so a later standalone phase cannot consume it.
The opt-in is off by default, folded into the parse-cache key, and bounded by executable-region and edge caps. Providers report unsupported regions and cap drops instead of fabricating complete flow. All dependence edges remain BasicBlock → BasicBlock in the existing CodeRelation table. Ordinary function ownership uses the BasicBlock id prefix and source span. A provider may supply an exact graph ownerId for a larger executable region; COBOL uses its existing program Module identity so paragraph fallthrough and PERFORM return continuations remain inside one region. This identity is persisted on BasicBlocks and used by PDG symbol projection. No new function-to-block relation is introduced. The layers build on each other:
- M1 — CFG (#2081):
BasicBlocknodes +CFGedges. Edge kind (seq/cond-true/loop-back/…) rides thereasoncolumn (CFG is oneCodeRelationtype, not one per kind). - M2 — REACHING_DEF (#2082): GEN/KILL def→use data dependence from a pure fixpoint solver; the variable name rides
reason. - M3/M4 — TAINTED / SANITIZES / TAINT_PATH (#2083–#2084): intra- and inter-procedural taint (source→sink) — the
explaintool's data. - M5 — CDG (#2085): Ferrante control dependence over a Cooper–Harvey–Kennedy post-dominator tree (the EXIT-rooted reverse CFG); branch sense (
'T'/'F') ridesreason. A CFG whose EXIT is unreachable from some block is skipped for CDG (post-dominance would be unsound) while its CFG/REACHING_DEF layers are kept. - M6 — read surface (#2086): the
pdg_queryMCP tool answers "what gates X?" (CDG,mode: controls) and "where does Y flow?" (REACHING_DEF,mode: flows);explainis the taint consumer. Both are always anchored +LIMIT-bounded (LadybugDB has no rel-property index) and share oneresolveBlockAnchorhelper. These PDG edge types are deliberately kept out of the defaultVALID_RELATION_TYPES/ web schema. - Cross-repo trace enrichment: group-mode
trace(pdg: true) reuses the same anchored REACHING_DEFflowsquery to annotate a boundary-adjacent segment with how a value reaches the cross-repo call — strictly intra-procedural (data flow never crosses the repo boundary). See the group-aware tools note above.
See core/ingestion/cfg/ (emit + the pure CFG / post-dominator / control-dependence / reaching-defs / taint passes) and mcp/local/local-backend.ts (_pdgQueryImpl, _explainImpl, the shared resolveBlockAnchor).
ScopeResolver contract
Single interface a language implements to plug into the pipeline. Contract fully documented in scope-resolution/contract/scope-resolver.ts.
| Hook | Purpose |
|---|---|
languageProvider |
Base LanguageProvider (tree-sitter query, emitScopeCaptures, import/binding interpreters, hooks) |
populateOwners(parsed) |
Fill deferred ownerId fields on method defs (captures can't always know the owning class at parse time) |
buildMro(graph, parsed, nodeLookup) |
Produce mroByClassDefId: Map<DefId, DefId[]> — C3, Ruby-mixin, or first-wins per language |
resolveImportTarget(target, fromFile, allFiles) |
(rawImportPath, sourceFile) → targetFilePath (PEP-328 for Python, etc.) |
isNamespaceImport(parsedImport, targetFile, fromFile) |
Optionally reclassify a resolved named import as a namespace handle when the imported symbol is itself a module |
mergeBindings(existing, incoming, scopeId) |
Shadowing / LEGB precedence |
arityCompatibility |
Provider consumed by registry during MethodRegistry.lookup Step 2 |
importEdgeReason |
Confidence-tier string for IMPORTS edge reason field |
propagatesReturnTypesAcrossImports? |
Opt out of cross-file return-type propagation (default on) |
fieldFallbackOnMethodLookup? |
Statically-typed languages turn this OFF — the heuristic over-connects (default on) |
elementTypeOf? |
(containerType, via: {kind:'index'} | {kind:'accessor',name}) → elementType | undefined — element type of a container, reached by subscript (repos[0]) or by a property-style collection view (data.Values). ONE hook for both routes (it replaced the split unwrapCollectionAccessor / unwrapCollectionElement, where implementing one silently answered nothing for the other). Consulted only where the source actually performed the access — never as a general type-name normalizer |
stripTypePreservingDecoration? |
(typeName) → strippedName | undefined — strip ONE layer of TYPE-PRESERVING decoration (pointer, reference, const, nullable, borrow, sigil) so a receiver declared *Host still finds the Host binding (#2766). Never a container: unwrapping Repo[] here would fold repos.find(x) to Repo.find — that is elementTypeOf's job, and only after a real subscript. Consulted only after every undecorated lookup fails, and only by receiver-chain base/step resolution — default off |
qualifiedTypeLookupSpelling? |
(typeRef, scopes?) → 'pkg.Type' | null | undefined — the namespace-qualified spelling of a declared type whose qualifier capture cut from rawName (*models.User stored as User), recovered from declaredSpelling. Receiver typing tries it first, grounded on the qualifier's import (no unique-name guess). A failed written-qualified lookup stops instead of falling back to a bare type name. The optional scope indexes also let a provider expand a visible namespace alias; null refuses the written lookup and its fallback. The binding is not rewritten — default off |
collapseMemberCallsByCallerTarget? |
One CALLS edge per (caller, target) instead of per-site — default off |
populateNamespaceSiblings? |
Cross-file implicit visibility (compiler-implicit namespace sharing) — default off; ctx carries treeCache |
resolveImplicitInheritanceBase? |
Fallback for a bare inheritance base the shared chain left unbound, bound by the implicit namespace rule (siblings exist only after the pre-pass); Java, Kotlin, C# opt in |
hoistTypeBindingsToModule? |
Walk up to Module scope when looking up a method's return-type typeBinding — default off; enable only when bindings are stored at module level |
hasFileLocalCallableLinkage? |
Precise internal-linkage predicate used only when joining callable declarations/prototypes to cross-file definitions; C/C++ use it for static free functions |
constructorCallTargetsClass? |
A constructor-form call Type(...) links to the Class def rather than its explicit Constructor def — default off; Swift and Dart opt in |
constructionSyntax? |
How the language spells construction, so an INLINE constructor receiver (Service(db).m(), new Service(db).m(), Service.new.m()) can be typed — bare / keyword / selector; default off, opt in per language only where measured to be needed (#2708) |
resolveQualifiedCallee? |
(calleeText, inScope, …) → callable | undefined — resolve a qualified callee only the language can read (Rust rp::make in x = rp::make() / rp::make().m(), Kotlin package path com.acme.mod.make) so chain-follow types the call from its return annotation; default off |
resolveQualifiedTypeSpellings? |
A receiver's declared or return type written QUALIFIED (rp::C x, f(a::Config c)) that binds nothing through the scope chain resolves through resolveQualifiedInheritanceBase — qualifier matched against the candidate's namespace, refuse on a tie — instead of by its tail, which binds the nearer same-named class. Runs after every existing lookup and after the template-argument match; default off, C++ opts in |
splitQualifiedCallee? |
(callee, callerScope?, scopes?, position?) → { receiver, member } | undefined — map a qualified callee spelling (rp::make) onto a receiver/member pair that retains the full written namespace qualifier, so a factory result (auto x = rp::make(); x.m(), rp::make().m()) is typed from the definition resolveQualifiedReceiverMember returns and that definition's own declared return type. Caller scope, indexes and source position let a provider reject shadowed or aliased namespace qualifiers only when visible at the factory expression. Shared code never splits on a separator; default off, C++ implements it |
onDemandImportTargets?(parsed, indexes) |
Files supplying what a source file takes through on-demand (wildcard) imports; narrows persisted File→File IMPORTS edges only — undefined keeps every edge. Default: no narrowing |
groupsWildcardImportTargets? |
Store a wildcard import that resolves to a list of files as one group over that list instead of one import edge per file. Applies when finalize creates no per-name wildcard bindings; later name resolution uses ImportVisibility. Default: one edge per file |
Per-language registration
- Implement
ScopeResolverinlanguages/<lang>/scope-resolver.ts. - Add entry to
SCOPE_RESOLVERSinscope-resolution/pipeline/registry.ts.
CI auto-discovers the set via tsx. No workflow edit required.
Code references
| Module | Purpose |
|---|---|
scope-resolution/contract/scope-resolver.ts |
ScopeResolver interface + shared types |
scope-resolution/pipeline/run.ts |
Generic orchestrator |
scope-resolution/pipeline/phase.ts |
Pipeline-phase wrapper (deps: parse, structure) |
scope-resolution/pipeline/registry.ts |
SCOPE_RESOLVERS map |
scope-resolution/passes/*.ts |
Reference-resolution passes (receiver-bound, free-call fallback, compound-receiver, MRO, cross-file return-type propagation) |
scope-resolution/graph-bridge/*.ts |
CLI-local translation from resolved references → KnowledgeGraph edges |
scope-resolution/scope/*.ts |
Generic scope-chain walkers + namespace targets |
scope-resolution/workspace-index.ts |
Build-once O(1) lookup index |
languages/python/index.ts |
Python ScopeResolver hooks + known-limitation docs |
languages/python/captures.ts |
emitPythonScopeCaptures (honors cross-phase Tree cache) |
languages/csharp/index.ts |
C# ScopeResolver hooks + known-limitation docs |
languages/csharp/captures.ts |
emitCsharpScopeCaptures (honors cross-phase Tree cache) |
languages/csharp/namespace-siblings.ts |
Cross-file implicit-namespace visibility hook (reads treeCache) |
Performance notes
- Cross-phase Tree cache: the orchestrator's
treeCache(RunScopeResolutionInput.treeCache) lets a scope-resolution per-language hook (emitScopeCaptures) reuse a tree instead of re-parsing. Workers leave it empty — Trees can't cross MessageChannels — so in normal (worker-pool) runs scope-resolution does NOT rely on it: workers serialize each file'sParsedFile(+ capture side-channel) and stream them in, so scope-resolution consumes the pre-extracted artifact rather than re-parsing on the main thread (§ Chunked parse-and-resolve).PROF_SCOPE_RESOLUTION=1emits hit/miss counters and a worker-engaged warning. - Typed relationship iteration: heritage + MRO walk only the EXTENDS / IMPLEMENTS / HAS_METHOD edges via
iterRelationshipsByType, not the full relationship map. - Workspace-resolution-index: O(1)
findOwnedMember/findExportedDef/classScopeByDefIdbuilt once per run. - Callable-value worklist: dependency-indexed inclusion propagation is linear in a reverse-ordered copy-chain fixture; target/address sets cap at 32 and the whole worklist has a finite budget with no partial edge emission on exhaustion.
- SCC-ordered cross-file return-type propagation (PR #1050):
propagateImportedReturnTypeswalksindexes.sccsin reverse-topological order (leaves first), so multi-hop alias chains likemodels.User → service.user → app.usercollapse to the terminal class in a single linear pass. Within each importer, the source module'stypeBindingsis chain-followed BEFORE mirroring (so we mirror terminal types, not intermediate refs), and the importer's owntypeBindingsis chain-followed AFTER mirroring (so localconst x = importedFn()resolves before downstream importers run). Cyclic SCCs reach a partial fixpoint within a single pass without iterating to convergence — see thets-circularcross-file-binding fixture which only asserts pipeline-no-throw. PROF output (PROF_SCOPE_RESOLUTION=1) splitsfinalizefrompropagateso quadratic regressions in the chain-follow surface independently.
Language-agnostic graph feeding
19 languages → single unified graph. Four abstraction layers:
Unified Graph Schema (44 node types, 21 relationship types)
↑
Scope-Resolution Pipeline (registry lookup + 3-tier import resolution + MRO)
↑
Language Providers (import semantics, type config, export checker, MRO strategy)
↑
Tree-Sitter Queries (per-language S-expressions, unified capture tags)
Language providers
Each language implements LanguageProvider (language-provider.ts). Key fields:
| Field | Purpose |
|---|---|
id, extensions |
Language identity and file matching |
treeSitterQueries |
S-expression queries for AST extraction |
importSemantics |
named / wildcard-leaf / wildcard-transitive / namespace |
exportChecker |
Public/exported symbol detection |
typeConfig |
Type annotation extraction rules |
mroStrategy |
first-wins / c3 / none |
descriptionExtractor |
Optional hook returning a symbol's doc-comment text as its description; feeds the embedding metadata header so doc-only terms are semantically searchable (issue #2270). Most languages register createLeadingDocDescriptionExtractor (shared, language-neutral; per-language comment/wrapper config passed at the call site) |
definitionPropertiesExtractor |
Optional language-owned hook for structured, clone-safe definition metadata. Shared ingestion persists these properties opaquely; the owning provider supplies the extraction semantics. |
postParse |
Optional. Whole-graph pass a language runs once after every chunk is merged and before scope resolution (deferred owner resolution, manifest-driven export refinement). Called once per analyze, awaited, only when the language has parsed files; a throw aborts the parse phase. Incremental analyse writes back only changed files, so a mutation of an unchanged file's nodes is not persisted; a hook whose result depends on manifests that are not parsed sources needs --force after such an edit. R: deferred setMethod/R6 owners + NAMESPACE exports. |
resolveMemberOwnerNode |
Optional. For languages whose members are owned by a call/assignment rather than an enclosing container node (R: R6/RefClass): returns the node the method and field extractors read members from, or null. Consulted by the enclosing-owner slot after the container walk and resolveFileTypeOwner (same slot; Zig file-owner is the precedent). Not an S4 mechanism: R's setMethod(...) returns null (its owner is a string-literal class name, not a node); S4 ownership arrives only through the ownerNameHint → postParse path. |
19 providers in languages/index.ts via satisfies Record<SupportedLanguages, LanguageProvider> — missing a language is a compile error.
Unified capture tags
Per-language tree-sitter queries use different AST node names but produce the same semantic capture tags: @definition.class, @definition.function, @call.name, @import.source, @reference.inherits. Downstream extraction needs no language branching. Defined in tree-sitter-queries.ts.
Import resolution
Per-language import resolution runs through ScopeResolver.resolveImportTarget, registered in SCOPE_RESOLVERS. The shared orchestrator (scope-resolution/pipeline/run.ts) passes each language's workspace configuration to the resolver hook. The hook maps a parsed import to its target file or files; finalization links imports and materializes bindings for scope lookup.
Language-specific import helpers and namespace rules live beside each resolver in languages/<language>/. Language-neutral package-directory and suffix indexes, workspace indexes, and per-file-set caches live in ingestion/utils/; suffix lookups receive their ordered extension candidates from callers. The dormant LanguageProvider.importResolver field, adapter, and strategy factory have been removed; new languages implement the ScopeResolver hook.
Chunked parse-and-resolve
parse processes files in ~20 MB byte-budget chunks to bound memory. Per chunk:
- Worker pool dispatches files (the sole parse path — there is no sequential fallback;
skipWorkers,--workers 0, andGITNEXUS_WORKER_POOL_SIZE=0are rejected with an actionable error) - Each worker: detect language → load grammar → run queries → return unified
ParseWorkerResult - Synthesize wildcard bindings (
wildcard-synthesis.ts) - Resolve imports
- Collect
BindingAccumulatorentries for cross-file propagation
Inheritance edges are emitted later, by the scope-resolution phase (preEmitInheritanceEdges + emitHeritageEdges), not during parse.
Workers: workers/worker-pool.ts, workers/parse-worker.ts.
Worker-serialized ParsedFiles (#2038). To index very large repos (e.g. the Linux kernel) without OOM, the worker pool is the sole parse path and workers serialize each file's ParsedFile (plus its capture side-channel) in parallel, streaming them to scope-resolution through a disk-backed store. Scope-resolution consumes the pre-extracted artifact instead of re-parsing every file on the main thread — tree-sitter's native input buffers are not GC-reclaimable, so the former main-thread re-parse leaked native memory until the process died. Pool creation is lazy / cache-miss-gated, so a warm all-cache-hit run replays cached worker output without spawning a worker (hence usedWorkerPool can be false even when the repo has parseable files).
Inheritance and MRO
Inheritance is captured by the @reference.inherits tag and emitted by the scope-resolution phase: preEmitInheritanceEdges resolves each base in scope, then emitHeritageEdges writes the EXTENDS/IMPLEMENTS edges. A bare base the shared chain cannot bind falls back to ScopeResolver.resolveImplicitInheritanceBase, because same-namespace sibling bindings (populateNamespaceSiblings) are populated only after this pre-pass; without it a Java class C extends B with no import loses its edge whenever another package also declares a B. The phase then computes method resolution order via each ScopeResolver's buildMro hook, feeding a MethodDispatchIndex used for owner-scoped lookups. Per-language strategy:
first-wins— Java, C#, C++, TS, Ruby, Goc3— Python (C3 linearization)ruby-mixin— Ruby (mixin-aware linearization)none— single-inheritance languages
Full analysis flow
runFullAnalysis in run-analyze.ts orchestrates everything around the pipeline:
CLI (analyze.ts) → runFullAnalysis(repoPath, options, callbacks)
1. Admit phase resources and recover any prepared graph publication.
2. Reuse unchanged graph/parser work where its receipts still match.
3. runPipelineFromRepo() → KnowledgeGraph → bounded graph write → FTS.
4. Prepare the owned graph and publication receipt; drain native resources.
5. Supervisor waits for graph-process exit, verifies and publishes metadata.
6. If embeddings are requested/pending, open the resumable embedding job.
7. Reuse verified vectors, commit bounded units, then seal/checkpoint/publish.
8. Register the repo and generate AI context files.
Graph-only legacy slots keep their existing path until separate publication is
needed. A ready graph remains queryable while an embedding job is pending;
semantic search reports degradation until a compatible sealed artifact is ready.
Unit acknowledgements follow verified, durable WAL commits. Native automatic checkpoints bound WAL growth; the final checkpoint prepares the sealed artifact for read-only publication without requiring WAL replay.
Automatic resource admission uses 75% of effective process/container RAM as a fixed process-family ceiling, divided across concurrent analyses. Each phase accounts for the main heap, retained supervisor, native pools and headroom; parser workers and embedding model/queues use separate phase reservations. The parser pool enforces each worker's own heap cap, so a worker reserves that cap plus native memory; the automatic main heap is sized first, beside the required workers, and automatic worker count uses what remains. Explicit limits never expand the family ceiling; combinations that cannot fit fail admission. Community-detection workers request the inherited V8 limits and sit outside the parser and embedding reservations. Process RSS can exceed the reserved total.
Options: --force (rebuild regardless), --embeddings (opt-in, resumable), --skipGit, --noStats.
Storage
<repo>/.gitnexus/
├── lbug # Legacy monolithic database, until first separate publication
├── lbug.generation.<id> # Owned private graph, selected by graphPath in metadata
├── analysis-publication.json # Recoverable prepared graph receipt
├── embeddings/<identity>/ # Job journal, manifest and separate vector database
├── embeddings/spaces/ # Model-space ownership/reuse receipts
├── lbug.wal # Write-ahead log
├── lbug.shadow # Shadow sidecar (checkpoint staging)
├── lbug.lock # Single-writer lock
├── lbug.wal.checkpoint, lbug.checkpoint.{intent,apply}.lock # checkpoint-in-flight artifacts; left behind only by an interrupted checkpoint, consumed by the next writable open
├── lbug.{wal,shadow}.dirty-recovery # parked sidecars from a crashed run; safe to delete
├── gitnexus.json # lastCommit, indexedAt, stats (primary metadata file)
└── meta.json # legacy mirror of gitnexus.json, kept in sync (see MIGRATION.md)
~/.gitnexus/
├── registry.json # Global repo registry (MCP discovery)
└── stores/<key>/ # Shared sibling index store (see below)
├── caches/ # parse cache + durable ParsedFile store
├── commits/<commit>-<featureKey>/ # one immutable graph per commit + settings
└── checkouts/<slot>/ # one checkout's metadata, membership, and
# private graph when it has local edits
The flat <repo>/.gitnexus/ layout applies to a standalone repository and
whenever GITNEXUS_STORAGE_PATH / GITNEXUS_STORAGE_ROOT is set. A repository
with linked worktrees, and clones with the same origin URL, share one
stores/<key>/ automatically (a clone opts out with analyze --no-share;
GITNEXUS_SHARED_STORE=off turns sharing off entirely). Each sharing checkout
keeps only a .gitnexus/store.json pointer to its store. Path resolution lives
in shared-store.ts.
Read-only opens self-heal an interrupted checkpoint: the refusal is
classified and cleared by one writable open (probe + CHECKPOINT) before
the read-only open is retried — see sidecar-recovery.ts
(isReadOnlyCheckpointInProgressError) and the
lbug-interrupted-checkpoint-recovery integration test.
Managed by repo-manager.ts. Publication reclaims unreferenced private graphs
and job artifacts under the slot lock, preserving current jobs, model spaces,
legacy reuse sources and prepared publications. Busy reader files are retried on
a later publication. See MIGRATION.md
before mixing binary versions or rolling back.
Automatic parse-cache identity
core/parse-cache-identity.ts derives full SHA-256 base and PDG identities
from sorted, framed logical paths and raw artifact bytes. It needs no Git
history, branch name, timestamp, network access, or contributor-assigned
semantic version. The boundary is intentionally conservative:
| Component | Owned inputs |
|---|---|
| Base | core/ingestion/** except the PDG-only paths below, core/tree-sitter/**, lib/**, core/graph/**, and the audited support/storage files listed in PARSE_CACHE_BASE_FILES |
| PDG | core/ingestion/cfg/** and the classified COBOL extraction helpers languages/cobol/flow.ts and flow-harvest.ts; the shared COBOL tokenizer remains in base |
| Runtime and dependencies | The actual selected worker, shared source/compiled runtime or packaged dist/_shared, grammar/parser/native/loader dependency closure, and effective runtime/loader options |
Source execution covers both source inputs and the compiled worker when that
is the selected entry. Editing source invalidates identity immediately; it
does not compile that worker. Run npm run build before expecting changed
worker facts. Installed packages derive identity from their shipped runtime
without requiring source, Git metadata, or a development compiler. Native
binary bytes and loader fallback candidates are covered even when package
versions stay the same. Unsupported resolution modes such as
--preserve-symlinks cannot be verified and disable persistent cache reuse.
Raw bytes mean comments and formatting inside owned roots can invalidate
reuse. Repository documentation, UI, unrelated CLI files, and unrelated
dependencies do not change this parser identity; broader analyzer freshness
rules still apply. New files inside an owned root are included automatically.
Inputs outside that boundary require an ownership decision and an update to
test/unit/parse-cache-input-coverage.test.ts, which audits imports, dynamic
loaders, runtime assets, and shared dependencies.
Each logical cache entry belongs to one source path and content hash, bound to its base parser identity. PDG entries also bind the PDG identity and resolved function-line cap. Chunk membership, byte budgets and worker assignment affect scheduling only: editing, adding or renaming one file does not invalidate its unchanged neighbours. Cross-file resolution still runs from all current facts.
Workers encode facts and ParsedFile scopes separately, with runtime-checked V8
envelopes and bounded compression. The coordinator appends these sections to
32 MiB target packs (a larger valid file occupies a dedicated pack), with range
references in parse-cache/files/index.json. It accepts a hit only after both
sections validate and the scope bytes are pinned into the run-owned store.
Scope resolution reads only its requested files. Empty scope sections are
explicit; warnings, quarantine and incomplete scope extraction prevent reuse.
Publication retains immutable live packs by hard link (atomic copy fallback) under the existing store lock, repacking when less than half a pack's bytes remain selected. New staged records are packed separately. It retains compatible sibling keys and excludes retired files or missing staged repairs. Bounds are checked during publication; section hashes are checked on every read before a cache hit is accepted. The child/supervisor receipt binds the graph generation, parser identity and selected file keys. The format transition changes parser identity, so old chunk caches miss once; legacy helpers remain for compatibility. Missing, malformed, incompatible or concurrently pruned records are misses.
RepoMeta.parseCacheIdentity records the effective parser identity for
unchanged-analysis and shared-current adoption checks. Analysis resolves it
once, stages fresh cache writes, and verifies artifacts again before
publication. A changed build rejects publication; failed staging or build
verification keeps the published cache pair. Cache-write failures after graph
publication warn without rolling back the successful graph. If identity is
unverifiable, the run uses bounded transient ParsedFile storage without
persistent cache reads or writes.
--no-parse-cache instead requests a cold parse and publishes its fresh cache
generation on success. FTS-only maintenance retains the old parser receipt.
These checks complement graph SCHEMA_FINGERPRINT, the analyzer runner
receipt, embedding preservation, and explicit wire-format checks such as the
V8 envelope and receiver-chain version. Benchmark semantic goldens still
require review of changed facts and pack membership; automatic compatibility
does not approve a new baseline.
LadybugDB schema
Defined in lbug/schema.ts. Separate node tables per type, single CodeRelation table.
Node tables: File, Folder, Function, Class, Interface, Method, Constructor, CodeElement, Struct, Enum, Macro, Typedef, Union, Namespace, Trait, Impl, TypeAlias, Const, Static, Property, Record, Delegate, Annotation, Template, Module, Community, Process, Route, Tool, Section, Embedding.
Relation types (CodeRelation.type): CONTAINS, DEFINES, CALLS, IMPORTS, INHERITS, EXTENDS, IMPLEMENTS, USES, DECORATES, HAS_METHOD, HAS_PROPERTY, ACCESSES, METHOD_OVERRIDES, METHOD_IMPLEMENTS, MEMBER_OF, STEP_IN_PROCESS, HANDLES_ROUTE, FETCHES, HANDLES_TOOL, ENTRY_POINT_OF, WRAPS, QUERIES, INJECTS, CONDITIONAL_ON, DECLARES, ADVISED_BY, BINDS_EVENT_HANDLER, EMITS_EVENT.
Optional --pdg additions (off by default, opt-in via gitnexus analyze --pdg; see Optional CFG/PDG emission above): a BasicBlock node table, plus the PDG relation types CFG, REACHING_DEF, CDG, TAINTED, SANITIZES, and TAINT_PATH on the same CodeRelation table. These are deliberately kept out of the default VALID_RELATION_TYPES / web graph schema — query them via cypher, explain, or pdg_query.
Embeddings and search
Embeddings (src/core/embeddings/): Snowflake arctic-embed-xs (384D). Embeddable: File, Function, Class, Method, Interface. Incremental via SHA1 content hash. Separate Embedding table.
Search (src/core/search/): Hybrid BM25 + semantic vector, merged via Reciprocal Rank Fusion (K=60).
Known limitations
Overloaded method resolution
Node IDs use arity suffix (#<paramCount>): Method:file:Class.method#1 vs #2.
Same-arity disambiguation: type-hash suffix ~type1,type2 when collision detected and type annotations present. Languages without types (Python, Ruby, JS) use arity-only. TS/JS overload signatures excluded (collapse to implementation body). See #651.
C++ const-qualified: $const suffix after type-hash when non-const collision exists: Method:file:Container.begin#0$const.
Generic/template types: type-hash uses rawType (full AST text including generics): ~vector<int> vs ~vector<std::string>.
ID stability: collision-only tags mean IDs change when overloads are added. save#1 becomes save#1~int when save(String) is added.
Variadic matching: confidence 0.7 when one side is variadic and the other has fixed count.
METHOD_IMPLEMENTS confidence tiering:
| Match quality | Confidence |
|---|---|
| Exact parameter types match | 1.0 |
| Arity match, types unavailable | 1.0 |
| Variadic vs fixed | 0.7 |
| Insufficient info | 0.7 |
Related docs
- MIGRATION.md — breaking changes and migration guidance
- RUNBOOK.md — operational commands and recovery
- GUARDRAILS.md — safety boundaries for humans and agents
- TESTING.md — how to run tests
- docs/languages/objective-c-provider.md — Objective-C provider behavior and limits
- docs/languages/r-provider.md — R provider behavior and limits
AGENTS.md/CLAUDE.md— agent workflows and tool usage