mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-12-01 23:57:21 +00:00
Some checks are pending
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (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: rebuild changed graphs in fresh databases Populated-table writes inflate LadybugDB storage (#3852). Bulk-load fresh graphs while retaining parse caches, no-ops and logical counts. Read prior graphs without writes so staging failures preserve their bytes. Restore compatible vectors and rebuild derived layers and FTS under the existing checkpoint and publication guards. Keep the write policy, preservation guards and regressions together so the replacement has one coherent publication contract. Closes #3852 * perf: skip FTS builds for empty tables * fix: align CI with compact graph writes Validate populated-table FTS coverage and cached full writes while keeping the performance budget unchanged. Compare database bytes without enumerating Buffer keys, and retain native checkpoint failure details. * perf: use bounded hybrid graph writes Keep small edits selective and scale the mutation budget with graph size. Compact accumulated native storage growth without copying every graph on every edit. Preserve physical receipts across shared-store publication and native resource limits during recovery. Align CI assertions with selective writes and populated FTS tables. Refs #3852 * fix: close hybrid compaction gaps Count removed rows before selective writes and preserve the shared graph's compaction receipt when publishing completed vectors. * test: serialize compaction native suites * test: declare capped count determinism * test: mock persisted rows in FTS fixtures * fix: address hybrid write review (#3854) Retain unreadable graph bytes before recovery and stop destructive writes when the real embedding cache probe fails. Keep small deletions and renames selective, preserve healthy private graphs through edit/revert cycles, and bound FTS presence probes. Cover durability, footprint boundaries and vector restoration. Align mock graph fixtures and fix the pre-existing WAL test's UUID false positive found by full-suite validation; its nine-test suite now passes. * test: clarify selective restore fixture (#3854) * test: isolate recovery CI fixtures (#3854) Cap embedding generation in the missing-graph recovery fixture so it does not require optional model packages. Allow cold PowerShell startup in the OS identity smoke test; retain the five-second production probe limit. * test: finish review cleanup (#3854) * test: strengthen graph integrity checks Hash persisted node and edge properties; clean failed fixtures and gate FTS setup through the test lifecycle. Refs #3854 --------- Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
13 KiB
13 KiB
Guardrails — GitNexus
Rules for human contributors and AI agents. Complements AGENTS.md (workflows) and CONTRIBUTING.md (PR process).
Scope (least privilege)
- Read: Source, tests, docs, public config as needed.
- Write: Only files required for the fix or feature; no unrelated formatting or refactors.
- Execute: Tests, typecheck, documented CLI commands. No destructive commands on user data without approval.
- Off-limits: Other people's machines, production deployments you don't own, credentials you lack permission to use.
Maintainer may widen scope per task.
Non-negotiables
- Never commit secrets — API keys, tokens, real
.envvalues, private URLs, session cookies. Use.env.examplewith placeholders. - Never rename with find-and-replace in GitNexus-indexed projects — use
renamewithdry_run: truefirst (omittingdry_runalso previews), review exact graph-backed semantic spans and coverage, then apply withrename,dry_run: false, and that preview'splan_token. Unsupported targets fail closed; inspect and refactor them manually with language-aware tools. No separategitnexus renameCLI exists. - Run impact analysis before editing shared symbols —
impact(upstream) for functions/classes/methods others call. Do not ignore HIGH/CRITICAL without maintainer sign-off. - Run
detect_changesbefore commit — confirm diffs map to expected symbols/processes when the graph is available. - Preserve embeddings — plain
npx gitnexus analyzenow preserves any embeddings recorded in the index metadata (.gitnexus/gitnexus.json, mirrored to the legacymeta.json) — the previous behavior wiped them. Use--embeddingsto also generate vectors for new/changed nodes; use--drop-embeddingsonly when an explicit wipe is intended (e.g., model swap). - Never
terminate()a worker that may be inside a native call — killing a worker thread mid-N-API aborts the entire process (Napi::Error→std::terminate→ SIGABRT, #2432), so a timeout meant to trigger a graceful fallback takes the whole run down instead. Any worker running native code (tree-sitter grammars, LadybugDB, Icebug) must either reach a JS-visible safe point first — the parse pool'sshutdownDrainMshandshake insrc/core/ingestion/workers/worker-pool.ts— or be abandoned withunref()and left to exit on its own. A one-shot worker that ends after a singlepostMessageneeds noterminate()at all: it exits by itself. This bites hardest on the path you cannot test locally, because the abort only reproduces once the native module actually loads.
Signs (recurring failure patterns)
Format: Trigger → Instruction → Reason. Append new Signs when the same mistake repeats.
Stale graph after edits
- Trigger: MCP warns index is behind
HEAD, or search doesn't match latest commit. - Do:
npx gitnexus analyze(plus--embeddingsif used). Runs incrementally by default — the pipeline parses every file every run (cross-file resolution requires it), but tree-sitter dispatch is skipped for unchanged file chunks via the content-addressed cache, and only changed-file rows (plus their importers, transitively) are rewritten in LadybugDB. When the effective write set exceeds ~50% of the repo's files (minimum 50 files), the run transparently switches to the full wipe + bulk-COPY write plan and logs "switching to a full DB write" — expected behavior, not a bug, and file-level bookkeeping stays incremental. That same line also appears — regardless of write-set size, even for a one-file change — when a LadybugDB extension the existing index depends on cannot load on this machine (VECTOR, #2623; FTS, #2841), because a DB carrying those indexes refuses all row-level DML until the extension is loaded; rungitnexus doctorfor live extension status and re-run withGITNEXUS_LBUG_EXTENSION_INSTALL=auto(with network access) to allow one bounded install attempt. The rebuild is one-shot: it clears the indexes, so the next run goes back to the incremental plan. - Compaction (#3852): Small edits, deletions and renames remain selective. A fresh bulk load is selected after 16 successful incremental writes, storage growth beyond the larger of 50% or 16 MiB, or an old/new source-file footprint reaching the larger of 2,000 graph rows or 5% of the graph. Missing or invalid compaction metadata establishes a fresh baseline once. Compaction can run on an unchanged snapshot when due; other unchanged snapshots still return immediately. Counters and size baselines belong to each index and advance only after verified publication.
- Why: Tools query LadybugDB from last analyze; git changes are invisible until re-indexed.
Index seems corrupt or "incremental" is misbehaving
- Trigger:
analyzeproduces unexpected results, orincrementalInProgressis set in the index metadata (.gitnexus/gitnexus.json/ legacymeta.json), or the index is in a half-state after a crash. - Do:
npx gitnexus analyze --forceto rebuild the graph and FTS indexes. This may reuse unchanged parser output; when debugging parser/capture changes, usenpx gitnexus analyze --no-parse-cacheto rebuild that output too. The dirty-flag check forces the graph rebuild automatically when a previous incremental run didn't complete cleanly. A dirty-flag recovery rebuild parks the interrupted run's sidecars beside the DB aslbug.wal.dirty-recovery/lbug.shadow.dirty-recoveryfor post-mortem debugging — harmless, and removable withnpx gitnexus clean --lbug-sidecars. Safe to delete the.gitnexus/parse-cache/directory (and any legacy.gitnexus/parse-cache.json) at any time — content-addressed, will be regenerated. - Why: Incremental writeback is selective DB row replacement; if the on-disk state is inconsistent for any reason, a full rebuild is the cheapest path back to a known-good index.
Embeddings vanished after analyze
- Trigger: Semantic search quality drops;
stats.embeddingsin the index metadata (gitnexus.json/ legacymeta.json) is 0 after refresh. - Do: Re-run
npx gitnexus analyze --embeddingsto regenerate. A missing old graph has no legacy rows to restore. Recovery from a corrupt or storage-incompatible graph retains its bytes inlbug.unreadable.<id>before rebuilding; keep that file if its vectors may be recoverable with the previous engine. A read failure after opening the database stops analysis: fix the read failure, or explicitly pass--drop-embeddingsto discard the old vectors. - Why: Plain
analyzepreserves prior vectors in their artifact (or restores the legacy in-graph cache). An explicit drop, unavailable old storage, or an incompatible embedding schema can leave no reusable vectors; an arbitrary probe/read error is not evidence that the cache is empty. See the Sign below for partial embedding failures. A dirty-recovery run that cannot move the crashed WAL aside either discards it (logged: forensics lost, embeddings still preserved) or fails fast with a lock error naming the holder.
Analyze finishes but embeddings are incomplete (partial embedding index)
- Trigger:
gitnexus status --jsonreportsembedding-job-pending(or the legacyembedding-checkpoint-pending), or an embedding failure follows graph publication. - Do: Re-run plain
gitnexus analyze; retained work resumes without--embeddings. InspectembeddingProgressfor completed, reused, failed and excluded nodes.--forcerebuilds the graph and retains compatible vectors for reuse;--drop-embeddingsdeliberately abandons embedding work. - Why: Graph and vector publication are separate. The graph is usable while a job is pending; semantic search reports degradation until a sealed compatible artifact is published. Deterministic input rejections are retried across at most three invocations, then excluded with a recorded reason. Provider outages remain resumable. Do not delete job artifacts to clear a status warning: they contain paid vectors.
Scope extraction is incomplete
- Trigger:
npx gitnexus statusreportsincompleteReasons: ["scope-extraction-failed"]when files were omitted, orincompleteReasons: ["scope-extraction-unverified"]when the index predates the completeness receipt or its metadata is unreadable.impact/contextreports the same uncertainty asepistemic: "lower-bound"; confirmed omissions setcauses.scopeExtractionFiles > 0. - Do: Re-run
npx gitnexus analyze(--forcefor a full graph rebuild). If the reason persists, inspect the scope-extraction warnings and treat impact counts as floors until the affected source is supported or corrected. - Why: Parsing continued, but scope captures for the reported file count could not be produced even after the main-thread fallback. Calls, inheritance, imports, or accesses originating there may therefore be absent from the graph.
Analyze reports INCOMPLETE with a collapsed graph write
- Trigger: Analysis rejects a staged graph write with expected and persisted relationship counts, or an in-place run prints
Repository indexed INCOMPLETELY, exits nonzero, and recordsincompleteReasons: ["graph-write-collapsed"]. - Do: Inspect COPY errors, available memory, and free disk space on the volume holding
.gitnexus/; confirm no secondanalyzeis running against the same repo, then runnpx gitnexus doctor. For native buffer-pool exhaustion, see RUNBOOK.md forGITNEXUS_LBUG_BUFFER_POOL_SIZEand memory-budget guidance. Re-runnpx gitnexus analyze --forceafter addressing the cause. - Why: Far fewer relationships are readable back than the pipeline produced. A staged build throws before publication and preserves the previous index, if any. In-place writes cannot roll back, so the incomplete stamp and nonzero exit prevent a partial graph from being presented as successful. Recognized buffer exhaustion also throws immediately during COPY or fallback inserts. The collapse check compares in-memory totals (including streamed rows) against the post-write count, stays unmeasurable when the count cannot be read, and is skipped on incremental runs where whole-scope counts are not comparable.
MCP lists no repos
- Trigger: MCP stderr says no indexed repos.
- Do:
npx gitnexus analyzein the target repo; verifynpx gitnexus listshows it. - Why: MCP discovers repos via
~/.gitnexus/registry.json, populated by analyze.
Wrong repo in multi-repo setups
- Trigger: Query/impact results belong to another project.
- Do: Confirm an MCP default is configured or the GitNexus process was launched inside the intended registered path without crossing into an unindexed nested Git checkout. Otherwise call
list_repos, then passrepoon subsequent tools; pass it for mutating tools when multiple repos are registered and no MCP default exists. - Why: Read-only tools derive their default from MCP configuration or a process cwd that stays within one registered Git boundary. Outside those paths the target remains ambiguous, and mutating tools stay explicit unless configuration supplies the target.
LadybugDB lock / "database busy"
- Trigger: Errors opening
.gitnexus/lbugwhile MCP and analyze both run. - Do: Stop overlapping processes (one writer at a time). Retry analyze or restart MCP.
- Why: Embedded DB expects single-process ownership.
@ladybugdb/core0.18.0 also reports this contention as"Only one write transaction at a time is allowed in the system."— our busy/lock retry matcher (isDbBusyErrorinsrc/core/lbug/lbug-config.ts) recognizes this exact string too, so it's auto-retried the same as any other lock error. If you see that exact message, it's the same "one writer at a time" issue above, not a new failure mode.
Publishing & supply chain
- npm: Do not publish from unreviewed automation. Bump version intentionally; tag releases to match
package.json. - Dependencies: Minimal, auditable
package.jsonchanges; run tests and CI after lockfile updates. - License: PolyForm Noncommercial 1.0.0 — do not relicense without maintainer approval.
Escalation
Stop and ask a human maintainer when:
- Impact analysis shows HIGH/CRITICAL risk and the task still requires the change.
- You need to alter CI, release, or security-sensitive config.
- Requirements conflict (e.g. "speed up analyze" vs "must keep all embeddings on huge repo").
- You are unsure whether data loss is acceptable (
clean, forced migrations, schema changes).
Related docs
- ARCHITECTURE.md — components and data flow
- RUNBOOK.md — commands for recovery
- CONTRIBUTING.md — PR and commit expectations