@optave/codegraph 3.12.0 → 3.13.0

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.
Files changed (144) hide show
  1. package/README.md +71 -35
  2. package/dist/cli/commands/audit.d.ts.map +1 -1
  3. package/dist/cli/commands/audit.js +2 -1
  4. package/dist/cli/commands/audit.js.map +1 -1
  5. package/dist/cli/commands/batch.d.ts.map +1 -1
  6. package/dist/cli/commands/batch.js +1 -0
  7. package/dist/cli/commands/batch.js.map +1 -1
  8. package/dist/cli/commands/build.d.ts.map +1 -1
  9. package/dist/cli/commands/build.js +6 -1
  10. package/dist/cli/commands/build.js.map +1 -1
  11. package/dist/cli/commands/config.d.ts +3 -0
  12. package/dist/cli/commands/config.d.ts.map +1 -0
  13. package/dist/cli/commands/config.js +272 -0
  14. package/dist/cli/commands/config.js.map +1 -0
  15. package/dist/cli/commands/triage.js +1 -1
  16. package/dist/cli/commands/triage.js.map +1 -1
  17. package/dist/cli/index.d.ts.map +1 -1
  18. package/dist/cli/index.js +10 -0
  19. package/dist/cli/index.js.map +1 -1
  20. package/dist/cli/shared/options.d.ts +2 -1
  21. package/dist/cli/shared/options.d.ts.map +1 -1
  22. package/dist/cli/shared/options.js +11 -1
  23. package/dist/cli/shared/options.js.map +1 -1
  24. package/dist/cli/types.d.ts +2 -0
  25. package/dist/cli/types.d.ts.map +1 -1
  26. package/dist/db/migrations.js +1 -1
  27. package/dist/db/migrations.js.map +1 -1
  28. package/dist/domain/graph/builder/call-resolver.d.ts +12 -8
  29. package/dist/domain/graph/builder/call-resolver.d.ts.map +1 -1
  30. package/dist/domain/graph/builder/call-resolver.js +93 -38
  31. package/dist/domain/graph/builder/call-resolver.js.map +1 -1
  32. package/dist/domain/graph/builder/cha.d.ts +9 -1
  33. package/dist/domain/graph/builder/cha.d.ts.map +1 -1
  34. package/dist/domain/graph/builder/cha.js +17 -2
  35. package/dist/domain/graph/builder/cha.js.map +1 -1
  36. package/dist/domain/graph/builder/helpers.d.ts +8 -0
  37. package/dist/domain/graph/builder/helpers.d.ts.map +1 -1
  38. package/dist/domain/graph/builder/helpers.js +22 -3
  39. package/dist/domain/graph/builder/helpers.js.map +1 -1
  40. package/dist/domain/graph/builder/incremental.d.ts.map +1 -1
  41. package/dist/domain/graph/builder/incremental.js +1 -1
  42. package/dist/domain/graph/builder/incremental.js.map +1 -1
  43. package/dist/domain/graph/builder/pipeline.d.ts.map +1 -1
  44. package/dist/domain/graph/builder/pipeline.js +37 -2
  45. package/dist/domain/graph/builder/pipeline.js.map +1 -1
  46. package/dist/domain/graph/builder/stages/build-edges.d.ts +0 -2
  47. package/dist/domain/graph/builder/stages/build-edges.d.ts.map +1 -1
  48. package/dist/domain/graph/builder/stages/build-edges.js +88 -318
  49. package/dist/domain/graph/builder/stages/build-edges.js.map +1 -1
  50. package/dist/domain/graph/builder/stages/detect-changes.js +1 -1
  51. package/dist/domain/graph/builder/stages/detect-changes.js.map +1 -1
  52. package/dist/domain/graph/builder/stages/finalize.d.ts.map +1 -1
  53. package/dist/domain/graph/builder/stages/finalize.js +4 -0
  54. package/dist/domain/graph/builder/stages/finalize.js.map +1 -1
  55. package/dist/domain/graph/builder/stages/native-orchestrator.d.ts.map +1 -1
  56. package/dist/domain/graph/builder/stages/native-orchestrator.js +341 -82
  57. package/dist/domain/graph/builder/stages/native-orchestrator.js.map +1 -1
  58. package/dist/domain/graph/builder/stages/resolve-imports.js +1 -1
  59. package/dist/domain/graph/builder/stages/resolve-imports.js.map +1 -1
  60. package/dist/domain/parser.d.ts +4 -5
  61. package/dist/domain/parser.d.ts.map +1 -1
  62. package/dist/domain/parser.js +46 -15
  63. package/dist/domain/parser.js.map +1 -1
  64. package/dist/domain/wasm-worker-entry.js +10 -2
  65. package/dist/domain/wasm-worker-entry.js.map +1 -1
  66. package/dist/domain/wasm-worker-pool.d.ts.map +1 -1
  67. package/dist/domain/wasm-worker-pool.js +2 -0
  68. package/dist/domain/wasm-worker-pool.js.map +1 -1
  69. package/dist/domain/wasm-worker-protocol.d.ts +1 -0
  70. package/dist/domain/wasm-worker-protocol.d.ts.map +1 -1
  71. package/dist/extractors/cpp.d.ts.map +1 -1
  72. package/dist/extractors/cpp.js +42 -1
  73. package/dist/extractors/cpp.js.map +1 -1
  74. package/dist/extractors/cuda.d.ts.map +1 -1
  75. package/dist/extractors/cuda.js +42 -1
  76. package/dist/extractors/cuda.js.map +1 -1
  77. package/dist/extractors/helpers.d.ts +11 -0
  78. package/dist/extractors/helpers.d.ts.map +1 -1
  79. package/dist/extractors/helpers.js +40 -0
  80. package/dist/extractors/helpers.js.map +1 -1
  81. package/dist/extractors/java.d.ts.map +1 -1
  82. package/dist/extractors/java.js +8 -7
  83. package/dist/extractors/java.js.map +1 -1
  84. package/dist/extractors/javascript.js +137 -6
  85. package/dist/extractors/javascript.js.map +1 -1
  86. package/dist/features/structure-query.d.ts +1 -1
  87. package/dist/features/structure-query.d.ts.map +1 -1
  88. package/dist/features/structure-query.js +6 -6
  89. package/dist/features/structure-query.js.map +1 -1
  90. package/dist/index.d.ts +1 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +1 -1
  93. package/dist/index.js.map +1 -1
  94. package/dist/infrastructure/config.d.ts +77 -4
  95. package/dist/infrastructure/config.d.ts.map +1 -1
  96. package/dist/infrastructure/config.js +395 -21
  97. package/dist/infrastructure/config.js.map +1 -1
  98. package/dist/infrastructure/registry.d.ts +27 -0
  99. package/dist/infrastructure/registry.d.ts.map +1 -1
  100. package/dist/infrastructure/registry.js +59 -1
  101. package/dist/infrastructure/registry.js.map +1 -1
  102. package/dist/presentation/structure.d.ts +1 -1
  103. package/dist/presentation/structure.d.ts.map +1 -1
  104. package/dist/presentation/structure.js +2 -2
  105. package/dist/presentation/structure.js.map +1 -1
  106. package/dist/types.d.ts +37 -0
  107. package/dist/types.d.ts.map +1 -1
  108. package/grammars/tree-sitter-gleam.wasm +0 -0
  109. package/package.json +7 -8
  110. package/src/cli/commands/audit.ts +2 -1
  111. package/src/cli/commands/batch.ts +1 -0
  112. package/src/cli/commands/build.ts +6 -1
  113. package/src/cli/commands/config.ts +353 -0
  114. package/src/cli/commands/triage.ts +1 -1
  115. package/src/cli/index.ts +10 -0
  116. package/src/cli/shared/options.ts +11 -1
  117. package/src/cli/types.ts +2 -0
  118. package/src/db/migrations.ts +1 -1
  119. package/src/domain/graph/builder/call-resolver.ts +99 -41
  120. package/src/domain/graph/builder/cha.ts +18 -1
  121. package/src/domain/graph/builder/helpers.ts +24 -4
  122. package/src/domain/graph/builder/incremental.ts +1 -0
  123. package/src/domain/graph/builder/pipeline.ts +49 -2
  124. package/src/domain/graph/builder/stages/build-edges.ts +130 -399
  125. package/src/domain/graph/builder/stages/detect-changes.ts +1 -1
  126. package/src/domain/graph/builder/stages/finalize.ts +4 -0
  127. package/src/domain/graph/builder/stages/native-orchestrator.ts +396 -92
  128. package/src/domain/graph/builder/stages/resolve-imports.ts +1 -1
  129. package/src/domain/parser.ts +45 -14
  130. package/src/domain/wasm-worker-entry.ts +10 -2
  131. package/src/domain/wasm-worker-pool.ts +1 -0
  132. package/src/domain/wasm-worker-protocol.ts +1 -0
  133. package/src/extractors/cpp.ts +44 -1
  134. package/src/extractors/cuda.ts +44 -1
  135. package/src/extractors/helpers.ts +43 -0
  136. package/src/extractors/java.ts +8 -7
  137. package/src/extractors/javascript.ts +127 -6
  138. package/src/features/structure-query.ts +7 -7
  139. package/src/index.ts +5 -1
  140. package/src/infrastructure/config.ts +481 -22
  141. package/src/infrastructure/registry.ts +82 -1
  142. package/src/presentation/structure.ts +3 -3
  143. package/src/types.ts +41 -0
  144. package/grammars/tree-sitter-erlang.wasm +0 -0
