@vibgrate/cli 2026.813.1 → 2026.814.2

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 (123) hide show
  1. package/DOCS.md +258 -22
  2. package/NOTICE +7 -0
  3. package/README.md +273 -11
  4. package/dist/agent-5ANHRYEI.js +26 -0
  5. package/dist/{agent-N3CP3SPI.js.map → agent-5ANHRYEI.js.map} +1 -1
  6. package/dist/approvals-T2KXPJLV.js +9 -0
  7. package/dist/approvals-T2KXPJLV.js.map +1 -0
  8. package/dist/baseline-WVD6P5IO.js +9 -0
  9. package/dist/{baseline-ZMRZRGFI.js.map → baseline-WVD6P5IO.js.map} +1 -1
  10. package/dist/{checkpoint-4WFZMKEO.js → checkpoint-UYMYMMQO.js} +6 -3
  11. package/dist/checkpoint-UYMYMMQO.js.map +1 -0
  12. package/dist/chunk-2H2U3DC7.js +6 -0
  13. package/dist/{chunk-RT7P5AYU.js.map → chunk-2H2U3DC7.js.map} +1 -1
  14. package/dist/chunk-2U37PFB2.js +64 -0
  15. package/dist/chunk-2U37PFB2.js.map +1 -0
  16. package/dist/{chunk-GOPANQZT.js → chunk-54RGT2T5.js} +3 -3
  17. package/dist/{chunk-GOPANQZT.js.map → chunk-54RGT2T5.js.map} +1 -1
  18. package/dist/{chunk-OYHAF2J2.js → chunk-5GLQNMTI.js} +5 -5
  19. package/dist/{chunk-OYHAF2J2.js.map → chunk-5GLQNMTI.js.map} +1 -1
  20. package/dist/{chunk-EWZKOU66.js → chunk-75LJM5XD.js} +30 -66
  21. package/dist/chunk-75LJM5XD.js.map +1 -0
  22. package/dist/{chunk-KF2QT6RY.js → chunk-7NMXE6KG.js} +4 -4
  23. package/dist/{chunk-KF2QT6RY.js.map → chunk-7NMXE6KG.js.map} +1 -1
  24. package/dist/{chunk-UZP623Y4.js → chunk-7QDHQLUS.js} +4 -4
  25. package/dist/{chunk-UZP623Y4.js.map → chunk-7QDHQLUS.js.map} +1 -1
  26. package/dist/chunk-AJS4EL2C.js +266 -0
  27. package/dist/chunk-AJS4EL2C.js.map +1 -0
  28. package/dist/{chunk-Z3MUWXP3.js → chunk-BH54SLGZ.js} +4 -4
  29. package/dist/{chunk-Z3MUWXP3.js.map → chunk-BH54SLGZ.js.map} +1 -1
  30. package/dist/{chunk-CJNWHXQD.js → chunk-DSUGC7F5.js} +4 -4
  31. package/dist/{chunk-CJNWHXQD.js.map → chunk-DSUGC7F5.js.map} +1 -1
  32. package/dist/{chunk-FBVKQXBH.js → chunk-FOW5IF73.js} +3 -3
  33. package/dist/{chunk-FBVKQXBH.js.map → chunk-FOW5IF73.js.map} +1 -1
  34. package/dist/{chunk-6GQLEDVK.js → chunk-IHLLWBZU.js} +6 -5
  35. package/dist/chunk-IHLLWBZU.js.map +1 -0
  36. package/dist/{chunk-RHKJPTON.js → chunk-IHXNOY3R.js} +208 -56
  37. package/dist/chunk-IHXNOY3R.js.map +1 -0
  38. package/dist/{chunk-5JJBGBP2.js → chunk-JCN6MSXQ.js} +7 -7
  39. package/dist/{chunk-5JJBGBP2.js.map → chunk-JCN6MSXQ.js.map} +1 -1
  40. package/dist/{chunk-YJU7S7N6.js → chunk-KGPX4EUN.js} +4 -4
  41. package/dist/{chunk-YJU7S7N6.js.map → chunk-KGPX4EUN.js.map} +1 -1
  42. package/dist/{chunk-ADP6ITGF.js → chunk-N3XFY3PX.js} +68 -11
  43. package/dist/chunk-N3XFY3PX.js.map +1 -0
  44. package/dist/{chunk-JYM4QT6F.js → chunk-NKFXXP6W.js} +5 -5
  45. package/dist/{chunk-JYM4QT6F.js.map → chunk-NKFXXP6W.js.map} +1 -1
  46. package/dist/{chunk-5ROZODMW.js → chunk-TFAXW7VM.js} +2 -2
  47. package/dist/chunk-TFAXW7VM.js.map +1 -0
  48. package/dist/{chunk-6423BHLN.js → chunk-TNROG5CO.js} +19 -9
  49. package/dist/chunk-TNROG5CO.js.map +1 -0
  50. package/dist/chunk-TVDYEHIM.js +174 -0
  51. package/dist/chunk-TVDYEHIM.js.map +1 -0
  52. package/dist/{chunk-7ZHSSGUF.js → chunk-WQLZSVNF.js} +4 -3
  53. package/dist/chunk-WQLZSVNF.js.map +1 -0
  54. package/dist/{chunk-3WUTQYRY.js → chunk-WWGLVF7D.js} +9 -8
  55. package/dist/chunk-WWGLVF7D.js.map +1 -0
  56. package/dist/{chunk-KBP7GJV6.js → chunk-X76VPOYH.js} +19 -9
  57. package/dist/chunk-X76VPOYH.js.map +1 -0
  58. package/dist/{chunk-IJQOZ6ZD.js → chunk-YNV5M3JW.js} +8 -8
  59. package/dist/chunk-YNV5M3JW.js.map +1 -0
  60. package/dist/{chunk-Z3AYOZ3C.js → chunk-YQNTIBKS.js} +6 -6
  61. package/dist/{chunk-Z3AYOZ3C.js.map → chunk-YQNTIBKS.js.map} +1 -1
  62. package/dist/cli.js +1130 -489
  63. package/dist/cli.js.map +1 -1
  64. package/dist/embed-worker-main.js +4 -3
  65. package/dist/embed-worker-main.js.map +1 -1
  66. package/dist/{ensure-map-PHAJACFF.js → ensure-map-HQ7A5NDL.js} +15 -14
  67. package/dist/{ensure-map-PHAJACFF.js.map → ensure-map-HQ7A5NDL.js.map} +1 -1
  68. package/dist/fastembed-S6YEJYQV.js +292 -0
  69. package/dist/fastembed-S6YEJYQV.js.map +1 -0
  70. package/dist/graph-backend-W2TNTMY7.js +14 -0
  71. package/dist/{graph-backend-4B3MTVIW.js.map → graph-backend-W2TNTMY7.js.map} +1 -1
  72. package/dist/index.d.ts +4 -3
  73. package/dist/index.js +14 -13
  74. package/dist/index.js.map +1 -1
  75. package/dist/{interactive-WUXMXFNM.js → interactive-EW2VJ3BZ.js} +32 -30
  76. package/dist/interactive-EW2VJ3BZ.js.map +1 -0
  77. package/dist/load-64RK5O6C.js +10 -0
  78. package/dist/{load-EUZSV73H.js.map → load-64RK5O6C.js.map} +1 -1
  79. package/dist/{run-outcome-O5PR7ZCK.js → run-outcome-6QNQIHPV.js} +6 -5
  80. package/dist/run-outcome-6QNQIHPV.js.map +1 -0
  81. package/dist/runtime-session-RJHH3KMF.js +21 -0
  82. package/dist/{runtime-session-PPQDTFIK.js.map → runtime-session-RJHH3KMF.js.map} +1 -1
  83. package/dist/session-4BGYASOH.js +16 -0
  84. package/dist/{session-WS7SOVJE.js.map → session-4BGYASOH.js.map} +1 -1
  85. package/dist/session-store-AQUORKWB.js +4 -0
  86. package/dist/{session-store-KGONLWHN.js.map → session-store-AQUORKWB.js.map} +1 -1
  87. package/dist/{stream-json-7MK3QQYG.js → stream-json-GY5N7WZT.js} +76 -24
  88. package/dist/stream-json-GY5N7WZT.js.map +1 -0
  89. package/dist/version-DPAMQW6M.js +4 -0
  90. package/dist/version-DPAMQW6M.js.map +1 -0
  91. package/dist/{vg-mcp-bridge-DQLCHBI6.js → vg-mcp-bridge-IGHJKKSL.js} +11 -10
  92. package/dist/vg-mcp-bridge-IGHJKKSL.js.map +1 -0
  93. package/dist/{vgd-Y25XSQGZ.js → vgd-ORPA5C2K.js} +12 -11
  94. package/dist/vgd-ORPA5C2K.js.map +1 -0
  95. package/dist/worktree-session-D575IQWM.js +82 -0
  96. package/dist/worktree-session-D575IQWM.js.map +1 -0
  97. package/package.json +4 -2
  98. package/dist/agent-N3CP3SPI.js +0 -24
  99. package/dist/baseline-ZMRZRGFI.js +0 -9
  100. package/dist/checkpoint-4WFZMKEO.js.map +0 -1
  101. package/dist/chunk-3WUTQYRY.js.map +0 -1
  102. package/dist/chunk-5ROZODMW.js.map +0 -1
  103. package/dist/chunk-6423BHLN.js.map +0 -1
  104. package/dist/chunk-6GQLEDVK.js.map +0 -1
  105. package/dist/chunk-7ZHSSGUF.js.map +0 -1
  106. package/dist/chunk-ADP6ITGF.js.map +0 -1
  107. package/dist/chunk-EWZKOU66.js.map +0 -1
  108. package/dist/chunk-IJQOZ6ZD.js.map +0 -1
  109. package/dist/chunk-KBP7GJV6.js.map +0 -1
  110. package/dist/chunk-RHKJPTON.js.map +0 -1
  111. package/dist/chunk-RT7P5AYU.js +0 -6
  112. package/dist/chunk-Z7FM3ETS.js +0 -126
  113. package/dist/chunk-Z7FM3ETS.js.map +0 -1
  114. package/dist/graph-backend-4B3MTVIW.js +0 -13
  115. package/dist/interactive-WUXMXFNM.js.map +0 -1
  116. package/dist/load-EUZSV73H.js +0 -9
  117. package/dist/run-outcome-O5PR7ZCK.js.map +0 -1
  118. package/dist/runtime-session-PPQDTFIK.js +0 -20
  119. package/dist/session-WS7SOVJE.js +0 -15
  120. package/dist/session-store-KGONLWHN.js +0 -4
  121. package/dist/stream-json-7MK3QQYG.js.map +0 -1
  122. package/dist/vg-mcp-bridge-DQLCHBI6.js.map +0 -1
  123. package/dist/vgd-Y25XSQGZ.js.map +0 -1
@@ -1,4 +1,5 @@
1
- import { resolveGraphPath, cacheDir } from './chunk-EWZKOU66.js';
1
+ import { cacheDir } from './chunk-2U37PFB2.js';
2
+ import { resolveGraphPath } from './chunk-75LJM5XD.js';
2
3
  import { hashString } from './chunk-JFGYT6BI.js';
3
4
  import * as fs2 from 'fs';
4
5
  import { createRequire } from 'module';
