gitnexus 1.6.9-rc.44 → 1.6.9-rc.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -40,14 +40,14 @@ To configure MCP for your editor, run `npx gitnexus setup` once — or set it up
40
40
 
41
41
  | Editor | MCP | Skills | Hooks (auto-augment) | Support |
42
42
  | ------------------------ | --- | ------ | ------------------------------------------------------------------------------------------ | ------------ |
43
- | **Claude Code** | Yes | Yes | Yes (PreToolUse) | **Full** |
43
+ | **Claude Code** | Yes | Yes | Yes (PreToolUse + PostToolUse) | **Full** |
44
44
  | **Cursor** | Yes | Yes | Yes (postToolUse, [manual install](../gitnexus-cursor-integration/README.md#hook-install)) | **Full** |
45
45
  | **Antigravity** (Google) | Yes | Yes | Yes (AfterTool, [Gemini CLI hooks schema](https://geminicli.com/docs/hooks/reference/)) | **Full** |
46
46
  | **Codex** | Yes | Yes | — | MCP + Skills |
47
- | **Windsurf** | Yes | — | — | MCP |
48
47
  | **OpenCode** | Yes | Yes | — | MCP + Skills |
48
+ | **Windsurf** | Yes | — | — | MCP |
49
49
 
50
- > **Claude Code** gets the deepest integration: MCP tools + agent skills + PreToolUse hooks that automatically enrich grep/glob/bash calls with knowledge graph context.
50
+ > **Claude Code** gets the deepest integration: MCP tools + agent skills + PreToolUse hooks that automatically enrich grep/glob/bash calls with knowledge graph context + PostToolUse hooks that detect a stale index after commits and prompt the agent to reindex.
51
51
 
52
52
  ### Community Integrations
53
53
 
@@ -122,31 +122,44 @@ The result is a **LadybugDB graph database** stored locally in `.gitnexus/` with
122
122
 
123
123
  ## MCP Tools
124
124
 
125
- Your AI agent gets these tools automatically:
126
-
127
- | Tool | What It Does | `repo` Param |
128
- | ---------------- | ---------------------------------------------------------------- | ------------ |
129
- | `list_repos` | Discover all indexed repositories (paginated — `limit`/`offset`) | — |
130
- | `query` | Process-grouped hybrid search (BM25 + semantic + RRF) | Optional |
131
- | `context` | 360-degree symbol view — categorized refs, process participation | Optional |
132
- | `impact` | Blast radius analysis with depth grouping and confidence | Optional |
133
- | `detect_changes` | Git-diff impact maps changed lines to affected processes | Optional |
134
- | `rename` | Multi-file coordinated rename with graph + text search | Optional |
135
- | `cypher` | Raw Cypher graph queries | Optional |
136
-
137
- > With one indexed repo, the `repo` param is optional. With multiple, specify which: `query({search_query: "auth", repo: "my-app"})`.
125
+ Your AI agent gets **17 tools** (15 per-repo + 2 group) automatically:
126
+
127
+ | Tool | What It Does |
128
+ | ---------------- | ----------------------------------------------------------------------- |
129
+ | `list_repos` | Discover all indexed repositories (paginated — `limit`/`offset`) |
130
+ | `query` | Process-grouped hybrid search (BM25 + semantic + RRF) |
131
+ | `context` | 360-degree symbol view — categorized refs, process participation |
132
+ | `impact` | Blast radius analysis with depth grouping and confidence |
133
+ | `trace` | Shortest directed path between two symbols (call + class-member edges) |
134
+ | `detect_changes` | Git-diff impact maps changed lines to affected processes |
135
+ | `check` | Read-only structural checks against the indexed graph |
136
+ | `rename` | Multi-file coordinated rename with graph + text search |
137
+ | `cypher` | Raw Cypher graph queries |
138
+ | `route_map` | API route map — which components fetch which endpoints, and handlers |
139
+ | `tool_map` | MCP/RPC tool definitions — where they're defined and handled |
140
+ | `shape_check` | Validate API response shapes against consumers' property accesses |
141
+ | `api_impact` | Pre-change impact report for an API route handler |
142
+ | `explain` | Explain persisted taint findings (source→sink flows, `--pdg` indexes) |
143
+ | `pdg_query` | Query control/data dependence at statement level (`--pdg` indexes) |
144
+ | `group_list` | List configured repository groups |
145
+ | `group_sync` | Rebuild a group's Contract Registry and cross-repo links |
146
+
147
+ > With one indexed repo, the `repo` param is optional. With multiple, specify which: `query({search_query: "auth", repo: "my-app"})`. Per-repo tools also take an optional `branch` for multi-branch indexes. `explain` and `pdg_query` need an index built with `gitnexus analyze --pdg`.
138
148
 
139
149
  ## MCP Resources
140
150
 
141
151
  | Resource | Purpose |
142
152
  | --------------------------------------- | ---------------------------------------------------- |
143
153
  | `gitnexus://repos` | List all indexed repositories (read first) |
154
+ | `gitnexus://setup` | Setup and usage guidance for agents |
144
155
  | `gitnexus://repo/{name}/context` | Codebase stats, staleness check, and available tools |
145
156
  | `gitnexus://repo/{name}/clusters` | All functional clusters with cohesion scores |
146
157
  | `gitnexus://repo/{name}/cluster/{name}` | Cluster members and details |
147
158
  | `gitnexus://repo/{name}/processes` | All execution flows |
148
159
  | `gitnexus://repo/{name}/process/{name}` | Full process trace with steps |
149
160
  | `gitnexus://repo/{name}/schema` | Graph schema for Cypher queries |
161
+ | `gitnexus://group/{name}/contracts` | A group's extracted contracts and cross-links |
162
+ | `gitnexus://group/{name}/status` | Staleness of repos in a group |
150
163
 
151
164
  ## MCP Prompts
152
165
 
@@ -164,7 +177,11 @@ gitnexus analyze [path] # Index a repository (or update stale index)
164
177
  gitnexus analyze --repair-fts # Fast path: rebuild/verify only FTS indexes on existing index data
165
178
  gitnexus analyze --force # Full rebuild: re-parse + graph rebuild + FTS rebuild
166
179
  gitnexus analyze --embeddings # Enable embedding generation (slower, better search)
180
+ gitnexus analyze --skills # Generate repo-specific skill files from detected communities
167
181
  gitnexus analyze --skip-agents-md # Preserve custom AGENTS.md/CLAUDE.md gitnexus section edits
182
+ gitnexus analyze --skip-skills # Skip installing .claude/skills/gitnexus/ skill files
183
+ gitnexus analyze --skip-git # Index folders that are not Git repositories
184
+ gitnexus analyze --workers <n> # Parse worker pool size (>=1; default: cores-1, capped at 16)
168
185
  gitnexus analyze --verbose # Log skipped files when parsers are unavailable
169
186
  gitnexus analyze --max-file-size 1024 # Skip files larger than N KB (default: 512, cap: 32768)
170
187
  gitnexus analyze --worker-timeout 60 # Increase worker idle timeout for slow parses
@@ -177,13 +194,16 @@ gitnexus status # Show index status for current repo
177
194
  gitnexus clean # Delete index for current repo
178
195
  gitnexus clean --all --force # Delete all indexes
179
196
  gitnexus wiki [path] # Generate LLM-powered docs from knowledge graph
180
- gitnexus wiki --model <model> # Wiki with custom LLM model (default: gpt-4o-mini)
197
+ gitnexus wiki --model <model> # Wiki with custom LLM model (default: minimax/minimax-m2.5)
198
+ gitnexus doctor # Show runtime platform capabilities and embedding configuration
181
199
 
182
200
  # Direct graph queries — the same tools the MCP server exposes, no MCP daemon needed
183
201
  gitnexus query "<concept>" # Process-grouped hybrid search
184
202
  gitnexus context <symbol> [--uid <uid> | --file <path>] # 360° symbol view; flags disambiguate a shared name
185
203
  gitnexus impact <symbol> [--uid <uid> | --file <path> | --kind <kind>] # Blast radius; flags disambiguate a shared name
204
+ gitnexus trace <from> <to> # Shortest directed path between two symbols
186
205
  gitnexus detect-changes # Map the working-tree diff to affected symbols and execution flows
206
+ gitnexus check # Read-only structural checks against the indexed graph
187
207
  gitnexus cypher "<query>" # Run a raw Cypher query against the knowledge graph
188
208
 
189
209
  # Repository groups (multi-repo / monorepo service tracking)
@@ -195,6 +215,7 @@ gitnexus group sync <name> # Extract contrac
195
215
  gitnexus group contracts <name> # Inspect extracted contracts and cross-links
196
216
  gitnexus group query <name> <q> # Search execution flows across all repos in a group
197
217
  gitnexus group status <name> # Check staleness of repos in a group
218
+ gitnexus group impact <name> --target <symbol> --repo <groupPath> # Cross-repo blast radius
198
219
  ```
199
220
 
200
221
  > **`gitnexus uninstall`** reverses `gitnexus setup` — it removes the GitNexus MCP entries, hooks, and skill directories it added to each detected editor. Skill directories are identified **by bundled gitnexus skill name** (e.g. `gitnexus-cli/`), so if you customized files inside an installed skill directory, back them up first. It is a dry-run preview by default and prints the exact paths it would remove; pass `--force` to apply. Per-repo indexes (`gitnexus clean --all`) and the global npm package (`npm uninstall -g gitnexus`) are left for you to remove.
@@ -219,7 +240,7 @@ GitNexus supports indexing multiple repositories. Each `gitnexus analyze` regist
219
240
 
220
241
  ## Supported Languages
221
242
 
222
- TypeScript, JavaScript, Python, Java, C, C++, C#, Go, Rust, PHP, Kotlin, Swift, Ruby
243
+ TypeScript, JavaScript, Python, Java, C, C++, C#, Go, Rust, PHP, Kotlin, Swift, Ruby, Dart
223
244
 
224
245
  ### Language Feature Matrix
225
246
 
@@ -238,6 +259,7 @@ TypeScript, JavaScript, Python, Java, C, C++, C#, Go, Rust, PHP, Kotlin, Swift,
238
259
  | Swift | — | — | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ |
239
260
  | C | — | — | ✓ | — | ✓ | ✓ | — | ✓ | ✓ |
240
261
  | C++ | — | — | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ |
262
+ | Dart | ✓ | — | ✓ | ✓ | ✓ | ✓ | — | ✓ | ✓ |
241
263
 
242
264
  **Imports** — cross-file import resolution · **Named Bindings** — `import { X as Y }` / re-export tracking · **Exports** — public/exported symbol detection · **Heritage** — class inheritance, interfaces, mixins · **Type Annotations** — explicit type extraction for receiver resolution · **Constructor Inference** — infer receiver type from constructor calls (`self`/`this` resolution included for all languages) · **Config** — language toolchain config parsing (tsconfig, go.mod, etc.) · **Frameworks** — AST-based framework pattern detection · **Entry Points** — entry point scoring heuristics
243
265
 
@@ -249,12 +271,14 @@ GitNexus ships with skill files that teach AI agents how to use the tools effect
249
271
  - **Debugging** — Trace bugs through call chains
250
272
  - **Impact Analysis** — Analyze blast radius before changes
251
273
  - **Refactoring** — Plan safe refactors using dependency mapping
274
+ - **Guide** — GitNexus tool/resource/schema reference for the agent
275
+ - **CLI** — Run analyze/status/clean/wiki commands on request
252
276
 
253
- Installed automatically by both `gitnexus analyze` (per-repo) and `gitnexus setup` (global).
277
+ Installed automatically by both `gitnexus analyze` (per-repo) and `gitnexus setup` (global). Run `gitnexus analyze --skills` to additionally generate repo-specific skills for each detected functional area under `.claude/skills/generated/`.
254
278
 
255
279
  ## Requirements
256
280
 
257
- - Node.js >= 18
281
+ - Node.js >= 22
258
282
  - Git repository (uses git for commit tracking)
259
283
 
260
284
  ## Release candidates
@@ -340,7 +364,7 @@ gitnexus serve
340
364
 
341
365
  ### Installation fails with native module errors
342
366
 
343
- Some optional language grammars (Dart, Kotlin, Swift) require native compilation. If they fail, GitNexus still works — those languages will be skipped.
367
+ Some optional language grammars (Dart, Proto, Swift, Kotlin) require native compilation. If they fail, GitNexus still works — those languages will be skipped. To skip them intentionally (no C++ toolchain needed), set `GITNEXUS_SKIP_OPTIONAL_GRAMMARS=1` before installing.
344
368
 
345
369
  If `npm install -g gitnexus` fails on native modules:
346
370
 
@@ -162,7 +162,7 @@ export declare const en: {
162
162
  readonly 'help.option.analyze.embeddingBatchSize': "Number of nodes per embedding batch";
163
163
  readonly 'help.option.analyze.embeddingSubBatchSize': "Number of chunks per embedding model call";
164
164
  readonly 'help.option.analyze.embeddingDevice': "Embedding device: auto, cpu, dml, cuda, or wasm";
165
- readonly 'help.option.index.force': "Register even if meta.json is missing (stats will be empty)";
165
+ readonly 'help.option.index.force': "Register even if index metadata is missing (stats will be empty)";
166
166
  readonly 'help.option.index.allowNonGit': "Allow registering folders that are not Git repositories";
167
167
  readonly 'help.option.port': "Port number";
168
168
  readonly 'help.option.serve.host': "Bind address (default: 127.0.0.1, use 0.0.0.0 for remote access)";
@@ -162,7 +162,7 @@ export const en = {
162
162
  'help.option.analyze.embeddingBatchSize': 'Number of nodes per embedding batch',
163
163
  'help.option.analyze.embeddingSubBatchSize': 'Number of chunks per embedding model call',
164
164
  'help.option.analyze.embeddingDevice': 'Embedding device: auto, cpu, dml, cuda, or wasm',
165
- 'help.option.index.force': 'Register even if meta.json is missing (stats will be empty)',
165
+ 'help.option.index.force': 'Register even if index metadata is missing (stats will be empty)',
166
166
  'help.option.index.allowNonGit': 'Allow registering folders that are not Git repositories',
167
167
  'help.option.port': 'Port number',
168
168
  'help.option.serve.host': 'Bind address (default: 127.0.0.1, use 0.0.0.0 for remote access)',
@@ -163,7 +163,7 @@ export declare const cliResources: {
163
163
  readonly 'help.option.analyze.embeddingBatchSize': "Number of nodes per embedding batch";
164
164
  readonly 'help.option.analyze.embeddingSubBatchSize': "Number of chunks per embedding model call";
165
165
  readonly 'help.option.analyze.embeddingDevice': "Embedding device: auto, cpu, dml, cuda, or wasm";
166
- readonly 'help.option.index.force': "Register even if meta.json is missing (stats will be empty)";
166
+ readonly 'help.option.index.force': "Register even if index metadata is missing (stats will be empty)";
167
167
  readonly 'help.option.index.allowNonGit': "Allow registering folders that are not Git repositories";
168
168
  readonly 'help.option.port': "Port number";
169
169
  readonly 'help.option.serve.host': "Bind address (default: 127.0.0.1, use 0.0.0.0 for remote access)";
@@ -162,7 +162,7 @@ export const zhCN = {
162
162
  'help.option.analyze.embeddingBatchSize': '每个嵌入批次的节点数',
163
163
  'help.option.analyze.embeddingSubBatchSize': '每次嵌入模型调用的分块数',
164
164
  'help.option.analyze.embeddingDevice': '嵌入设备:auto、cpu、dml、cuda 或 wasm',
165
- 'help.option.index.force': '即使缺少 meta.json 也注册(统计为空)',
165
+ 'help.option.index.force': '即使缺少索引元数据也注册(统计为空)',
166
166
  'help.option.index.allowNonGit': '允许注册非 Git 仓库文件夹',
167
167
  'help.option.port': '端口号',
168
168
  'help.option.serve.host': '绑定地址(默认:127.0.0.1;远程访问可用 0.0.0.0)',
@@ -1,10 +1,14 @@
1
1
  /**
2
2
  * Index Command
3
3
  *
4
- * Registers an existing .gitnexus/ folder into the global registry so the
4
+ * Registers an existing GitNexus index into the global registry so the
5
5
  * MCP server can discover the repo without running a full `gitnexus analyze`.
6
6
  *
7
- * Useful when a pre-built .gitnexus/ directory is already present (e.g. after
7
+ * The index can be either:
8
+ * - A per-worktree gitnexus.json file under .gitnexus/ (new format, worktree-compatible)
9
+ * - A legacy .gitnexus/meta.json file (auto-migrated on analyze)
10
+ *
11
+ * Useful when a pre-built index is already present (e.g. after
8
12
  * cloning a repo that ships its index, restoring from backup, or using a
9
13
  * shared team index).
10
14
  */
@@ -1,16 +1,20 @@
1
1
  /**
2
2
  * Index Command
3
3
  *
4
- * Registers an existing .gitnexus/ folder into the global registry so the
4
+ * Registers an existing GitNexus index into the global registry so the
5
5
  * MCP server can discover the repo without running a full `gitnexus analyze`.
6
6
  *
7
- * Useful when a pre-built .gitnexus/ directory is already present (e.g. after
7
+ * The index can be either:
8
+ * - A per-worktree gitnexus.json file under .gitnexus/ (new format, worktree-compatible)
9
+ * - A legacy .gitnexus/meta.json file (auto-migrated on analyze)
10
+ *
11
+ * Useful when a pre-built index is already present (e.g. after
8
12
  * cloning a repo that ships its index, restoring from backup, or using a
9
13
  * shared team index).
10
14
  */
11
15
  import path from 'path';
12
16
  import fs from 'fs/promises';
13
- import { getStoragePaths, loadMeta, ensureGitNexusIgnored, registerRepo, } from '../storage/repo-manager.js';
17
+ import { getStoragePaths, INDEX_METADATA_FILE, loadMeta, ensureGitNexusIgnored, registerRepo, } from '../storage/repo-manager.js';
14
18
  import { getGitRoot, getRemoteUrl, isGitRepo } from '../storage/git.js';
15
19
  export const indexCommand = async (inputPathParts, options) => {
16
20
  console.log('\n GitNexus Index\n');
@@ -50,22 +54,35 @@ export const indexCommand = async (inputPathParts, options) => {
50
54
  return;
51
55
  }
52
56
  const { storagePath, lbugPath } = getStoragePaths(repoPath);
53
- // ── Verify .gitnexus/ exists ──────────────────────────────────────
57
+ // ── Verify index exists (metadata file, legacy metadata, or restorable DB) ─
58
+ let hasMetadataIndex = false;
59
+ let hasLegacyIndex = false;
60
+ let hasLbugIndex = false;
61
+ try {
62
+ await fs.access(path.join(storagePath, INDEX_METADATA_FILE));
63
+ hasMetadataIndex = true;
64
+ }
65
+ catch { }
54
66
  try {
55
- await fs.access(storagePath);
67
+ await fs.access(path.join(storagePath, 'meta.json'));
68
+ hasLegacyIndex = true;
56
69
  }
57
- catch {
58
- console.log(` No .gitnexus/ folder found at: ${storagePath}`);
70
+ catch { }
71
+ try {
72
+ await fs.access(lbugPath);
73
+ hasLbugIndex = true;
74
+ }
75
+ catch { }
76
+ if (!hasMetadataIndex && !hasLegacyIndex && !hasLbugIndex) {
77
+ console.log(` No GitNexus index found.`);
78
+ console.log(` Expected gitnexus.json, .gitnexus/meta.json, or LadybugDB at: ${storagePath}`);
59
79
  console.log(' Run `gitnexus analyze` to build the index first.\n');
60
80
  process.exitCode = 1;
61
81
  return;
62
82
  }
63
83
  // ── Verify lbug database exists ───────────────────────────────────
64
- try {
65
- await fs.access(lbugPath);
66
- }
67
- catch {
68
- console.log(` .gitnexus/ folder exists but contains no LadybugDB index.`);
84
+ if (!hasLbugIndex) {
85
+ console.log(` Index exists but contains no LadybugDB database.`);
69
86
  console.log(' Run `gitnexus analyze` to build the index.\n');
70
87
  process.exitCode = 1;
71
88
  return;
@@ -74,7 +91,7 @@ export const indexCommand = async (inputPathParts, options) => {
74
91
  let meta = await loadMeta(storagePath);
75
92
  if (!meta) {
76
93
  if (!options?.force) {
77
- console.log(` .gitnexus/ exists but meta.json is missing.`);
94
+ console.log(` gitnexus.json or .gitnexus/meta.json is missing.`);
78
95
  console.log(' Use --force to register anyway (stats will be empty),');
79
96
  console.log(' or run `gitnexus analyze` to rebuild properly.\n');
80
97
  process.exitCode = 1;
package/dist/cli/index.js CHANGED
@@ -123,7 +123,7 @@ program
123
123
  program
124
124
  .command('index [path...]')
125
125
  .description('Register an existing .gitnexus/ folder into the global registry (no re-analysis needed)')
126
- .option('-f, --force', 'Register even if meta.json is missing (stats will be empty)')
126
+ .option('-f, --force', 'Register even if index metadata is missing (stats will be empty)')
127
127
  .option('--allow-non-git', 'Allow registering folders that are not Git repositories')
128
128
  .action(createLazyAction(() => import('./index-repo.js'), 'indexCommand'));
129
129
  program
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * Remove Command (#664)
3
3
  *
4
- * Delete the `.gitnexus/` index for a registered repo and unregister it
5
- * from the global registry (~/.gitnexus/registry.json). The target is
6
- * identified by alias / basename-derived name / remote-inferred name /
4
+ * Delete the `.gitnexus/` index directory for a registered repo (including
5
+ * both metadata filenames gitnexus.json and its legacy meta.json mirror
6
+ * which live inside it) and unregister it from the global registry
7
+ * (~/.gitnexus/registry.json).
8
+ *
9
+ * The target is identified by alias / basename-derived name / remote-inferred name /
7
10
  * absolute path — no `--repo` flag, just a positional argument so the
8
11
  * destructive-command ergonomics match `clean` (which is also
9
12
  * destructive but scoped to `process.cwd()`).
@@ -1,9 +1,12 @@
1
1
  /**
2
2
  * Remove Command (#664)
3
3
  *
4
- * Delete the `.gitnexus/` index for a registered repo and unregister it
5
- * from the global registry (~/.gitnexus/registry.json). The target is
6
- * identified by alias / basename-derived name / remote-inferred name /
4
+ * Delete the `.gitnexus/` index directory for a registered repo (including
5
+ * both metadata filenames gitnexus.json and its legacy meta.json mirror
6
+ * which live inside it) and unregister it from the global registry
7
+ * (~/.gitnexus/registry.json).
8
+ *
9
+ * The target is identified by alias / basename-derived name / remote-inferred name /
7
10
  * absolute path — no `--repo` flag, just a positional argument so the
8
11
  * destructive-command ergonomics match `clean` (which is also
9
12
  * destructive but scoped to `process.cwd()`).
@@ -110,7 +110,6 @@ export declare function queryBridge<T>(handle: BridgeHandle, cypher: string, par
110
110
  * is a lease release, so the file may stay open under other readers.
111
111
  */
112
112
  export declare function closeBridgeDb(handle: BridgeHandle): Promise<void>;
113
- export declare function retryRename(src: string, dst: string, attempts?: number): Promise<void>;
114
113
  export declare function writeBridgeMeta(groupDir: string, meta: BridgeMeta): Promise<void>;
115
114
  export declare function readBridgeMeta(groupDir: string): Promise<BridgeMeta>;
116
115
  export interface WriteBridgeInput {
@@ -6,6 +6,7 @@ import { BRIDGE_SCHEMA_QUERIES, BRIDGE_SCHEMA_VERSION } from './bridge-schema.js
6
6
  import { closeLbugConnection, openLbugConnection, } from '../lbug/lbug-config.js';
7
7
  import { dedupeContracts, dedupeCrossLinks } from './normalization.js';
8
8
  import { createLogger } from '../logger.js';
9
+ import { retryRename } from '../../storage/fs-atomic.js';
9
10
  const bridgeLogger = createLogger('bridge-db', {
10
11
  debugEnvVar: 'GITNEXUS_DEBUG_BRIDGE',
11
12
  });
@@ -512,24 +513,6 @@ export async function closeBridgeDb(handle) {
512
513
  // The read-only CHECKPOINT skip above remains the load-bearing fix on
513
514
  // Linux/macOS.
514
515
  /* ------------------------------------------------------------------ */
515
- /* retryRename — handles transient EBUSY/EPERM/EACCES on Windows */
516
- /* ------------------------------------------------------------------ */
517
- const RETRY_CODES = new Set(['EBUSY', 'EPERM', 'EACCES']);
518
- export async function retryRename(src, dst, attempts = 3) {
519
- for (let i = 1; i <= attempts; i++) {
520
- try {
521
- await fsp.rename(src, dst);
522
- return;
523
- }
524
- catch (err) {
525
- const code = err.code;
526
- if (!code || !RETRY_CODES.has(code) || i === attempts)
527
- throw err;
528
- await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i - 1)));
529
- }
530
- }
531
- }
532
- /* ------------------------------------------------------------------ */
533
516
  /* writeBridgeMeta / readBridgeMeta */
534
517
  /* ------------------------------------------------------------------ */
535
518
  export async function writeBridgeMeta(groupDir, meta) {
@@ -5,6 +5,7 @@
5
5
  import fsp from 'node:fs/promises';
6
6
  import path from 'node:path';
7
7
  import { checkStaleness } from '../git-staleness.js';
8
+ import { loadMeta } from '../../storage/repo-manager.js';
8
9
  import { GroupNotFoundError, loadGroupConfig } from './config-parser.js';
9
10
  import { fileMatchesServicePrefix, normalizeServicePrefix, repoInSubgroup, } from './group-path-utils.js';
10
11
  import { getDefaultGitnexusDir, getGroupDir, listGroups, readContractRegistry } from './storage.js';
@@ -370,9 +371,7 @@ export class GroupService {
370
371
  for (const [repoPath, registryName] of Object.entries(config.repos)) {
371
372
  try {
372
373
  const repoObj = await this.port.resolveRepo(registryName);
373
- const metaPath = path.join(repoObj.storagePath, 'meta.json');
374
- const metaRaw = await fsp.readFile(metaPath, 'utf-8').catch(() => '{}');
375
- const meta = JSON.parse(metaRaw);
374
+ const meta = (await loadMeta(repoObj.storagePath)) ?? {};
376
375
  const staleness = meta.lastCommit
377
376
  ? checkStaleness(repoObj.repoPath, meta.lastCommit)
378
377
  : { isStale: true, commitsBehind: -1 };
@@ -3,7 +3,7 @@ import * as fsp from 'node:fs/promises';
3
3
  import * as path from 'node:path';
4
4
  import * as os from 'node:os';
5
5
  import { randomBytes } from 'node:crypto';
6
- import { retryRename } from './bridge-db.js';
6
+ import { retryRename } from '../../storage/fs-atomic.js';
7
7
  /**
8
8
  * Build an unpredictable suffix for atomic-write tmp files. Replaces the
9
9
  * previous `Date.now()` pattern which CodeQL flagged as
@@ -207,11 +207,14 @@ export declare const PHASE_LABELS: Record<string, string>;
207
207
  export declare const primaryInversionWarning: (defaultBranch: string | null | undefined, flatOwner: string | null | undefined) => string | undefined;
208
208
  /**
209
209
  * Collect the recorded parse-cache chunk keys across the flat + every branch
210
- * meta under a flat `.gitnexus` storage, EXCLUDING `excludeDir` (the current
211
- * run's own meta dir) so a single-branch repo collects nothing and its prune
212
- * stays byte-identical to today (#2106 R6). `complete` is false when a sibling
213
- * meta.json exists but fails to parse callers then retain the whole shared
214
- * cache rather than over-evict another branch's still-live shards. Exported for
210
+ * metadata directory under a flat `.gitnexus` storage, EXCLUDING `excludeDir`
211
+ * (the current run's own meta dir) so a single-branch repo collects nothing and
212
+ * its prune stays byte-identical to today (#2106 R6 the byte-identity claim
213
+ * is about the PRUNE result; the metadata FILENAME read here changed with
214
+ * PR #2363's rename, checking `gitnexus.json` first then the legacy
215
+ * `meta.json` mirror). `complete` is false when a sibling metadata file exists
216
+ * but fails to read or parse — callers then retain the whole shared cache
217
+ * rather than over-evict another branch's still-live shards. Exported for
215
218
  * testing.
216
219
  */
217
220
  export declare const collectBranchCacheKeys: (storagePath: string, excludeDir?: string) => Promise<{
@@ -18,7 +18,7 @@ import { createSearchFTSIndexes, initialiseSearchFTSStemmer, verifySearchFTSInde
18
18
  import { cjkSegmentationModeMismatch, getSearchFTSCjkSegmentation, initialiseSearchFTSCjkSegmentation, } from './search/cjk-segmentation.js';
19
19
  import { resolveAnalyzeInstallPolicy } from './lbug/extension-loader.js';
20
20
  import { startWalCheckpointDriver, } from './lbug/wal-checkpoint-driver.js';
21
- import { getStoragePaths, resolveBranchPlacement, saveMeta, loadMeta, ensureGitNexusIgnored, registerRepo, isRepoRegistered, cleanupOldKuzuFiles, INCREMENTAL_SCHEMA_VERSION, } from '../storage/repo-manager.js';
21
+ import { getStoragePaths, resolveBranchPlacement, saveMeta, loadMeta, ensureGitNexusIgnored, registerRepo, isRepoRegistered, cleanupOldKuzuFiles, reconcileMetadataFiles, isMissingFilesystemError, INDEX_METADATA_FILE, INCREMENTAL_SCHEMA_VERSION, } from '../storage/repo-manager.js';
22
22
  import { DEFAULT_PDG_MAX_FUNCTION_LINES } from './ingestion/cfg/collect.js';
23
23
  import { DEFAULT_MAX_CFG_EDGES_PER_FUNCTION, DEFAULT_PDG_MAX_REACHING_DEF_EDGES_PER_FUNCTION, DEFAULT_PDG_MAX_CDG_EDGES_PER_FUNCTION, } from './ingestion/cfg/emit.js';
24
24
  import { DEFAULT_PDG_MAX_TAINT_FINDINGS_PER_FUNCTION, DEFAULT_PDG_MAX_TAINT_HOPS, } from './ingestion/taint/propagate.js';
@@ -97,11 +97,14 @@ export const primaryInversionWarning = (defaultBranch, flatOwner) => {
97
97
  };
98
98
  /**
99
99
  * Collect the recorded parse-cache chunk keys across the flat + every branch
100
- * meta under a flat `.gitnexus` storage, EXCLUDING `excludeDir` (the current
101
- * run's own meta dir) so a single-branch repo collects nothing and its prune
102
- * stays byte-identical to today (#2106 R6). `complete` is false when a sibling
103
- * meta.json exists but fails to parse callers then retain the whole shared
104
- * cache rather than over-evict another branch's still-live shards. Exported for
100
+ * metadata directory under a flat `.gitnexus` storage, EXCLUDING `excludeDir`
101
+ * (the current run's own meta dir) so a single-branch repo collects nothing and
102
+ * its prune stays byte-identical to today (#2106 R6 the byte-identity claim
103
+ * is about the PRUNE result; the metadata FILENAME read here changed with
104
+ * PR #2363's rename, checking `gitnexus.json` first then the legacy
105
+ * `meta.json` mirror). `complete` is false when a sibling metadata file exists
106
+ * but fails to read or parse — callers then retain the whole shared cache
107
+ * rather than over-evict another branch's still-live shards. Exported for
105
108
  * testing.
106
109
  */
107
110
  export const collectBranchCacheKeys = async (storagePath, excludeDir) => {
@@ -117,10 +120,21 @@ export const collectBranchCacheKeys = async (storagePath, excludeDir) => {
117
120
  continue;
118
121
  let raw;
119
122
  try {
120
- raw = await fs.readFile(path.join(dir, 'meta.json'), 'utf-8');
123
+ raw = await fs.readFile(path.join(dir, INDEX_METADATA_FILE), 'utf-8');
121
124
  }
122
- catch {
123
- continue; // no meta here — not a branch index, not a failure
125
+ catch (newErr) {
126
+ if (!isMissingFilesystemError(newErr)) {
127
+ complete = false;
128
+ continue;
129
+ }
130
+ try {
131
+ raw = await fs.readFile(path.join(dir, 'meta.json'), 'utf-8');
132
+ }
133
+ catch (legacyErr) {
134
+ if (!isMissingFilesystemError(legacyErr))
135
+ complete = false;
136
+ continue; // no metadata here — not a branch index, not a failure
137
+ }
124
138
  }
125
139
  try {
126
140
  const parsed = JSON.parse(raw);
@@ -306,10 +320,21 @@ export async function runFullAnalysis(repoPath, options, callbacks) {
306
320
  const branchLabel = options.branch ?? checkedOutBranch;
307
321
  const placement = await resolveBranchPlacement(repoPath, branchLabel);
308
322
  const { lbugPath, metaPath } = getStoragePaths(repoPath, placement.branch);
309
- // Directory that owns this run's meta.json (flat `.gitnexus` for the primary
310
- // slot, `branches/<slug>/` otherwise). loadMeta/saveMeta operate on it so
311
- // each branch keeps its own lastCommit / fileHashes / incremental dirty flag.
323
+ // metaPath now points to the metadata file (gitnexus.json) in a branch-specific directory.
324
+ // metaDir is the directory containing the metadata file (and branch-specific DBs).
312
325
  const metaDir = path.dirname(metaPath);
326
+ // Keep gitnexus.json and the legacy meta.json mirror in sync (fresher
327
+ // indexedAt wins; nothing is deleted). Best-effort: loadMeta has its own
328
+ // legacy fallback, so a reconciliation failure (read-only mount, full disk)
329
+ // must never abort the analyze run — a repo that indexed fine read-only
330
+ // before the rename must keep doing so.
331
+ try {
332
+ await reconcileMetadataFiles(repoPath);
333
+ }
334
+ catch (err) {
335
+ const code = err?.code;
336
+ log(`Metadata reconciliation failed (non-critical${code ? `, ${code}` : ''}); continuing.`);
337
+ }
313
338
  const existingMeta = await loadMeta(metaDir);
314
339
  // ── #2106 (R8): warn when the repo's default branch is not the primary ──
315
340
  // A non-default branch can own the flat slot (it was indexed first). That
@@ -968,14 +968,15 @@ export class LocalBackend {
968
968
  return; // Checked recently — skip
969
969
  this.lastStalenessCheck.set(poolKey, now);
970
970
  try {
971
- // Read the meta.json that sits next to THIS handle's lbug. For the
972
- // flat/primary handle this is `<storagePath>/meta.json` (unchanged);
973
- // for a branch handle it is `<storagePath>/branches/<slug>/meta.json`.
971
+ // Read the metadata that sits next to THIS handle's lbug. For the
972
+ // flat/primary handle this is `<storagePath>/gitnexus.json`; for a
973
+ // branch handle it is `<storagePath>/branches/<slug>/gitnexus.json`.
974
+ // loadMeta falls back to legacy meta.json during migration.
974
975
  // Reading the flat meta for a branch handle would compare the branch
975
976
  // index's indexedAt against the primary's and thrash the pool (#2106).
976
- const metaPath = path.join(path.dirname(repo.lbugPath), 'meta.json');
977
- const metaRaw = await fs.readFile(metaPath, 'utf-8');
978
- const meta = JSON.parse(metaRaw);
977
+ const meta = await loadMeta(path.dirname(repo.lbugPath));
978
+ if (!meta)
979
+ return;
979
980
  // Compare against the last indexedAt OBSERVED for this pool (keyed by
980
981
  // lbugPath), not the handle's — branch handles are fresh spreads so a
981
982
  // handle mutation would not persist and would reinit on every check.
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Rename with retry on transient EBUSY/EPERM/EACCES (observed on Windows
3
+ * when a concurrent reader holds the target file open).
4
+ */
5
+ export declare function retryRename(src: string, dst: string, attempts?: number): Promise<void>;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Atomic file-write primitives shared across storage/ and core/group/.
3
+ *
4
+ * `retryRename` originated in core/group/bridge-db.ts; it lives here so
5
+ * storage/repo-manager.ts can use it without introducing a storage/ ->
6
+ * core/group/ import (the established direction is core/group/ -> storage/,
7
+ * e.g. core/group/service.ts already imports loadMeta from here).
8
+ */
9
+ import fsp from 'fs/promises';
10
+ const RETRY_CODES = new Set(['EBUSY', 'EPERM', 'EACCES']);
11
+ /**
12
+ * Rename with retry on transient EBUSY/EPERM/EACCES (observed on Windows
13
+ * when a concurrent reader holds the target file open).
14
+ */
15
+ export async function retryRename(src, dst, attempts = 3) {
16
+ for (let i = 1; i <= attempts; i++) {
17
+ try {
18
+ await fsp.rename(src, dst);
19
+ return;
20
+ }
21
+ catch (err) {
22
+ const code = err.code;
23
+ if (!code || !RETRY_CODES.has(code) || i === attempts)
24
+ throw err;
25
+ await new Promise((r) => setTimeout(r, 100 * Math.pow(2, i - 1)));
26
+ }
27
+ }
28
+ }