@@ -1,9 +1,13 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
2
3
  import fs from 'node:fs';
4
+ import os from 'node:os';
3
5
  import path from 'node:path';
4
6
  import { ConfigError, toErrorMessage } from '../shared/errors.js';
5
- import type { CodegraphConfig } from '../types.js';
7
+ import { compileGlobs, matchesAny } from '../shared/globs.js';
8
+ import type { CodegraphConfig, ConfigSource, ConsentDecision } from '../types.js';
6
9
  import { debug, warn } from './logger.js';
10
+ import { getUserConfigConsent, REGISTRY_PATH, setUserConfigConsent } from './registry.js';
7
11
 
8
12
  export type { CodegraphConfig } from '../types.js';
9
13
 
@@ -24,7 +28,7 @@ export const DEFAULTS = {
24
28
  dbPath: '.codegraph/graph.db',
25
29
  driftThreshold: 0.2,
26
30
  smallFilesThreshold: 5,
27
- typescriptResolver: false,
31
+ typescriptResolver: true,
28
32
  },
29
33
  query: {
30
34
  defaultDepth: 3,
@@ -90,7 +94,7 @@ export const DEFAULTS = {
90
94
  * Maximum fixed-point iterations for the Phase 8.3 points-to solver.
91
95
  * @reserved — currently not wired to either the WASM solver
92
96
  * (`MAX_SOLVER_ITERATIONS` in `points-to.ts`) or the native Rust solver
93
- * (`MAX_SOLVER_ITERATIONS` in `edge_builder.rs`), both of which use the
97
+ * (`MAX_SOLVER_ITERATIONS` in `stages/build_edges.rs`), both of which use the
94
98
  * same hardcoded value of 50. See the TODO comment above.
95
99
  */
96
100
  pointsToMaxIterations: 50,
@@ -166,43 +170,438 @@ export const DEFAULTS = {
166
170
  },
167
171
  } satisfies CodegraphConfig;
168
172
 
173
+ // ── Per-process user-config override (set by CLI flags) ────────────────
174
+ // Set once by the preAction hook before any command runs; cleared when changed.
175
+ let _userConfigOverride: string | boolean | undefined;
176
+
177
+ /**
178
+ * Set the per-run user-config override from CLI flags.
179
+ * Called by the CLI preAction hook before any command executes.
180
+ * - false → --no-user-config
181
+ * - string → --user-config <path>
182
+ * - true → --user-config (bare, use default global file)
183
+ * - undefined → clear override, revert to consent-based resolution
184
+ */
185
+ export function setUserConfigOverride(v: string | boolean | undefined): void {
186
+ _userConfigOverride = v;
187
+ _configCache.clear();
188
+ _globalConfigCache.clear();
189
+ }
190
+
169
191
  // Per-cwd config cache — avoids re-reading the config file on every query call.
170
- // The config file rarely changes within a single process lifetime.
192
+ // Key includes the applied global path so toggled flags/consent are reflected.
171
193
  const _configCache = new Map<string, CodegraphConfig>();
194
+ // Parallel cache for the sanitized global layer — needed so loadConfigWithProvenance
195
+ // can correctly attribute global-layer keys even on a _configCache hit.
196
+ const _globalConfigCache = new Map<string, Record<string, unknown> | null>();
197
+
198
+ // ── Global config file location ─────────────────────────────────────────
199
+
200
+ /**
201
+ * Return the canonical path where a new global config file should be written.
202
+ *
203
+ * Uses the same priority logic as resolveUserConfigPath() but always returns a
204
+ * path — it does not check whether the file exists. Used by `--init` to know
205
+ * where to scaffold the file.
206
+ *
207
+ * Priority:
208
+ * 1. CODEGRAPH_USER_CONFIG env var (used as-is)
209
+ * 2. $XDG_CONFIG_HOME/codegraph/config.json
210
+ * %APPDATA%\codegraph\config.json (Windows)
211
+ * fallback: ~/.config/codegraph/config.json
212
+ */
213
+ export function getDefaultUserConfigPath(): string {
214
+ const envPath = process.env.CODEGRAPH_USER_CONFIG;
215
+ if (envPath) return envPath;
216
+
217
+ const home = os.homedir();
218
+ const xdgConfig = process.env.XDG_CONFIG_HOME;
219
+ if (xdgConfig) return path.join(xdgConfig, 'codegraph', 'config.json');
220
+ if (process.platform === 'win32') {
221
+ const appdata = process.env.APPDATA;
222
+ return appdata
223
+ ? path.join(appdata, 'codegraph', 'config.json')
224
+ : path.join(home, '.config', 'codegraph', 'config.json');
225
+ }
226
+ return path.join(home, '.config', 'codegraph', 'config.json');
227
+ }
228
+
229
+ /**
230
+ * Resolve the absolute path to the user-level global config file.
231
+ *
232
+ * Priority:
233
+ * 1. CODEGRAPH_USER_CONFIG env var (location override only — not forced-on)
234
+ * 2. $XDG_CONFIG_HOME/codegraph/config.json (Unix/macOS)
235
+ * %APPDATA%\codegraph\config.json (Windows)
236
+ * fallback: ~/.config/codegraph/config.json
237
+ * 3. ~/.codegraph/config.json (legacy, next to registry.json)
238
+ *
239
+ * Returns the path of the first existing file, or null if none exist.
240
+ */
241
+ export function resolveUserConfigPath(): string | null {
242
+ const envPath = process.env.CODEGRAPH_USER_CONFIG;
243
+ if (envPath) {
244
+ if (fs.existsSync(envPath)) return envPath;
245
+ debug(`CODEGRAPH_USER_CONFIG points to missing file: ${envPath}`);
246
+ return null;
247
+ }
248
+
249
+ const home = os.homedir();
250
+
251
+ // XDG_CONFIG_HOME takes priority on all platforms when explicitly set.
252
+ // Falls back to %APPDATA% on Windows, or ~/.config on Unix/macOS.
253
+ let platformDefault: string;
254
+ const xdgConfig = process.env.XDG_CONFIG_HOME;
255
+ if (xdgConfig) {
256
+ platformDefault = path.join(xdgConfig, 'codegraph', 'config.json');
257
+ } else if (process.platform === 'win32') {
258
+ const appdata = process.env.APPDATA;
259
+ platformDefault = appdata
260
+ ? path.join(appdata, 'codegraph', 'config.json')
261
+ : path.join(home, '.config', 'codegraph', 'config.json');
262
+ } else {
263
+ platformDefault = path.join(home, '.config', 'codegraph', 'config.json');
264
+ }
265
+
266
+ if (fs.existsSync(platformDefault)) return platformDefault;
267
+
268
+ const legacyPath = path.join(home, '.codegraph', 'config.json');
269
+ if (fs.existsSync(legacyPath)) return legacyPath;
270
+
271
+ return null;
272
+ }
273
+
274
+ // ── Global config file loading ──────────────────────────────────────────
275
+
276
+ interface ParsedUserConfig {
277
+ globalConfig: Record<string, unknown>;
278
+ appliesToGlobs: string[];
279
+ }
280
+
281
+ /**
282
+ * Read and parse a user-level global config file.
283
+ * Handles both plain-config and appliesTo-wrapper formats.
284
+ * Returns null on missing or malformed files (never throws).
285
+ */
286
+ function loadUserConfigFile(filePath: string): ParsedUserConfig | null {
287
+ try {
288
+ const raw = fs.readFileSync(filePath, 'utf-8');
289
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
290
+ // Wrapper format: { appliesTo: [...], config: {...} }
291
+ if ('appliesTo' in parsed && typeof parsed.config === 'object' && parsed.config !== null) {
292
+ const globs = Array.isArray(parsed.appliesTo)
293
+ ? (parsed.appliesTo as unknown[]).filter((g): g is string => typeof g === 'string')
294
+ : [];
295
+ return { globalConfig: parsed.config as Record<string, unknown>, appliesToGlobs: globs };
296
+ }
297
+ // Plain config (no appliesTo wrapper)
298
+ return { globalConfig: parsed, appliesToGlobs: [] };
299
+ } catch (err) {
300
+ debug(`Failed to load user config at ${filePath}: ${toErrorMessage(err)}`);
301
+ return null;
302
+ }
303
+ }
304
+
305
+ // ── Safety sanitisation ─────────────────────────────────────────────────
306
+
307
+ /**
308
+ * Drop any unsafe keys from the global layer before merging.
309
+ * Currently: absolute build.dbPath (would make all repos share one DB).
310
+ * Relative dbPaths resolve per-repo and are allowed through unchanged.
311
+ */
312
+ function sanitizeUserLayer(raw: Record<string, unknown>): Record<string, unknown> {
313
+ const build = raw.build as Record<string, unknown> | undefined;
314
+ if (build && typeof build.dbPath === 'string' && path.isAbsolute(build.dbPath)) {
315
+ warn(
316
+ `User config: build.dbPath "${build.dbPath}" is absolute and was ignored ` +
317
+ '(an absolute dbPath would share one database across all repos).',
318
+ );
319
+ const sanitizedBuild = { ...build };
320
+ delete sanitizedBuild.dbPath;
321
+ return { ...raw, build: sanitizedBuild };
322
+ }
323
+ return raw;
324
+ }
325
+
326
+ // ── excludeTests shorthand (per-layer) ─────────────────────────────────
327
+
328
+ /**
329
+ * Hoist a top-level `excludeTests` key from a raw layer into `query.excludeTests`.
330
+ * If the layer already has `query.excludeTests`, that value wins (no-op).
331
+ * Also removes any stale `excludeTests` key that may have leaked into `merged`.
332
+ */
333
+ function applyExcludeTestsShorthand(
334
+ merged: Record<string, unknown>,
335
+ rawLayer: Record<string, unknown>,
336
+ ): Record<string, unknown> {
337
+ if ('excludeTests' in rawLayer) {
338
+ // Only hoist if this layer doesn't also set query.excludeTests
339
+ if (!(rawLayer.query && 'excludeTests' in (rawLayer.query as object))) {
340
+ (merged.query as Record<string, unknown>).excludeTests = Boolean(rawLayer.excludeTests);
341
+ }
342
+ const result = { ...merged };
343
+ delete result.excludeTests;
344
+ return result;
345
+ }
346
+ if ('excludeTests' in merged) {
347
+ const result = { ...merged };
348
+ delete result.excludeTests;
349
+ return result;
350
+ }
351
+ return merged;
352
+ }
353
+
354
+ // ── Consent resolution ──────────────────────────────────────────────────
355
+
356
+ interface ConsentResolutionResult {
357
+ applied: boolean;
358
+ globalPath: string | null;
359
+ consentDecision: ConsentDecision | undefined;
360
+ }
361
+
362
+ /**
363
+ * Resolve whether the global user config should be applied for a given repo.
364
+ * Implements the §4.1/§4.2 precedence chain from the spec.
365
+ *
366
+ * @param rootDir Absolute repo root.
367
+ * @param override Per-run override from CLI flags (_userConfigOverride).
368
+ * @param registryPath Optional registry path (for tests).
369
+ */
370
+ function resolveConsent(
371
+ rootDir: string,
372
+ override: string | boolean | undefined,
373
+ registryPath: string = REGISTRY_PATH,
374
+ ): ConsentResolutionResult {
375
+ // §4.1 step 1: --no-user-config
376
+ if (override === false) {
377
+ return { applied: false, globalPath: null, consentDecision: undefined };
378
+ }
379
+
380
+ // §4.1 steps 2–3: explicit path or bare --user-config
381
+ if (override !== undefined) {
382
+ const explicitPath = typeof override === 'string' ? override : resolveUserConfigPath();
383
+ if (explicitPath && fs.existsSync(explicitPath)) {
384
+ return { applied: true, globalPath: explicitPath, consentDecision: undefined };
385
+ }
386
+ if (typeof override === 'string') {
387
+ warn(`--user-config path "${override}" does not exist; skipping global layer.`);
388
+ }
389
+ return { applied: false, globalPath: null, consentDecision: undefined };
390
+ }
391
+
392
+ // §4.1 step 4: resolve global file — if none, NOT applied
393
+ const globalPath = resolveUserConfigPath();
394
+ if (!globalPath) {
395
+ return { applied: false, globalPath: null, consentDecision: undefined };
396
+ }
397
+
398
+ // §4.2: check per-repo decision
399
+ const consentDecision = getUserConfigConsent(rootDir, registryPath);
400
+
401
+ // §4.2 step 1: recorded disabled
402
+ if (consentDecision === 'disabled') {
403
+ return { applied: false, globalPath, consentDecision };
404
+ }
405
+
406
+ // §4.2 step 2: recorded enabled
407
+ if (consentDecision === 'enabled') {
408
+ return { applied: true, globalPath, consentDecision };
409
+ }
410
+
411
+ // §4.2 step 3: appliesTo glob match (dynamic, never persisted)
412
+ const parsed = loadUserConfigFile(globalPath);
413
+ if (parsed?.appliesToGlobs.length) {
414
+ const expanded = parsed.appliesToGlobs.map((g) =>
415
+ g.startsWith('~') ? path.join(os.homedir(), g.slice(1)) : g,
416
+ );
417
+ const regexes = compileGlobs(expanded);
418
+ const absRoot = path.resolve(rootDir);
419
+ if (matchesAny(regexes, absRoot)) {
420
+ return { applied: true, globalPath, consentDecision: undefined };
421
+ }
422
+ }
423
+
424
+ // §4.2 steps 4–5: undecided — caller decides whether to prompt
425
+ return { applied: false, globalPath, consentDecision: undefined };
426
+ }
427
+
428
+ // Last applied global path and parsed data — exposed so pipeline.ts and
429
+ // loadConfigWithProvenance can reuse the already-parsed file contents without a
430
+ // second disk read (eliminating the TOCTOU window between loadConfig and callers).
431
+ let _lastAppliedGlobalPath: string | null = null;
432
+ let _lastAppliedGlobalConfig: Record<string, unknown> | null = null;
433
+ export function getLastAppliedGlobalPath(): string | null {
434
+ return _lastAppliedGlobalPath;
435
+ }
436
+ export function getLastAppliedGlobalConfig(): Record<string, unknown> | null {
437
+ return _lastAppliedGlobalConfig;
438
+ }
439
+
440
+ // ── Build-relevant config hash ──────────────────────────────────────────
441
+
442
+ const BUILD_HASH_KEYS: ReadonlyArray<keyof CodegraphConfig> = [
443
+ 'include',
444
+ 'exclude',
445
+ 'ignoreDirs',
446
+ 'extensions',
447
+ 'aliases',
448
+ 'build',
449
+ ];
450
+
451
+ /**
452
+ * Compute a short stable hash of the build-relevant config subset.
453
+ * Used by the pipeline to detect config changes that require a full rebuild.
454
+ */
455
+ export function computeConfigHash(config: CodegraphConfig): string {
456
+ const subset: Partial<CodegraphConfig> = {};
457
+ for (const k of BUILD_HASH_KEYS) {
458
+ (subset as Record<string, unknown>)[k] = config[k];
459
+ }
460
+ return createHash('sha256').update(JSON.stringify(subset)).digest('hex').slice(0, 16);
461
+ }
462
+
463
+ // ── Interactive consent prompt ──────────────────────────────────────────
464
+
465
+ /**
466
+ * When called from the build command, check whether we should prompt the user
467
+ * for global-config consent and, if so, prompt and persist the answer.
468
+ *
469
+ * Only fires when ALL of:
470
+ * - A global config file exists
471
+ * - The repo is undecided (no recorded consent)
472
+ * - Not matched by appliesTo globs
473
+ * - process.stdin.isTTY && process.stdout.isTTY
474
+ * - CI env is not set
475
+ * - No per-run --user-config / --no-user-config flag is active
476
+ */
477
+ export async function promptForConsentIfNeeded(
478
+ rootDir: string,
479
+ registryPath: string = REGISTRY_PATH,
480
+ ): Promise<void> {
481
+ // No-op if per-run override is active
482
+ if (_userConfigOverride !== undefined) return;
483
+
484
+ const globalPath = resolveUserConfigPath();
485
+ if (!globalPath) return;
486
+
487
+ const consentDecision = getUserConfigConsent(rootDir, registryPath);
488
+ if (consentDecision !== undefined) return; // already decided
489
+
490
+ // Check appliesTo globs (dynamic consent — no prompt needed)
491
+ const parsed = loadUserConfigFile(globalPath);
492
+ if (parsed?.appliesToGlobs.length) {
493
+ const expanded = parsed.appliesToGlobs.map((g) =>
494
+ g.startsWith('~') ? path.join(os.homedir(), g.slice(1)) : g,
495
+ );
496
+ const regexes = compileGlobs(expanded);
497
+ const absRoot = path.resolve(rootDir);
498
+ if (matchesAny(regexes, absRoot)) return; // covered by appliesTo
499
+ }
500
+
501
+ // Only prompt in fully interactive sessions
502
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
503
+ if (process.env.CI) return;
504
+
505
+ const { createInterface } = await import('node:readline');
506
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
507
+
508
+ const answer = await new Promise<string>((resolve) => {
509
+ rl.question(
510
+ `\nA global codegraph config was found at ${globalPath}.\n` +
511
+ `Apply settings not explicitly configured in this repo to ${path.resolve(rootDir)}? [y/N]\n` +
512
+ `(remembered per-repo; change later with \`codegraph config --enable-global|--disable-global\`)\n` +
513
+ `> `,
514
+ (ans) => {
515
+ rl.close();
516
+ resolve(ans.trim().toLowerCase());
517
+ },
518
+ );
519
+ });
520
+
521
+ const decided = answer === 'y' || answer === 'yes' ? 'enabled' : 'disabled';
522
+ setUserConfigConsent(rootDir, decided, registryPath);
523
+ process.stderr.write(`Global config consent recorded: ${decided}\n`);
524
+ }
525
+
526
+ // ── Main config loader ──────────────────────────────────────────────────
527
+
528
+ /** Options for loadConfig. */
529
+ export interface LoadConfigOpts {
530
+ /** Per-run user-config override (from CLI flags or programmatic call). */
531
+ userConfig?: string | boolean;
532
+ /** Registry path override (mainly for tests). */
533
+ registryPath?: string;
534
+ }
172
535
 
173
536
  /**
174
537
  * Load project configuration from a .codegraphrc.json or similar file.
175
- * Returns merged config with defaults. Results are cached per cwd.
538
+ * Returns merged config with defaults: defaults global (if applied) → project → env → secrets.
539
+ * Results are cached per cwd + applied global path.
176
540
  */
177
- export function loadConfig(cwd?: string): CodegraphConfig {
178
- cwd = cwd || process.cwd();
179
- const cached = _configCache.get(cwd);
180
- if (cached) return structuredClone(cached);
541
+ export function loadConfig(cwd?: string, opts?: LoadConfigOpts): CodegraphConfig {
542
+ cwd = path.resolve(cwd || process.cwd());
543
+
544
+ // Determine effective override: explicit opts win over module-level variable
545
+ const override = opts?.userConfig !== undefined ? opts.userConfig : _userConfigOverride;
546
+
547
+ // Resolve consent and global path
548
+ const { applied, globalPath } = resolveConsent(cwd, override, opts?.registryPath);
549
+
550
+ // Cache key includes applied global path and override flag so toggled consent is reflected
551
+ const cacheKey = `${cwd}::${applied ? (globalPath ?? 'default') : 'none'}`;
552
+ // Always update _lastAppliedGlobalPath/_lastAppliedGlobalConfig before returning —
553
+ // on a cache hit the previous call may have been for a different repo or different
554
+ // opts, so stale values here would misbehave for programmatic callers making
555
+ // multiple buildGraph calls in the same process.
556
+ _lastAppliedGlobalPath = applied ? globalPath : null;
557
+ _lastAppliedGlobalConfig = null; // updated below if a global file is loaded
558
+ const cached = _configCache.get(cacheKey);
559
+ if (cached) {
560
+ // Restore global config so loadConfigWithProvenance gets correct provenance on cache hits.
561
+ _lastAppliedGlobalConfig = _globalConfigCache.get(cacheKey) ?? null;
562
+ return structuredClone(cached);
563
+ }
564
+
565
+ // ── Layer 0: DEFAULTS ─────────────────────────────────────────────
566
+ let merged = DEFAULTS as unknown as Record<string, unknown>;
181
567
 
568
+ // ── Layer 1: global (if applied) ──────────────────────────────────
569
+ if (applied && globalPath) {
570
+ const userFileData = loadUserConfigFile(globalPath);
571
+ if (userFileData) {
572
+ debug(`Applying global user config from ${globalPath}`);
573
+ const sanitized = sanitizeUserLayer(userFileData.globalConfig);
574
+ // Cache the sanitized global data so pipeline.ts and loadConfigWithProvenance
575
+ // can use it without a second disk read (eliminates TOCTOU window).
576
+ _lastAppliedGlobalConfig = sanitized;
577
+ merged = mergeConfig(merged, sanitized);
578
+ merged = applyExcludeTestsShorthand(merged, sanitized);
579
+ }
580
+ }
581
+
582
+ // ── Layer 2: project ──────────────────────────────────────────────
182
583
  for (const name of CONFIG_FILES) {
183
584
  const filePath = path.join(cwd, name);
184
585
  if (fs.existsSync(filePath)) {
185
586
  try {
186
587
  const raw = fs.readFileSync(filePath, 'utf-8');
187
- const config = JSON.parse(raw);
188
- debug(`Loaded config from ${filePath}`);
189
- const merged = mergeConfig(DEFAULTS as unknown as Record<string, unknown>, config);
190
- if ('excludeTests' in config && !(config.query && 'excludeTests' in config.query)) {
191
- (merged.query as Record<string, unknown>).excludeTests = Boolean(config.excludeTests);
192
- }
193
- delete merged.excludeTests;
194
- const result = resolveSecrets(applyEnvOverrides(merged as unknown as CodegraphConfig));
195
- _configCache.set(cwd, structuredClone(result));
196
- return result;
588
+ const projectConfig = JSON.parse(raw) as Record<string, unknown>;
589
+ debug(`Loaded project config from ${filePath}`);
590
+ merged = mergeConfig(merged, projectConfig);
591
+ merged = applyExcludeTestsShorthand(merged, projectConfig);
592
+ break;
197
593
  } catch (err: unknown) {
198
594
  if (err instanceof ConfigError) throw err;
199
595
  debug(`Failed to parse config ${filePath}: ${toErrorMessage(err)}`);
200
596
  }
201
597
  }
202
598
  }
203
- const defaults = resolveSecrets(applyEnvOverrides({ ...DEFAULTS }));
204
- _configCache.set(cwd, structuredClone(defaults));
205
- return defaults;
599
+
600
+ // ── Layers 3–4: env overrides + secret resolution ─────────────────
601
+ const result = resolveSecrets(applyEnvOverrides(merged as unknown as CodegraphConfig));
602
+ _configCache.set(cacheKey, structuredClone(result));
603
+ _globalConfigCache.set(cacheKey, _lastAppliedGlobalConfig);
604
+ return result;
206
605
  }
207
606
 
208
607
  /**
@@ -212,6 +611,66 @@ export function loadConfig(cwd?: string): CodegraphConfig {
212
611
  */
213
612
  export function clearConfigCache(): void {
214
613
  _configCache.clear();
614
+ _globalConfigCache.clear();
615
+ }
616
+
617
+ /**
618
+ * Load config and return it together with per-key provenance information.
619
+ * Used by `codegraph config --explain`.
620
+ *
621
+ * Calls loadConfig first so _lastAppliedGlobalConfig is populated, then uses
622
+ * that cached data for the global-layer provenance — avoiding a second disk
623
+ * read and eliminating the TOCTOU window between the two reads.
624
+ */
625
+ export function loadConfigWithProvenance(
626
+ cwd?: string,
627
+ opts?: LoadConfigOpts,
628
+ ): import('../types.js').ConfigWithProvenance {
629
+ cwd = path.resolve(cwd || process.cwd());
630
+ const override = opts?.userConfig !== undefined ? opts.userConfig : _userConfigOverride;
631
+ const { applied, globalPath, consentDecision } = resolveConsent(
632
+ cwd,
633
+ override,
634
+ opts?.registryPath,
635
+ );
636
+
637
+ // Load (or return from cache) the merged config first — this also populates
638
+ // _lastAppliedGlobalConfig with the already-parsed and sanitized global layer.
639
+ const config = loadConfig(cwd, opts);
640
+
641
+ // Build provenance by tracking which layer supplies each top-level key
642
+ const provenance: Record<string, ConfigSource> = {};
643
+
644
+ // Layer 0: defaults — everything starts as 'default'
645
+ for (const k of Object.keys(DEFAULTS)) provenance[k] = 'default';
646
+
647
+ // Layer 1: global — reuse the data loadConfig already parsed (no second disk read)
648
+ const globalRaw = applied && globalPath ? _lastAppliedGlobalConfig : null;
649
+ if (globalRaw) {
650
+ for (const k of Object.keys(globalRaw)) provenance[k] = 'user';
651
+ }
652
+
653
+ // Layer 2: project
654
+ for (const name of CONFIG_FILES) {
655
+ const filePath = path.join(cwd, name);
656
+ if (fs.existsSync(filePath)) {
657
+ try {
658
+ const raw = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as Record<string, unknown>;
659
+ for (const k of Object.keys(raw)) provenance[k] = 'project';
660
+ break;
661
+ } catch {
662
+ // ignore
663
+ }
664
+ }
665
+ }
666
+
667
+ // Layer 3+: env overrides (LLM keys)
668
+ const ENV_LLM_KEYS = ['CODEGRAPH_LLM_PROVIDER', 'CODEGRAPH_LLM_API_KEY', 'CODEGRAPH_LLM_MODEL'];
669
+ if (ENV_LLM_KEYS.some((k) => process.env[k] !== undefined)) {
670
+ provenance.llm = 'env';
671
+ }
672
+
673
+ return { config, provenance, appliedGlobalPath: applied ? globalPath : null, consentDecision };
215
674
  }
216
675
 
217
676
  const ENV_LLM_MAP: Record<string, string> = {
@@ -1,6 +1,7 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import type { ConsentDecision } from '../types.js';
4
5
  import { debug, warn } from './logger.js';
5
6
 
6
7
  export const REGISTRY_PATH: string =
@@ -16,8 +17,15 @@ interface RegistryEntry {
16
17
  lastAccessedAt?: string;
17
18
  }
18
19
 
20
+ interface UserConfigSection {
21
+ /** Per-repo consent decisions keyed by absolute repo path. */
22
+ consent: Record<string, ConsentDecision>;
23
+ }
24
+
19
25
  interface Registry {
20
26
  repos: Record<string, RegistryEntry>;
27
+ /** User-level global config consent store — separate from MCP repo listings. */
28
+ userConfig?: UserConfigSection;
21
29
  }
22
30
 
23
31
  /**
@@ -160,6 +168,67 @@ export function resolveRepoDbPath(
160
168
  return entry.dbPath;
161
169
  }
162
170
 
171
+ // ── User-config consent ────────────────────────────────────────────────
172
+
173
+ /**
174
+ * Read the per-repo consent decision for the global user config.
175
+ * Returns `undefined` when the repo is undecided (no recorded decision).
176
+ */
177
+ export function getUserConfigConsent(
178
+ rootDir: string,
179
+ registryPath: string = REGISTRY_PATH,
180
+ ): ConsentDecision | undefined {
181
+ const registry = loadRegistry(registryPath);
182
+ const absRoot = path.resolve(rootDir);
183
+ return registry.userConfig?.consent?.[absRoot];
184
+ }
185
+
186
+ /**
187
+ * Persist a per-repo consent decision. Atomic write via temp+rename.
188
+ */
189
+ export function setUserConfigConsent(
190
+ rootDir: string,
191
+ decision: ConsentDecision,
192
+ registryPath: string = REGISTRY_PATH,
193
+ ): void {
194
+ const registry = loadRegistry(registryPath);
195
+ const absRoot = path.resolve(rootDir);
196
+ if (!registry.userConfig) registry.userConfig = { consent: {} };
197
+ if (!registry.userConfig.consent) registry.userConfig.consent = {};
198
+ registry.userConfig.consent[absRoot] = decision;
199
+ saveRegistry(registry, registryPath);
200
+ debug(`User-config consent for "${absRoot}" set to "${decision}"`);
201
+ }
202
+
203
+ /**
204
+ * List every repo with a recorded consent decision, sorted by path.
205
+ */
206
+ export function listUserConfigConsent(
207
+ registryPath: string = REGISTRY_PATH,
208
+ ): Array<{ path: string; decision: ConsentDecision }> {
209
+ const registry = loadRegistry(registryPath);
210
+ const consent = registry.userConfig?.consent ?? {};
211
+ return Object.entries(consent)
212
+ .map(([p, decision]) => ({ path: p, decision }))
213
+ .sort((a, b) => a.path.localeCompare(b.path));
214
+ }
215
+
216
+ /**
217
+ * Revert a repo to undecided state. Returns true if a decision was removed.
218
+ */
219
+ export function clearUserConfigConsent(
220
+ rootDir: string,
221
+ registryPath: string = REGISTRY_PATH,
222
+ ): boolean {
223
+ const registry = loadRegistry(registryPath);
224
+ const absRoot = path.resolve(rootDir);
225
+ const consent = registry.userConfig?.consent;
226
+ if (!consent || !(absRoot in consent)) return false;
227
+ delete consent[absRoot];
228
+ saveRegistry(registry, registryPath);
229
+ return true;
230
+ }
231
+
163
232
  interface PrunedEntry {
164
233
  name: string;
165
234
  path: string;
@@ -200,7 +269,19 @@ export function pruneRegistry(
200
269
  }
201
270
  }
202
271
 
203
- if (!dryRun && pruned.length > 0) {
272
+ // Prune consent entries whose repo paths no longer exist on disk.
273
+ // Consent entries are TTL-exempt — only the missing-path rule applies.
274
+ let consentChanged = false;
275
+ if (!dryRun && registry.userConfig?.consent) {
276
+ for (const p of Object.keys(registry.userConfig.consent)) {
277
+ if (!fs.existsSync(p)) {
278
+ delete registry.userConfig.consent[p];
279
+ consentChanged = true;
280
+ }
281
+ }
282
+ }
283
+
284
+ if (!dryRun && (pruned.length > 0 || consentChanged)) {
204
285
  saveRegistry(registry, registryPath);
205
286
  }
206
287
 
@@ -53,15 +53,15 @@ interface HotspotsResult {
53
53
  metric: string;
54
54
  level: string;
55
55
  limit: number;
56
- hotspots: any[];
56
+ items: any[];
57
57
  }
58
58
 
59
59
  export function formatHotspots(data: HotspotsResult): string {
60
- if (data.hotspots.length === 0) return 'No hotspots found. Run "codegraph build" first.';
60
+ if (data.items.length === 0) return 'No hotspots found. Run "codegraph build" first.';
61
61
 
62
62
  const lines = [`\nHotspots by ${data.metric} (${data.level}-level, top ${data.limit}):\n`];
63
63
  let rank = 1;
64
- for (const h of data.hotspots) {
64
+ for (const h of data.items) {
65
65
  const extra =
66
66
  h.kind === 'directory'
67
67
  ? `${h.fileCount} files, cohesion=${h.cohesion !== null ? h.cohesion!.toFixed(2) : 'n/a'}`