@@ -192,18 +193,27 @@ async function importEmbedBackend() {
192
193
  if (hostDir) {
193
194
  try {
194
195
  const req = createRequire(path2.join(hostDir, "package.json"));
195
- const mod = await import(pathToFileURL(req.resolve("fastembed")).href);
196
- const resolved = unwrapBackend(mod);
197
- if (resolved) return { mod: resolved };
198
- error = `${hostDir}: fastembed loaded but exported no FlagEmbedding`;
196
+ let entry = null;
197
+ try {
198
+ entry = req.resolve("fastembed");
199
+ } catch {
200
+ }
201
+ if (entry) {
202
+ const mod = await import(pathToFileURL(entry).href);
203
+ const resolved = unwrapBackend(mod);
204
+ if (resolved) return { mod: resolved };
205
+ error = `${hostDir}: fastembed loaded but exported no FlagEmbedding`;
206
+ }
199
207
  } catch (e) {
200
208
  error = `${hostDir}: ${errText(e)}`;
201
209
  }
202
210
  }
203
211
  try {
204
- const mod = await import('fastembed');
212
+ const mod = await import('./fastembed-S6YEJYQV.js');
205
213
  const resolved = unwrapBackend(mod);
206
- return resolved ? { mod: resolved } : { mod: null, error: error ?? "fastembed exported no FlagEmbedding" };
214
+ if (!resolved) return { mod: null, error: error ?? "embed backend exported no FlagEmbedding" };
215
+ if (typeof resolved.ensureNativeDeps === "function") await resolved.ensureNativeDeps();
216
+ return { mod: resolved };
207
217
  } catch (e) {
208
218
  return { mod: null, error: error ?? errText(e) };
209
219
  }
@@ -585,5 +595,5 @@ function safe(id) {
585
595
  }
586
596
 
587
597
  export { acquireLock, clearModelCache, cosine, countPending, embeddingsCached, embeddingsPath, embeddingsPathFor, getNodeEmbeddings, isModelReady, loadEmbedder, modelCacheInfo, nodeEmbedText, releaseLock, resolveEmbedModel, unavailableMessage, withTimeout };
588
- //# sourceMappingURL=chunk-KBP7GJV6.js.map
589
- //# sourceMappingURL=chunk-KBP7GJV6.js.map
598
+ //# sourceMappingURL=chunk-X76VPOYH.js.map
599
+ //# sourceMappingURL=chunk-X76VPOYH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine/lock.ts","../src/engine/embeddings.ts"],"names":["fs","path"],"mappings":";;;;;;;;;AAWO,IAAM,qBAAA,GAAwB,KAAK,EAAA,GAAK,GAAA;AAE/C,SAAS,eAAe,GAAA,EAAsB;AAC5C,EAAA,IAAI;AACF,IAAA,OAAA,CAAQ,IAAA,CAAK,KAAK,CAAC,CAAA;AACnB,IAAA,OAAO,IAAA;AAAA,EACT,SAAS,CAAA,EAAG;AACV,IAAA,OAAQ,EAA4B,IAAA,KAAS,OAAA;AAAA,EAC/C;AACF;AAEA,SAAS,WAAA,CAAY,MAAc,OAAA,EAA0B;AAC3D,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAK,EAAA,EAAG,GAAI,KAAK,KAAA,CAASA,GAAA,CAAA,YAAA,CAAa,IAAA,EAAM,MAAM,CAAC,CAAA;AAC5D,IAAA,IAAI,OAAO,OAAO,QAAA,IAAY,IAAA,CAAK,KAAI,GAAI,EAAA,GAAK,SAAS,OAAO,I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from 'node:fs';\nimport * as path from 'node:path';\n\n/**\n * Cross-process single-writer lock (O_EXCL create), shared by the embedding\n * cache writer and the auto-refresh rebuild so two vg processes never write\n * the same repo-local artifact at once. A lock whose owning process is dead,\n * or that is older than `staleMs`, is presumed abandoned and reclaimed.\n */\n\n/** A lock older than this is presumed dead (crashed process). */\nexport const DEFAULT_LOCK_STALE_MS = 15 * 60 * 1000;\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (e) {\n return (e as NodeJS.ErrnoException).code === 'EPERM'; // exists, just not ours to signal\n }\n}\n\nfunction lockIsStale(file: string, staleMs: number): boolean {\n try {\n const { pid, at } = JSON.parse(fs.readFileSync(file, 'utf8')) as { pid?: number; at?: number };\n if (typeof at === 'number' && Date.now() - at > staleMs) return true;\n if (typeof pid === 'number' && !isProcessAlive(pid)) return true;\n return false;\n } catch {\n return true; // unreadable/corrupt → reclaim it\n }\n}\n\n/** Take the lock (O_EXCL), reclaiming a stale/dead one. Returns success. */\nexport function acquireLock(file: string, staleMs = DEFAULT_LOCK_STALE_MS): boolean {\n const write = (): boolean => {\n try {\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const fd = fs.openSync(file, 'wx');\n fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, at: Date.now() }));\n fs.closeSync(fd);\n return true;\n } catch {\n return false;\n }\n };\n if (write()) return true;\n if (lockIsStale(file, staleMs)) {\n try {\n fs.rmSync(file, { force: true });\n } catch {\n /* another process may have reclaimed it */\n }\n return write();\n }\n return false;\n}\n\nexport function releaseLock(file: string): void {\n try {\n fs.rmSync(file, { force: true });\n } catch {\n /* best-effort */\n }\n}\n","import * as fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { hashString } from './hash.js';\nimport { cacheDir } from './cache.js';\nimport { resolveGraphPath } from './artifacts.js';\nimport { acquireLock, releaseLock } from './lock.js';\nimport type { GraphNode, VgGraph } from '../schema.js';\n\n/**\n * Local-embedding semantic search for `vg ask --semantic`/`--deep` (no API key).\n *\n * The embedding backend is OPTIONAL and lazily loaded (the vendored\n * `src/vendor/fastembed` dense backend over `onnxruntime-node`, local ONNX)\n * so the core install stays lean and `ask` never breaks:\n * if the backend or model isn't available it degrades to (prefix-fuzzy) lexical\n * search with a clear note. Per-repo vectors live in a binary `*.embeddings`\n * file **alongside the code map** (global store under Application Support /\n * XDG data, or `.vibgrate/embeddings` in-repo) — never model-named, never under\n * `.vibgrate/cache/`, and NEVER inside the committed `graph.json`, so the map\n * stays byte-deterministic. The model id is recorded inside the file header so\n * a model change still invalidates the cache without putting the name in the\n * path.\n *\n * `--local` disables the model download (semantic is skipped unless already\n * cached via an injected backend), keeping the air-gapped guarantee.\n */\n\nexport interface Embedder {\n /** Stable model id (recorded with cached vectors so a model change invalidates them). */\n id: string;\n /** Embed documents → unit-or-raw vectors (cosine handles normalization). */\n embed(texts: string[]): Promise<number[][]>;\n /** Embed a single query string. */\n embedQuery(text: string): Promise<number[]>;\n}\n\n/** Why semantic fell back to lexical — for calm, specific messaging. */\nexport type EmbedUnavailable = 'not-installed' | 'no-permission' | 'download-failed' | 'init-failed';\n\nexport interface LoadEmbedderOptions {\n local?: boolean; // --local: do not download a model\n model?: string; // override the embedding model id\n noDownload?: boolean; // only load if the model is already cached (never fetch)\n showDownloadProgress?: boolean; // let fastembed print its one-time download progress\n /**\n * Called (not thrown) when the backend can't load. `detail` carries the\n * underlying loader error when there is one, so a host can log something\n * actionable instead of a bare category.\n */\n onUnavailable?: (reason: EmbedUnavailable, detail?: string) => void;\n}\n\n/** The embedding model id in effect (explicit override → default). */\nexport function resolveEmbedModel(model?: string): string {\n return model ?? 'bge-small-en-v1.5';\n}\n\n/**\n * The **central, per-user** model cache — downloaded once per machine and shared\n * across every repo/folder (devs have many repos; the ~tens-of-MB model should\n * not re-download per project). Uses the XDG standard:\n * `$XDG_CACHE_HOME/vibgrate/models` (or `~/.cache/vibgrate/models`); relocate via\n * the standard `XDG_CACHE_HOME`. NB: fastembed's own default is the relative\n * `./local_cache`, i.e. per-CWD — which we override.\n */\nexport function modelCacheDir(): string {\n const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');\n return path.join(base, 'vibgrate', 'models');\n}\n\n/** A machine-global marker written once the model has loaded successfully. */\nfunction modelReadyMarker(modelId: string): string {\n return path.join(modelCacheDir(), `.ready-${safe(modelId)}`);\n}\n\n/**\n * Whether the embedding model is already present on this machine (loaded at least\n * once), so it can be used with **no network**. Lets the background warm-up\n * trigger only when it won't surprise-download.\n */\nexport function isModelReady(modelId = resolveEmbedModel()): boolean {\n return fs.existsSync(modelReadyMarker(modelId));\n}\n\n/**\n * A calm, specific, actionable one-liner for why semantic isn't available right\n * now — built to reassure (lexical still works) and inform, never to alarm. No\n * stack traces, no scary words; always names the off switch and the fix.\n */\nexport function unavailableMessage(reason: EmbedUnavailable): string {\n switch (reason) {\n case 'no-permission':\n return `semantic search couldn't write its model cache at ${modelCacheDir()} — using fast lexical search instead. Relocate it with the standard XDG_CACHE_HOME, or run with --local to stay lexical quietly. (No admin/sudo is ever needed — the cache lives in your home folder.)`;\n case 'download-failed':\n return `the semantic model isn't downloaded yet and couldn't be fetched (offline?) — using fast lexical search. It'll try again next time; run with --local to keep lexical without retrying.`;\n case 'not-installed':\n return `the optional semantic backend isn't available here — using fast lexical search.`;\n case 'init-failed':\n default:\n return `the semantic model couldn't load — using fast lexical search.`;\n }\n}\n\nexport interface ModelCacheInfo {\n dir: string;\n present: boolean;\n bytes: number;\n}\n\n/** Where the shared model lives, whether it's present, and how big it is. */\nexport function modelCacheInfo(modelId = resolveEmbedModel()): ModelCacheInfo {\n const dir = modelCacheDir();\n return { dir, present: isModelReady(modelId) || fs.existsSync(dir), bytes: dirSize(dir) };\n}\n\n/** Remove the shared, re-downloadable model from the central cache. Returns bytes freed. */\nexport function clearModelCache(): number {\n const dir = modelCacheDir();\n const bytes = dirSize(dir);\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* best-effort */\n }\n return bytes;\n}\n\nfunction dirSize(dir: string): number {\n let total = 0;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n return 0;\n }\n for (const e of entries) {\n const p = path.join(dir, e.name);\n if (e.isDirectory()) total += dirSize(p);\n else {\n try {\n total += fs.statSync(p).size;\n } catch {\n /* skip unreadable */\n }\n }\n }\n return total;\n}\n\nfunction isPermissionError(e: unknown): boolean {\n const code = (e as NodeJS.ErrnoException | undefined)?.code;\n return code === 'EACCES' || code === 'EPERM' || code === 'EROFS';\n}\n\n/**\n * Whether this repo already has a cached vector set for `modelId` — i.e. semantic\n * search has run here before, so the next run is fast (no first-use download/embed).\n * Lets `ask` show the one-time setup note only when it's actually warranted.\n * Checks the binary sidecar next to the map (and the legacy JSON path once).\n */\nexport function embeddingsCached(root: string, modelId: string): boolean {\n const file = vectorCachePath(root);\n if (fs.existsSync(file) && readCacheHeader(file)?.model === modelId) return true;\n // One-shot legacy: pre-binary caches lived under `.vibgrate/cache/embeddings-<model>.json`.\n return fs.existsSync(legacyVectorCachePath(root, modelId));\n}\n\n/**\n * Path of the binary embeddings file for this repo's current map — always named\n * `embeddings` (or `<snapshot>.embeddings` next to a branch-keyed graph), never\n * after the model. Exported for `vg embed --where` and tests.\n */\nexport function embeddingsPath(root: string): string {\n return vectorCachePath(root);\n}\n\n/** Sidecar path next to a map file: `…/branch-main.graph.json` → `…/branch-main.embeddings`. */\nexport function embeddingsPathFor(graphPath: string): string {\n // Branch-keyed global maps: `…/graphs/branch-main.graph.json` → `…/graphs/branch-main.embeddings`.\n if (graphPath.endsWith('.graph.json')) return `${graphPath.slice(0, -'.graph.json'.length)}.embeddings`;\n if (graphPath.endsWith('.graph.snap')) return `${graphPath.slice(0, -'.graph.snap'.length)}.embeddings`;\n // In-repo map is exactly `…/graph.json` (or `graph.snap`) → plain `…/embeddings`.\n const base = path.basename(graphPath);\n if (base === 'graph.json' || base === 'graph.snap') {\n return path.join(path.dirname(graphPath), 'embeddings');\n }\n if (graphPath.endsWith('.json')) return `${graphPath.slice(0, -5)}.embeddings`;\n if (graphPath.endsWith('.snap')) return `${graphPath.slice(0, -5)}.embeddings`;\n return `${graphPath}.embeddings`;\n}\n\n/**\n * Try to load the optional local embedding backend. Returns null (→ caller falls\n * back to lexical) when running `--local`, when the dependency isn't installed,\n * or when the model can't initialize.\n */\nexport async function loadEmbedder(options: LoadEmbedderOptions = {}): Promise<Embedder | null> {\n // `--local` forces the deterministic lexical floor with no model load/download\n // (air-gapped guarantee; also how tests stay offline).\n if (options.local) return null;\n const modelId = resolveEmbedModel(options.model);\n // noDownload (used by the background warm-up): never fetch — bail if not cached.\n if (options.noDownload && !isModelReady(modelId)) return null;\n const fail = (reason: EmbedUnavailable, detail?: string): null => {\n options.onUnavailable?.(reason, detail);\n return null;\n };\n\n // Lazy, optional dependency (native ONNX): loaded only for `vg ask`/`embed`,\n // never by build/verify, so the graph artifact stays deterministic.\n const backend = await importEmbedBackend();\n const mod: any = backend.mod;\n if (!mod?.FlagEmbedding) return fail('not-installed', backend.error);\n\n const cache = modelCacheDir(); // central, shared across all repos\n try {\n fs.mkdirSync(cache, { recursive: true });\n } catch (e) {\n return fail(isPermissionError(e) ? 'no-permission' : 'init-failed');\n }\n\n try {\n // First use fetches the model. A refused connection fails fast, but a\n // black-holing proxy (common on corporate networks) would hang the first\n // `vg ask` / MCP query_graph forever — bound the wait and fall back to\n // lexical instead. Cached loads are local disk and get the same generous\n // ceiling without ever hitting it.\n const model: any = await withTimeout(\n mod.FlagEmbedding.init({\n model: mapModel(mod, modelId),\n cacheDir: cache,\n showDownloadProgress: options.showDownloadProgress ?? false,\n }) as Promise<unknown>,\n embedInitTimeoutMs(),\n 'embedding model init timed out',\n );\n // Record machine-global readiness so future builds can warm up offline.\n try {\n fs.writeFileSync(modelReadyMarker(modelId), new Date(0).toISOString());\n } catch {\n /* marker is best-effort */\n }\n return {\n id: modelId,\n async embed(texts) {\n const out: number[][] = [];\n for await (const batch of model.embed(texts, 64)) {\n for (const v of batch) out.push(Array.from(v as ArrayLike<number>));\n }\n return out;\n },\n async embedQuery(text) {\n const v = await model.queryEmbed(text);\n return Array.from(v as ArrayLike<number>);\n },\n };\n } catch (e) {\n return fail(isPermissionError(e) ? 'no-permission' : 'download-failed', errText(e));\n }\n}\n\n/**\n * Import the optional embedding backend — the VENDORED dense backend\n * (src/vendor/fastembed). It still needs the optional native deps\n * (`onnxruntime-node`, `@anush008/tokenizers`, `tar`), which a host can supply\n * out-of-tree via `VIBGRATE_EMBEDDER_PATH` — a directory whose `node_modules`\n * contains them. Editor integrations use this when their bundled engine ships\n * without the native optional dependencies (the VS Code extension installs\n * them into its own storage on consent); the host dir wins over this package's\n * own dependency tree so the copies the user consented to are the ones that\n * load (see `ensureNativeDeps` in the vendored module).\n *\n * Legacy host contract: a host dir holding a whole upstream `fastembed`\n * install (what older extension versions set up) is still honored, and wins,\n * so an engine upgrade never breaks a backend the user already consented to.\n * Any resolution failure falls through — never throws.\n */\nasync function importEmbedBackend(): Promise<{ mod: any | null; error?: string }> {\n const hostDir = process.env.VIBGRATE_EMBEDDER_PATH;\n let error: string | undefined;\n if (hostDir) {\n try {\n const req = createRequire(path.join(hostDir, 'package.json'));\n let entry: string | null = null;\n try {\n entry = req.resolve('fastembed');\n } catch {\n // No upstream fastembed in the host dir — the normal state under the\n // current contract (the host supplies only the native deps, resolved\n // by the vendored backend below). Not an error worth reporting.\n }\n if (entry) {\n const mod: any = await import(pathToFileURL(entry).href);\n const resolved = unwrapBackend(mod);\n if (resolved) return { mod: resolved };\n error = `${hostDir}: fastembed loaded but exported no FlagEmbedding`;\n }\n } catch (e) {\n // Keep the reason. A host-supplied backend that resolves but won't load\n // (native binary built for another ABI, a half-extracted tree, a missing\n // transitive dep) is indistinguishable from \"never installed\" once the\n // error is dropped — and that is the one failure a user cannot act on.\n error = `${hostDir}: ${errText(e)}`;\n }\n }\n try {\n const mod: any = await import('../vendor/fastembed/index.js');\n const resolved = unwrapBackend(mod);\n if (!resolved) return { mod: null, error: error ?? 'embed backend exported no FlagEmbedding' };\n // Load the native deps now (host dir first — see the vendored module), so\n // a missing or broken install surfaces here as \"not-installed\" with the\n // real reason instead of failing later mid-init.\n if (typeof resolved.ensureNativeDeps === 'function') await resolved.ensureNativeDeps();\n return { mod: resolved };\n } catch (e) {\n return { mod: null, error: error ?? errText(e) };\n }\n}\n\n/** A CJS entry imported over ESM may nest its exports one or two `default`s deep. */\nfunction unwrapBackend(mod: any): any | null {\n for (const candidate of [mod, mod?.default, mod?.default?.default]) {\n if (candidate?.FlagEmbedding) return candidate;\n }\n return null;\n}\n\nfunction errText(e: unknown): string {\n const msg = e instanceof Error ? e.message : String(e);\n return msg.replace(/\\s+/g, ' ').trim().slice(0, 300);\n}\n\n/** Ceiling for the one-time model fetch/init; override via VG_EMBED_TIMEOUT_MS. */\nfunction embedInitTimeoutMs(): number {\n const n = Number(process.env.VG_EMBED_TIMEOUT_MS);\n return Number.isFinite(n) && n > 0 ? n : 60_000;\n}\n\n/** Reject `promise` if it hasn't settled within `ms` (the work itself is not cancelled). */\nexport async function withTimeout<T>(promise: Promise<T>, ms: number, message: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(message)), ms);\n timer.unref?.();\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction mapModel(mod: any, id: string): unknown {\n const m = mod.EmbeddingModel ?? {};\n if (/bge-small/i.test(id)) return m.BGESmallENV15 ?? m.BGESmallEN ?? id;\n if (/bge-base/i.test(id)) return m.BGEBaseENV15 ?? id;\n if (/all-minilm/i.test(id)) return m.AllMiniLML6V2 ?? id;\n return id;\n}\n\n/** Path segments that carry no semantic signal — dropped from embed context. */\nconst PATH_NOISE = new Set([\n 'src', 'app', 'apps', 'lib', 'libs', 'dist', 'build', 'out', 'index', 'main',\n 'packages', 'pkg', 'test', 'tests', '__tests__', 'spec', 'node_modules', 'internal',\n 'com', 'example', 'demo', 'java', 'net', 'org', 'www',\n]);\n\n/** Meaningful path context for a node: a couple of parent dirs + the filename stem. */\nfunction pathContext(file: string): string {\n const parts = file.split('/');\n const stem = (parts.pop() ?? '').replace(/\\.[^.]+$/, '');\n const dirs = parts.filter((p) => p && !PATH_NOISE.has(p.toLowerCase()));\n return [...dirs.slice(-2), stem].filter(Boolean).join(' ');\n}\n\n/**\n * The text we embed for a node. Alongside identity + signature we add the\n * strongest available signal — the node's **doc-comment / docstring** summary —\n * plus lightweight context already on the graph (file-path words, area label), so\n * a tersely-named symbol (`Table`, `NotificationJob`) a concept query can reach.\n *\n * `document` nodes (markdown, manifests, Docker, CI, OpenAPI, …) put the\n * scrubbed body in `doc` — that body is the primary embed signal so `vg ask`\n * can answer project-context questions, not only code symbols.\n */\nexport function nodeEmbedText(node: GraphNode, areaLabel?: string): string {\n if (node.kind === 'document') {\n const category = (node.signature ?? 'document').replace(/^document:/, '');\n // Category keywords help ops/config queries land on the right file type.\n const categoryHints: Record<string, string> = {\n manifest: 'package dependencies scripts install dependencies versions',\n docker: 'dockerfile container image build runtime',\n compose: 'docker-compose services containers networking volumes',\n ci: 'continuous integration github actions workflow pipeline test build deploy',\n 'build-config': 'typescript tsconfig bundler vite webpack eslint prettier test',\n 'api-contract': 'openapi swagger graphql protobuf api schema endpoints',\n 'task-runner': 'makefile justfile tasks build test run commands',\n workspace: 'monorepo workspace packages pnpm turbo nx',\n infra: 'deploy infrastructure kubernetes kubernetes terraform helm kubernetes',\n 'env-example': 'environment variables configuration secrets template',\n markdown: 'documentation readme guide',\n };\n const hint = categoryHints[category] ?? category;\n return [\n node.qualifiedName,\n 'document',\n category,\n hint,\n pathContext(node.file),\n (node.doc ?? '').slice(0, 5000),\n ]\n .filter(Boolean)\n .join('\\n');\n }\n return [node.qualifiedName, node.kind, node.signature ?? '', node.doc ?? '', pathContext(node.file), areaLabel ?? '']\n .filter(Boolean)\n .join(' ');\n}\n\nexport function cosine(a: number[], b: number[]): number {\n let dot = 0;\n let na = 0;\n let nb = 0;\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n dot += a[i] * b[i];\n na += a[i] * a[i];\n nb += b[i] * b[i];\n }\n if (na === 0 || nb === 0) return 0;\n return dot / (Math.sqrt(na) * Math.sqrt(nb));\n}\n\ninterface EmbedCache {\n model: string;\n entries: Record<string, { hash: string; vec: number[] }>;\n}\n\n/** Reports embedding progress: how many of `total` nodes are done so far. */\nexport type EmbedProgress = (done: number, total: number) => void;\n\n/** Nodes embedded per chunk — bounds memory and gives progress granularity. */\nconst EMBED_CHUNK = 256;\n/** Min gap between incremental cache writes (ms) — caps IO on big repos. */\nconst CACHE_WRITE_INTERVAL_MS = 1500;\n\n/**\n * Binary embeddings format (local cache next to the map, never committed):\n *\n * MAGIC \"VGEMB1\\0\" · u16 version · u16 modelLen · model utf8 ·\n * u32 dims · u32 count ·\n * for each entry: u16 idLen · id · u16 hashLen · hash ·\n * then contiguous Float32LE vectors [count × dims]\n *\n * Why binary: a medium map (~4k nodes × 384 dims) is ~6 MB of floats but was\n * ~30 MB of JSON with full decimal text — slow to parse and noisy in source\n * control if it ever landed under the repo. The filename is always\n * `embeddings` / `<snapshot>.embeddings`; the model id lives only in the header.\n */\n/** 8-byte little-endian-friendly magic (same width as graph `VGSNAP1\\0`). */\nconst EMB_MAGIC = Buffer.from('VGEMB01\\0', 'latin1');\nconst EMB_VERSION = 1;\n\nfunction vectorCachePath(root: string): string {\n return embeddingsPathFor(resolveGraphPath(root));\n}\n\n/** Pre-binary path: `.vibgrate/cache/embeddings-<model>.json` (read once to migrate). */\nfunction legacyVectorCachePath(root: string, modelId: string): string {\n return path.join(cacheDir(root), `embeddings-${safe(modelId)}.json`);\n}\n\n/**\n * How many searchable nodes still need embedding for `modelId` — cheap (hashes\n * the embed-text, reads only the cache; never loads the model). Lets the embed\n * command / background warm-up exit instantly when nothing changed.\n */\nexport function countPending(graph: VgGraph, root: string, modelId: string): number {\n const entries = loadCache(root, modelId).entries;\n const areaLabel = new Map(graph.areas.map((a) => [a.id, a.label] as const));\n let pending = 0;\n for (const n of graph.nodes) {\n // file/external stay out of the index; document (docs/env examples) are in.\n if (n.kind === 'file' || n.kind === 'external') continue;\n const h = hashString(nodeEmbedText(n, areaLabel.get(n.area)));\n const cached = entries[n.id];\n if (!cached || cached.hash !== h) pending++;\n }\n return pending;\n}\n\nfunction loadCache(root: string, modelId: string): EmbedCache {\n const file = vectorCachePath(root);\n const binary = readBinaryCache(file, modelId);\n if (binary) return binary;\n\n // Migrate legacy JSON if present (once) — keep working after upgrade without\n // re-embedding the whole repo.\n const legacy = legacyVectorCachePath(root, modelId);\n if (fs.existsSync(legacy)) {\n try {\n const loaded = JSON.parse(fs.readFileSync(legacy, 'utf8')) as EmbedCache;\n if (loaded.model === modelId && loaded.entries) {\n return { model: modelId, entries: loaded.entries };\n }\n } catch {\n /* treat as empty */\n }\n }\n return { model: modelId, entries: {} };\n}\n\ninterface EmbedHeader {\n model: string;\n dims: number;\n count: number;\n}\n\n/** Cheap header-only peek (no vectors) for `embeddingsCached` / diagnostics. */\nfunction readCacheHeader(file: string): EmbedHeader | null {\n let fd: number | null = null;\n try {\n fd = fs.openSync(file, 'r');\n const prefix = Buffer.alloc(8 + 2 + 2 + 512); // magic + ver + modelLen + model (capped)\n const n = fs.readSync(fd, prefix, 0, prefix.length, 0);\n if (n < EMB_MAGIC.length + 4 || !prefix.subarray(0, EMB_MAGIC.length).equals(EMB_MAGIC)) return null;\n let o = EMB_MAGIC.length;\n const version = prefix.readUInt16LE(o);\n o += 2;\n if (version !== EMB_VERSION) return null;\n const modelLen = prefix.readUInt16LE(o);\n o += 2;\n if (o + modelLen + 8 > n) {\n // model spills past our prefix — re-read exactly\n const full = Buffer.alloc(EMB_MAGIC.length + 2 + 2 + modelLen + 8);\n fs.readSync(fd, full, 0, full.length, 0);\n return parseHeaderPrefix(full);\n }\n return parseHeaderPrefix(prefix);\n } catch {\n return null;\n } finally {\n if (fd !== null) fs.closeSync(fd);\n }\n}\n\nfunction parseHeaderPrefix(buf: Buffer): EmbedHeader | null {\n try {\n if (!buf.subarray(0, EMB_MAGIC.length).equals(EMB_MAGIC)) return null;\n let o = EMB_MAGIC.length;\n if (buf.readUInt16LE(o) !== EMB_VERSION) return null;\n o += 2;\n const modelLen = buf.readUInt16LE(o);\n o += 2;\n if (o + modelLen + 8 > buf.length) return null;\n const model = buf.subarray(o, o + modelLen).toString('utf8');\n o += modelLen;\n const dims = buf.readUInt32LE(o);\n o += 4;\n const count = buf.readUInt32LE(o);\n return { model, dims, count };\n } catch {\n return null;\n }\n}\n\nfunction readBinaryCache(file: string, modelId: string): EmbedCache | null {\n if (!fs.existsSync(file)) return null;\n try {\n const buf = fs.readFileSync(file);\n if (buf.length < EMB_MAGIC.length + 4 || !buf.subarray(0, EMB_MAGIC.length).equals(EMB_MAGIC)) return null;\n let o = EMB_MAGIC.length;\n if (buf.readUInt16LE(o) !== EMB_VERSION) return null;\n o += 2;\n const modelLen = buf.readUInt16LE(o);\n o += 2;\n const model = buf.subarray(o, o + modelLen).toString('utf8');\n o += modelLen;\n if (model !== modelId) return null;\n const dims = buf.readUInt32LE(o);\n o += 4;\n const count = buf.readUInt32LE(o);\n o += 4;\n if (dims === 0 || count === 0) return { model, entries: {} };\n\n const ids: string[] = [];\n const hashes: string[] = [];\n for (let i = 0; i < count; i++) {\n const idLen = buf.readUInt16LE(o);\n o += 2;\n ids.push(buf.subarray(o, o + idLen).toString('utf8'));\n o += idLen;\n const hashLen = buf.readUInt16LE(o);\n o += 2;\n hashes.push(buf.subarray(o, o + hashLen).toString('utf8'));\n o += hashLen;\n }\n const floatsNeeded = count * dims;\n const bytesNeeded = floatsNeeded * 4;\n if (o + bytesNeeded > buf.length) return null;\n // Copy into a standalone ArrayBuffer so Float32Array views are safe after buf is GC'd.\n const floatBuf = Buffer.from(buf.subarray(o, o + bytesNeeded));\n const floats = new Float32Array(floatBuf.buffer, floatBuf.byteOffset, floatsNeeded);\n\n const entries: EmbedCache['entries'] = {};\n for (let i = 0; i < count; i++) {\n const start = i * dims;\n const vec = Array.from(floats.subarray(start, start + dims));\n entries[ids[i]!] = { hash: hashes[i]!, vec };\n }\n return { model, entries };\n } catch {\n return null;\n }\n}\n\nfunction writeBinaryCache(file: string, cache: EmbedCache): void {\n const ids = Object.keys(cache.entries);\n const count = ids.length;\n let dims = 0;\n for (const id of ids) {\n const d = cache.entries[id]!.vec.length;\n if (d > 0) {\n dims = d;\n break;\n }\n }\n // Empty or all-zero-dim cache: still write a valid header so \"cached\" is true.\n const modelBuf = Buffer.from(cache.model, 'utf8');\n if (modelBuf.length > 0xffff) throw new Error('embed model id too long');\n\n // Index size (ids + hashes)\n let indexBytes = 0;\n const idBufs: Buffer[] = [];\n const hashBufs: Buffer[] = [];\n for (const id of ids) {\n const ib = Buffer.from(id, 'utf8');\n const hb = Buffer.from(cache.entries[id]!.hash, 'utf8');\n if (ib.length > 0xffff || hb.length > 0xffff) throw new Error('embed entry key too long');\n idBufs.push(ib);\n hashBufs.push(hb);\n indexBytes += 2 + ib.length + 2 + hb.length;\n }\n\n const headerBytes = EMB_MAGIC.length + 2 + 2 + modelBuf.length + 4 + 4;\n const vecBytes = count * dims * 4;\n const out = Buffer.allocUnsafe(headerBytes + indexBytes + vecBytes);\n let o = 0;\n EMB_MAGIC.copy(out, o);\n o += EMB_MAGIC.length;\n out.writeUInt16LE(EMB_VERSION, o);\n o += 2;\n out.writeUInt16LE(modelBuf.length, o);\n o += 2;\n modelBuf.copy(out, o);\n o += modelBuf.length;\n out.writeUInt32LE(dims, o);\n o += 4;\n out.writeUInt32LE(count, o);\n o += 4;\n\n for (let i = 0; i < count; i++) {\n const ib = idBufs[i]!;\n const hb = hashBufs[i]!;\n out.writeUInt16LE(ib.length, o);\n o += 2;\n ib.copy(out, o);\n o += ib.length;\n out.writeUInt16LE(hb.length, o);\n o += 2;\n hb.copy(out, o);\n o += hb.length;\n }\n\n if (dims > 0 && count > 0) {\n const floats = new Float32Array(count * dims);\n for (let i = 0; i < count; i++) {\n const vec = cache.entries[ids[i]!]!.vec;\n const base = i * dims;\n for (let d = 0; d < dims; d++) floats[base + d] = vec[d] ?? 0;\n }\n Buffer.from(floats.buffer, floats.byteOffset, floats.byteLength).copy(out, o);\n }\n\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const tmp = `${file}.tmp.${process.pid}`;\n fs.writeFileSync(tmp, out);\n fs.renameSync(tmp, file);\n}\n\n/** Best-effort drop of the old model-named JSON caches under `.vibgrate/cache/`. */\nfunction purgeLegacyJsonCaches(root: string): void {\n const dir = cacheDir(root);\n let names: string[];\n try {\n names = fs.readdirSync(dir);\n } catch {\n return;\n }\n for (const name of names) {\n if (/^embeddings-.+\\.json$/.test(name) || /^embeddings-.+\\.json\\.lock$/.test(name)) {\n try {\n fs.rmSync(path.join(dir, name), { force: true });\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n// Single-writer lock (shared helper — see ./lock.ts) so a foreground `ask`\n// and a background `embed` never both embed the same repo at once (which\n// would race on the cache file).\n\n/**\n * Node embeddings for the searchable (non-file/external) nodes, cache-backed:\n * only nodes whose embed-text changed are re-embedded. The first run embeds in\n * chunks, **persists the cache incrementally** (so an interrupted/timed-out run\n * resumes instead of wasting the work), and reports progress via `onProgress`.\n */\nexport async function getNodeEmbeddings(\n graph: VgGraph,\n embedder: Embedder,\n root: string,\n onProgress?: EmbedProgress,\n): Promise<Map<string, number[]>> {\n const file = vectorCachePath(root);\n const cache = loadCache(root, embedder.id);\n\n const areaLabel = new Map(graph.areas.map((a) => [a.id, a.label] as const));\n // Include document nodes (markdown/txt/env examples) so ask can retrieve docs.\n const targets = graph.nodes.filter((n) => n.kind !== 'file' && n.kind !== 'external');\n const toEmbed: { id: string; text: string; hash: string }[] = [];\n const vectors = new Map<string, number[]>();\n for (const n of targets) {\n const text = nodeEmbedText(n, areaLabel.get(n.area));\n const h = hashString(text);\n const cached = cache.entries[n.id];\n if (cached && cached.hash === h) vectors.set(n.id, cached.vec);\n else toEmbed.push({ id: n.id, text, hash: h });\n }\n\n // Atomic write (temp + rename) so a reader never sees a half-written cache.\n const persist = (): void => {\n try {\n writeBinaryCache(file, cache);\n purgeLegacyJsonCaches(root);\n } catch {\n /* cache write best-effort */\n }\n };\n\n if (toEmbed.length) {\n // Single-writer: if another process (e.g. a background warm-up) is already\n // embedding this repo, don't double-work or race the cache — return what's\n // cached so far (lexical floor still applies). It will be complete next run.\n const lock = `${file}.lock`;\n if (!acquireLock(lock)) return vectors;\n try {\n onProgress?.(0, toEmbed.length);\n let lastWrite = Date.now();\n for (let i = 0; i < toEmbed.length; i += EMBED_CHUNK) {\n const slice = toEmbed.slice(i, i + EMBED_CHUNK);\n const vecs = await embedder.embed(slice.map((t) => t.text));\n slice.forEach((t, j) => {\n const vec = vecs[j] ?? [];\n vectors.set(t.id, vec);\n cache.entries[t.id] = { hash: t.hash, vec };\n });\n onProgress?.(Math.min(i + EMBED_CHUNK, toEmbed.length), toEmbed.length);\n // Persist periodically so a crash/timeout resumes from here next run.\n if (Date.now() - lastWrite >= CACHE_WRITE_INTERVAL_MS) {\n persist();\n lastWrite = Date.now();\n }\n }\n // prune entries for nodes no longer present, then a final authoritative write\n const live = new Set(targets.map((n) => n.id));\n for (const id of Object.keys(cache.entries)) if (!live.has(id)) delete cache.entries[id];\n persist();\n } finally {\n releaseLock(lock);\n }\n } else if (!fs.existsSync(file) && Object.keys(cache.entries).length > 0) {\n // Migrating from legacy JSON with a full hit set — rewrite as binary once\n // so the next run never reads the old path again.\n persist();\n }\n\n return vectors;\n}\n\nfunction safe(id: string): string {\n return id.replace(/[^a-z0-9.-]+/gi, '_');\n}\n"]}
@@ -1,9 +1,9 @@
1
- import { refreshIfStale } from './chunk-6GQLEDVK.js';
2
- import { sanitizeClient, recordSaving, SAVINGS_TOOLS, PER_FILE_TOKENS } from './chunk-CJNWHXQD.js';
3
- import { listedToolNames, budgetSuffix, TOOLS, renderToolResult, warmEmbedderInBackground, countTokens } from './chunk-3WUTQYRY.js';
4
- import { loadGraphPreferIndex } from './chunk-7ZHSSGUF.js';
5
- import { mapFileStat, parseGraph, slimGraphForExport, renderHtml, renderReport, serializeGraph } from './chunk-EWZKOU66.js';
6
- import { VERSION } from './chunk-RT7P5AYU.js';
1
+ import { refreshIfStale } from './chunk-IHLLWBZU.js';
2
+ import { listedToolNames, budgetSuffix, TOOLS, renderToolResult, warmEmbedderInBackground, countTokens } from './chunk-WWGLVF7D.js';
3
+ import { sanitizeClient, recordSaving, SAVINGS_TOOLS, PER_FILE_TOKENS } from './chunk-DSUGC7F5.js';
4
+ import { loadGraphPreferIndex } from './chunk-WQLZSVNF.js';
5
+ import { mapFileStat, parseGraph, slimGraphForExport, renderHtml, renderReport, serializeGraph } from './chunk-75LJM5XD.js';
6
+ import { VERSION } from './chunk-2H2U3DC7.js';
7
7
  import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
@@ -593,5 +593,5 @@ function spdx(ctx) {
593
593
  }
594
594
 
595
595
  export { GraphSource, RefreshScheduler, createServer, exportGraph, formatForExt, isRelevantChange, serveStdio };
596
- //# sourceMappingURL=chunk-IJQOZ6ZD.js.map
597
- //# sourceMappingURL=chunk-IJQOZ6ZD.js.map
596
+ //# sourceMappingURL=chunk-YNV5M3JW.js.map
597
+ //# sourceMappingURL=chunk-YNV5M3JW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/engine/refresh-scheduler.ts","../src/engine/watch-filter.ts","../src/mcp/server.ts","../src/engine/export.ts"],"names":["path2"],"mappings":";;;;;;;;;;;;;AAkCO,IAAM,iBAAA,GAAoB,GAAA;AAE1B,IAAM,qBAAA,GAAwB,GAAA;AAE9B,IAAM,iBAAA,GAAoB,EAAA;AAM1B,IAAM,iBAAA,GAAoB,GAAA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A,SAAA,EAAY,GAAA,CAAI,KAAA,CAAM,UAAA,CAAW,OAAO,EAAE,CAAA,EAAE;AAAA,IACjG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC","file":"chunk-YNV5M3JW.js","sourcesContent":["import { refreshIfStale, type RefreshOutcome } from './refresh.js';\n\n/**\n * Debounced, single-flight, budget-capped auto-refresh.\n *\n * `refreshIfStale` is expensive and **synchronous in its hot half**: the\n * freshness probe walks the whole corpus (`discover` + `discoverDocs`) and\n * `statSync`s every file before anything can drift-check, and a real drift then\n * runs a full incremental `buildGraph`. On a 22k-file repo that is seconds for a\n * clean tree and over a minute for a dirty one.\n *\n * No interactive surface may pay that inline. This scheduler is the shared\n * discipline that keeps it off the request path, and it exists as one module\n * precisely because the previous per-server copies diverged: `vg serve` (MCP)\n * grew the guard while `vg lsp` kept a bare `await refreshIfStale(...)`, which\n * made a single editor Ask block for ~90s on a large workspace.\n *\n * Four properties, all load-bearing:\n * - **Single-flight** — concurrent callers share one refresh, never stack.\n * - **Debounced** — at most one probe per `probeIntervalMs`.\n * - **Self-tuning** — the interval grows with the *measured* cost of the last\n * refresh, so probe/rebuild work stays under ~1/`PROBE_DUTY_FACTOR` of wall\n * time however big the repo is.\n * - **Budget-capped** — a caller waits `refreshBudgetMs` at most, then proceeds\n * with the map it already has. A warm probe lands inside the budget; a\n * rebuild never does, and shouldn't.\n *\n * Answering from a map that is one edit stale is always better than making the\n * user wait: the rebuild lands for the next call.\n */\n\nexport type RefreshImpl = typeof refreshIfStale;\n\n/** Min gap between freshness probes — bounds stat-walk cost under bursty calls. */\nexport const PROBE_INTERVAL_MS = 2000;\n/** Ceiling for the self-tuned probe interval on very large repos. */\nexport const MAX_PROBE_INTERVAL_MS = 30_000;\n/** Probe/rebuild may consume at most ~1/PROBE_DUTY_FACTOR of wall-time (20 → ≤5%). */\nexport const PROBE_DUTY_FACTOR = 20;\n/**\n * How long a caller waits for an in-flight refresh before answering from the\n * current map. Deliberately small: warm lookups are sub-10ms, so a multi-second\n * budget turns every call during a large-repo rebuild into a multi-second stall.\n */\nexport const REFRESH_BUDGET_MS = 100;\n/** After a refresh failure (e.g. read-only checkout), don't retry for this long. */\nexport const FAILURE_COOLDOWN_MS = 60_000;\n\nexport interface RefreshSchedulerOptions {\n /** Workspace root for freshness probes and rebuilds. */\n root: string;\n /**\n * The already-resolved map path, or a getter for it. Passing it through spares\n * `refreshIfStale` a `defaultGraphPath` re-resolution (which consults git).\n */\n graphPath?: string | (() => string | undefined);\n /** Min gap between probes. `0` probes every call (tests). */\n probeIntervalMs?: number;\n /** Max wait before a caller gives up and uses the current map. */\n refreshBudgetMs?: number;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n /** Force single-threaded parsing on a rebuild (constrained hosts / tests). */\n inline?: boolean;\n /**\n * Called when a refresh settles, with the outcome (`null` if it threw) and the\n * ms timestamp the refresh started at. Lets an owner react — invalidate a\n * cached graph, clear a pending-change set — without re-implementing any of\n * the scheduling above.\n */\n onSettled?: (outcome: RefreshOutcome | null, startedAt: number) => void;\n}\n\nexport class RefreshScheduler {\n private lastProbeAt = 0;\n private failedUntil = 0;\n private inflight: Promise<void> | null = null;\n /** Self-tuned: grows with measured probe/rebuild cost so huge repos aren't penalized. */\n private tunedIntervalMs = PROBE_INTERVAL_MS;\n private readonly refreshImpl: RefreshImpl;\n\n constructor(private readonly opts: RefreshSchedulerOptions) {\n this.refreshImpl = opts.refreshImpl ?? refreshIfStale;\n }\n\n /** The interval currently in force — diagnostics and tests. */\n get probeIntervalMs(): number {\n return this.opts.probeIntervalMs ?? this.tunedIntervalMs;\n }\n\n /** Is a refresh running right now? Lets a caller report \"refreshing\" state. */\n get busy(): boolean {\n return this.inflight !== null;\n }\n\n /**\n * Re-arm the next probe regardless of the debounce interval — for a watcher\n * event or an explicit user action, where waiting out the interval would feel\n * broken. Clears the failure cooldown too: a real event is evidence the tree\n * moved, not a poll, and the condition that failed may be exactly what\n * changed. Does not itself start a refresh; the next `maybeRefresh` does.\n */\n arm(): void {\n this.lastProbeAt = 0;\n this.failedUntil = 0;\n }\n\n /**\n * Probe/rebuild if due, and wait at most the budget for it. Never throws —\n * a refresh problem must degrade to \"answer from the current map\", not break\n * the caller.\n */\n async maybeRefresh(): Promise<void> {\n const now = Date.now();\n if (!this.inflight) {\n if (now < this.failedUntil || now - this.lastProbeAt < this.probeIntervalMs) return;\n this.lastProbeAt = now;\n const graphPath =\n typeof this.opts.graphPath === 'function' ? this.opts.graphPath() : this.opts.graphPath;\n this.inflight = this.refreshImpl(this.opts.root, { graphPath, inline: this.opts.inline })\n .then((outcome) => {\n if (outcome.status === 'error') this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n this.tune(outcome, now);\n this.opts.onSettled?.(outcome, now);\n })\n .catch(() => {\n this.failedUntil = Date.now() + FAILURE_COOLDOWN_MS;\n this.tune(null, now);\n this.opts.onSettled?.(null, now);\n })\n .finally(() => {\n this.inflight = null;\n });\n }\n await Promise.race([this.inflight, sleep(this.opts.refreshBudgetMs ?? REFRESH_BUDGET_MS)]);\n }\n\n /**\n * Back off proportionally to what the refresh actually cost — including a\n * multi-second rebuild. Tuning off probe-only outcomes alone would re-arm\n * after the floor and make every sequential call pay the budget again for the\n * whole duration of a large rebuild.\n */\n private tune(outcome: RefreshOutcome | null, startedAt: number): void {\n const elapsed = Date.now() - startedAt;\n const cost =\n outcome?.status === 'refreshed' && typeof outcome.ms === 'number'\n ? Math.max(outcome.ms, elapsed)\n : elapsed;\n this.tunedIntervalMs = Math.min(\n MAX_PROBE_INTERVAL_MS,\n Math.max(PROBE_INTERVAL_MS, cost * PROBE_DUTY_FACTOR),\n );\n }\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, ms);\n timer.unref?.();\n });\n}\n","import * as path from 'node:path';\n\n/**\n * Shared change-event filter for the two file watchers (`vg watch` and the\n * serve-loop watcher in mcp/server.ts): which filesystem events are real\n * source changes, and which are dependency/artifact/VCS noise that must never\n * trigger a rebuild — including vg's own artifacts, or every build would\n * re-trigger itself.\n */\nexport const WATCH_SKIP_NAMES = new Set([\n '.git',\n 'node_modules',\n '.vibgrate',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.next',\n 'target',\n '__pycache__',\n '.venv',\n 'venv',\n]);\n\n/** True when a watch event's filename is a change worth rebuilding for. */\nexport function isRelevantChange(filename: string): boolean {\n if (filename.split(path.sep).some((p) => WATCH_SKIP_NAMES.has(p))) return false;\n if (filename.includes(`${path.sep}.vibgrate${path.sep}`) || filename.startsWith('.vibgrate')) return false;\n return true;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { parseGraph } from '../engine/serialize.js';\nimport { mapFileStat } from '../engine/snapshot.js';\nimport { loadGraphPreferIndex } from '../engine/index-db.js';\nimport type { RefreshOutcome, refreshIfStale } from '../engine/refresh.js';\nimport { RefreshScheduler, REFRESH_BUDGET_MS as SCHEDULER_BUDGET_MS } from '../engine/refresh-scheduler.js';\nimport { TOOLS, budgetSuffix, listedToolNames, warmEmbedderInBackground, type ToolSurface } from './tools.js';\nimport { isRelevantChange } from '../engine/watch-filter.js';\nimport { renderToolResult } from './response.js';\nimport { recordSaving, sanitizeClient, PER_FILE_TOKENS, SAVINGS_TOOLS, type Outcome } from '../engine/savings.js';\nimport type { SessionStats } from './serve-stats.js';\nimport { countTokens } from '../engine/tokens.js';\nimport { VERSION } from '../version.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * The local `vg serve` MCP server. Self-contained and offline. Freshness is\n * two-layered, with no filesystem watcher (freshness only matters at the\n * moment of a query, so we check on read instead of watching):\n *\n * 1. **Hot reload** — `graph.json` is re-read whenever its mtime changes, so a\n * rebuild from ANY source (a foreground `vg`, another serve process, CI)\n * is picked up on the next tool call.\n * 2. **Auto-refresh** (default on) — each tool call runs a debounced, stat-only\n * freshness probe against the last build's snapshot; if the working tree\n * drifted, an incremental rebuild runs in-process (cross-process locked,\n * single-flight). The call waits only a **micro-budget** so a warm probe can\n * land without stalling MCP tools — otherwise it answers from the current\n * map while the rebuild finishes for a later call (hot-reload picks it up).\n *\n * Every tool remains read-only and auto-approvable; the refresh only rewrites\n * vg's own artifacts under `.vibgrate/`, never user code.\n */\n\n/**\n * How long a tool call waits for an in-flight refresh before answering from\n * the current map. Kept deliberately small: MCP tool latency is sub-10ms on\n * warm maps, and a multi-second budget (the previous 5s ceiling matched\n * `git rev-parse`'s spawn timeout) turned every sequential tool call during a\n * large-repo rebuild into a multi-second stall — measured as TypeScript p50\n * ~5.2s on the release benchmark for the `vg-cli-public` corpus entry.\n * Warm probes still finish inside this window; heavy rebuilds never should.\n *\n * Re-exported from the shared scheduler, which owns this and the probe-interval\n * tuning for every surface (`vg serve` and `vg lsp` alike).\n */\nexport const REFRESH_BUDGET_MS = SCHEDULER_BUDGET_MS;\n/** Settle time between a watcher event and the background refresh it triggers. */\nconst WATCH_DEBOUNCE_MS = 400;\n\nexport type RefreshImpl = typeof refreshIfStale;\n\nexport interface GraphSourceTuning {\n probeIntervalMs?: number;\n refreshBudgetMs?: number;\n /**\n * Workspace root for freshness probes. Prefer passing this explicitly —\n * deriving it from `graphPath` via `dirname` twice only works for the legacy\n * `root/.vibgrate/graph.json` layout, not the global branch-keyed store.\n */\n root?: string;\n /** Tests only: inject a slow/fake refresh to assert the micro-budget. */\n refreshImpl?: RefreshImpl;\n}\n\nexport interface ServeOptions {\n /** Record local, counts-only usage savings (opt-in). */\n savings?: boolean;\n /**\n * Periodically upload the counts-only ledger to Vibgrate (opt-in; off by\n * default). Implies recording. The upload itself is driven by the serve\n * command (see commands/serve.ts + engine/stats-share.ts); here it just also\n * turns recording on so there's something to send.\n */\n shareStats?: boolean;\n /** Air-gapped mode (no model downloads). */\n local?: boolean;\n /** Collapse repeat heavy relation lists within a session (opt-in). */\n dedup?: boolean;\n /** Auto-refresh the map when the working tree drifts (default true). */\n refresh?: boolean;\n /**\n * Event-driven refresh: recursive fs.watch on the workspace so a save\n * rebuilds in ~400 ms instead of waiting out the freshness poll (default\n * true when refresh is on; `--no-watch` opts out). Where recursive watch is\n * unavailable the poll silently remains the only mechanism.\n */\n watch?: boolean;\n /**\n * Workspace root (project directory). When set, freshness probes and tools\n * use this instead of inferring root from the graph path.\n */\n root?: string;\n /**\n * In-memory session stats behind the live `vg serve` status display. Always\n * safe to pass: nothing recorded here is persisted or uploaded — it dies with\n * the process (the opt-in ledger above is a separate concern).\n */\n stats?: SessionStats;\n /**\n * Listing surface (`--surface hot` / `--tools a,b`). Filters ONLY what\n * `tools/list` advertises; every tool stays callable so behaviour is\n * byte-identical across surfaces. See `listedToolNames` in ./tools.ts.\n */\n toolSurface?: ToolSurface;\n}\n\nexport class GraphSource {\n private cachedMtimeMs = -1;\n private cached: VgGraph | null = null;\n /** Project root used for freshness probes and rebuilds. */\n readonly root: string;\n /** Debounce, single-flight, self-tuning and budget cap — shared with `vg lsp`. */\n private readonly refresher: RefreshScheduler;\n /**\n * Files seen changing since the last COMMITTED refresh (watcher events,\n * filename → last-seen ms). Entries are cleared only after a refresh that\n * started at-or-after their last event completes with 'fresh'/'refreshed' —\n * a change landing mid-refresh stays pending, so the staleness signal can\n * be a false positive but never a false negative.\n */\n private readonly pendingChanges = new Map<string, number>();\n private watcher: fs.FSWatcher | null = null;\n private watchTimer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n readonly graphPath: string,\n private readonly refresh = false,\n /** Timing / root overrides (production passes `root`; tests may pass more). */\n private readonly tuning: GraphSourceTuning = {},\n ) {\n // Prefer an explicit root. Fallback assumes legacy `root/.vibgrate/graph.json`\n // (dirname twice); wrong for the global store — callers should pass `root`.\n this.root = tuning.root ?? path.dirname(path.dirname(graphPath));\n this.refresher = new RefreshScheduler({\n root: this.root,\n graphPath,\n probeIntervalMs: tuning.probeIntervalMs,\n refreshBudgetMs: tuning.refreshBudgetMs,\n refreshImpl: tuning.refreshImpl,\n onSettled: (outcome, startedAt) => this.onRefreshSettled(outcome, startedAt),\n });\n }\n\n /** Current graph: auto-refreshed if the tree drifted, reloaded if the file changed. */\n async get(): Promise<VgGraph> {\n if (this.refresh) await this.maybeRefresh();\n // JSON when present, else the standalone snapshot (global-store mode);\n // throws if neither exists → surfaced as tool error.\n const stat = mapFileStat(this.graphPath);\n if (stat.mtimeMs !== this.cachedMtimeMs || !this.cached) {\n // Prefer SQLite reconstruct when corpusHash matches (scale past JSON parse).\n const preferred = loadGraphPreferIndex(this.root, this.graphPath);\n this.cached = preferred\n ? preferred.graph\n : parseGraph(fs.readFileSync(this.graphPath, 'utf8'));\n this.cachedMtimeMs = stat.mtimeMs;\n }\n return this.cached;\n }\n\n /**\n * Debounced, single-flight refresh — the shared scheduler does the work (see\n * engine/refresh-scheduler.ts). Never throws: a refresh problem must degrade\n * to \"answer from the current map\", not break the tool call.\n */\n private maybeRefresh(): Promise<void> {\n return this.refresher.maybeRefresh();\n }\n\n /**\n * A COMMITTED outcome (map verified fresh, or rebuilt) clears the pending\n * set — but only entries whose last event predates the refresh start.\n * 'locked'/'error'/'no-snapshot' clear nothing: the map may still be behind\n * those changes.\n */\n private onRefreshSettled(outcome: RefreshOutcome | null, startedAt: number): void {\n if (outcome?.status !== 'fresh' && outcome?.status !== 'refreshed') return;\n for (const [file, seenAt] of this.pendingChanges) {\n if (seenAt <= startedAt) this.pendingChanges.delete(file);\n }\n }\n\n /**\n * Record a source change (watcher event, or a test). Arms the next probe to\n * run immediately (bypassing the self-tuned interval — a real event is not a\n * poll) and schedules a debounced background refresh so the rebuild happens\n * BETWEEN tool calls instead of on the next call's 100 ms budget.\n */\n notePendingChange(filename: string): void {\n this.pendingChanges.set(filename, Date.now());\n this.refresher.arm();\n if (!this.refresh) return;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = setTimeout(() => {\n this.watchTimer = null;\n void this.maybeRefresh();\n }, WATCH_DEBOUNCE_MS);\n this.watchTimer.unref?.();\n }\n\n /**\n * Event-driven freshness (the serve-loop watcher): a recursive `fs.watch`\n * on the workspace feeds `notePendingChange`, so a save triggers a rebuild\n * in ~WATCH_DEBOUNCE_MS instead of waiting out the 2–30 s poll. The poll\n * stays armed as the fallback — on filesystems where recursive watch fails\n * (some containers/NFS) this returns false and behaviour is unchanged.\n */\n startWatching(): boolean {\n if (this.watcher) return true;\n try {\n this.watcher = fs.watch(this.root, { recursive: true }, (_event, filename) => {\n if (!filename) return;\n if (!isRelevantChange(filename)) return;\n this.notePendingChange(filename);\n });\n this.watcher.unref?.();\n return true;\n } catch {\n this.watcher = null;\n return false;\n }\n }\n\n stopWatching(): void {\n this.watcher?.close();\n this.watcher = null;\n if (this.watchTimer) clearTimeout(this.watchTimer);\n this.watchTimer = null;\n }\n\n /**\n * In-band staleness signal for tool responses: what has changed since the\n * last committed refresh. Null when the map is current (the common case —\n * responses carry zero overhead then).\n */\n stalenessNote(): string | null {\n const n = this.pendingChanges.size;\n if (n === 0) return null;\n const names = [...this.pendingChanges.keys()].sort().slice(0, 3);\n const more = n > names.length ? `, +${n - names.length} more` : '';\n return `map freshness: ${n} file(s) changed since the last rebuild (${names.join(', ')}${more}) — auto-refresh pending; symbol locations may have shifted`;\n }\n}\n\nexport function createServer(source: GraphSource, opts: ServeOptions = {}): Server {\n const { savings = false, shareStats = false, local = false, dedup = false, stats } = opts;\n // Recording feeds both the local `vg savings` report and the opt-in upload, so\n // enabling either turns it on. Absent both, `vg serve` records nothing.\n const record = savings || shareStats;\n // Prefer GraphSource's explicit root (set by serve from the project cwd).\n const root = opts.root ?? source.root;\n // Per-session memory of node ids whose full detail was already returned — the\n // basis for opt-in cross-call dedup (`--dedup`). Scoped to this server\n // instance so it never leaks across sessions. Node ids are content-addressed\n // (blake3 of content), so an edited node gets a new id and is never falsely\n // treated as already-seen — dedup is stale-safe by construction.\n const seen = new Set<string>();\n const server = new Server(\n { name: 'vg', version: VERSION },\n {\n capabilities: { tools: {} },\n // Routing guidance once at the server level (hosts that surface\n // `instructions` get it at zero per-step schema cost): the flashlight\n // vs the map.\n instructions:\n 'vg is a code map. Use search_symbols to find a known name or literal string fast — ' +\n 'a multi-word/quoted phrase runs a complete literal sweep and reports totalTextMatches, ' +\n 'so reach for it instead of grep even for plain-string \"find every occurrence\" lookups. ' +\n 'Use orient/query_graph for meaning: symptoms, relationships, and what-breaks-if. ' +\n 'Responses are concise by default; pass response_format:\"detailed\" only when a node proves load-bearing. ' +\n // Stop-discipline: the failure mode on a focused task is over-navigation\n // — one more query, one more get_node — which re-bills the whole context\n // every step. One good navigation call usually locates the code.\n 'Navigate as little as possible: one good search/query usually locates the code. ' +\n 'As soon as you have the file and line, read that file and make the edit — ' +\n 'do not call further graph tools unless the edit fails or the match was wrong. ' +\n // Library docs: position against web search (version-correct beats\n // SEO results), and give a stopping rule so a thin doc doesn't turn\n // into an open-ended search loop.\n 'For how-do-I-use-this-library questions call resolve_library once, then library_docs ' +\n 'with the returned targetId and a focused query: the docs are official and matched to ' +\n 'the version THIS project has installed (drift-annotated) — prefer them over web search ' +\n 'or training-data recall when they conflict. Skip them for language built-ins or APIs ' +\n 'already shown in context. If two library_docs calls have not surfaced the section you ' +\n 'need, read the package source under node_modules instead of searching again.',\n },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const listed = new Set(listedToolNames(opts.toolSurface));\n // Repo-size call budget on orient's listed description: the stop-discipline\n // where the model decides, priced once per list, not per step. Best-effort —\n // when no map is loadable yet the description ships without the line.\n let budget = '';\n try {\n const graph = await source.get();\n budget = budgetSuffix(new Set(graph.nodes.map((n) => n.file)).size);\n } catch {\n /* no map yet — plain description */\n }\n return {\n tools: TOOLS.filter((t) => listed.has(t.name)).map((t) => ({\n name: t.name,\n description: t.name === 'orient' && budget ? `${t.description}${budget}` : t.description,\n inputSchema: t.inputSchema,\n annotations: { readOnlyHint: true, openWorldHint: false },\n })),\n };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const tool = TOOLS.find((t) => t.name === request.params.name);\n if (!tool) {\n return errorResult(`unknown tool \"${request.params.name}\"`);\n }\n let graph: VgGraph;\n try {\n graph = await source.get();\n } catch {\n return errorResult(\n 'no code map found. Run `vg` in the project to build .vibgrate/graph.json, then retry.',\n );\n }\n const startedAt = Date.now();\n try {\n const args = (request.params.arguments ?? {}) as Record<string, unknown>;\n const result = await tool.handler(graph, args, { root, local, dedup, seen, graphPath: source.graphPath });\n const ms = Date.now() - startedAt;\n // Live, in-memory session stats for the serve status display — always on\n // when a serve process passed them (nothing leaves the process).\n stats?.record({ ...measureCall(tool.name, result), client: sanitizeClient(detectClient(server)), ms });\n // Opt-in, counts-only usage ledger: one entry per navigation call, with its\n // outcome, the grep-baseline token counts, and — so `vg savings` can show\n // the command-vs-MCP split and which AI is calling — the source (`mcp`) and\n // the client detected from the initialize handshake.\n if (record) recordUsage(root, tool.name, result, detectClient(server), ms);\n // Compact → clamp to the token ceiling → compact-serialise. See ./response.ts.\n const rendered = renderToolResult(result);\n // In-band staleness (serve-loop watcher): when the working tree has\n // drifted past the served map, say so ON the response — the agent is the\n // one acting on possibly-moved symbols, and stderr never reaches it.\n // Zero overhead when the map is current (the overwhelmingly common case).\n const staleness = source.stalenessNote();\n if (staleness) rendered.content = [...(rendered.content ?? []), { type: 'text', text: `[${staleness}]` }];\n return rendered;\n } catch (err) {\n // A failed call still counts in the live display — as a miss, so the\n // operator sees trouble instead of a silently frozen dashboard.\n stats?.record({\n tool: tool.name,\n client: sanitizeClient(detectClient(server)),\n outcome: 'miss',\n ms: Date.now() - startedAt,\n vgTokens: 0,\n baselineTokens: 0,\n });\n return errorResult(`tool \"${tool.name}\" failed: ${(err as Error).message}`);\n }\n });\n\n return server;\n}\n\nexport async function serveStdio(graphPath: string, opts: ServeOptions = {}): Promise<void> {\n const source = new GraphSource(graphPath, opts.refresh !== false, { root: opts.root });\n if (opts.refresh !== false && opts.watch !== false) source.startWatching();\n const server = createServer(source, opts);\n // Start the semantic-model warm-up as soon as the server boots, so the first\n // orient/query_graph doesn't pay a cold download. Non-blocking: navigation\n // answers lexically until the model is ready, then upgrades to semantic.\n warmEmbedderInBackground(opts.local);\n await server.connect(new StdioServerTransport());\n}\n\n\n/**\n * Append a counts-only usage entry for a navigation call: which tool, how it\n * resolved (complete/partial/miss), and — for the grep-baseline tools — the\n * tokens vg spent vs the grep/read baseline it replaced.\n *\n * `vgTokens` is the size of the payload vg ACTUALLY returned — the rendered text\n * block the model receives and re-pays on every subsequent turn — measured with\n * the same token counter the budget uses. It is deliberately NOT read from a\n * `tokensEstimate` field: only query_graph's rarely-used *detailed* mode ever\n * set that (get_node never did), so the old code recorded nothing under normal\n * concise usage and `vg savings` always reported \"recording is off\".\n */\nexport function recordUsage(root: string, tool: string, result: unknown, client?: string, ms?: number): void {\n recordSaving(\n root,\n { ...measureCall(tool, result), source: 'mcp', client: sanitizeClient(client), ...(ms !== undefined ? { ms } : {}) },\n Date.now(),\n );\n}\n\n/**\n * Measure one tool call for the ledger and the live session stats: its outcome\n * plus — for the grep-baseline tools only — the context tokens vg returned and\n * the baseline they replaced (other tools report zeros, meaning \"no baseline\").\n */\nfunction measureCall(tool: string, result: unknown): { tool: string; outcome: Outcome; vgTokens: number; baselineTokens: number } {\n const outcome = classifyOutcome(result);\n let vgTokens = 0;\n let baselineTokens = 0;\n if (SAVINGS_TOOLS.has(tool) && result && typeof result === 'object') {\n vgTokens = countTokens(renderedText(renderToolResult(result)));\n // Grep/read baseline: ~PER_FILE_TOKENS per distinct file the answer points\n // at — the files a grep/read agent would have had to open to learn the same\n // thing. query_graph surfaces them as `matches[].file`; get_node as its own\n // `file` plus the files of the callers/callees it returned in one call.\n baselineTokens = referencedFiles(result).size * PER_FILE_TOKENS;\n }\n return { tool, outcome, vgTokens, baselineTokens };\n}\n\n/**\n * The coarse client label from the MCP `initialize` handshake, if the host sent\n * `clientInfo`. Read defensively — `getClientVersion()` exists on the SDK Server\n * once initialized, but we never want telemetry bookkeeping to throw. Returns\n * undefined when unknown (then sanitized to `'unknown'`).\n */\nfunction detectClient(server: Server): string | undefined {\n try {\n const info = (server as { getClientVersion?: () => { name?: string } | undefined }).getClientVersion?.();\n return typeof info?.name === 'string' ? info.name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Bucket a tool result into complete / partial / miss. A `miss` is an answer\n * that found nothing (no match, not-found, not-connected, or an empty listing);\n * a `partial` found results but capped or paginated some of them; everything\n * else is `complete`. Note that a legitimately empty `affected`/`covers` (e.g.\n * \"nothing depends on this\") is a successful answer, not a miss — only the\n * primary discovery signals below mark a miss.\n */\nfunction classifyOutcome(result: unknown): Outcome {\n if (Array.isArray(result)) return result.length === 0 ? 'miss' : 'complete';\n if (!result || typeof result !== 'object') return 'miss';\n const r = result as Record<string, unknown>;\n if (typeof r.error === 'string' && r.error) return 'miss'; // not_found / ambiguous / unresolved\n if (r.connected === false) return 'miss'; // find_path\n if (Array.isArray(r.matches) && r.matches.length === 0) return 'miss'; // query_graph / search_symbols\n return isPartial(r) ? 'partial' : 'complete';\n}\n\n/** True when a hit left results on the table: paginated, or a capped relation list. */\nfunction isPartial(r: Record<string, unknown>): boolean {\n if (r.moreAvailable === true) return true;\n if (r._truncated && typeof r._truncated === 'object') return true;\n // A `<name>Total` greater than the length of its sibling `<name>` array means\n // the array was capped (e.g. get_node's callsTotal vs the shown calls).\n for (const [key, value] of Object.entries(r)) {\n if (typeof value !== 'number' || !key.endsWith('Total')) continue;\n const base = key.slice(0, -'Total'.length);\n const shown = Array.isArray(r[base]) ? (r[base] as unknown[]).length : 0;\n if (value > shown) return true;\n }\n return false;\n}\n\n/** The text block of a rendered tool result — what the model is billed for. */\nfunction renderedText(rendered: CallToolResult): string {\n const block = rendered.content?.find((b) => b.type === 'text');\n return block && 'text' in block && typeof block.text === 'string' ? block.text : '';\n}\n\n/** Distinct files a navigation result points at (its grep/read baseline set). */\nfunction referencedFiles(result: unknown): Set<string> {\n const r = result as { file?: unknown; matches?: unknown; calls?: unknown; calledBy?: unknown };\n const files = new Set<string>();\n if (typeof r.file === 'string' && r.file) files.add(r.file);\n for (const m of asArray(r.matches)) {\n const f = (m as { file?: unknown }).file;\n if (typeof f === 'string' && f) files.add(f);\n }\n // get_node's calls/calledBy are qualified names of the form `path:symbol`; the\n // path prefix is the file a grep/read agent would open to inspect that edge.\n for (const name of [...asArray(r.calls), ...asArray(r.calledBy)]) {\n if (typeof name !== 'string') continue;\n const i = name.indexOf(':');\n if (i > 0) files.add(name.slice(0, i));\n }\n return files;\n}\n\nfunction asArray(v: unknown): unknown[] {\n return Array.isArray(v) ? v : [];\n}\n\nfunction errorResult(message: string) {\n return { content: [{ type: 'text', text: message }], isError: true };\n}\n","import { serializeGraph, slimGraphForExport } from './serialize.js';\nimport { renderReport } from './report.js';\nimport { renderHtml } from './html.js';\nimport type { DepRecord } from './drift.js';\nimport type { LocalModel } from './models.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Above this node count, JSON export defaults to compact (no pretty-print). */\nexport const COMPACT_JSON_NODES = 5_000;\n\n/**\n * Deterministic exporters (VG-CLI-SPEC §4.2). One `vg export <file>` verb, format\n * inferred from the extension. Live graph-DB push is deliberately out (a file\n * import covers the same need offline). CycloneDX/SPDX power the SBOM/AI-BOM seam\n * (VG-LOCAL-MODELS §9.4).\n */\n\nexport type ExportFormat =\n | 'json'\n | 'ndjson'\n | 'graphml'\n | 'dot'\n | 'cypher'\n | 'sql'\n | 'md'\n | 'html'\n | 'cyclonedx'\n | 'spdx';\n\nexport function formatForExt(ext: string): ExportFormat | null {\n switch (ext.toLowerCase()) {\n case '.json':\n return 'json';\n case '.ndjson':\n return 'ndjson';\n case '.graphml':\n return 'graphml';\n case '.dot':\n case '.gv':\n return 'dot';\n case '.cypher':\n return 'cypher';\n case '.sql':\n return 'sql';\n case '.md':\n return 'md';\n case '.html':\n return 'html';\n default:\n return null;\n }\n}\n\nexport interface ExportContext {\n graph: VgGraph;\n deps?: DepRecord[];\n models?: LocalModel[];\n generatedAt: string;\n /** Force compact JSON (no indent). Default: auto when nodes > COMPACT_JSON_NODES. */\n compact?: boolean;\n /** Drop area members + grounding for smaller artifacts. */\n slim?: boolean;\n}\n\nexport function exportGraph(format: ExportFormat, ctx: ExportContext): string {\n const graph = ctx.slim ? slimGraphForExport(ctx.graph) : ctx.graph;\n const compact =\n ctx.compact === true ||\n (ctx.compact !== false && format === 'json' && graph.meta.counts.nodes > COMPACT_JSON_NODES);\n\n switch (format) {\n case 'json':\n return serializeGraph(graph, { compact });\n case 'md':\n return renderReport(graph);\n case 'html':\n return renderHtml(graph);\n case 'ndjson':\n return ndjson(graph);\n case 'graphml':\n return graphml(graph);\n case 'dot':\n return dot(graph);\n case 'cypher':\n return cypher(graph);\n case 'sql':\n return sql({ ...ctx, graph });\n case 'cyclonedx':\n return cyclonedx({ ...ctx, graph });\n case 'spdx':\n return spdx({ ...ctx, graph });\n }\n}\n\nfunction ndjson(graph: VgGraph): string {\n // Facts stream if present, else the node stream — one JSON object per line.\n const rows = graph.facts && graph.facts.length ? graph.facts : graph.nodes;\n return rows.map((r) => JSON.stringify(r)).join('\\n') + '\\n';\n}\n\nfunction esc(s: string): string {\n return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;');\n}\n\nfunction graphml(graph: VgGraph): string {\n const lines: string[] = [];\n lines.push('<?xml version=\"1.0\" encoding=\"UTF-8\"?>');\n lines.push('<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\">');\n lines.push(' <key id=\"name\" for=\"node\" attr.name=\"name\" attr.type=\"string\"/>');\n lines.push(' <key id=\"kind\" for=\"node\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <key id=\"file\" for=\"node\" attr.name=\"file\" attr.type=\"string\"/>');\n lines.push(' <key id=\"ekind\" for=\"edge\" attr.name=\"kind\" attr.type=\"string\"/>');\n lines.push(' <graph edgedefault=\"directed\">');\n for (const n of graph.nodes) {\n lines.push(` <node id=\"${esc(n.id)}\"><data key=\"name\">${esc(n.qualifiedName)}</data><data key=\"kind\">${esc(n.kind)}</data><data key=\"file\">${esc(n.file)}</data></node>`);\n }\n for (const e of graph.edges) {\n lines.push(` <edge source=\"${esc(e.src)}\" target=\"${esc(e.dst)}\"><data key=\"ekind\">${esc(e.kind)}</data></edge>`);\n }\n lines.push(' </graph>');\n lines.push('</graphml>');\n return lines.join('\\n') + '\\n';\n}\n\nfunction dot(graph: VgGraph): string {\n const lines: string[] = ['digraph vg {'];\n for (const n of graph.nodes) lines.push(` \"${n.id}\" [label=\"${dotEsc(n.qualifiedName)}\"];`);\n for (const e of graph.edges) lines.push(` \"${e.src}\" -> \"${e.dst}\" [label=\"${e.kind}\"];`);\n lines.push('}');\n return lines.join('\\n') + '\\n';\n}\nfunction dotEsc(s: string): string {\n return s.replace(/\"/g, '\\\\\"');\n}\n\nfunction cypher(graph: VgGraph): string {\n const lines: string[] = [];\n for (const n of graph.nodes) {\n lines.push(\n `CREATE (:\\`${cypherLabel(n.kind)}\\` {id:${q(n.id)}, name:${q(n.qualifiedName)}, file:${q(n.file)}});`,\n );\n }\n for (const e of graph.edges) {\n lines.push(\n `MATCH (a {id:${q(e.src)}}),(b {id:${q(e.dst)}}) CREATE (a)-[:\\`${cypherLabel(e.kind)}\\`]->(b);`,\n );\n }\n return lines.join('\\n') + '\\n';\n}\nfunction cypherLabel(s: string): string {\n return s.replace(/[^A-Za-z0-9_]/g, '_');\n}\nfunction q(s: string): string {\n return JSON.stringify(s);\n}\n\n/**\n * Portable SQL fact-DB (VG-CLI-SPEC §4.2, agent-consumption). Emits deterministic\n * DDL + INSERT text — NOT a native driver — that loads identically into BOTH\n * sqlite3 and duckdb (`sqlite3 map.db < map.sql` / `duckdb map.db < map.sql`).\n * Text keeps the CLI dependency-free, offline, and byte-diffable; an identical\n * graph yields identical bytes. An agent can then run e.g.\n * SELECT src, dst FROM edges WHERE epistemic = 'observed' AND confidence >= 0.9;\n * Determinism: single transaction, `CREATE TABLE IF NOT EXISTS`, rows emitted in\n * the graph's own (already-sorted) array order, single quotes doubled, NULL for\n * absent optionals, booleans as 0/1, and no timestamp but the graph's generatedAt.\n */\nfunction sql(ctx: ExportContext): string {\n const graph = ctx.graph;\n const lines: string[] = [];\n lines.push('BEGIN;');\n\n // meta — provenance / toolchain fingerprint (key/value; agent can read the corpus hash).\n lines.push('CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT);');\n const meta: [string, string | null][] = [\n ['schemaVersion', graph.schemaVersion],\n ['generatedAt', ctx.generatedAt],\n ['corpusHash', graph.provenance.corpusHash],\n ['tool', graph.provenance.tool],\n ['toolVersion', graph.provenance.version],\n ['resolver', graph.provenance.resolver.join(',')],\n ['fingerprint', graph.provenance.toolchain?.fingerprint ?? null],\n ];\n for (const [k, v] of meta) lines.push(`INSERT INTO meta VALUES (${sqlStr(k)}, ${sqlStr(v)});`);\n\n // nodes\n lines.push(\n 'CREATE TABLE IF NOT EXISTS nodes (id TEXT PRIMARY KEY, kind TEXT, name TEXT, qualified_name TEXT, file TEXT, span_start INTEGER, span_end INTEGER, lang TEXT, visibility TEXT, signature TEXT, importance REAL, area INTEGER, is_hub INTEGER, tested INTEGER, coverage REAL);',\n );\n for (const n of graph.nodes) {\n lines.push(\n `INSERT INTO nodes VALUES (${sqlStr(n.id)}, ${sqlStr(n.kind)}, ${sqlStr(n.name)}, ${sqlStr(n.qualifiedName)}, ${sqlStr(n.file)}, ${sqlNum(n.span.start)}, ${sqlNum(n.span.end)}, ${sqlStr(n.lang)}, ${sqlStr(n.visibility)}, ${sqlStr(n.signature)}, ${sqlNum(n.importance)}, ${sqlNum(n.area)}, ${sqlBool(n.isHub)}, ${sqlBool(n.tested)}, ${sqlNum(n.coverage)});`,\n );\n }\n\n // edges — the epistemic column is the point: SELECT ... WHERE epistemic='observed'.\n lines.push(\n 'CREATE TABLE IF NOT EXISTS edges (id TEXT PRIMARY KEY, kind TEXT, src TEXT, dst TEXT, resolution TEXT, confidence REAL, epistemic TEXT, surprise REAL, \"count\" INTEGER);',\n );\n for (const e of graph.edges) {\n lines.push(\n `INSERT INTO edges VALUES (${sqlStr(e.id)}, ${sqlStr(e.kind)}, ${sqlStr(e.src)}, ${sqlStr(e.dst)}, ${sqlStr(e.resolution)}, ${sqlNum(e.confidence)}, ${sqlStr(e.epistemic)}, ${sqlNum(e.surprise)}, ${sqlNum(e.count)});`,\n );\n }\n\n // areas (+ members)\n lines.push('CREATE TABLE IF NOT EXISTS areas (id INTEGER PRIMARY KEY, label TEXT, size INTEGER, cohesion REAL, external_edges INTEGER);');\n lines.push('CREATE TABLE IF NOT EXISTS area_members (area_id INTEGER, node_id TEXT);');\n for (const a of graph.areas) {\n lines.push(`INSERT INTO areas VALUES (${sqlNum(a.id)}, ${sqlStr(a.label)}, ${sqlNum(a.size)}, ${sqlNum(a.cohesion)}, ${sqlNum(a.externalEdges)});`);\n for (const m of a.members) lines.push(`INSERT INTO area_members VALUES (${sqlNum(a.id)}, ${sqlStr(m)});`);\n }\n\n // facts (+ subjects, evidence) when the graph carried them.\n if (graph.facts && graph.facts.length) {\n lines.push('CREATE TABLE IF NOT EXISTS facts (id TEXT PRIMARY KEY, kind TEXT, predicate_json TEXT, derived_by TEXT, confidence TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_subjects (fact_id TEXT, node_id TEXT);');\n lines.push('CREATE TABLE IF NOT EXISTS fact_evidence (fact_id TEXT, file TEXT, span_start INTEGER, span_end INTEGER);');\n for (const f of graph.facts) {\n lines.push(`INSERT INTO facts VALUES (${sqlStr(f.id)}, ${sqlStr(f.kind)}, ${sqlStr(JSON.stringify(f.predicate))}, ${sqlStr(f.derivedBy)}, ${sqlStr(f.confidence)});`);\n for (const s of f.subjectIds) lines.push(`INSERT INTO fact_subjects VALUES (${sqlStr(f.id)}, ${sqlStr(s)});`);\n for (const ev of f.evidence) lines.push(`INSERT INTO fact_evidence VALUES (${sqlStr(f.id)}, ${sqlStr(ev.file)}, ${sqlNum(ev.span.start)}, ${sqlNum(ev.span.end)});`);\n }\n }\n\n lines.push('COMMIT;');\n return lines.join('\\n') + '\\n';\n}\n\n/** SQL string literal (single quotes doubled) or NULL for absent values. */\nfunction sqlStr(v: string | null | undefined): string {\n if (v == null) return 'NULL';\n return `'${v.replace(/'/g, \"''\")}'`;\n}\n/** Numeric literal or NULL for absent values. */\nfunction sqlNum(v: number | null | undefined): string {\n return v == null || !Number.isFinite(v) ? 'NULL' : String(v);\n}\n/** Boolean as 0/1, NULL when unknown (e.g. an unanalyzable node's `tested`). */\nfunction sqlBool(v: boolean | null | undefined): string {\n return v == null ? 'NULL' : v ? '1' : '0';\n}\n\nfunction cyclonedx(ctx: ExportContext): string {\n // CycloneDX 1.6 JSON — dependencies as library components + local models as\n // machine-learning-model components (AI-BOM). Deterministic ordering; no\n // timestamps beyond the pinned generatedAt.\n const components: unknown[] = [];\n for (const d of ctx.deps ?? []) {\n components.push({\n type: 'library',\n name: d.name,\n version: d.installed ?? d.declared,\n purl: d.ecosystem === 'npm' ? `pkg:npm/${d.name}@${d.installed ?? ''}` : undefined,\n });\n }\n for (const m of ctx.models ?? []) {\n components.push({ type: 'machine-learning-model', name: m.name, properties: [{ name: 'vg:runtime', value: m.runtime }] });\n }\n const bom = {\n bomFormat: 'CycloneDX',\n specVersion: '1.6',\n metadata: { timestamp: ctx.generatedAt, tools: [{ name: 'vg', version: ctx.graph.provenance.version }] },\n components,\n };\n return JSON.stringify(bom, null, 2) + '\\n';\n}\n\nfunction spdx(ctx: ExportContext): string {\n const packages = (ctx.deps ?? []).map((d) => ({\n SPDXID: `SPDXRef-Package-${cypherLabel(d.name)}`,\n name: d.name,\n versionInfo: d.installed ?? d.declared,\n downloadLocation: 'NOASSERTION',\n }));\n const doc = {\n spdxVersion: 'SPDX-2.3',\n dataLicense: 'CC0-1.0',\n SPDXID: 'SPDXRef-DOCUMENT',\n name: 'vg-sbom',\n creationInfo: { created: ctx.generatedAt, creators: [`Tool: vg-${ctx.graph.provenance.version}`] },\n packages,\n };\n return JSON.stringify(doc, null, 2) + '\\n';\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-ADP6ITGF.js';
2
- import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-CJNWHXQD.js';
3
- import { userAskFromInstruction } from './chunk-YJU7S7N6.js';
4
- import { analyzeQuestion, loadTopicTags } from './chunk-EWZKOU66.js';
1
+ import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-N3XFY3PX.js';
2
+ import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-DSUGC7F5.js';
3
+ import { userAskFromInstruction } from './chunk-KGPX4EUN.js';
4
+ import { analyzeQuestion, loadTopicTags } from './chunk-75LJM5XD.js';
5
5
  import { repositoryIdFromRoot } from './chunk-BWPBB45M.js';
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
@@ -259,5 +259,5 @@ function shortId() {
259
259
  }
260
260
 
261
261
  export { commitChanges, nodeCodeFs, runCodeSession, undoChanges };
262
- //# sourceMappingURL=chunk-Z3AYOZ3C.js.map
263
- //# sourceMappingURL=chunk-Z3AYOZ3C.js.map
262
+ //# sourceMappingURL=chunk-YQNTIBKS.js.map
263
+ //# sourceMappingURL=chunk-YQNTIBKS.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;;;;AAsFA,eAAsB,eAAe,OAAA,EAAwD;AAC3F,EAAA,MAAM;AAAA,IACJ,KAA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,SAAS,OAAA,GAAkB;AACzB,EAAA,IAAI,CAAA,GAAI,EAAA;AACR,EAAA,MAAM,QAAA,GAAW,sCAAA;AACjB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,KAAK,CAAA,IAAK,QAAA,CAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-Z3AYOZ3C.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { analyzeQuestion, type RelevanceAnalysis } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // Optional relevance provider: widens capsule seed vocabulary when\n // installed; null (the default) changes nothing.\n const relevance = await analyzeQuestion(userAskFromInstruction(instruction));\n const topicTags = relevance ? await loadTopicTags(graph, root) : null;\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n relevance,\n topicTags,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; relevance?: RelevanceAnalysis | null; topicTags?: Map<string, readonly string[]> | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, relevance: opts.relevance, topicTags: opts.topicTags });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n relevance: opts.relevance,\n topicTags: opts.topicTags,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}
1
+ {"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;;;;AAsFA,eAAsB,eAAe,OAAA,EAAwD;AAC3F,EAAA,MAAM;AAAA,IACJ,KAAA;AAAA,IACA,IAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,KAAA,GAAQ,KAAA;AAAA,IACR,OAAA,GAAU,KAAA;AAAA,IACV,KAAA;AAAA,IACA,MAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAM,MAAM,CAAA;AAAA,IACZ,UA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,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-YQNTIBKS.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { analyzeQuestion, type RelevanceAnalysis } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // Optional relevance provider: widens capsule seed vocabulary when\n // installed; null (the default) changes nothing.\n const relevance = await analyzeQuestion(userAskFromInstruction(instruction));\n const topicTags = relevance ? await loadTopicTags(graph, root) : null;\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n relevance,\n topicTags,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; relevance?: RelevanceAnalysis | null; topicTags?: Map<string, readonly string[]> | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, relevance: opts.relevance, topicTags: opts.topicTags });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n relevance: opts.relevance,\n topicTags: opts.topicTags,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}