GitNexus/RUNBOOK.md
glier 3da42dce99
Some checks are pending
Gitleaks / gitleaks (push) Waiting to run
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
fix(analyze): enforce parser-worker heap caps and stop charging workers the main heap (#4045)
* 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>
2026-11-24 20:25:03 +00:00

24 KiB
Raw Permalink Blame History

Runbook — GitNexus

Short, copy-paste operations for local development, MCP, and CI. Commands assume a Unix shell; on Windows use Git Bash or equivalent paths.

Prerequisites

  • Node.js ≥ 20 (gitnexus-web/package.json engines).
  • Git (analyze requires a git repository).
  • From repo root, install and build the CLI package:
cd gitnexus
npm install
npm run build

Use npx gitnexus … from any path after global/published install, or node dist/cli/index.js … when developing from gitnexus/ with a local build.


Index out of date / “stale” tools

Symptom: MCP or resources warn the index is behind HEAD, or results don’t reflect recent commits.

Fix (from the target repo root):

npx gitnexus analyze

Force full rebuild (same commit but suspect corruption or changed ignore rules):

npx gitnexus analyze --force

Check status:

npx gitnexus status

List what MCP knows about:

npx gitnexus list

Scope extraction incomplete: npx gitnexus status reports incompleteReasons: ["scope-extraction-failed"] when one or more files still lack scope captures after the worker and fallback passes. impact and context then report a lower bound with causes.scopeExtractionFiles set to the affected file count. Re-run npx gitnexus analyze --force; if the reason remains, inspect the scope-extraction warnings for the unsupported or malformed source file. Every pre-existing index remains unverified until it is analyzed once by a version that writes the completeness receipt. An older index or unreadable completeness record reports incompleteReasons: ["scope-extraction-unverified"]; re-analyze it before treating empty impact results as exact.

Invalid symbol identity: query, context, or impact can return The index returned an invalid symbol identity with recovery guidance instead of returning malformed results. Rebuild from the affected repository root with npx gitnexus analyze --force. If the error returns, retain the failing command, GitNexus/Node versions and gitnexus doctor output for investigation. This check detects blank IDs and NUL-containing identity fields; it does not prove that every otherwise plausible name, path or source range is correct.

MCP freshness after rebuilding: a warm session refreshes its index reference when it opens the replacement graph, including a rebuild at the same commit. A busy reader keeps its old reference until it can reopen. During an observed graph/metadata publication gap, freshness is unknown; retry after analysis finishes rather than treating that response as current.


Embeddings

First time with vectors (slower, more disk/RAM):

npx gitnexus analyze --embeddings

Chunking defaults to AST boundaries with a 1,200-character budget and 120-character overlap. Set GITNEXUS_EMBEDDING_CHUNK_SIZE, GITNEXUS_EMBEDDING_CHUNK_OVERLAP, and GITNEXUS_EMBEDDING_CHUNK_STRATEGY=ast|fixed to override them. The size must be a safe integer of at least 2, and overlap must be a nonnegative integer smaller than the size. Blank values use the configured defaults. Smaller chunks can increase embedding requests. Class inputs retain declarations and fields; method implementations remain searchable through their own nodes. Unsupported parsers and indivisible oversized expressions use bounded character windows; Class parser failures retain metadata only. AST overlap repeats only whole statements that fit the overlap budget. Preceding context excludes text already in the next chunk, avoiding duplicate model input.

Full-retention indexes read original source for classes and long or truncated snippets, after skipping unchanged nodes. This preserves indentation, tails beyond the FTS snippet cap, and source ranges. The source must match the indexed file fingerprint: if embedding sync reports missing or changed source, restore the checkout or run gitnexus analyze before retrying. Older non-git indexes did not store file fingerprints. From that checkout, run gitnexus analyze once, then retry gitnexus embeddings sync or the server's embedding job. Sync cannot safely reconstruct the old snapshot's fingerprints from current files, so it requires reanalysis instead of reading unverified source. Symbol/none retention never reads checkout content for embedding; limited retained snippets use conservative enclosing ranges. Changed chunk policies and source-aware layouts refresh affected vectors once; unchanged short default inputs retain their hashes. Recovering source beyond the old snippet cap can increase vector counts and initial embedding time; unchanged nodes still skip source reads and inference. When a file changes, verified identical inputs and ranges reuse their existing vectors and refresh only the cached fingerprint. Changed tails and incomplete checkpoint groups still regenerate their vectors.

For paired performance measurements, build both checkouts and run from gitnexus/: node --expose-gc bench/embedding-chunking/measure.mjs /path/to/baseline /path/to/candidate /tmp/chunk-bench.json. The embedding-chunking-benchmark job in .github/workflows/ci-tests.yml builds the comparison revision and candidate, runs this benchmark with --source, and uploads the JSON samples and log as embedding-chunking-performance for 30 days. The benchmark uses the local embedding model and saves raw samples outside the repository. Recorded paired measurements and their environment are in gitnexus/bench/embedding-chunking/baseline.json. These are diagnostic references, not machine-independent timing gates. Compare per-cohort median/p95, input counts, and memory observations; it does not substitute for native analyze and persistence tests. To include source verification and the stored-snippet cap in the comparison, run node --expose-gc bench/embedding-chunking/measure.mjs /path/to/baseline /path/to/candidate /tmp/chunk-bench.json --source. The large-function and medium-statement cohorts expose extra coverage and overlap costs; compare complete-source candidates separately from older capped inputs.

Important: If you already had embeddings, a plain npx gitnexus analyze preserves them (Non-negotiable 5 in GUARDRAILS.md) — pass --embeddings when you also want vectors generated for new or changed nodes, and --drop-embeddings only for a deliberate wipe. See stats.embeddings in .gitnexus/gitnexus.json (or its legacy meta.json mirror; 0 means none) — but that figure isn't always freshly measured: if a run's embedding-count query can't answer, it carries the previous run's number forward instead of writing a wrong zero. For a certified read, check capabilities.vectorSearch.status instead — it reads unavailable (never a stale count) whenever GitNexus can't vouch for the live vector index.

Embedding work interrupted after graph publication: The graph and keyword index become available before embedding work starts. An embedding failure makes analyze exit nonzero while keeping that graph available and retaining acknowledged embedding work. npx gitnexus status --json reports graph freshness separately from embedding progress and vector readiness. Resume with:

npx gitnexus analyze

No --embeddings flag is needed for a retained job. npx gitnexus embeddings sync also resumes work against an already published graph. Compatible acknowledged units do not call the provider again; a unit interrupted before acknowledgement may replay. A source or embedding-configuration change revalidates reuse, and changing worker counts or memory budgets does not invalidate paid vectors. --drop-embeddings deliberately abandons retained vectors. --force rebuilds the graph while retaining compatible paid work for reuse.

Older indexes may instead carry an embeddingCheckpoint and report embedding-checkpoint-pending. Plain analyze recovers that checkpoint, including any explicitly referenced staging data, before migrating it. Historical vectors without verified provider/model provenance are retained without being relabeled as output from the current model.

Collapsed graph write (analyze exits NON-ZERO and says INCOMPLETE): A run can finish writing metadata while only a fraction of the relationships it produced are readable back from the index — edges collapsing to a small share of what was built, or a CodeRelation table that never materialized (which reads as a persisted count of zero). Because the metadata IS written and the DB does hold rows, nothing looks broken: queries answer with missing edges rather than an error, which is a confident empty answer rather than a failure. npx gitnexus status reports incompleteReasons: ["graph-write-collapsed"], the analyze summary prints Repository indexed INCOMPLETELY with the expected and persisted counts, and the CLI exits non-zero so automation is not told an unusable index is fine.

Recovery is a full rebuild:

npx gitnexus analyze --force

If it recurs, the cause is almost always environmental rather than a code defect: check free disk space on the volume holding .gitnexus/, make sure no second analyze is running against the same repo (both use .gitnexus/csv for staging), then run npx gitnexus doctor. The check compares in-memory relationship totals (including streamed rows) against what the DB hands back, and is deliberately skipped on incremental runs, where the two counts are not comparable.

Weak semantic recall despite existing embeddings: If paraphrased queries look like keyword-only search, the distance cutoff may be too strict for the embedding model. CLI and MCP query default to 0.6. From the indexed repository, try a broader cutoff:

GITNEXUS_VECTOR_MAX_DISTANCE=0.8 npx gitnexus query "how are expired sessions removed" --limit 10

Compare target inclusion and ranking against the default; a broader cutoff also admits less relevant hits. Set the variable in the MCP/serve launch environment and restart that process when tuning a server. A cutoff change needs no reindex and setting it only during analyze does not persist it. If the index has no vectors, generate embeddings first; if the embedding model or dimensions differ between indexing and querying, align that configuration and regenerate vectors. See Vector cutoff tuning for validation rules and the limited voyage-code-4 evidence from #3457.

Large repos: Analyze may skip or limit embedding work when node counts are very high; watch CLI output.


Debugging reference provenance

Analysis emits a structured graph_reference_integrity summary to stderr with checked sites, suppressed duplicates, and unverified counts by reason. These describe ingestion checks, not persisted database totals, query completeness, or resolution accuracy. Successful single-repository MCP graph object responses expose the corresponding graph_integrity status. Empty and non-tabular Cypher results retain their raw array shape without a receipt. A missing graph_integrity field means provenance is unverified.

Run gitnexus analyze --force to replace an index with a missing or invalid receipt. This checks the new ingestion; it does not certify historical indexes or measurements. A fresh receipt can still be unverified when emitters lack original-file provenance. Responses that span mismatched database generations also remain unverified.

For examples of unverified identities, enable debug logging:

GITNEXUS_LOG_LEVEL=debug npx gitnexus analyze --force 2>gitnexus-debug.log

graph_reference_unverified includes at most one example per reason per analysis: opaque IDs, collapsed IDs, point-only sites, extracted coordinates, and partial mappings. graph_reference_rejected identifies the invalid relationship, endpoints, source file, emission reason, and stack before the write is rejected. Source buffers are not logged; diagnostic IDs and emission reasons can contain source-derived names or literals. Concurrent edits and unreadable sources remain unverified (sourceChanged / sourceUnavailable, with the read error code); they do not abort analysis. A rejected record prevents a successful ingestion summary; the previous published index remains available when the failed run used staging.

MCP: no repos / empty tools

Symptom: GitNexus: No indexed repos yet on stderr when starting MCP.

Fix: In each project you want indexed:

cd /path/to/repo
npx gitnexus analyze

Restart the editor MCP session if needed. The server refreshes the registry lazily; new analyzes are picked up without necessarily reinstalling MCP.

Symptom: Wrong repo when multiple are indexed — pass repo on tools or use list_repos first.


Clean slate (corrupt or huge .gitnexus)

Current repo only (prompts for confirmation):

npx gitnexus clean

Skip confirmation:

npx gitnexus clean --force

All registered repos:

npx gitnexus clean --all --force

Then re-run npx gitnexus analyze (and --embeddings if you need vectors).


Local bridge for the web UI

cd gitnexus
npx gitnexus serve
# default http://127.0.0.1:4747 — see serve --help for port/host

Use when the browser UI should talk to local indexed repos instead of WASM-only mode.


CLI equivalents of MCP tools

Useful for debugging without an editor:

cd gitnexus
npx gitnexus query "authentication flow" --repo MyRepo
npx gitnexus context SomeSymbol --repo MyRepo
npx gitnexus impact SomeSymbol --direction upstream --repo MyRepo
npx gitnexus cypher "MATCH (n) RETURN count(n) LIMIT 1" --repo MyRepo

CI failures (contributors)

Orchestrator: .github/workflows/ci.yml.

Job Typical local repro
quality cd gitnexus && npx tsc --noEmit
unit-tests cd gitnexus && npx vitest run test/unit
integration cd gitnexus && npx vitest run test/integration (see workflow matrix for groups)
e2e Triggered when gitnexus-web/ changes; cd gitnexus-web && E2E=1 npx playwright test (requires gitnexus serve + npm run dev)

Note: Pushes that touch only certain markdown paths may be skipped by paths-ignore in CI — see workflow file for exact patterns.


Query memory limit

Symptom: a CLI, MCP, or HTTP server process exits with code 70 and GitNexus stopped: process memory reached … on stderr.

The pooled-read guard detected memory above its process-wide budget. Native query allocations are outside both V8's heap limit and LadybugDB's buffer pool. The Node binding cannot interrupt them, so the guard exits the process to release memory. Every request in that process is interrupted; restart the CLI/server or reconnect the MCP client. A read-only query does not require a reindex after this exit.

To diagnose a repeat, set GITNEXUS_QUERY_TRACE=1 in the query/server environment and retain stderr. It includes query text but not bound parameters. Review the output before sharing it with issue #3696. Set GITNEXUS_QUERY_MAX_RSS_MB=<MiB> to change the limit; 0 disables it. The default is max(8 GiB, 25% of available RAM), capped at 75% of available RAM, including a reported container/runtime constraint.

RSS is checked at query start/end and every 200 ms while reads run. On macOS, queries lasting at least one second also sample physical footprint at most once per second, including compressed/swapped memory. If the OS footprint command is unavailable, monitoring falls back to RSS. Sampling is a mitigation, not a hard OS memory limit: rapid allocation or a blocked event loop can outrun it. Writes during analyze are outside this guard.

The caller's 30-second read deadline covers prepare, execution, and row materialization. Timing out does not cancel native work: monitoring and its checked-out connection remain owned by that work until it settles. An impact frontier is separately capped at 100,000 relationship rows per depth. A capped walk stops and reports partial: true. Both risk and riskSharedAxes retain HIGH/CRITICAL or report UNKNOWN instead of LOW/MEDIUM. This row cap does not bound the database's intermediate allocations. Narrow the target or relation filters before relying on a partial result.

Memory / analyze crashes

PDG indexing can spill lexical scopes to temporary storage for any language that builds a PDG when V8 heap usage reaches 70%. If the automatic spill cannot write its shards, indexing continues in memory and logs a warning. Check free space in the index storage directory if you see that warning. See scope index environment settings for explicit disk and resident overrides.

Analyze re-execs Node with a large old-space heap when needed (analyze.ts). If you still OOM on huge repos, close other processes, avoid --embeddings for a first pass, or analyze a smaller path if supported by your workflow.

--resource-budget <MiB> admits the analyzer process family within one memory reservation: the frontend, main heap, parser workers, native graph/vector pools, embedding model, bounded input queue, and headroom. For example:

npx gitnexus analyze --embeddings --resource-budget 8192 --memory-budget 1024 --workers 2

Each parser worker reserves its old-space cap plus 128 MiB for the young generation and native allocations. Raising --memory-budget leaves less room for worker heaps or additional workers. Explicit settings that do not fit the family budget fail before work starts. Without a family override, GitNexus fixes the family ceiling at 75% of effective process/container RAM, divided among concurrent auto-sync analyses. Automatic heap, worker and native pool allocations must fit that ceiling; it never grows to accommodate them. Explicit heap, worker or pool requests that cannot fit are rejected before work. Small hosts may need an HTTP embedding provider or more RAM for the local model. Community-detection workers and user preload isolates sit outside these reservations. An admission error reports the minimum for the allocations at the rejected budget. A larger total can also increase headroom and pool sizes, so it may take more than that minimum. Watch mode accepts the same family budget and drains active work before shutdown.

When setting the heap manually with GITNEXUS_MEMORY=off, parser workers keep their caps under --max-old-space-size, --max-semi-space-size, --max-heap-size and --max-old-space-size-percentage, in every spelling Node and V8 accept, and other workers keep the main heap those flags give. If V8's flags are frozen (--freeze-flags-after-init) or the flags analyze reads do not match the heap V8 reports, parser workers keep the main heap and admission charges each one for it.

Unable to allocate memory / The buffer pool is full during graph writes refers to LadybugDB's native buffer pool. Increasing NODE_OPTIONS, --memory-budget, or worker heap limits does not resize that pool. Recognized pool exhaustion aborts analysis instead of retrying with row skipping.

If the host has enough memory, set an explicit pool size in bytes, then rebuild. For example, 3 GiB is 3221225472 bytes:

GITNEXUS_LBUG_BUFFER_POOL_SIZE=3221225472 npx gitnexus analyze --force

The override bypasses automatic pool sizing. Budget for the Node heap, parse workers, other native allocations, and the OS alongside it; a larger pool can exhaust the host. Outside bounded analysis, GITNEXUS_LBUG_BUFFER_POOL_SIZE=0 selects LadybugDB's native 80%-of-RAM default. Analysis and embedding admission reject zero because that native allocation cannot fit alongside their other reservations. Unset the variable for automatic sizing, or set an explicit byte limit of at least 8 MiB that fits the resource budget. If memory is insufficient, exclude generated/vendor directories or use a larger host.

A measured graph-write collapse aborts a staged build before publication, leaving the previous index, if any, intact. An in-place run cannot roll back: it records graph-write-collapsed and exits nonzero. Rebuild a previously collapsed index with --force after addressing memory, disk space, or the reported COPY error; do not rely on its incomplete query results.


LadybugDB / lock errors

Only one process should open a repo's .gitnexus/lbug store at a time. If MCP and a second analyze run conflict, stop one process, then retry analyze or restart MCP.

If the error text is "Only one write transaction at a time is allowed in the system." instead of a lock/busy message, it's the same underlying conflict — our retry matcher (isDbBusyError in src/core/lbug/lbug-config.ts) recognizes this exact string and auto-retries it. The fix if it still surfaces after retries is the same: stop the overlapping process.


File acquisition/reclaim guard recovery

The portable file-lock backend uses analyze.lock.guard beside analyze.lock. Every acquisition, including an empty slot, exclusively creates the guard before inspecting, reclaiming, creating, and verifying the main lock. It removes the guard before returning a workload handle or waiting on a live workload holder. Linux abstract-socket and Windows named-pipe locking are unchanged.

A stalled or crashed guard owner blocks file acquisition even when its PID is dead, its metadata is incomplete, or no main lock exists. The guard is never automatically stolen. Guard contention times out after at most 30 seconds, capped by the remaining acquisition timeout. This separate ceiling applies even when GITNEXUS_INDEX_LOCK_TIMEOUT_MS is zero or negative (unbounded workload wait). A guard-cleanup failure rejects acquisition; it must not start unprotected work.

Manual recovery is an outage procedure, not an age/PID-based cleanup:

  1. Identify the exact lock directory named in the error. This shared primitive also protects group sync and registry operations, not just repo analysis.
  2. Stop all relevant writers and prevent restart: editor/agent hooks, watch processes, scheduled jobs, services, and any containers sharing the directory. Account for paused processes and every host with access. If quiescence cannot be established, do not remove the guard. PID metadata is diagnostic only.
  3. While restart remains disabled, inspect and preserve the guard/main records for diagnosis, then remove only that directory's orphan analyze.lock.guard and, if present, its orphan analyze.lock. Do not remove databases or sidecars as part of lock recovery. Do not use a recursive or wildcard cleanup.
  4. Ensure all participating writers use the guarded version and the same locking backend/domain, then restart in a controlled fashion.

Upgrade requires a coordinated stop/upgrade/restart. Concurrent older versions ignore the guard and can still displace live locks; mixed-version mutual exclusion is not guaranteed. The file protocol assumes reliable atomic local-filesystem O_EXCL creation and cooperating processes. Network/distributed filesystems, external file replacement, and uncoordinated manual deletion are not covered. A process crash while holding the short-lived guard trades automatic recovery for fail-closed safety. Denied file creation returns a non-owning lockFree handle only when neither workload lock nor acquisition guard exists; unreadable paths fail closed. No staging sweep runs without ownership. Analysis, registry transactions, group synchronization, and embeddings sync refuse lockFree handles, including an otherwise up-to-date analysis on a file-backend read-only mount. The socket backend can still acquire ownership on a read-only index mount. Heterogeneous permissions are not proof that another process cannot write.

If guard cleanup fails after this attempt created its workload record, acquisition is refused and token-exact workload cleanup is attempted before returning the error. Failed or unverifiable cleanup must be diagnosed under the same quiesced recovery procedure above; never delete a possibly active successor's record.


Where to dig deeper