@vibgrate/cli 2026.825.1 → 2026.825.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 (92) hide show
  1. package/dist/{agent-IHNUBFBM.js → agent-DHQYEHVW.js} +13 -13
  2. package/dist/{agent-IHNUBFBM.js.map → agent-DHQYEHVW.js.map} +1 -1
  3. package/dist/{approvals-HRIMDIX3.js → approvals-KBM72NU2.js} +5 -5
  4. package/dist/{approvals-HRIMDIX3.js.map → approvals-KBM72NU2.js.map} +1 -1
  5. package/dist/{attach-L43JUJ7A.js → attach-O74NL4M5.js} +3 -3
  6. package/dist/{attach-L43JUJ7A.js.map → attach-O74NL4M5.js.map} +1 -1
  7. package/dist/{baseline-EZQ7SCRT.js → baseline-4X6MQBDA.js} +3 -3
  8. package/dist/{baseline-EZQ7SCRT.js.map → baseline-4X6MQBDA.js.map} +1 -1
  9. package/dist/{chunk-X34HVFZ6.js → chunk-27TS2AUJ.js} +8 -8
  10. package/dist/{chunk-X34HVFZ6.js.map → chunk-27TS2AUJ.js.map} +1 -1
  11. package/dist/{chunk-RHYRMMN3.js → chunk-2NUS5BOR.js} +3 -3
  12. package/dist/{chunk-RHYRMMN3.js.map → chunk-2NUS5BOR.js.map} +1 -1
  13. package/dist/{chunk-TLYNLQL2.js → chunk-3E7QT4NE.js} +9 -9
  14. package/dist/{chunk-TLYNLQL2.js.map → chunk-3E7QT4NE.js.map} +1 -1
  15. package/dist/{chunk-L3YEEJ6U.js → chunk-6MIJLO5B.js} +3 -3
  16. package/dist/{chunk-L3YEEJ6U.js.map → chunk-6MIJLO5B.js.map} +1 -1
  17. package/dist/{chunk-5BFA532E.js → chunk-7M4E7UGX.js} +3 -3
  18. package/dist/{chunk-5BFA532E.js.map → chunk-7M4E7UGX.js.map} +1 -1
  19. package/dist/{chunk-M7O6IVKN.js → chunk-BICZR6UJ.js} +3 -3
  20. package/dist/{chunk-M7O6IVKN.js.map → chunk-BICZR6UJ.js.map} +1 -1
  21. package/dist/{chunk-BCK2NIBM.js → chunk-DIZ5KI5Q.js} +6 -6
  22. package/dist/{chunk-BCK2NIBM.js.map → chunk-DIZ5KI5Q.js.map} +1 -1
  23. package/dist/{chunk-QTQRM7HQ.js → chunk-E3XVIFSH.js} +3 -3
  24. package/dist/{chunk-QTQRM7HQ.js.map → chunk-E3XVIFSH.js.map} +1 -1
  25. package/dist/{chunk-B5X246UH.js → chunk-FQHWPOTS.js} +3 -3
  26. package/dist/{chunk-B5X246UH.js.map → chunk-FQHWPOTS.js.map} +1 -1
  27. package/dist/chunk-G3ACLBMG.js +6 -0
  28. package/dist/{chunk-KFLNWYZG.js.map → chunk-G3ACLBMG.js.map} +1 -1
  29. package/dist/{chunk-CIC3NY2D.js → chunk-GR7SFCQJ.js} +12 -12
  30. package/dist/{chunk-CIC3NY2D.js.map → chunk-GR7SFCQJ.js.map} +1 -1
  31. package/dist/{chunk-Y3X3ORQ3.js → chunk-GWSJYDK7.js} +5 -5
  32. package/dist/{chunk-Y3X3ORQ3.js.map → chunk-GWSJYDK7.js.map} +1 -1
  33. package/dist/{chunk-ECQFRZJI.js → chunk-HFQIYM6E.js} +4 -4
  34. package/dist/{chunk-ECQFRZJI.js.map → chunk-HFQIYM6E.js.map} +1 -1
  35. package/dist/{chunk-GRMZU24V.js → chunk-IJVWKZRS.js} +3 -3
  36. package/dist/{chunk-GRMZU24V.js.map → chunk-IJVWKZRS.js.map} +1 -1
  37. package/dist/{chunk-YIRDV4YJ.js → chunk-JAEHLTVX.js} +3 -3
  38. package/dist/{chunk-YIRDV4YJ.js.map → chunk-JAEHLTVX.js.map} +1 -1
  39. package/dist/{chunk-LUJ4H4RJ.js → chunk-K3SXWOTT.js} +3 -3
  40. package/dist/{chunk-LUJ4H4RJ.js.map → chunk-K3SXWOTT.js.map} +1 -1
  41. package/dist/{chunk-JSZ46IDG.js → chunk-KYM55VZX.js} +6 -6
  42. package/dist/{chunk-JSZ46IDG.js.map → chunk-KYM55VZX.js.map} +1 -1
  43. package/dist/{chunk-YP243ZKD.js → chunk-L7GCJNDT.js} +3 -3
  44. package/dist/{chunk-YP243ZKD.js.map → chunk-L7GCJNDT.js.map} +1 -1
  45. package/dist/{chunk-UUVOA6WD.js → chunk-NS4DL3QR.js} +8 -8
  46. package/dist/{chunk-UUVOA6WD.js.map → chunk-NS4DL3QR.js.map} +1 -1
  47. package/dist/{chunk-S3HMG6BC.js → chunk-NZES47ST.js} +3 -3
  48. package/dist/{chunk-S3HMG6BC.js.map → chunk-NZES47ST.js.map} +1 -1
  49. package/dist/{chunk-FVBN4E5C.js → chunk-OIUVWCKM.js} +3 -3
  50. package/dist/{chunk-FVBN4E5C.js.map → chunk-OIUVWCKM.js.map} +1 -1
  51. package/dist/{chunk-DLNNNESQ.js → chunk-SIXWWQ6S.js} +3 -3
  52. package/dist/{chunk-DLNNNESQ.js.map → chunk-SIXWWQ6S.js.map} +1 -1
  53. package/dist/{chunk-6VLOI2ZP.js → chunk-SYMJSRYF.js} +3 -3
  54. package/dist/{chunk-6VLOI2ZP.js.map → chunk-SYMJSRYF.js.map} +1 -1
  55. package/dist/{chunk-LKJIYGO5.js → chunk-TT2J2TB6.js} +6 -6
  56. package/dist/{chunk-LKJIYGO5.js.map → chunk-TT2J2TB6.js.map} +1 -1
  57. package/dist/{chunk-4PCFSRYH.js → chunk-VMPKOMHG.js} +5 -5
  58. package/dist/{chunk-4PCFSRYH.js.map → chunk-VMPKOMHG.js.map} +1 -1
  59. package/dist/cli.js +49 -49
  60. package/dist/{daemon-WPX2SBVV.js → daemon-RZS5FPIW.js} +9 -9
  61. package/dist/{daemon-WPX2SBVV.js.map → daemon-RZS5FPIW.js.map} +1 -1
  62. package/dist/embed-worker-main.js +3 -3
  63. package/dist/{ensure-map-MLI4XCRV.js → ensure-map-DL2S774J.js} +14 -14
  64. package/dist/{ensure-map-MLI4XCRV.js.map → ensure-map-DL2S774J.js.map} +1 -1
  65. package/dist/{graph-backend-LK5EFQXN.js → graph-backend-JXARVT3R.js} +7 -7
  66. package/dist/{graph-backend-LK5EFQXN.js.map → graph-backend-JXARVT3R.js.map} +1 -1
  67. package/dist/index.d.ts +1 -1
  68. package/dist/index.js +15 -15
  69. package/dist/{interactive-K446F42I.js → interactive-2XRBRFRB.js} +25 -25
  70. package/dist/{interactive-K446F42I.js.map → interactive-2XRBRFRB.js.map} +1 -1
  71. package/dist/load-7C5VETRD.js +11 -0
  72. package/dist/{load-2FRH37JY.js.map → load-7C5VETRD.js.map} +1 -1
  73. package/dist/parse-worker.js +2 -2
  74. package/dist/{run-outcome-4ETNDPX6.js → run-outcome-TMB5TJNA.js} +5 -5
  75. package/dist/{run-outcome-4ETNDPX6.js.map → run-outcome-TMB5TJNA.js.map} +1 -1
  76. package/dist/{runtime-session-RMSKXFIJ.js → runtime-session-Y23NVY7R.js} +9 -9
  77. package/dist/{runtime-session-RMSKXFIJ.js.map → runtime-session-Y23NVY7R.js.map} +1 -1
  78. package/dist/{session-22BGDYWF.js → session-KXT2ZTPE.js} +8 -8
  79. package/dist/{session-22BGDYWF.js.map → session-KXT2ZTPE.js.map} +1 -1
  80. package/dist/{stream-json-MD7MSSCH.js → stream-json-NW6AOE47.js} +13 -13
  81. package/dist/{stream-json-MD7MSSCH.js.map → stream-json-NW6AOE47.js.map} +1 -1
  82. package/dist/version-7ABYXWOZ.js +4 -0
  83. package/dist/{version-FRUT6RI2.js.map → version-7ABYXWOZ.js.map} +1 -1
  84. package/dist/{vg-mcp-bridge-H6I3ALUW.js → vg-mcp-bridge-LXBHKEFR.js} +8 -8
  85. package/dist/{vg-mcp-bridge-H6I3ALUW.js.map → vg-mcp-bridge-LXBHKEFR.js.map} +1 -1
  86. package/dist/{vgd-TW7HU2PH.js → vgd-RW7HCEIP.js} +8 -8
  87. package/dist/vgd-RW7HCEIP.js.map +1 -0
  88. package/package.json +1 -1
  89. package/dist/chunk-KFLNWYZG.js +0 -6
  90. package/dist/load-2FRH37JY.js +0 -11
  91. package/dist/version-FRUT6RI2.js +0 -4
  92. package/dist/vgd-TW7HU2PH.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/install/module-core.ts","../src/install/relevance-module.ts","../src/engine/refresh-scheduler.ts","../src/runtime/vgd/semantic-client.ts","../src/mcp/server.ts","../src/engine/export.ts"],"names":["path2","fs2","sleep","path3","fs3"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,gBAAA,GAAmB,4BAAA;AA6BzB,SAAS,aAAa,IAAA,EAA8B;AAClD,EAAA,OAAA,CAAQ,OAAA,CAAQ,IAAI,wBAAA,IAA4B,IAAA,CAAK,YAAY,gBAAA,EAAkB,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvG;AAGO,SAAS,cAAA,GAAyB;AACvC,EAAA,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,kBAAuB,IAAA,CAAA,IAAA,CAAQ,EAAA,CAAA,OAAA,IAAW,QAAQ,CAAA;AAC3E,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,IAAA,EAAM,UAAA,EAAY,SAAS,CAAA;AAC9C;AAEA,SAAS,SAAA,GAAoB;AAC3B,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,cAAA,EAAe,EAAG,cAAc,CAAA;AACnD;AAKO,SAAS,WAAA,GAA4B;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,KAAK,KAAA,CAAS,EAAA,CAAA,YAAA,CAAa,SAAA,EAAU,EAAG,MAAM,CAAC,CAAA;AAAA,EACxD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEO,SAAS,aAAa,KAAA,EAA2B;AACtD,EAAA,IAAI;AACF,IAAG,EAAA,CAAA,SAAA,CAAe,aAAQ,SAAA,EAAW,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AAC3D,IAAG,iBAAc,SAAA,EAAU,EAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EACrD,CAAA,CA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,IAAA,EAAM,IAAA,EAAM,SAAS,GAAA,CAAI,KAAA,CAAM,UAAA,CAAW,OAAA,EAAS,CAAA,EAAE;AAAA,IACvG;AAAA,GACF;AACA,EAAA,OAAO,IAAA,CAAK,SAAA,CAAU,GAAA,EAAK,IAAA,EAAM,CAAC,CAAA,GAAI,IAAA;AACxC;AAEA,SAAS,KAAK,GAAA,EAA4B;AACxC,EAAA,MAAM,YAAY,GAAA,CAAI,IAAA,IAAQ,EAAC,EAAG,GAAA,CAAI,CAAC,CAAA,MAAO;AAAA,IAC5C,MAAA,EAAQ,CAAA,gBAAA,EAAmB,WAAA,CAAY,CAAA,CAAE,IAAI,CAAC,CAAA,CAAA;AAAA,IAC9C,MAAM,CAAA,CAAE,IAAA;AAAA,IACR,WAAA,EAAa,CAAA,CAAE,SAAA,IAAa,CAAA,CAAE,QAAA;AAAA,IAC9B,gBAAA,EAAkB;AAAA,GACpB,CAAE,CAAA;AACF,EAAA,MAAM,GAAA,GAAM;AAAA,IACV,WAAA,EAAa,UAAA;AAAA,IACb,WAAA,EAAa,SAAA;AAAA,IACb,MAAA,EAAQ,kBAAA;AAAA,IACR,IAAA,EAAM,SAAA;AAAA,IACN,YAAA,EAAc,EAAE,OAAA,EAAS,GAAA,CAAI,WAAA,EAAa,QAAA,EAAU,CAAC,CAAA,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-TLYNLQL2.js","sourcesContent":["/**\n * Generic installer for optional local modules (relevance, hcs, …).\n *\n * A module is a separately licensed, separately distributed local package that\n * the CLI loads through a provider seam. This core manages the shared\n * lifecycle without touching the user's project: it installs into the\n * vibgrate modules cache dir via a direct registry tarball fetch with an\n * integrity check — never a `package.json` mutation, never a postinstall\n * script execution (the tarball is unpacked, nothing in it is run at install\n * time). Per-module policy (consent posture, auto-provisioning, error\n * loudness) lives with each module's own wrapper (relevance-module.ts,\n * hcs-module.ts) — this file is mechanism only.\n */\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as zlib from 'node:zlib';\nimport { createHash } from 'node:crypto';\n\nconst DEFAULT_REGISTRY = 'https://registry.npmjs.org';\n\n/** Everything the generic installer needs to know about one module. */\nexport interface ModuleDescriptor {\n /** Short id — the consent key and the cache dir name (e.g. \"relevance\"). */\n id: string;\n /** npm package name fetched from the registry. */\n npmName: string;\n /** Absolute install dir for this module. */\n dir(): string;\n /** Invalidate any memoized loader after install/remove. */\n onChanged?(): void;\n}\n\nexport interface InstallResult {\n status: 'installed' | 'already-installed' | 'disabled' | 'declined' | 'unavailable';\n version?: string;\n detail?: string;\n}\n\nexport interface InstallOptions {\n /** Injectable fetch (tests). Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /** Registry base URL; VIBGRATE_MODULE_REGISTRY overrides, then this. */\n registry?: string;\n /** Reinstall even when already present. */\n force?: boolean;\n}\n\nfunction registryBase(opts: InstallOptions): string {\n return (process.env.VIBGRATE_MODULE_REGISTRY || opts.registry || DEFAULT_REGISTRY).replace(/\\/+$/, '');\n}\n\n/** Base dir all modules install under: `$XDG_CACHE_HOME|~/.cache /vibgrate/modules`. */\nexport function modulesBaseDir(): string {\n const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');\n return path.join(base, 'vibgrate', 'modules');\n}\n\nfunction stateFile(): string {\n return path.join(modulesBaseDir(), 'consent.json');\n}\n\n/** Per-module consent, keyed by module id, shared in one state file. */\nexport type ConsentState = Partial<Record<string, 'granted' | 'denied'>>;\n\nexport function readConsent(): ConsentState {\n try {\n return JSON.parse(fs.readFileSync(stateFile(), 'utf8')) as ConsentState;\n } catch {\n return {};\n }\n}\n\nexport function writeConsent(state: ConsentState): void {\n try {\n fs.mkdirSync(path.dirname(stateFile()), { recursive: true });\n fs.writeFileSync(stateFile(), JSON.stringify(state));\n } catch {\n /* consent persistence is best-effort */\n }\n}\n\n/** The one kill switch for every optional module. */\nexport function kernelDisabled(): boolean {\n const v = process.env.VIBGRATE_NO_KERNEL;\n return v === '1' || v === 'true';\n}\n\nexport function moduleInstalledAt(dir: string): { installed: boolean; version?: string } {\n try {\n const meta = JSON.parse(fs.readFileSync(path.join(dir, '.module.json'), 'utf8')) as {\n version?: string;\n };\n if (fs.existsSync(path.join(dir, 'index.js'))) {\n return { installed: true, version: meta.version };\n }\n } catch {\n /* not installed */\n }\n return { installed: false };\n}\n\n/**\n * Verify a registry integrity string (\"sha512-<b64>\" / \"sha1-<b64>\") or a hex\n * shasum against the tarball bytes. Throws on mismatch; missing metadata is a\n * hard failure too — we never unpack unverified bytes.\n */\nexport function verifyIntegrity(buf: Buffer, integrity?: string, shasum?: string): void {\n if (integrity) {\n const [algo, expected] = integrity.split('-', 2);\n if (!algo || !expected) throw new Error('malformed integrity metadata');\n const actual = createHash(algo).update(buf).digest('base64');\n if (actual !== expected) throw new Error(`integrity mismatch (${algo})`);\n return;\n }\n if (shasum) {\n const actual = createHash('sha1').update(buf).digest('hex');\n if (actual !== shasum) throw new Error('integrity mismatch (shasum)');\n return;\n }\n throw new Error('registry provided no integrity metadata');\n}\n\n/**\n * Minimal ustar reader — enough for npm-pack tarballs (ustar + pax extended\n * headers + GNU longname). Returns file entries only. No symlinks, no device\n * nodes, and every emitted path is validated against traversal.\n */\nexport function untar(data: Buffer): Array<{ name: string; body: Buffer }> {\n const out: Array<{ name: string; body: Buffer }> = [];\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= data.length) {\n const block = data.subarray(offset, offset + 512);\n offset += 512;\n if (block.every((b) => b === 0)) continue; // end-of-archive padding\n const rawName = block.subarray(0, 100).toString('utf8').replace(/\\0.*$/, '');\n const size = parseInt(block.subarray(124, 136).toString('utf8').replace(/\\0.*$/, '').trim() || '0', 8);\n const type = String.fromCharCode(block[156]!);\n const prefix = block.subarray(345, 500).toString('utf8').replace(/\\0.*$/, '');\n const body = data.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (type === 'L') {\n pendingName = body.toString('utf8').replace(/\\0.*$/, '');\n continue;\n }\n if (type === 'x' || type === 'g') {\n const m = /(?:^|\\n)\\d+ path=([^\\n]+)\\n/.exec(body.toString('utf8'));\n if (m) pendingName = m[1]!;\n continue;\n }\n if (type !== '0' && type !== '\\0') continue; // files only\n const name = pendingName ?? (prefix ? `${prefix}/${rawName}` : rawName);\n pendingName = null;\n if (name.split('/').includes('..') || path.isAbsolute(name)) {\n throw new Error(`unsafe path in tarball: ${name}`);\n }\n out.push({ name, body: Buffer.from(body) });\n }\n return out;\n}\n\n/**\n * Fetch, verify, and unpack a module into its cache dir. The loadable surface\n * is the tarball's `package/dist/*` mapped to the module root (so\n * `<dir>/index.js` is the seam's entrypoint), plus LICENSE/README.\n */\nexport async function installModule(mod: ModuleDescriptor, opts: InstallOptions = {}): Promise<InstallResult> {\n if (kernelDisabled()) return { status: 'disabled', detail: 'VIBGRATE_NO_KERNEL is set' };\n const existing = moduleInstalledAt(mod.dir());\n if (existing.installed && !opts.force) return { status: 'already-installed', version: existing.version };\n\n const doFetch = opts.fetchImpl ?? fetch;\n const base = registryBase(opts);\n try {\n const metaRes = await doFetch(`${base}/${mod.npmName.replace('/', '%2f')}`);\n if (!metaRes.ok) return { status: 'unavailable', detail: `registry ${metaRes.status}` };\n const meta = (await metaRes.json()) as {\n 'dist-tags'?: Record<string, string>;\n versions?: Record<string, { dist?: { tarball?: string; integrity?: string; shasum?: string } }>;\n };\n const version = meta['dist-tags']?.latest;\n const dist = version ? meta.versions?.[version]?.dist : undefined;\n if (!version || !dist?.tarball) return { status: 'unavailable', detail: 'no published version' };\n\n const tarRes = await doFetch(dist.tarball);\n if (!tarRes.ok) return { status: 'unavailable', detail: `tarball ${tarRes.status}` };\n const gz = Buffer.from(await tarRes.arrayBuffer());\n verifyIntegrity(gz, dist.integrity, dist.shasum);\n\n const entries = untar(zlib.gunzipSync(gz));\n const dir = mod.dir();\n fs.rmSync(dir, { recursive: true, force: true });\n fs.mkdirSync(dir, { recursive: true });\n let wrote = 0;\n for (const e of entries) {\n let rel: string | null = null;\n if (e.name.startsWith('package/dist/')) rel = e.name.slice('package/dist/'.length);\n else if (e.name === 'package/LICENSE' || e.name === 'package/README.md') rel = e.name.slice('package/'.length);\n if (!rel) continue;\n const target = path.join(dir, rel);\n if (!target.startsWith(dir + path.sep) && target !== dir) throw new Error(`unsafe extract path: ${rel}`);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, e.body);\n wrote += 1;\n }\n if (!wrote || !fs.existsSync(path.join(dir, 'index.js'))) {\n fs.rmSync(dir, { recursive: true, force: true });\n return { status: 'unavailable', detail: 'package layout not recognized (no dist/index.js)' };\n }\n fs.writeFileSync(path.join(dir, '.module.json'), JSON.stringify({ name: mod.npmName, version }));\n mod.onChanged?.();\n return { status: 'installed', version };\n } catch (e) {\n return { status: 'unavailable', detail: String((e as Error).message ?? e).slice(0, 200) };\n }\n}\n\nexport function removeModule(mod: ModuleDescriptor): void {\n fs.rmSync(mod.dir(), { recursive: true, force: true });\n mod.onChanged?.();\n}\n","/**\n * Install / remove / auto-provision the optional relevance module.\n *\n * The relevance module is a separately licensed, separately distributed local\n * package (`@vibgrate/relevance`) that the CLI loads through the generic\n * provider seam (engine/relevance-provider.ts). The shared fetch/verify/unpack\n * mechanism lives in install/module-core.ts; this file holds the relevance\n * descriptor and its consent posture.\n *\n * Consent posture (maintainer decision, 2026-08 — see\n * docs/RELEVANCE-KERNEL-PLAN.md §4 in the monorepo): ON by default. First\n * interactive use asks once and persists the answer; non-interactive runs\n * (CI) install silently with a one-line stderr notice. `VIBGRATE_NO_KERNEL=1`\n * always wins and disables both install and use. Offline or fetch failure\n * degrades with a one-line message — never an error (GUARDRAILS §3.4).\n */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { relevanceModuleDir, resetRelevanceProviderCache } from '../engine/relevance-provider.js';\nimport {\n type InstallOptions,\n type InstallResult,\n type ModuleDescriptor,\n installModule,\n kernelDisabled,\n moduleInstalledAt,\n readConsent,\n removeModule,\n writeConsent,\n} from './module-core.js';\n\nexport type { InstallOptions, InstallResult };\nexport { kernelDisabled, readConsent, writeConsent };\nexport { verifyIntegrity, untar } from './module-core.js';\n\nexport const RELEVANCE_MODULE_NAME = '@vibgrate/relevance';\n\nconst RELEVANCE_MODULE: ModuleDescriptor = {\n id: 'relevance',\n npmName: RELEVANCE_MODULE_NAME,\n dir: relevanceModuleDir,\n onChanged: resetRelevanceProviderCache,\n};\n\nexport function moduleInstalled(): { installed: boolean; version?: string } {\n return moduleInstalledAt(relevanceModuleDir());\n}\n\n/** The one-line disclosure shown before/at install. Public copy — keep plain. */\nexport const DISCLOSURE =\n 'vg can install the optional Vibgrate relevance module (proprietary license, runs fully locally, ' +\n 'improves how questions find the code they mean). Disable any time with VIBGRATE_NO_KERNEL=1.';\n\n/**\n * Fetch, verify, and unpack the module into the modules cache dir. The\n * loadable surface is the tarball's `package/dist/*` mapped to the module\n * root (so `<dir>/index.js` is the seam's entrypoint), plus LICENSE/README.\n */\nexport async function installRelevanceModule(opts: InstallOptions = {}): Promise<InstallResult> {\n return installModule(RELEVANCE_MODULE, opts);\n}\n\nexport function removeRelevanceModule(): void {\n removeModule(RELEVANCE_MODULE);\n}\n\n/**\n * Auto-provision hook for `vg code` startup — fully SILENT by design\n * (maintainer decision, 2026-08): the module installs automatically with no\n * prompt and no notice; if the install or the module itself fails for any\n * reason the run simply proceeds without it, exactly as if it were never\n * there. Fast no-op when already installed. Two opt-outs still always win:\n * `VIBGRATE_NO_KERNEL=1`, and an explicit decline recorded via\n * `vg module install relevance` answering \"no\" (or `vg module remove`\n * followed by a recorded denial). Never throws, never blocks a run on\n * anything but the (bounded) fetch itself.\n */\n/**\n * Oldest module version whose provider carries the `rankSymbols` ranking API\n * (the 2026-08 relevance relocation). An older install still loads for\n * analyze/tagNode, but the seam treats it as \"no ranking engine\", so the\n * ensure path force-upgrades it in place.\n */\nexport const RANKING_MIN_MODULE_VERSION = '2026.823.0';\n\n/** Dotted-numeric version compare (module versions are `YYYY.MDD.N`). */\nfunction versionAtLeast(version: string | undefined, min: string): boolean {\n if (!version) return false;\n const a = version.split('.').map((n) => Number(n));\n const b = min.split('.').map((n) => Number(n));\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (!Number.isFinite(x)) return false;\n if (x !== y) return x > y;\n }\n return true;\n}\n\nexport async function ensureRelevanceModule(io: { fetchImpl?: typeof fetch } = {}): Promise<InstallResult> {\n try {\n if (kernelDisabled()) return { status: 'disabled' };\n if (readConsent().relevance === 'denied') return { status: 'declined' };\n const existing = moduleInstalled();\n if (existing.installed) {\n // Pre-ranking installs upgrade in place — since the relocation, the\n // module IS the relevance engine, so an old version is as good as none.\n if (versionAtLeast(existing.version, RANKING_MIN_MODULE_VERSION)) {\n return { status: 'already-installed', version: existing.version };\n }\n return await installRelevanceModule({ fetchImpl: io.fetchImpl, force: true });\n }\n return await installRelevanceModule({ fetchImpl: io.fetchImpl });\n } catch {\n return { status: 'unavailable', detail: 'auto-install failed' };\n }\n}\n\n/** Stamp file throttling background readiness attempts (offline machines must\n * not pay a fetch on every `vg` invocation). Lives beside the module dir. */\nconst READINESS_THROTTLE_MS = 60 * 60 * 1000;\n\n/**\n * Fire-and-forget readiness kick, called on EVERY `vg` invocation (cli.ts):\n * when the module is missing (or predates the ranking API) and no attempt was\n * made within the last hour, start a silent background install and return\n * immediately — the command never waits on it. `vg ask` / `vg code` still\n * run their own bounded `ensureRelevanceModule()` retry at use time, so a\n * fresh machine gets the module on the first ask even if this kick's install\n * has not finished. Failures are invisible by design: the run proceeds on\n * the mechanical fallback exactly as if the module never existed.\n */\nexport function kickRelevanceReadiness(io: { fetchImpl?: typeof fetch } = {}): void {\n try {\n if (kernelDisabled()) return;\n if (readConsent().relevance === 'denied') return;\n const existing = moduleInstalled();\n if (existing.installed && versionAtLeast(existing.version, RANKING_MIN_MODULE_VERSION)) return;\n const modulesRoot = path.dirname(relevanceModuleDir());\n const stamp = path.join(modulesRoot, 'relevance.last-attempt');\n try {\n const at = Number(fs.readFileSync(stamp, 'utf8'));\n if (Number.isFinite(at) && Date.now() - at < READINESS_THROTTLE_MS) return;\n } catch {\n /* no stamp yet — attempt */\n }\n try {\n fs.mkdirSync(modulesRoot, { recursive: true });\n fs.writeFileSync(stamp, String(Date.now()));\n } catch {\n /* unwritable cache dir — skip quietly */\n }\n void ensureRelevanceModule(io).catch(() => {});\n } catch {\n /* readiness must never affect the command */\n }\n}\n","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 { attachVgd, type AttachOptions } from './attach.js';\nimport { vgdRequest } from './client.js';\nimport { formatSemanticProgress } from './semantic-status.js';\n\n/**\n * One way to ask the daemon for a semantic ranking, shared by every surface.\n *\n * `vg ask`, `vg serve` and `vg lsp` each grew their own copy of \"load the\n * embedder, embed the corpus, rank\" — and `engine/refresh-scheduler.ts` records\n * what that costs: the per-server copies diverged, and one of them blocked an\n * editor Ask for ninety seconds. This is the single implementation of the\n * daemon path so that cannot happen again.\n *\n * Long-lived callers (the MCP server, the language server) hold one of these\n * for the process: it attaches once, remembers the slot, and per request sends\n * only the question. Short-lived callers get the same behaviour with the attach\n * folded into the first call.\n *\n * Every failure resolves to `null`, never a throw. `null` means \"rank it\n * yourself\" — the in-process path each caller already has, which is also what\n * happens when no daemon is running at all.\n */\n\nexport interface DaemonRanking {\n ranked: Array<{ id: string; score: number }>;\n /** How many vectors the slot holds — for logging, not correctness. */\n vectors: number;\n model?: string;\n}\n\nexport interface SemanticProgress {\n state: string;\n vectors: number;\n pending?: number;\n nodeCount?: number;\n model?: string;\n /** One line for a live status spinner. */\n detail: string;\n}\n\nexport interface RankWaitOptions {\n /** Called whenever the slot's status is sampled during a wait. */\n onProgress?: (status: SemanticProgress) => void;\n /** How often to poll `embed-status` while the index is warming (default 300ms). */\n pollMs?: number;\n /** Give up waiting and return null (default 10 minutes). */\n timeoutMs?: number;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface SemanticSessionOptions extends Omit<AttachOptions, 'corpusHash'> {\n /** How long to wait before retrying after a failed attach (default 30s). */\n retryAfterMs?: number;\n now?: () => number;\n /** Injected (tests). */\n attach?: typeof attachVgd;\n request?: typeof vgdRequest;\n}\n\nexport class DaemonSemanticSession {\n private repositoryId: string | undefined;\n private gitRef: string | undefined;\n private socketPath: string | undefined;\n /** The map the daemon was last told about, so an unchanged one is not resent. */\n private publishedHash: string | undefined;\n /** Do not re-attach before this time — a down daemon must not cost every request. */\n private retryAfter = 0;\n private attaching: Promise<void> | null = null;\n\n private readonly root: string;\n private readonly options: SemanticSessionOptions;\n private readonly retryAfterMs: number;\n private readonly now: () => number;\n private readonly attachImpl: typeof attachVgd;\n private readonly requestImpl: typeof vgdRequest;\n\n constructor(root: string, options: SemanticSessionOptions = {}) {\n this.root = root;\n this.options = options;\n this.retryAfterMs = options.retryAfterMs ?? 30_000;\n this.now = options.now ?? ((): number => Date.now());\n this.attachImpl = options.attach ?? attachVgd;\n this.requestImpl = options.request ?? vgdRequest;\n }\n\n /** True once a slot is known — useful for a one-line status log. */\n get attached(): boolean {\n return !!this.repositoryId;\n }\n\n /**\n * Rank `question` against the daemon's index for this repo.\n * `corpusHash` is the caller's current map: when it differs from what the\n * daemon holds, the map is republished before ranking, so a locally\n * refreshed map never ranks against yesterday's vectors.\n */\n async rank(question: string, corpusHash?: string, wait?: RankWaitOptions): Promise<DaemonRanking | null> {\n await this.ensureAttached(corpusHash);\n if (!this.repositoryId) return null;\n try {\n const first = await this.requestRank(question);\n if (first.status === 'ranked') return first.ranking;\n if (first.status === 'empty') return null;\n // Index is warming (or an older daemon returned unavailable). Kick a\n // non-blocking build and poll status so the caller can show progress\n // instead of sitting on a silent socket for tens of seconds.\n await this.requestImpl(\n { op: 'embed-index', repositoryId: this.repositoryId, gitRef: this.gitRef, wait: false },\n { socketPath: this.socketPath },\n );\n const now = wait?.now ?? this.now;\n const sleep = wait?.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n const deadline = now() + (wait?.timeoutMs ?? 600_000);\n const pollMs = wait?.pollMs ?? 300;\n while (now() < deadline) {\n const progress = await this.readProgress(first);\n if (progress) wait?.onProgress?.(progress);\n if (progress && (progress.state === 'failed' || progress.state === 'unavailable')) return null;\n if (progress && (progress.state === 'ready' || progress.vectors > 0)) {\n const again = await this.requestRank(question);\n if (again.status === 'ranked') return again.ranking;\n if (again.status === 'empty') return null;\n }\n await sleep(pollMs);\n }\n return null;\n } catch {\n // The daemon went away mid-session (a restart, an upgrade). Forget the\n // slot so the next call re-attaches instead of retrying a dead socket.\n this.reset();\n return null;\n }\n }\n\n private async readProgress(hint?: RankAttempt): Promise<SemanticProgress | null> {\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'embed-status', repositoryId: this.repositoryId },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('semantic' in res)) {\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n const slots = res.semantic.slots ?? [];\n const slot =\n slots.find((s) => s.repositoryId === this.repositoryId && (!this.gitRef || s.gitRef === this.gitRef)) ??\n slots.find((s) => s.repositoryId === this.repositoryId) ??\n slots[0];\n if (!slot) {\n if (res.semantic.worker === 'unavailable') {\n return { state: 'unavailable', vectors: 0, detail: res.semantic.reason ?? 'semantic worker unavailable' };\n }\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n const view = {\n state: slot.state,\n vectors: slot.vectors,\n pending: slot.pending,\n nodeCount: slot.nodeCount,\n model: res.semantic.model,\n error: slot.error,\n };\n return { ...view, detail: formatSemanticProgress(view) };\n } catch {\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n }\n\n private async requestRank(question: string): Promise<RankAttempt> {\n if (!this.repositoryId) return { status: 'unavailable' };\n const res = await this.requestImpl(\n { op: 'embed-rank', repositoryId: this.repositoryId, gitRef: this.gitRef, text: question },\n { socketPath: this.socketPath },\n );\n if (res.ok && 'ranked' in res) {\n if (res.ranked.length === 0) return { status: 'empty' };\n return { status: 'ranked', ranking: { ranked: res.ranked, vectors: res.vectors, model: res.model } };\n }\n if (!res.ok && res.code === 'semantic_warming') {\n return {\n status: 'warming',\n state: res.state,\n vectors: res.vectors ?? 0,\n pending: res.pending,\n nodeCount: res.nodeCount,\n };\n }\n return { status: 'unavailable' };\n }\n\n /**\n * The daemon's shared dependency context for this repo — the manifest digest\n * and the dependency records — computed once per daemon instead of once per\n * process. Null whenever the daemon cannot answer, so the caller falls back\n * to computing it locally.\n */\n async depContext(): Promise<{\n manifestHash: string;\n dependencies: Array<{ name: string; ecosystem: string; declared: string; installed?: string }>;\n } | null> {\n await this.ensureAttached();\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'dep-context', repositoryId: this.repositoryId },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('manifestHash' in res)) return null;\n return { manifestHash: res.manifestHash, dependencies: res.dependencies };\n } catch {\n this.reset();\n return null;\n }\n }\n\n private reset(): void {\n this.repositoryId = undefined;\n this.gitRef = undefined;\n this.publishedHash = undefined;\n this.retryAfter = this.now() + this.retryAfterMs;\n }\n\n /** Attach once; concurrent callers share the one attempt. */\n private ensureAttached(corpusHash?: string): Promise<void> {\n // Already attached and the map has not moved under us.\n if (this.repositoryId && (!corpusHash || corpusHash === this.publishedHash)) return Promise.resolve();\n if (this.now() < this.retryAfter) return Promise.resolve();\n if (this.attaching) return this.attaching;\n\n this.attaching = (async () => {\n const result = await this.attachImpl(this.root, { ...this.options, corpusHash });\n if (result.status === 'attached' && result.repositoryId) {\n this.repositoryId = result.repositoryId;\n this.gitRef = result.gitRef;\n this.socketPath = result.socketPath;\n this.publishedHash = corpusHash;\n } else {\n this.reset();\n }\n })().finally(() => {\n this.attaching = null;\n });\n return this.attaching;\n }\n}\n\ntype RankAttempt =\n | { status: 'ranked'; ranking: DaemonRanking }\n | { status: 'warming'; state?: string; vectors?: number; pending?: number; nodeCount?: number }\n | { status: 'unavailable' }\n | { status: 'empty' };\n\nfunction warmingProgress(hint: Extract<RankAttempt, { status: 'warming' }>): SemanticProgress {\n const view = {\n state: hint.state ?? 'building',\n vectors: hint.vectors ?? 0,\n pending: hint.pending,\n nodeCount: hint.nodeCount,\n };\n return { ...view, detail: formatSemanticProgress(view) };\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 { DaemonSemanticSession } from '../runtime/vgd/semantic-client.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 /** `--no-daemon`: never auto-start or use the local runtime. */\n daemon?: 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 /**\n * True while the daemon owns freshness for this workspace. Set only after\n * the daemon confirms a subscription, cleared the instant it drops — so the\n * failure mode is \"this process watches again\", never \"nobody watches\".\n */\n private daemonOwnsFreshness = false;\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 /**\n * Hand freshness to the daemon: stop probing on every call and stop watching.\n * The daemon pushes `slot-changed` and we reload from disk then.\n */\n deferFreshnessToDaemon(): void {\n this.daemonOwnsFreshness = true;\n this.stopWatching();\n }\n\n /** The daemon went away — resume owning freshness locally. */\n resumeLocalFreshness(): void {\n this.daemonOwnsFreshness = false;\n this.startWatching();\n }\n\n /** The daemon says the map moved; drop the cache so the next get() re-reads. */\n reloadFromDisk(): void {\n this.cachedMtimeMs = -1;\n this.pendingChanges.clear();\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 && !this.daemonOwnsFreshness) 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\n/**\n * Prefer the daemon's watcher to our own.\n *\n * Both notice the same edits and both drive the same incremental rebuild, so\n * running them together means two inotify registrations over one tree and two\n * rebuilds racing for one lock. The daemon wins when it is there: it is the\n * process that already holds the map and, unlike this one, is shared by every\n * other client on the machine.\n *\n * Standing down is conditional on the daemon *confirming* the subscription,\n * and reversed the instant that connection drops — a dead daemon degrades this\n * server to watching for itself, never to nothing watching at all.\n *\n * The confirmation has to be about *this* repository. The daemon only watches\n * a repo once it holds that repo's slot, so a subscription it acknowledges for\n * a workspace it has no map for would push nothing, forever — and this server\n * would have retired its own watcher to listen to silence. Publishing first is\n * what makes the acknowledgement mean something: it hands the daemon the map,\n * which is what starts its watcher, and answers with the repository id to\n * scope the subscription to.\n */\nasync function watchViaDaemonOrLocally(source: GraphSource, opts: ServeOptions): Promise<void> {\n if (opts.daemon === false) {\n source.startWatching();\n return;\n }\n try {\n const [{ publishGraphToVgd }, { subscribeToSlots }] = await Promise.all([\n import('../runtime/vgd/publish.js'),\n import('../runtime/vgd/slot-subscription.js'),\n ]);\n // Never starts a daemon; \"not-running\" simply means we watch locally.\n const published = await publishGraphToVgd(opts.root ?? source.root);\n if (published.status === 'published' || published.status === 'current') {\n const subscription = await subscribeToSlots({\n repositoryId: published.repositoryId,\n onChange: () => source.reloadFromDisk(),\n onDetach: () => source.resumeLocalFreshness(),\n });\n if (subscription.active) {\n source.deferFreshnessToDaemon();\n return;\n }\n }\n } catch {\n /* no daemon, or it cannot push — watch locally */\n }\n source.startWatching();\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 // One runtime session for the life of the server: attach once, then send only\n // the question per navigation call. Absent a daemon it stays null-returning\n // and every tool answers exactly as it does today.\n const semanticSession = local\n ? undefined\n : new DaemonSemanticSession(root, { disabled: opts.daemon === false });\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, {\n root,\n local,\n dedup,\n seen,\n graphPath: source.graphPath,\n semanticSession,\n });\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 const wantWatch = opts.refresh !== false && opts.watch !== false;\n if (wantWatch) await watchViaDaemonOrLocally(source, opts);\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
+ {"version":3,"sources":["../src/install/module-core.ts","../src/install/relevance-module.ts","../src/engine/refresh-scheduler.ts","../src/runtime/vgd/semantic-client.ts","../src/mcp/server.ts","../src/engine/export.ts"],"names":["path2","fs2","sleep","path3","fs3"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmBA,IAAM,gBAAA,GAAmB,4BAAA;AA6BzB,SAAS,aAAa,IAAA,EAA8B;AAClD,EAAA,OAAA,CAAQ,OAAA,CAAQ,IAAI,wBAAA,IAA4B,IAAA,CAAK,YAAY,gBAAA,EAAkB,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACvG;AAGO,SAAS,cAAA,GAAyB;AACvC,EAAA,MAAM,OAAO,OAAA,CAAQ,GAAA,CAAI,kBAAuB,IAAA,CAAA,IAAA,CAAQ,EAAA,CAAA,OAAA,IAAW,QAAQ,CAAA;AAC3E,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,IAAA,EAAM,UAAA,EAAY,SAAS,CAAA;AAC9C;AAEA,SAAS,SAAA,GAAoB;AAC3B,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,cAAA,EAAe,EAAG,cAAc,CAAA;AACnD;AAKO,SAAS,WAAA,GAA4B;AAC1C,EAAA,IAAI;AACF,IAAA,OAAO,KAAK,KAAA,CAAS,EAAA,CAAA,YAAA,CAAa,SAAA,EAAU,EAAG,MAAM,CAAC,CAAA;AAAA,EACxD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAEO,SAAS,aAAa,KAAA,EAA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QT4NE.js","sourcesContent":["/**\n * Generic installer for optional local modules (relevance, hcs, …).\n *\n * A module is a separately licensed, separately distributed local package that\n * the CLI loads through a provider seam. This core manages the shared\n * lifecycle without touching the user's project: it installs into the\n * vibgrate modules cache dir via a direct registry tarball fetch with an\n * integrity check — never a `package.json` mutation, never a postinstall\n * script execution (the tarball is unpacked, nothing in it is run at install\n * time). Per-module policy (consent posture, auto-provisioning, error\n * loudness) lives with each module's own wrapper (relevance-module.ts,\n * hcs-module.ts) — this file is mechanism only.\n */\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport * as zlib from 'node:zlib';\nimport { createHash } from 'node:crypto';\n\nconst DEFAULT_REGISTRY = 'https://registry.npmjs.org';\n\n/** Everything the generic installer needs to know about one module. */\nexport interface ModuleDescriptor {\n /** Short id — the consent key and the cache dir name (e.g. \"relevance\"). */\n id: string;\n /** npm package name fetched from the registry. */\n npmName: string;\n /** Absolute install dir for this module. */\n dir(): string;\n /** Invalidate any memoized loader after install/remove. */\n onChanged?(): void;\n}\n\nexport interface InstallResult {\n status: 'installed' | 'already-installed' | 'disabled' | 'declined' | 'unavailable';\n version?: string;\n detail?: string;\n}\n\nexport interface InstallOptions {\n /** Injectable fetch (tests). Defaults to global fetch. */\n fetchImpl?: typeof fetch;\n /** Registry base URL; VIBGRATE_MODULE_REGISTRY overrides, then this. */\n registry?: string;\n /** Reinstall even when already present. */\n force?: boolean;\n}\n\nfunction registryBase(opts: InstallOptions): string {\n return (process.env.VIBGRATE_MODULE_REGISTRY || opts.registry || DEFAULT_REGISTRY).replace(/\\/+$/, '');\n}\n\n/** Base dir all modules install under: `$XDG_CACHE_HOME|~/.cache /vibgrate/modules`. */\nexport function modulesBaseDir(): string {\n const base = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');\n return path.join(base, 'vibgrate', 'modules');\n}\n\nfunction stateFile(): string {\n return path.join(modulesBaseDir(), 'consent.json');\n}\n\n/** Per-module consent, keyed by module id, shared in one state file. */\nexport type ConsentState = Partial<Record<string, 'granted' | 'denied'>>;\n\nexport function readConsent(): ConsentState {\n try {\n return JSON.parse(fs.readFileSync(stateFile(), 'utf8')) as ConsentState;\n } catch {\n return {};\n }\n}\n\nexport function writeConsent(state: ConsentState): void {\n try {\n fs.mkdirSync(path.dirname(stateFile()), { recursive: true });\n fs.writeFileSync(stateFile(), JSON.stringify(state));\n } catch {\n /* consent persistence is best-effort */\n }\n}\n\n/** The one kill switch for every optional module. */\nexport function kernelDisabled(): boolean {\n const v = process.env.VIBGRATE_NO_KERNEL;\n return v === '1' || v === 'true';\n}\n\nexport function moduleInstalledAt(dir: string): { installed: boolean; version?: string } {\n try {\n const meta = JSON.parse(fs.readFileSync(path.join(dir, '.module.json'), 'utf8')) as {\n version?: string;\n };\n if (fs.existsSync(path.join(dir, 'index.js'))) {\n return { installed: true, version: meta.version };\n }\n } catch {\n /* not installed */\n }\n return { installed: false };\n}\n\n/**\n * Verify a registry integrity string (\"sha512-<b64>\" / \"sha1-<b64>\") or a hex\n * shasum against the tarball bytes. Throws on mismatch; missing metadata is a\n * hard failure too — we never unpack unverified bytes.\n */\nexport function verifyIntegrity(buf: Buffer, integrity?: string, shasum?: string): void {\n if (integrity) {\n const [algo, expected] = integrity.split('-', 2);\n if (!algo || !expected) throw new Error('malformed integrity metadata');\n const actual = createHash(algo).update(buf).digest('base64');\n if (actual !== expected) throw new Error(`integrity mismatch (${algo})`);\n return;\n }\n if (shasum) {\n const actual = createHash('sha1').update(buf).digest('hex');\n if (actual !== shasum) throw new Error('integrity mismatch (shasum)');\n return;\n }\n throw new Error('registry provided no integrity metadata');\n}\n\n/**\n * Minimal ustar reader — enough for npm-pack tarballs (ustar + pax extended\n * headers + GNU longname). Returns file entries only. No symlinks, no device\n * nodes, and every emitted path is validated against traversal.\n */\nexport function untar(data: Buffer): Array<{ name: string; body: Buffer }> {\n const out: Array<{ name: string; body: Buffer }> = [];\n let offset = 0;\n let pendingName: string | null = null;\n while (offset + 512 <= data.length) {\n const block = data.subarray(offset, offset + 512);\n offset += 512;\n if (block.every((b) => b === 0)) continue; // end-of-archive padding\n const rawName = block.subarray(0, 100).toString('utf8').replace(/\\0.*$/, '');\n const size = parseInt(block.subarray(124, 136).toString('utf8').replace(/\\0.*$/, '').trim() || '0', 8);\n const type = String.fromCharCode(block[156]!);\n const prefix = block.subarray(345, 500).toString('utf8').replace(/\\0.*$/, '');\n const body = data.subarray(offset, offset + size);\n offset += Math.ceil(size / 512) * 512;\n if (type === 'L') {\n pendingName = body.toString('utf8').replace(/\\0.*$/, '');\n continue;\n }\n if (type === 'x' || type === 'g') {\n const m = /(?:^|\\n)\\d+ path=([^\\n]+)\\n/.exec(body.toString('utf8'));\n if (m) pendingName = m[1]!;\n continue;\n }\n if (type !== '0' && type !== '\\0') continue; // files only\n const name = pendingName ?? (prefix ? `${prefix}/${rawName}` : rawName);\n pendingName = null;\n if (name.split('/').includes('..') || path.isAbsolute(name)) {\n throw new Error(`unsafe path in tarball: ${name}`);\n }\n out.push({ name, body: Buffer.from(body) });\n }\n return out;\n}\n\n/**\n * Fetch, verify, and unpack a module into its cache dir. The loadable surface\n * is the tarball's `package/dist/*` mapped to the module root (so\n * `<dir>/index.js` is the seam's entrypoint), plus LICENSE/README.\n */\nexport async function installModule(mod: ModuleDescriptor, opts: InstallOptions = {}): Promise<InstallResult> {\n if (kernelDisabled()) return { status: 'disabled', detail: 'VIBGRATE_NO_KERNEL is set' };\n const existing = moduleInstalledAt(mod.dir());\n if (existing.installed && !opts.force) return { status: 'already-installed', version: existing.version };\n\n const doFetch = opts.fetchImpl ?? fetch;\n const base = registryBase(opts);\n try {\n const metaRes = await doFetch(`${base}/${mod.npmName.replace('/', '%2f')}`);\n if (!metaRes.ok) return { status: 'unavailable', detail: `registry ${metaRes.status}` };\n const meta = (await metaRes.json()) as {\n 'dist-tags'?: Record<string, string>;\n versions?: Record<string, { dist?: { tarball?: string; integrity?: string; shasum?: string } }>;\n };\n const version = meta['dist-tags']?.latest;\n const dist = version ? meta.versions?.[version]?.dist : undefined;\n if (!version || !dist?.tarball) return { status: 'unavailable', detail: 'no published version' };\n\n const tarRes = await doFetch(dist.tarball);\n if (!tarRes.ok) return { status: 'unavailable', detail: `tarball ${tarRes.status}` };\n const gz = Buffer.from(await tarRes.arrayBuffer());\n verifyIntegrity(gz, dist.integrity, dist.shasum);\n\n const entries = untar(zlib.gunzipSync(gz));\n const dir = mod.dir();\n fs.rmSync(dir, { recursive: true, force: true });\n fs.mkdirSync(dir, { recursive: true });\n let wrote = 0;\n for (const e of entries) {\n let rel: string | null = null;\n if (e.name.startsWith('package/dist/')) rel = e.name.slice('package/dist/'.length);\n else if (e.name === 'package/LICENSE' || e.name === 'package/README.md') rel = e.name.slice('package/'.length);\n if (!rel) continue;\n const target = path.join(dir, rel);\n if (!target.startsWith(dir + path.sep) && target !== dir) throw new Error(`unsafe extract path: ${rel}`);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, e.body);\n wrote += 1;\n }\n if (!wrote || !fs.existsSync(path.join(dir, 'index.js'))) {\n fs.rmSync(dir, { recursive: true, force: true });\n return { status: 'unavailable', detail: 'package layout not recognized (no dist/index.js)' };\n }\n fs.writeFileSync(path.join(dir, '.module.json'), JSON.stringify({ name: mod.npmName, version }));\n mod.onChanged?.();\n return { status: 'installed', version };\n } catch (e) {\n return { status: 'unavailable', detail: String((e as Error).message ?? e).slice(0, 200) };\n }\n}\n\nexport function removeModule(mod: ModuleDescriptor): void {\n fs.rmSync(mod.dir(), { recursive: true, force: true });\n mod.onChanged?.();\n}\n","/**\n * Install / remove / auto-provision the optional relevance module.\n *\n * The relevance module is a separately licensed, separately distributed local\n * package (`@vibgrate/relevance`) that the CLI loads through the generic\n * provider seam (engine/relevance-provider.ts). The shared fetch/verify/unpack\n * mechanism lives in install/module-core.ts; this file holds the relevance\n * descriptor and its consent posture.\n *\n * Consent posture (maintainer decision, 2026-08 — see\n * docs/RELEVANCE-KERNEL-PLAN.md §4 in the monorepo): ON by default. First\n * interactive use asks once and persists the answer; non-interactive runs\n * (CI) install silently with a one-line stderr notice. `VIBGRATE_NO_KERNEL=1`\n * always wins and disables both install and use. Offline or fetch failure\n * degrades with a one-line message — never an error (GUARDRAILS §3.4).\n */\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { relevanceModuleDir, resetRelevanceProviderCache } from '../engine/relevance-provider.js';\nimport {\n type InstallOptions,\n type InstallResult,\n type ModuleDescriptor,\n installModule,\n kernelDisabled,\n moduleInstalledAt,\n readConsent,\n removeModule,\n writeConsent,\n} from './module-core.js';\n\nexport type { InstallOptions, InstallResult };\nexport { kernelDisabled, readConsent, writeConsent };\nexport { verifyIntegrity, untar } from './module-core.js';\n\nexport const RELEVANCE_MODULE_NAME = '@vibgrate/relevance';\n\nconst RELEVANCE_MODULE: ModuleDescriptor = {\n id: 'relevance',\n npmName: RELEVANCE_MODULE_NAME,\n dir: relevanceModuleDir,\n onChanged: resetRelevanceProviderCache,\n};\n\nexport function moduleInstalled(): { installed: boolean; version?: string } {\n return moduleInstalledAt(relevanceModuleDir());\n}\n\n/** The one-line disclosure shown before/at install. Public copy — keep plain. */\nexport const DISCLOSURE =\n 'vg can install the optional Vibgrate relevance module (proprietary license, runs fully locally, ' +\n 'improves how questions find the code they mean). Disable any time with VIBGRATE_NO_KERNEL=1.';\n\n/**\n * Fetch, verify, and unpack the module into the modules cache dir. The\n * loadable surface is the tarball's `package/dist/*` mapped to the module\n * root (so `<dir>/index.js` is the seam's entrypoint), plus LICENSE/README.\n */\nexport async function installRelevanceModule(opts: InstallOptions = {}): Promise<InstallResult> {\n return installModule(RELEVANCE_MODULE, opts);\n}\n\nexport function removeRelevanceModule(): void {\n removeModule(RELEVANCE_MODULE);\n}\n\n/**\n * Auto-provision hook for `vg code` startup — fully SILENT by design\n * (maintainer decision, 2026-08): the module installs automatically with no\n * prompt and no notice; if the install or the module itself fails for any\n * reason the run simply proceeds without it, exactly as if it were never\n * there. Fast no-op when already installed. Two opt-outs still always win:\n * `VIBGRATE_NO_KERNEL=1`, and an explicit decline recorded via\n * `vg module install relevance` answering \"no\" (or `vg module remove`\n * followed by a recorded denial). Never throws, never blocks a run on\n * anything but the (bounded) fetch itself.\n */\n/**\n * Oldest module version whose provider carries the `rankSymbols` ranking API\n * (the 2026-08 relevance relocation). An older install still loads for\n * analyze/tagNode, but the seam treats it as \"no ranking engine\", so the\n * ensure path force-upgrades it in place.\n */\nexport const RANKING_MIN_MODULE_VERSION = '2026.823.0';\n\n/** Dotted-numeric version compare (module versions are `YYYY.MDD.N`). */\nfunction versionAtLeast(version: string | undefined, min: string): boolean {\n if (!version) return false;\n const a = version.split('.').map((n) => Number(n));\n const b = min.split('.').map((n) => Number(n));\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const x = a[i] ?? 0;\n const y = b[i] ?? 0;\n if (!Number.isFinite(x)) return false;\n if (x !== y) return x > y;\n }\n return true;\n}\n\nexport async function ensureRelevanceModule(io: { fetchImpl?: typeof fetch } = {}): Promise<InstallResult> {\n try {\n if (kernelDisabled()) return { status: 'disabled' };\n if (readConsent().relevance === 'denied') return { status: 'declined' };\n const existing = moduleInstalled();\n if (existing.installed) {\n // Pre-ranking installs upgrade in place — since the relocation, the\n // module IS the relevance engine, so an old version is as good as none.\n if (versionAtLeast(existing.version, RANKING_MIN_MODULE_VERSION)) {\n return { status: 'already-installed', version: existing.version };\n }\n return await installRelevanceModule({ fetchImpl: io.fetchImpl, force: true });\n }\n return await installRelevanceModule({ fetchImpl: io.fetchImpl });\n } catch {\n return { status: 'unavailable', detail: 'auto-install failed' };\n }\n}\n\n/** Stamp file throttling background readiness attempts (offline machines must\n * not pay a fetch on every `vg` invocation). Lives beside the module dir. */\nconst READINESS_THROTTLE_MS = 60 * 60 * 1000;\n\n/**\n * Fire-and-forget readiness kick, called on EVERY `vg` invocation (cli.ts):\n * when the module is missing (or predates the ranking API) and no attempt was\n * made within the last hour, start a silent background install and return\n * immediately — the command never waits on it. `vg ask` / `vg code` still\n * run their own bounded `ensureRelevanceModule()` retry at use time, so a\n * fresh machine gets the module on the first ask even if this kick's install\n * has not finished. Failures are invisible by design: the run proceeds on\n * the mechanical fallback exactly as if the module never existed.\n */\nexport function kickRelevanceReadiness(io: { fetchImpl?: typeof fetch } = {}): void {\n try {\n if (kernelDisabled()) return;\n if (readConsent().relevance === 'denied') return;\n const existing = moduleInstalled();\n if (existing.installed && versionAtLeast(existing.version, RANKING_MIN_MODULE_VERSION)) return;\n const modulesRoot = path.dirname(relevanceModuleDir());\n const stamp = path.join(modulesRoot, 'relevance.last-attempt');\n try {\n const at = Number(fs.readFileSync(stamp, 'utf8'));\n if (Number.isFinite(at) && Date.now() - at < READINESS_THROTTLE_MS) return;\n } catch {\n /* no stamp yet — attempt */\n }\n try {\n fs.mkdirSync(modulesRoot, { recursive: true });\n fs.writeFileSync(stamp, String(Date.now()));\n } catch {\n /* unwritable cache dir — skip quietly */\n }\n void ensureRelevanceModule(io).catch(() => {});\n } catch {\n /* readiness must never affect the command */\n }\n}\n","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 { attachVgd, type AttachOptions } from './attach.js';\nimport { vgdRequest } from './client.js';\nimport { formatSemanticProgress } from './semantic-status.js';\n\n/**\n * One way to ask the daemon for a semantic ranking, shared by every surface.\n *\n * `vg ask`, `vg serve` and `vg lsp` each grew their own copy of \"load the\n * embedder, embed the corpus, rank\" — and `engine/refresh-scheduler.ts` records\n * what that costs: the per-server copies diverged, and one of them blocked an\n * editor Ask for ninety seconds. This is the single implementation of the\n * daemon path so that cannot happen again.\n *\n * Long-lived callers (the MCP server, the language server) hold one of these\n * for the process: it attaches once, remembers the slot, and per request sends\n * only the question. Short-lived callers get the same behaviour with the attach\n * folded into the first call.\n *\n * Every failure resolves to `null`, never a throw. `null` means \"rank it\n * yourself\" — the in-process path each caller already has, which is also what\n * happens when no daemon is running at all.\n */\n\nexport interface DaemonRanking {\n ranked: Array<{ id: string; score: number }>;\n /** How many vectors the slot holds — for logging, not correctness. */\n vectors: number;\n model?: string;\n}\n\nexport interface SemanticProgress {\n state: string;\n vectors: number;\n pending?: number;\n nodeCount?: number;\n model?: string;\n /** One line for a live status spinner. */\n detail: string;\n}\n\nexport interface RankWaitOptions {\n /** Called whenever the slot's status is sampled during a wait. */\n onProgress?: (status: SemanticProgress) => void;\n /** How often to poll `embed-status` while the index is warming (default 300ms). */\n pollMs?: number;\n /** Give up waiting and return null (default 10 minutes). */\n timeoutMs?: number;\n now?: () => number;\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface SemanticSessionOptions extends Omit<AttachOptions, 'corpusHash'> {\n /** How long to wait before retrying after a failed attach (default 30s). */\n retryAfterMs?: number;\n now?: () => number;\n /** Injected (tests). */\n attach?: typeof attachVgd;\n request?: typeof vgdRequest;\n}\n\nexport class DaemonSemanticSession {\n private repositoryId: string | undefined;\n private gitRef: string | undefined;\n private socketPath: string | undefined;\n /** The map the daemon was last told about, so an unchanged one is not resent. */\n private publishedHash: string | undefined;\n /** Do not re-attach before this time — a down daemon must not cost every request. */\n private retryAfter = 0;\n private attaching: Promise<void> | null = null;\n\n private readonly root: string;\n private readonly options: SemanticSessionOptions;\n private readonly retryAfterMs: number;\n private readonly now: () => number;\n private readonly attachImpl: typeof attachVgd;\n private readonly requestImpl: typeof vgdRequest;\n\n constructor(root: string, options: SemanticSessionOptions = {}) {\n this.root = root;\n this.options = options;\n this.retryAfterMs = options.retryAfterMs ?? 30_000;\n this.now = options.now ?? ((): number => Date.now());\n this.attachImpl = options.attach ?? attachVgd;\n this.requestImpl = options.request ?? vgdRequest;\n }\n\n /** True once a slot is known — useful for a one-line status log. */\n get attached(): boolean {\n return !!this.repositoryId;\n }\n\n /**\n * Rank `question` against the daemon's index for this repo.\n * `corpusHash` is the caller's current map: when it differs from what the\n * daemon holds, the map is republished before ranking, so a locally\n * refreshed map never ranks against yesterday's vectors.\n */\n async rank(question: string, corpusHash?: string, wait?: RankWaitOptions): Promise<DaemonRanking | null> {\n await this.ensureAttached(corpusHash);\n if (!this.repositoryId) return null;\n try {\n const first = await this.requestRank(question);\n if (first.status === 'ranked') return first.ranking;\n if (first.status === 'empty') return null;\n // Index is warming (or an older daemon returned unavailable). Kick a\n // non-blocking build and poll status so the caller can show progress\n // instead of sitting on a silent socket for tens of seconds.\n await this.requestImpl(\n { op: 'embed-index', repositoryId: this.repositoryId, gitRef: this.gitRef, wait: false },\n { socketPath: this.socketPath },\n );\n const now = wait?.now ?? this.now;\n const sleep = wait?.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n const deadline = now() + (wait?.timeoutMs ?? 600_000);\n const pollMs = wait?.pollMs ?? 300;\n while (now() < deadline) {\n const progress = await this.readProgress(first);\n if (progress) wait?.onProgress?.(progress);\n if (progress && (progress.state === 'failed' || progress.state === 'unavailable')) return null;\n if (progress && (progress.state === 'ready' || progress.vectors > 0)) {\n const again = await this.requestRank(question);\n if (again.status === 'ranked') return again.ranking;\n if (again.status === 'empty') return null;\n }\n await sleep(pollMs);\n }\n return null;\n } catch {\n // The daemon went away mid-session (a restart, an upgrade). Forget the\n // slot so the next call re-attaches instead of retrying a dead socket.\n this.reset();\n return null;\n }\n }\n\n private async readProgress(hint?: RankAttempt): Promise<SemanticProgress | null> {\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'embed-status', repositoryId: this.repositoryId },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('semantic' in res)) {\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n const slots = res.semantic.slots ?? [];\n const slot =\n slots.find((s) => s.repositoryId === this.repositoryId && (!this.gitRef || s.gitRef === this.gitRef)) ??\n slots.find((s) => s.repositoryId === this.repositoryId) ??\n slots[0];\n if (!slot) {\n if (res.semantic.worker === 'unavailable') {\n return { state: 'unavailable', vectors: 0, detail: res.semantic.reason ?? 'semantic worker unavailable' };\n }\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n const view = {\n state: slot.state,\n vectors: slot.vectors,\n pending: slot.pending,\n nodeCount: slot.nodeCount,\n model: res.semantic.model,\n error: slot.error,\n };\n return { ...view, detail: formatSemanticProgress(view) };\n } catch {\n return hint && hint.status === 'warming' ? warmingProgress(hint) : null;\n }\n }\n\n private async requestRank(question: string): Promise<RankAttempt> {\n if (!this.repositoryId) return { status: 'unavailable' };\n const res = await this.requestImpl(\n { op: 'embed-rank', repositoryId: this.repositoryId, gitRef: this.gitRef, text: question },\n { socketPath: this.socketPath },\n );\n if (res.ok && 'ranked' in res) {\n if (res.ranked.length === 0) return { status: 'empty' };\n return { status: 'ranked', ranking: { ranked: res.ranked, vectors: res.vectors, model: res.model } };\n }\n if (!res.ok && res.code === 'semantic_warming') {\n return {\n status: 'warming',\n state: res.state,\n vectors: res.vectors ?? 0,\n pending: res.pending,\n nodeCount: res.nodeCount,\n };\n }\n return { status: 'unavailable' };\n }\n\n /**\n * The daemon's shared dependency context for this repo — the manifest digest\n * and the dependency records — computed once per daemon instead of once per\n * process. Null whenever the daemon cannot answer, so the caller falls back\n * to computing it locally.\n */\n async depContext(): Promise<{\n manifestHash: string;\n dependencies: Array<{ name: string; ecosystem: string; declared: string; installed?: string }>;\n } | null> {\n await this.ensureAttached();\n if (!this.repositoryId) return null;\n try {\n const res = await this.requestImpl(\n { op: 'dep-context', repositoryId: this.repositoryId },\n { socketPath: this.socketPath },\n );\n if (!res.ok || !('manifestHash' in res)) return null;\n return { manifestHash: res.manifestHash, dependencies: res.dependencies };\n } catch {\n this.reset();\n return null;\n }\n }\n\n private reset(): void {\n this.repositoryId = undefined;\n this.gitRef = undefined;\n this.publishedHash = undefined;\n this.retryAfter = this.now() + this.retryAfterMs;\n }\n\n /** Attach once; concurrent callers share the one attempt. */\n private ensureAttached(corpusHash?: string): Promise<void> {\n // Already attached and the map has not moved under us.\n if (this.repositoryId && (!corpusHash || corpusHash === this.publishedHash)) return Promise.resolve();\n if (this.now() < this.retryAfter) return Promise.resolve();\n if (this.attaching) return this.attaching;\n\n this.attaching = (async () => {\n const result = await this.attachImpl(this.root, { ...this.options, corpusHash });\n if (result.status === 'attached' && result.repositoryId) {\n this.repositoryId = result.repositoryId;\n this.gitRef = result.gitRef;\n this.socketPath = result.socketPath;\n this.publishedHash = corpusHash;\n } else {\n this.reset();\n }\n })().finally(() => {\n this.attaching = null;\n });\n return this.attaching;\n }\n}\n\ntype RankAttempt =\n | { status: 'ranked'; ranking: DaemonRanking }\n | { status: 'warming'; state?: string; vectors?: number; pending?: number; nodeCount?: number }\n | { status: 'unavailable' }\n | { status: 'empty' };\n\nfunction warmingProgress(hint: Extract<RankAttempt, { status: 'warming' }>): SemanticProgress {\n const view = {\n state: hint.state ?? 'building',\n vectors: hint.vectors ?? 0,\n pending: hint.pending,\n nodeCount: hint.nodeCount,\n };\n return { ...view, detail: formatSemanticProgress(view) };\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 { DaemonSemanticSession } from '../runtime/vgd/semantic-client.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 /** `--no-daemon`: never auto-start or use the local runtime. */\n daemon?: 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 /**\n * True while the daemon owns freshness for this workspace. Set only after\n * the daemon confirms a subscription, cleared the instant it drops — so the\n * failure mode is \"this process watches again\", never \"nobody watches\".\n */\n private daemonOwnsFreshness = false;\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 /**\n * Hand freshness to the daemon: stop probing on every call and stop watching.\n * The daemon pushes `slot-changed` and we reload from disk then.\n */\n deferFreshnessToDaemon(): void {\n this.daemonOwnsFreshness = true;\n this.stopWatching();\n }\n\n /** The daemon went away — resume owning freshness locally. */\n resumeLocalFreshness(): void {\n this.daemonOwnsFreshness = false;\n this.startWatching();\n }\n\n /** The daemon says the map moved; drop the cache so the next get() re-reads. */\n reloadFromDisk(): void {\n this.cachedMtimeMs = -1;\n this.pendingChanges.clear();\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 && !this.daemonOwnsFreshness) 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\n/**\n * Prefer the daemon's watcher to our own.\n *\n * Both notice the same edits and both drive the same incremental rebuild, so\n * running them together means two inotify registrations over one tree and two\n * rebuilds racing for one lock. The daemon wins when it is there: it is the\n * process that already holds the map and, unlike this one, is shared by every\n * other client on the machine.\n *\n * Standing down is conditional on the daemon *confirming* the subscription,\n * and reversed the instant that connection drops — a dead daemon degrades this\n * server to watching for itself, never to nothing watching at all.\n *\n * The confirmation has to be about *this* repository. The daemon only watches\n * a repo once it holds that repo's slot, so a subscription it acknowledges for\n * a workspace it has no map for would push nothing, forever — and this server\n * would have retired its own watcher to listen to silence. Publishing first is\n * what makes the acknowledgement mean something: it hands the daemon the map,\n * which is what starts its watcher, and answers with the repository id to\n * scope the subscription to.\n */\nasync function watchViaDaemonOrLocally(source: GraphSource, opts: ServeOptions): Promise<void> {\n if (opts.daemon === false) {\n source.startWatching();\n return;\n }\n try {\n const [{ publishGraphToVgd }, { subscribeToSlots }] = await Promise.all([\n import('../runtime/vgd/publish.js'),\n import('../runtime/vgd/slot-subscription.js'),\n ]);\n // Never starts a daemon; \"not-running\" simply means we watch locally.\n const published = await publishGraphToVgd(opts.root ?? source.root);\n if (published.status === 'published' || published.status === 'current') {\n const subscription = await subscribeToSlots({\n repositoryId: published.repositoryId,\n onChange: () => source.reloadFromDisk(),\n onDetach: () => source.resumeLocalFreshness(),\n });\n if (subscription.active) {\n source.deferFreshnessToDaemon();\n return;\n }\n }\n } catch {\n /* no daemon, or it cannot push — watch locally */\n }\n source.startWatching();\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 // One runtime session for the life of the server: attach once, then send only\n // the question per navigation call. Absent a daemon it stays null-returning\n // and every tool answers exactly as it does today.\n const semanticSession = local\n ? undefined\n : new DaemonSemanticSession(root, { disabled: opts.daemon === false });\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, {\n root,\n local,\n dedup,\n seen,\n graphPath: source.graphPath,\n semanticSession,\n });\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 const wantWatch = opts.refresh !== false && opts.watch !== false;\n if (wantWatch) await watchViaDaemonOrLocally(source, opts);\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
1
  import { redactSecrets, catalogForLanguage, sourceHasRoleNeedle } from './chunk-T7RSQ5WD.js';
2
2
  import { LANGUAGES, langById } from './chunk-6WRG7VDO.js';
3
3
  import { loadCache } from './chunk-MVPRPSXU.js';
4
- import { VERSION } from './chunk-KFLNWYZG.js';
4
+ import { VERSION } from './chunk-G3ACLBMG.js';
5
5
  import { hashString } from './chunk-JFGYT6BI.js';
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
@@ -1215,5 +1215,5 @@ function dedupeImports(imports) {
1215
1215
  }
1216
1216
 
1217
1217
  export { TOOLCHAIN_GRAMMARS, fileRolesFromParseCache, fileRolesFromParses, grammarSetVersion, grammarsSourceDir, parseSource, resetParser, resolveToolchainGrammar, resolvedGrammarFiles, setGrammarsOverride, toolchainGrammarSetVersion, toolchainParser };
1218
- //# sourceMappingURL=chunk-L3YEEJ6U.js.map
1219
- //# sourceMappingURL=chunk-L3YEEJ6U.js.map
1218
+ //# sourceMappingURL=chunk-6MIJLO5B.js.map
1219
+ //# sourceMappingURL=chunk-6MIJLO5B.js.map