@vibgrate/cli 2026.803.1 → 2026.803.4

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 (106) hide show
  1. package/dist/agent-WYBWUBCC.js +26 -0
  2. package/dist/{agent-HNV2VUCO.js.map → agent-WYBWUBCC.js.map} +1 -1
  3. package/dist/baseline-3HECX4Q6.js +9 -0
  4. package/dist/{baseline-6WTULHM5.js.map → baseline-3HECX4Q6.js.map} +1 -1
  5. package/dist/{chunk-FKFRASAB.js → chunk-23UPIFRU.js} +8 -8
  6. package/dist/{chunk-FKFRASAB.js.map → chunk-23UPIFRU.js.map} +1 -1
  7. package/dist/chunk-2A7XCANX.js +375 -0
  8. package/dist/chunk-2A7XCANX.js.map +1 -0
  9. package/dist/{chunk-AJ2KE3NT.js → chunk-4LGDQBYK.js} +14 -102
  10. package/dist/chunk-4LGDQBYK.js.map +1 -0
  11. package/dist/{chunk-B2KLJPFY.js → chunk-4ZMJKR74.js} +451 -22
  12. package/dist/chunk-4ZMJKR74.js.map +1 -0
  13. package/dist/{chunk-DIU3MXB3.js → chunk-537JBQVB.js} +4 -4
  14. package/dist/{chunk-DIU3MXB3.js.map → chunk-537JBQVB.js.map} +1 -1
  15. package/dist/{chunk-4HFSUIIN.js → chunk-5TS7N7J2.js} +59 -9
  16. package/dist/chunk-5TS7N7J2.js.map +1 -0
  17. package/dist/{chunk-BWMMR5XA.js → chunk-5WMFX7TY.js} +4 -4
  18. package/dist/{chunk-BWMMR5XA.js.map → chunk-5WMFX7TY.js.map} +1 -1
  19. package/dist/{chunk-SNKTD23L.js → chunk-66B4ZQA3.js} +9 -8
  20. package/dist/chunk-66B4ZQA3.js.map +1 -0
  21. package/dist/{chunk-536J6HUR.js → chunk-7BU7CWXC.js} +39 -12
  22. package/dist/chunk-7BU7CWXC.js.map +1 -0
  23. package/dist/{chunk-N4IDP2M2.js → chunk-7TOIESUT.js} +5 -4
  24. package/dist/chunk-7TOIESUT.js.map +1 -0
  25. package/dist/{chunk-CE45STY5.js → chunk-BRUMBQV7.js} +4 -4
  26. package/dist/{chunk-CE45STY5.js.map → chunk-BRUMBQV7.js.map} +1 -1
  27. package/dist/{chunk-CC6F75GI.js → chunk-BUCNKYTW.js} +5 -5
  28. package/dist/{chunk-CC6F75GI.js.map → chunk-BUCNKYTW.js.map} +1 -1
  29. package/dist/{chunk-2TLQDF6C.js → chunk-FAA7RBIG.js} +9 -9
  30. package/dist/{chunk-2TLQDF6C.js.map → chunk-FAA7RBIG.js.map} +1 -1
  31. package/dist/chunk-FZ5Y4KEI.js +6 -0
  32. package/dist/{chunk-QT2PMGN3.js.map → chunk-FZ5Y4KEI.js.map} +1 -1
  33. package/dist/{chunk-S4NSF5AZ.js → chunk-HBQC4XQJ.js} +6 -6
  34. package/dist/{chunk-S4NSF5AZ.js.map → chunk-HBQC4XQJ.js.map} +1 -1
  35. package/dist/{chunk-O7MTBC52.js → chunk-HVHCXM2E.js} +9 -9
  36. package/dist/{chunk-O7MTBC52.js.map → chunk-HVHCXM2E.js.map} +1 -1
  37. package/dist/{chunk-NJFQCDGA.js → chunk-INIULQEP.js} +3 -3
  38. package/dist/{chunk-NJFQCDGA.js.map → chunk-INIULQEP.js.map} +1 -1
  39. package/dist/{chunk-Y7YKUZ3T.js → chunk-JZGVUH57.js} +30 -10
  40. package/dist/chunk-JZGVUH57.js.map +1 -0
  41. package/dist/{chunk-JUSXLCSE.js → chunk-KFK7KCAH.js} +3 -3
  42. package/dist/{chunk-JUSXLCSE.js.map → chunk-KFK7KCAH.js.map} +1 -1
  43. package/dist/{chunk-6I4TXAI6.js → chunk-OVDL76LB.js} +3 -3
  44. package/dist/{chunk-6I4TXAI6.js.map → chunk-OVDL76LB.js.map} +1 -1
  45. package/dist/{chunk-SJFBXCII.js → chunk-QUI3E3TQ.js} +54 -9
  46. package/dist/chunk-QUI3E3TQ.js.map +1 -0
  47. package/dist/chunk-RBMKBYGV.js +102 -0
  48. package/dist/chunk-RBMKBYGV.js.map +1 -0
  49. package/dist/{chunk-5VH3Y4QC.js → chunk-TVRM57CE.js} +78 -381
  50. package/dist/chunk-TVRM57CE.js.map +1 -0
  51. package/dist/{chunk-BBFQZ7CA.js → chunk-UWVFLVZX.js} +4 -4
  52. package/dist/{chunk-BBFQZ7CA.js.map → chunk-UWVFLVZX.js.map} +1 -1
  53. package/dist/{chunk-6JP7HGIF.js → chunk-Y4JO6LYP.js} +3 -3
  54. package/dist/{chunk-6JP7HGIF.js.map → chunk-Y4JO6LYP.js.map} +1 -1
  55. package/dist/cli.js +555 -351
  56. package/dist/cli.js.map +1 -1
  57. package/dist/embed-worker-main.d.ts +2 -0
  58. package/dist/embed-worker-main.js +64 -0
  59. package/dist/embed-worker-main.js.map +1 -0
  60. package/dist/ensure-map-DZ53QXRT.js +31 -0
  61. package/dist/{ensure-map-5YEI7R7V.js.map → ensure-map-DZ53QXRT.js.map} +1 -1
  62. package/dist/graph-backend-3A2M22QN.js +13 -0
  63. package/dist/{graph-backend-CPHLUKUC.js.map → graph-backend-3A2M22QN.js.map} +1 -1
  64. package/dist/index.d.ts +27 -2
  65. package/dist/index.js +16 -14
  66. package/dist/index.js.map +1 -1
  67. package/dist/{interactive-TNRE4OEK.js → interactive-DB7IC3BL.js} +35 -29
  68. package/dist/interactive-DB7IC3BL.js.map +1 -0
  69. package/dist/load-6KVGUQMU.js +11 -0
  70. package/dist/{load-MWG6WZTK.js.map → load-6KVGUQMU.js.map} +1 -1
  71. package/dist/{run-outcome-375HMSQG.js → run-outcome-YOYRC32U.js} +7 -6
  72. package/dist/run-outcome-YOYRC32U.js.map +1 -0
  73. package/dist/runtime-session-XEP7IPGP.js +22 -0
  74. package/dist/{runtime-session-3MPWXNRL.js.map → runtime-session-XEP7IPGP.js.map} +1 -1
  75. package/dist/session-5WKEACIF.js +17 -0
  76. package/dist/{session-2NGJLI5Y.js.map → session-5WKEACIF.js.map} +1 -1
  77. package/dist/{stream-json-AUMU3NLV.js → stream-json-3OJCPBWY.js} +13 -11
  78. package/dist/stream-json-3OJCPBWY.js.map +1 -0
  79. package/dist/{vg-mcp-bridge-D463EHQI.js → vg-mcp-bridge-PM3C4FQL.js} +12 -10
  80. package/dist/vg-mcp-bridge-PM3C4FQL.js.map +1 -0
  81. package/dist/{vgd-Z23PXSP4.js → vgd-UTLMMPIZ.js} +12 -10
  82. package/dist/vgd-UTLMMPIZ.js.map +1 -0
  83. package/package.json +1 -1
  84. package/scripts/postinstall.mjs +22 -1
  85. package/dist/agent-HNV2VUCO.js +0 -24
  86. package/dist/baseline-6WTULHM5.js +0 -9
  87. package/dist/chunk-4HFSUIIN.js.map +0 -1
  88. package/dist/chunk-536J6HUR.js.map +0 -1
  89. package/dist/chunk-5VH3Y4QC.js.map +0 -1
  90. package/dist/chunk-AJ2KE3NT.js.map +0 -1
  91. package/dist/chunk-B2KLJPFY.js.map +0 -1
  92. package/dist/chunk-N4IDP2M2.js.map +0 -1
  93. package/dist/chunk-QT2PMGN3.js +0 -6
  94. package/dist/chunk-SJFBXCII.js.map +0 -1
  95. package/dist/chunk-SNKTD23L.js.map +0 -1
  96. package/dist/chunk-Y7YKUZ3T.js.map +0 -1
  97. package/dist/ensure-map-5YEI7R7V.js +0 -29
  98. package/dist/graph-backend-CPHLUKUC.js +0 -11
  99. package/dist/interactive-TNRE4OEK.js.map +0 -1
  100. package/dist/load-MWG6WZTK.js +0 -10
  101. package/dist/run-outcome-375HMSQG.js.map +0 -1
  102. package/dist/runtime-session-3MPWXNRL.js +0 -20
  103. package/dist/session-2NGJLI5Y.js +0 -15
  104. package/dist/stream-json-AUMU3NLV.js.map +0 -1
  105. package/dist/vg-mcp-bridge-D463EHQI.js.map +0 -1
  106. package/dist/vgd-Z23PXSP4.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/runtime/vgd/protocol.ts","../src/runtime/active-graph-cache.ts","../src/runtime/vgd/registry.ts","../src/runtime/vgd/host-broker.ts","../src/runtime/vgd/embed-broker.ts","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AAK,KAAA,CAAM,GAAA,CAAI,IAAA,CAAK,YAAA,EAAc,QAAQ,KAAK,CAAA;AAC/C,MAAA,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,IAAA,CAAK,YAAA,EAAc,MAAM,CAAA;AAAA,IAC7C;AACA,IAAA,OAAO;AAAA,MACL,KAAA;AAAA,MACA,MAAA;AAAA,MACA,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,QAAA;AAAA,MACA,SAAA,EAAW,KAAA;AAAA,MACX,cAAc,IAAA,CAAK;AAAA,KACrB;AAAA,EACF;AAAA;AAAA,EAGA,SAAA,GAAY;AACV,IAAA,OAAO,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,IAAA,CAAK,YAAY,CAAA;AAAA,EAC1C;AACF","file":"chunk-4ZMJKR74.js","sourcesContent":["/**\n * Wire protocol for the lightweight Vibgrate daemon (`vgd`) — Fusion Runtime Phase 2 prototype.\n *\n * Line-delimited JSON over a local Unix domain socket (named pipe on Windows).\n * No credentials leave this process; the socket is local-only.\n */\n\nexport const VGD_PROTOCOL_VERSION = 'vgd/0' as const;\n\nexport interface WorkspaceRecord {\n /** Stable repository id (same as global store key). */\n id: string;\n /** Absolute repository root. */\n root: string;\n /** Absolute path to the current graph snapshot (may not exist yet). */\n graphPath: string;\n /** ISO timestamp when this workspace was last registered / refreshed. */\n registeredAt: string;\n /** Optional federation label. */\n label?: string;\n /** Optional federation role. */\n role?: 'primary' | 'member';\n /** Git branch or detached SHA at registration (multi-branch ActiveGraph). */\n gitRef?: string;\n}\n\n/** Lightweight ActiveGraph slot summary (no full graph payload). */\nexport interface GraphSlotSummary {\n repositoryId: string;\n gitRef: string;\n loadedAt: number;\n lastAccessAt: number;\n nodeCount: number;\n current: boolean;\n idleMs: number;\n evictable: boolean;\n}\n\nexport type VgdRequest =\n | { op: 'ping' }\n | { op: 'status' }\n /** Ask the daemon to exit cleanly (honoured only by a standalone `vg daemon start`). */\n | { op: 'shutdown' }\n | { op: 'list' }\n | { op: 'register'; root: string; label?: string; role?: 'primary' | 'member' }\n | { op: 'unregister'; root: string }\n | {\n op: 'register-federation';\n primaryRoot: string;\n members: Array<{ root: string; label?: string; role?: 'primary' | 'member' }>;\n }\n | { op: 'list-graph-slots'; repositoryId?: string }\n | { op: 'select-git-ref'; repositoryId: string; gitRef: string }\n | { op: 'put-graph'; repositoryId: string; gitRef: string; graph: unknown }\n /**\n * Load the workspace's on-disk code map into ActiveGraph inside the daemon\n * (binary snapshot first, JSON fallback). The fast-path alternative to\n * shipping the whole graph over the socket with put-graph — use it whenever\n * the map already exists on disk.\n */\n | { op: 'load-graph'; root: string; gitRef?: string; graphPath?: string }\n /** Lexical/structural query against the ActiveGraph for a repository. */\n | { op: 'query-graph'; repositoryId: string; query: string; limit?: number; gitRef?: string }\n /** Blast-radius impact for a symbol id or qualified name. */\n | { op: 'impact-of'; repositoryId: string; symbol: string; depth?: number; gitRef?: string }\n /** Compact graph meta for the current (or named) slot — not the full graph. */\n | { op: 'graph-summary'; repositoryId: string; gitRef?: string }\n /** Semantic warm (docs/VGD-SEMANTIC-WARM-SPEC.md): worker + per-slot index state. */\n | { op: 'embed-status'; repositoryId?: string }\n /** Embed one string in the daemon's warm worker; the caller ranks locally. */\n | { op: 'embed-query'; text: string }\n /** Ensure the slot's vector index exists, building it if needed. */\n | { op: 'embed-index'; repositoryId: string; gitRef?: string }\n /** Approach B host broker: warm model status inside vgd. */\n | { op: 'host-status' }\n | { op: 'host-load'; modelPath: string }\n | { op: 'host-unload'; modelPath?: string }\n | {\n op: 'host-generate';\n modelPath: string;\n messages: Array<{ role: string; content: string }>;\n grammar?: string;\n requireGrammar?: boolean;\n maxTokens?: number;\n temperature?: number;\n };\n\n/** Semantic warm state: the worker, and one row per resident slot index. */\nexport interface EmbedStatusPayload {\n worker: 'stopped' | 'starting' | 'ready' | 'unavailable';\n pid?: number;\n model?: string;\n crashes: number;\n reason?: string;\n slots: Array<{\n repositoryId: string;\n gitRef: string;\n state: string;\n vectors: number;\n nodeCount: number;\n builtAt?: number;\n buildMs?: number;\n error?: string;\n }>;\n}\n\n/** Compact match row for query-graph (no full node payloads). */\nexport interface VgdQueryMatch {\n id: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n score: number;\n why: string;\n}\n\nexport interface VgdImpactItem {\n id: string;\n name: string;\n kind: string;\n file: string;\n line: number;\n depth: number;\n confidence: number;\n}\n\nexport type VgdResponse =\n | { ok: true; pong: true; version: typeof VGD_PROTOCOL_VERSION }\n | {\n ok: true;\n pid: number;\n uptimeMs: number;\n workspaces: number;\n /** Resident multi-branch ActiveGraph slots (Fusion §4.1.1). */\n graphSlots?: number;\n version: typeof VGD_PROTOCOL_VERSION;\n socketPath: string;\n }\n | { ok: true; workspaces: WorkspaceRecord[] }\n | { ok: true; workspace: WorkspaceRecord }\n | { ok: true; workspaces: WorkspaceRecord[]; federation: true }\n | { ok: true; removed: boolean }\n | { ok: true; stopping: true }\n | { ok: true; slots: GraphSlotSummary[] }\n | { ok: true; semantic: EmbedStatusPayload }\n | { ok: true; vector: number[]; model?: string }\n | {\n ok: true;\n indexed: true;\n repositoryId: string;\n gitRef: string;\n state: string;\n vectors: number;\n buildMs?: number;\n }\n | { ok: true; selected: true; repositoryId: string; gitRef: string }\n | { ok: true; stored: true; repositoryId: string; gitRef: string; nodeCount: number }\n | {\n ok: true;\n query: string;\n repositoryId: string;\n gitRef: string;\n matches: VgdQueryMatch[];\n tokensEstimate: number;\n }\n | {\n ok: true;\n repositoryId: string;\n gitRef: string;\n symbol: string;\n root: { id: string; name: string };\n depth: number;\n affected: VgdImpactItem[];\n direct: number;\n transitive: number;\n }\n | {\n ok: true;\n repositoryId: string;\n gitRef: string;\n summary: {\n nodeCount: number;\n edgeCount: number;\n languages: string[];\n corpusHash: string | null;\n root: string | null;\n };\n }\n | {\n ok: true;\n host: {\n poolSize: number;\n loadedModels: string[];\n bindingReady: boolean;\n };\n }\n | { ok: true; hostLoaded: true; modelPath: string }\n | { ok: true; hostUnloaded: true; cleared: number }\n | {\n ok: true;\n hostGenerated: true;\n text: string;\n model: string;\n constrained: boolean;\n grammarApplied?: boolean;\n draftAcceptedChars?: number;\n latencyMs?: number;\n unknownIdentifiers?: string[];\n }\n | { ok: false; error: string; code?: string };\n\nexport function parseRequest(line: string): VgdRequest | { error: string } {\n let raw: unknown;\n try {\n raw = JSON.parse(line);\n } catch {\n return { error: 'invalid JSON' };\n }\n if (!raw || typeof raw !== 'object') return { error: 'request must be an object' };\n const op = (raw as { op?: unknown }).op;\n if (op === 'ping' || op === 'status' || op === 'shutdown' || op === 'list') return { op };\n if (op === 'list-graph-slots') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n return {\n op: 'list-graph-slots',\n repositoryId: typeof repositoryId === 'string' && repositoryId.trim() ? repositoryId.trim() : undefined,\n };\n }\n if (op === 'select-git-ref') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'select-git-ref requires repositoryId' };\n if (typeof gitRef !== 'string' || !gitRef.trim()) return { error: 'select-git-ref requires gitRef' };\n return { op: 'select-git-ref', repositoryId: repositoryId.trim(), gitRef: gitRef.trim() };\n }\n if (op === 'put-graph') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n const graph = (raw as { graph?: unknown }).graph;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'put-graph requires repositoryId' };\n if (typeof gitRef !== 'string' || !gitRef.trim()) return { error: 'put-graph requires gitRef' };\n if (!graph || typeof graph !== 'object') return { error: 'put-graph requires graph object' };\n return { op: 'put-graph', repositoryId: repositoryId.trim(), gitRef: gitRef.trim(), graph };\n }\n if (op === 'load-graph') {\n const root = (raw as { root?: unknown }).root;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n const graphPath = (raw as { graphPath?: unknown }).graphPath;\n if (typeof root !== 'string' || !root.trim()) return { error: 'load-graph requires a non-empty root' };\n return {\n op: 'load-graph',\n root: root.trim(),\n gitRef: typeof gitRef === 'string' && gitRef.trim() ? gitRef.trim() : undefined,\n graphPath: typeof graphPath === 'string' && graphPath.trim() ? graphPath.trim() : undefined,\n };\n }\n if (op === 'embed-status') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n return {\n op: 'embed-status',\n repositoryId: typeof repositoryId === 'string' && repositoryId.trim() ? repositoryId.trim() : undefined,\n };\n }\n if (op === 'embed-query') {\n const text = (raw as { text?: unknown }).text;\n if (typeof text !== 'string' || !text.trim()) return { error: 'embed-query requires text' };\n // Socket input is untrusted like every other op's; bound it so one caller\n // cannot make the worker chew on an arbitrarily large string.\n return { op: 'embed-query', text: text.trim().slice(0, 8_000) };\n }\n if (op === 'embed-index') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'embed-index requires repositoryId' };\n return {\n op: 'embed-index',\n repositoryId: repositoryId.trim(),\n gitRef: typeof gitRef === 'string' && gitRef.trim() ? gitRef.trim() : undefined,\n };\n }\n if (op === 'query-graph') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const query = (raw as { query?: unknown }).query;\n const limit = (raw as { limit?: unknown }).limit;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'query-graph requires repositoryId' };\n if (typeof query !== 'string' || !query.trim()) return { error: 'query-graph requires query' };\n return {\n op: 'query-graph',\n repositoryId: repositoryId.trim(),\n query: query.trim(),\n limit: typeof limit === 'number' && limit > 0 ? Math.min(Math.floor(limit), 50) : undefined,\n gitRef: typeof gitRef === 'string' && gitRef.trim() ? gitRef.trim() : undefined,\n };\n }\n if (op === 'impact-of') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const symbol = (raw as { symbol?: unknown }).symbol;\n const depth = (raw as { depth?: unknown }).depth;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'impact-of requires repositoryId' };\n if (typeof symbol !== 'string' || !symbol.trim()) return { error: 'impact-of requires symbol' };\n return {\n op: 'impact-of',\n repositoryId: repositoryId.trim(),\n symbol: symbol.trim(),\n depth: typeof depth === 'number' && depth > 0 ? Math.min(Math.floor(depth), 12) : undefined,\n gitRef: typeof gitRef === 'string' && gitRef.trim() ? gitRef.trim() : undefined,\n };\n }\n if (op === 'graph-summary') {\n const repositoryId = (raw as { repositoryId?: unknown }).repositoryId;\n const gitRef = (raw as { gitRef?: unknown }).gitRef;\n if (typeof repositoryId !== 'string' || !repositoryId.trim()) return { error: 'graph-summary requires repositoryId' };\n return {\n op: 'graph-summary',\n repositoryId: repositoryId.trim(),\n gitRef: typeof gitRef === 'string' && gitRef.trim() ? gitRef.trim() : undefined,\n };\n }\n if (op === 'register' || op === 'unregister') {\n const root = (raw as { root?: unknown }).root;\n if (typeof root !== 'string' || !root.trim()) return { error: `${op} requires a non-empty root` };\n const label = (raw as { label?: unknown }).label;\n const role = (raw as { role?: unknown }).role;\n if (op === 'register') {\n return {\n op: 'register',\n root: root.trim(),\n label: typeof label === 'string' ? label : undefined,\n role: role === 'primary' || role === 'member' ? role : undefined,\n };\n }\n return { op: 'unregister', root: root.trim() };\n }\n if (op === 'register-federation') {\n const primaryRoot = (raw as { primaryRoot?: unknown }).primaryRoot;\n const members = (raw as { members?: unknown }).members;\n if (typeof primaryRoot !== 'string' || !primaryRoot.trim()) return { error: 'register-federation requires primaryRoot' };\n if (!Array.isArray(members) || members.length === 0) return { error: 'register-federation requires members[]' };\n const parsed: Array<{ root: string; label?: string; role?: 'primary' | 'member' }> = [];\n for (const m of members) {\n if (!m || typeof m !== 'object') continue;\n const root = (m as { root?: unknown }).root;\n if (typeof root !== 'string' || !root.trim()) continue;\n const label = (m as { label?: unknown }).label;\n const role = (m as { role?: unknown }).role;\n parsed.push({\n root: root.trim(),\n label: typeof label === 'string' ? label : undefined,\n role: role === 'primary' || role === 'member' ? role : undefined,\n });\n }\n if (!parsed.length) return { error: 'register-federation members must include at least one root' };\n return { op: 'register-federation', primaryRoot: primaryRoot.trim(), members: parsed };\n }\n if (op === 'host-status') return { op: 'host-status' };\n if (op === 'host-load') {\n const modelPath = (raw as { modelPath?: unknown }).modelPath;\n if (typeof modelPath !== 'string' || !modelPath.trim()) return { error: 'host-load requires modelPath' };\n return { op: 'host-load', modelPath: modelPath.trim() };\n }\n if (op === 'host-unload') {\n const modelPath = (raw as { modelPath?: unknown }).modelPath;\n return {\n op: 'host-unload',\n modelPath: typeof modelPath === 'string' && modelPath.trim() ? modelPath.trim() : undefined,\n };\n }\n if (op === 'host-generate') {\n const modelPath = (raw as { modelPath?: unknown }).modelPath;\n const messages = (raw as { messages?: unknown }).messages;\n if (typeof modelPath !== 'string' || !modelPath.trim()) return { error: 'host-generate requires modelPath' };\n if (!Array.isArray(messages) || messages.length === 0) return { error: 'host-generate requires messages[]' };\n const parsed: Array<{ role: string; content: string }> = [];\n for (const m of messages) {\n if (!m || typeof m !== 'object') continue;\n const role = (m as { role?: unknown }).role;\n const content = (m as { content?: unknown }).content;\n if (typeof role !== 'string' || typeof content !== 'string') continue;\n parsed.push({ role, content });\n }\n if (!parsed.length) return { error: 'host-generate messages must include role+content' };\n const grammar = (raw as { grammar?: unknown }).grammar;\n const requireGrammar = (raw as { requireGrammar?: unknown }).requireGrammar;\n const maxTokens = (raw as { maxTokens?: unknown }).maxTokens;\n const temperature = (raw as { temperature?: unknown }).temperature;\n return {\n op: 'host-generate',\n modelPath: modelPath.trim(),\n messages: parsed,\n grammar: typeof grammar === 'string' ? grammar : undefined,\n requireGrammar: requireGrammar === true,\n maxTokens: typeof maxTokens === 'number' ? maxTokens : undefined,\n temperature: typeof temperature === 'number' ? temperature : undefined,\n };\n }\n return { error: `unknown op: ${String(op)}` };\n}\n","/**\n * Multi-branch ActiveGraph cache (Fusion plan §4.1.1).\n *\n * Holds several in-memory graphs for the same repository — one per gitRef\n * (branch or detached SHA). Memory management: after an idle timeout, slots\n * become evictable; among idle slots, LILO (last-in, last-out ≡ FIFO by\n * load order) reclaims the oldest-loaded idle graph first. The currently\n * selected slot for a repository is never evicted.\n */\n\nimport type { VgGraph } from '../schema.js';\nimport { activeGraphSlotKey } from './git-ref.js';\n\n/** Default idle timeout: 20 minutes (within the 15–30 min plan band). */\nexport const DEFAULT_ACTIVE_GRAPH_IDLE_MS = 20 * 60 * 1000;\n\nexport interface ActiveGraphSlot {\n repositoryId: string;\n gitRef: string;\n graph: VgGraph;\n /** When this slot was first loaded into the cache. */\n loadedAt: number;\n /** Last access / select time. */\n lastAccessAt: number;\n /** Approximate size hint for diagnostics (node count). */\n nodeCount: number;\n}\n\nexport interface ActiveGraphCacheOptions {\n /** Idle duration before a non-selected slot is evictable (default 20 min). */\n idleTimeoutMs?: number;\n /** Max resident graphs per repositoryId (default 8). */\n maxPerRepo?: number;\n /** Max resident graphs process-wide (default 32). */\n maxTotal?: number;\n now?: () => number;\n /**\n * Called for every slot leaving the cache, whatever removed it (idle\n * timeout, overflow, clear). Anything keyed by the same slot — the semantic\n * index in vgd — hangs off this so it can never outlive the graph it\n * describes. Must not throw; a listener error is swallowed rather than\n * corrupting eviction.\n */\n onEvict?: (slot: { repositoryId: string; gitRef: string }) => void;\n}\n\nexport interface ActiveGraphSlotSummary {\n repositoryId: string;\n gitRef: string;\n loadedAt: number;\n lastAccessAt: number;\n nodeCount: number;\n current: boolean;\n idleMs: number;\n evictable: boolean;\n}\n\n/**\n * In-memory multi-branch graph cache. Pure structure — does not load/save disk.\n */\nexport class ActiveGraphCache {\n private readonly slots = new Map<string, ActiveGraphSlot>();\n /** repositoryId → currently selected gitRef */\n private readonly currentRef = new Map<string, string>();\n private readonly idleTimeoutMs: number;\n private readonly maxPerRepo: number;\n private readonly maxTotal: number;\n private readonly now: () => number;\n private readonly onEvict?: (slot: { repositoryId: string; gitRef: string }) => void;\n\n constructor(options: ActiveGraphCacheOptions = {}) {\n this.onEvict = options.onEvict;\n this.idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_ACTIVE_GRAPH_IDLE_MS;\n this.maxPerRepo = options.maxPerRepo ?? 8;\n this.maxTotal = options.maxTotal ?? 32;\n this.now = options.now ?? (() => Date.now());\n }\n\n size(): number {\n return this.slots.size;\n }\n\n get(repositoryId: string, gitRef: string): ActiveGraphSlot | undefined {\n const slot = this.slots.get(activeGraphSlotKey(repositoryId, gitRef));\n if (slot) {\n slot.lastAccessAt = this.now();\n }\n return slot;\n }\n\n /**\n * Insert or replace a graph for (repositoryId, gitRef). Touches access time.\n * Runs eviction if over cap.\n */\n put(repositoryId: string, gitRef: string, graph: VgGraph): ActiveGraphSlot {\n const key = activeGraphSlotKey(repositoryId, gitRef);\n const t = this.now();\n const existing = this.slots.get(key);\n const slot: ActiveGraphSlot = {\n repositoryId,\n gitRef,\n graph,\n loadedAt: existing?.loadedAt ?? t,\n lastAccessAt: t,\n nodeCount: graph.nodes?.length ?? 0,\n };\n this.slots.set(key, slot);\n if (!this.currentRef.has(repositoryId)) {\n this.currentRef.set(repositoryId, gitRef);\n }\n this.evictIfNeeded();\n return slot;\n }\n\n /**\n * Mark gitRef as the current branch for this repository and touch it.\n * Returns the slot if present.\n */\n select(repositoryId: string, gitRef: string): ActiveGraphSlot | undefined {\n this.currentRef.set(repositoryId, gitRef);\n return this.get(repositoryId, gitRef);\n }\n\n /** Currently selected gitRef for a repository, if any. */\n selectedRef(repositoryId: string): string | undefined {\n return this.currentRef.get(repositoryId);\n }\n\n current(repositoryId: string): ActiveGraphSlot | undefined {\n const ref = this.currentRef.get(repositoryId);\n if (!ref) return undefined;\n return this.get(repositoryId, ref);\n }\n\n /**\n * Drop idle slots past the timeout (LILO among idle).\n * Returns keys of removed slots.\n */\n evictIdle(now: number = this.now()): string[] {\n return this.evict(now, false);\n }\n\n /** Force eviction of idle slots when over caps (timeout may be ignored for overflow). */\n evictIfNeeded(): string[] {\n return this.evict(this.now(), true);\n }\n\n list(repositoryId?: string): ActiveGraphSlotSummary[] {\n const t = this.now();\n const out: ActiveGraphSlotSummary[] = [];\n for (const slot of this.slots.values()) {\n if (repositoryId && slot.repositoryId !== repositoryId) continue;\n const current = this.currentRef.get(slot.repositoryId) === slot.gitRef;\n const idleMs = t - slot.lastAccessAt;\n out.push({\n repositoryId: slot.repositoryId,\n gitRef: slot.gitRef,\n loadedAt: slot.loadedAt,\n lastAccessAt: slot.lastAccessAt,\n nodeCount: slot.nodeCount,\n current,\n idleMs,\n evictable: !current && idleMs >= this.idleTimeoutMs,\n });\n }\n return out.sort(\n (a, b) => a.repositoryId.localeCompare(b.repositoryId) || a.gitRef.localeCompare(b.gitRef),\n );\n }\n\n clear(): void {\n for (const slot of this.slots.values()) this.notifyEvict(slot);\n this.slots.clear();\n this.currentRef.clear();\n }\n\n private notifyEvict(slot: { repositoryId: string; gitRef: string }): void {\n if (!this.onEvict) return;\n try {\n this.onEvict({ repositoryId: slot.repositoryId, gitRef: slot.gitRef });\n } catch {\n // A listener problem must never break cache maintenance.\n }\n }\n\n private evict(now: number, forceOverflow: boolean): string[] {\n const removed: string[] = [];\n\n const removeKey = (key: string): void => {\n const slot = this.slots.get(key);\n if (!slot) return;\n this.slots.delete(key);\n removed.push(key);\n this.notifyEvict(slot);\n };\n\n // 1) Idle timeout: LILO among idle (earliest loadedAt first).\n const idle = this.idleCandidates(now, this.idleTimeoutMs);\n idle.sort((a, b) => a.loadedAt - b.loadedAt);\n for (const slot of idle) {\n removeKey(activeGraphSlotKey(slot.repositoryId, slot.gitRef));\n }\n\n // 2) Overflow: if still over maxPerRepo or maxTotal, LILO among any non-current idle-or-all-non-current.\n if (forceOverflow) {\n while (this.slots.size > this.maxTotal) {\n const victim = this.pickLiloVictim(now, /* requireIdleTimeout */ false);\n if (!victim) break;\n removeKey(activeGraphSlotKey(victim.repositoryId, victim.gitRef));\n }\n // Per-repo caps\n const byRepo = new Map<string, ActiveGraphSlot[]>();\n for (const s of this.slots.values()) {\n const list = byRepo.get(s.repositoryId) ?? [];\n list.push(s);\n byRepo.set(s.repositoryId, list);\n }\n for (const [repoId, list] of byRepo) {\n if (list.length <= this.maxPerRepo) continue;\n const nonCurrent = list\n .filter((s) => this.currentRef.get(repoId) !== s.gitRef)\n .sort((a, b) => a.loadedAt - b.loadedAt);\n let excess = list.length - this.maxPerRepo;\n for (const s of nonCurrent) {\n if (excess <= 0) break;\n removeKey(activeGraphSlotKey(s.repositoryId, s.gitRef));\n excess--;\n }\n }\n }\n\n return removed;\n }\n\n private idleCandidates(now: number, timeoutMs: number): ActiveGraphSlot[] {\n const out: ActiveGraphSlot[] = [];\n for (const slot of this.slots.values()) {\n if (this.currentRef.get(slot.repositoryId) === slot.gitRef) continue;\n if (now - slot.lastAccessAt >= timeoutMs) out.push(slot);\n }\n return out;\n }\n\n private pickLiloVictim(now: number, requireIdleTimeout: boolean): ActiveGraphSlot | null {\n let best: ActiveGraphSlot | null = null;\n for (const slot of this.slots.values()) {\n if (this.currentRef.get(slot.repositoryId) === slot.gitRef) continue;\n if (requireIdleTimeout && now - slot.lastAccessAt < this.idleTimeoutMs) continue;\n if (!best || slot.loadedAt < best.loadedAt) best = slot;\n }\n return best;\n }\n}\n","import * as path from 'node:path';\nimport { repositoryIdFromRoot, globalGraphPathForRef, globalGraphPath } from '../paths.js';\nimport { detectGitRef } from '../git-ref.js';\nimport { ActiveGraphCache } from '../active-graph-cache.js';\nimport type { WorkspaceRecord } from './protocol.js';\nimport type { VgGraph } from '../../schema.js';\n\n/** Slot-scoped resource that must track the graph cache exactly. */\nexport interface GraphSlotListener {\n onGraphPut(repositoryId: string, gitRef: string, graph: VgGraph): void;\n onGraphSelect(repositoryId: string, gitRef: string): void;\n onGraphEvict(repositoryId: string, gitRef: string): void;\n}\n\n/**\n * In-memory workspace registry for the vgd prototype.\n *\n * Tracks which repository roots the daemon knows about and where their\n * graphs live. Holds a multi-branch {@link ActiveGraphCache} so several\n * git refs of the same repo can stay warm (Fusion §4.1.1).\n */\nexport class WorkspaceRegistry {\n private readonly byId = new Map<string, WorkspaceRecord>();\n /**\n * Anything keyed by the same (repositoryId, gitRef) slot as the graph — the\n * semantic index — attaches here. Wiring it through the registry rather than\n * the cache directly means every put/select/evict passes one funnel, so an\n * index can never describe a ref its graph no longer holds.\n */\n private slotListener?: GraphSlotListener;\n /** Multi-branch in-memory graphs (shared across registered workspaces). */\n readonly graphs = new ActiveGraphCache({\n onEvict: (slot) => this.slotListener?.onGraphEvict(slot.repositoryId, slot.gitRef),\n });\n\n /** Attach the semantic index (or any slot-scoped resource) to graph lifecycle. */\n setSlotListener(listener: GraphSlotListener | undefined): void {\n this.slotListener = listener;\n }\n\n register(\n root: string,\n now: () => Date = () => new Date(),\n meta: { label?: string; role?: 'primary' | 'member'; gitRef?: string } = {},\n ): WorkspaceRecord {\n const resolved = path.resolve(root);\n const id = repositoryIdFromRoot(resolved);\n const git = meta.gitRef ? { ref: meta.gitRef, kind: 'branch' as const } : detectGitRef(resolved);\n const graphPath =\n git.kind !== 'none' && git.ref ? globalGraphPathForRef(resolved, git.ref) : globalGraphPath(resolved);\n const record: WorkspaceRecord = {\n id,\n root: resolved,\n graphPath,\n registeredAt: now().toISOString(),\n label: meta.label,\n role: meta.role,\n gitRef: git.ref || undefined,\n };\n this.byId.set(id, record);\n if (git.ref) this.graphs.select(id, git.ref);\n return record;\n }\n\n /**\n * Activate or insert an in-memory graph for a workspace branch.\n * Call after load/build; runs LILO idle eviction as needed.\n */\n putGraph(repositoryId: string, gitRef: string, graph: VgGraph): void {\n this.graphs.put(repositoryId, gitRef, graph);\n this.graphs.select(repositoryId, gitRef);\n // Invalidate before anyone can query: the old vectors describe the old graph.\n this.slotListener?.onGraphPut(repositoryId, gitRef, graph);\n this.slotListener?.onGraphSelect(repositoryId, gitRef);\n }\n\n /** Switch the current branch slot for a repository (no load). */\n selectGitRef(repositoryId: string, gitRef: string): void {\n this.graphs.select(repositoryId, gitRef);\n this.slotListener?.onGraphSelect(repositoryId, gitRef);\n }\n\n /** Register every member of a federation (primary + members). */\n registerFederation(\n members: Array<{ root: string; label?: string; role?: 'primary' | 'member' }>,\n now: () => Date = () => new Date(),\n ): WorkspaceRecord[] {\n return members.map((m) => this.register(m.root, now, { label: m.label, role: m.role }));\n }\n\n unregister(root: string): boolean {\n const id = repositoryIdFromRoot(path.resolve(root));\n return this.byId.delete(id);\n }\n\n list(): WorkspaceRecord[] {\n return [...this.byId.values()].sort((a, b) => a.root.localeCompare(b.root));\n }\n\n get(root: string): WorkspaceRecord | undefined {\n return this.byId.get(repositoryIdFromRoot(path.resolve(root)));\n }\n\n /** Lookup by stable repository id. */\n getById(repositoryId: string): WorkspaceRecord | undefined {\n return this.byId.get(repositoryId);\n }\n\n size(): number {\n return this.byId.size;\n }\n\n /**\n * Resolve an ActiveGraph for query/impact: prefer the named gitRef, else the\n * selected current slot, else any warm slot for the repository.\n */\n resolveGraph(repositoryId: string, gitRef?: string): { graph: VgGraph; gitRef: string } | null {\n if (gitRef) {\n const slot = this.graphs.get(repositoryId, gitRef);\n if (slot) return { graph: slot.graph, gitRef: slot.gitRef };\n }\n const current = this.graphs.current(repositoryId);\n if (current) return { graph: current.graph, gitRef: current.gitRef };\n // Fall back to any warm slot for this repo (deterministic: earliest loaded).\n const any = this.graphs\n .list(repositoryId)\n .slice()\n .sort((a, b) => a.loadedAt - b.loadedAt)[0];\n if (any) {\n const slot = this.graphs.get(repositoryId, any.gitRef);\n if (slot) return { graph: slot.graph, gitRef: slot.gitRef };\n }\n return null;\n }\n}\n","/**\n * Model host broker inside vgd (Approach B / B4 + P4 multi-client).\n *\n * Long-lived daemon process can keep warm llama.cpp sessions so CLI and IDE\n * clients share one loaded model. Management (which pack/mode) stays in the\n * client/orchestrator; vgd only loads paths the client requests and generates.\n *\n * P4: clients acquire/release leases per model path so unload is refcounted\n * (one IDE + CLI can share a warm model without the first exit killing it).\n *\n * Binding is injected (never static node-llama-cpp import).\n */\n\nimport {\n acquireHostSession,\n clearHostSessionPool,\n dropHostSession,\n evictIdleSessions,\n generateOnSession,\n hostSessionPoolSize,\n listHostSessions,\n type HostGenerateReport,\n type HostSessionInfo,\n} from '../llm-host/session.js';\nimport type { LlmChatMessage, LlmGenerateOptions } from '../llm-host/types.js';\n\nexport interface HostBrokerStatus {\n poolSize: number;\n loadedModels: string[];\n bindingReady: boolean;\n /** Per-path client lease counts (P4). */\n leases: Record<string, number>;\n sessions: HostSessionInfo[];\n}\n\nexport interface HostClientLease {\n clientId: string;\n modelPath: string;\n}\n\nexport class VgdHostBroker {\n private binding: unknown | null = null;\n private readonly loaded = new Set<string>();\n /** modelPath → set of client ids holding a lease. */\n private readonly leases = new Map<string, Set<string>>();\n\n setBinding(lib: unknown | null): void {\n this.binding = lib;\n }\n\n hasBinding(): boolean {\n return this.binding != null;\n }\n\n status(): HostBrokerStatus {\n const leases: Record<string, number> = {};\n for (const [path, clients] of this.leases) {\n leases[path] = clients.size;\n }\n return {\n poolSize: hostSessionPoolSize(),\n loadedModels: [...this.loaded],\n bindingReady: this.binding != null,\n leases,\n sessions: listHostSessions(),\n };\n }\n\n /**\n * Load weights and optionally register a client lease (P4 multi-client).\n * When clientId is omitted, behaves like a one-shot load (no lease bookkeeping).\n */\n async load(\n modelPath: string,\n clientId?: string,\n ): Promise<{ ok: true; modelPath: string; leases: number } | { ok: false; error: string }> {\n if (!this.binding) {\n return { ok: false, error: 'host binding not configured — start vgd with llama runtime or attach binding' };\n }\n try {\n await acquireHostSession(this.binding, modelPath);\n this.loaded.add(modelPath);\n if (clientId) {\n let set = this.leases.get(modelPath);\n if (!set) {\n set = new Set();\n this.leases.set(modelPath, set);\n }\n set.add(clientId);\n }\n evictIdleSessions(4);\n return { ok: true, modelPath, leases: this.leases.get(modelPath)?.size ?? 0 };\n } catch (e) {\n return { ok: false, error: e instanceof Error ? e.message : String(e) };\n }\n }\n\n /**\n * Release a client lease. When the last lease is released, drop the warm\n * session for that path. Without clientId, clears all leases for the path\n * (or entire pool if modelPath omitted).\n */\n async unload(\n modelPath?: string,\n clientId?: string,\n ): Promise<{ ok: true; cleared: number; remainingLeases: number }> {\n if (!modelPath) {\n const n = hostSessionPoolSize();\n clearHostSessionPool();\n this.loaded.clear();\n this.leases.clear();\n return { ok: true, cleared: n, remainingLeases: 0 };\n }\n\n if (clientId) {\n const set = this.leases.get(modelPath);\n if (set) {\n set.delete(clientId);\n if (set.size === 0) this.leases.delete(modelPath);\n }\n const remaining = this.leases.get(modelPath)?.size ?? 0;\n if (remaining === 0) {\n const dropped = dropHostSession(modelPath) ? 1 : 0;\n this.loaded.delete(modelPath);\n return { ok: true, cleared: dropped, remainingLeases: 0 };\n }\n return { ok: true, cleared: 0, remainingLeases: remaining };\n }\n\n // No clientId: force drop path (all leases).\n this.leases.delete(modelPath);\n const dropped = dropHostSession(modelPath) ? 1 : 0;\n this.loaded.delete(modelPath);\n return { ok: true, cleared: dropped, remainingLeases: 0 };\n }\n\n /** How many clients hold a lease on modelPath. */\n leaseCount(modelPath: string): number {\n return this.leases.get(modelPath)?.size ?? 0;\n }\n\n async generate(\n modelPath: string,\n messages: LlmChatMessage[],\n opts?: LlmGenerateOptions,\n ): Promise<{ ok: true; result: HostGenerateReport } | { ok: false; error: string }> {\n if (!this.binding) {\n return { ok: false, error: 'host binding not configured' };\n }\n try {\n const session = await acquireHostSession(this.binding, modelPath);\n this.loaded.add(modelPath);\n const result = await generateOnSession(session, messages, {\n grammar: opts?.grammar,\n requireGrammar: opts?.requireGrammar,\n identifierTrie: opts?.identifierTrie,\n annotateUnknownIdentifiers: opts?.annotateUnknownIdentifiers,\n draftCandidates: opts?.draftCandidates,\n maxTokens: opts?.maxTokens,\n temperature: opts?.temperature,\n promptSegments: opts?.promptSegments,\n });\n return { ok: true, result };\n } catch (e) {\n return { ok: false, error: e instanceof Error ? e.message : String(e) };\n }\n }\n}\n\n/** Process-wide broker for the running vgd (tests may replace). */\nlet defaultBroker: VgdHostBroker | null = null;\n\nexport function getVgdHostBroker(): VgdHostBroker {\n if (!defaultBroker) defaultBroker = new VgdHostBroker();\n return defaultBroker;\n}\n\nexport function resetVgdHostBroker(): void {\n defaultBroker = null;\n clearHostSessionPool();\n}\n","/**\n * Semantic warm inside vgd (docs/VGD-SEMANTIC-WARM-SPEC.md).\n *\n * vgd already keeps the code map warm per repo-and-ref and local LLM weights\n * warm per path. The embedding model and the vector index were the gap: every\n * consumer — `vg lsp`, `vg code`, the CLI — loaded its own copy, so\n * `vg daemon status` could report a warm graph slot while the editor announced\n * \"warming semantic search\" on a fresh process, again.\n *\n * Two invariants shape everything here.\n *\n * **The addon lives in a child.** {@link EmbedBroker} never imports the\n * embedding backend; it talks NDJSON to `embed-worker.ts`. The backend can\n * abort its process (see `engine/embed-health.ts`) and no try/catch survives a\n * signal — so the worst case must be a dead worker vgd can restart, not a dead\n * daemon. A worker that dies repeatedly is given up on, and every caller falls\n * back to lexical exactly as it does when vgd is absent.\n *\n * **The index follows the graph slot.** Vectors are keyed by the same\n * `(repositoryId, gitRef)` slot key the graph uses, and the cache's eviction\n * hook drops them together. A branch switch selects a different index the same\n * moment it selects a different graph; a re-published graph invalidates the\n * vectors for exactly that slot and nothing else. Ranking against vectors that\n * belong to another ref would be a silent correctness bug, so the two are\n * never allowed to drift apart.\n */\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport * as fs from 'node:fs';\nimport { fileURLToPath } from 'node:url';\nimport * as path from 'node:path';\nimport { activeGraphSlotKey } from '../git-ref.js';\nimport type { VgGraph, GraphNode } from '../../schema.js';\n\n/** How a slot's index is doing — surfaced by `embed-status` and the daemon log. */\nexport type SlotIndexState = 'absent' | 'building' | 'ready' | 'stale' | 'failed';\n\nexport interface SlotIndex {\n repositoryId: string;\n gitRef: string;\n state: SlotIndexState;\n /** nodeId → vector. Empty until the first build completes. */\n vectors: Map<string, number[]>;\n nodeCount: number;\n builtAt?: number;\n buildMs?: number;\n error?: string;\n}\n\nexport interface SlotIndexSummary {\n repositoryId: string;\n gitRef: string;\n state: SlotIndexState;\n vectors: number;\n nodeCount: number;\n builtAt?: number;\n buildMs?: number;\n error?: string;\n}\n\nexport interface EmbedBrokerStatus {\n /** Worker process state. */\n worker: 'stopped' | 'starting' | 'ready' | 'unavailable';\n pid?: number;\n model?: string;\n /** Consecutive worker deaths; at the cap the broker stops restarting. */\n crashes: number;\n reason?: string;\n slots: SlotIndexSummary[];\n}\n\nexport type EmbedBrokerLog = (message: string) => void;\n\nexport interface EmbedBrokerOptions {\n /** Diagnostic sink — the daemon's log. */\n log?: EmbedBrokerLog;\n /** Injected worker spawn (tests). */\n spawnWorker?: () => ChildProcess;\n /** Consecutive crashes tolerated before the broker gives up (default 3). */\n maxCrashes?: number;\n /** Per-request timeout in ms (default 120s — a cold model load is slow). */\n requestTimeoutMs?: number;\n /** Documents per embed request (default 256). */\n batchSize?: number;\n now?: () => number;\n}\n\ninterface Pending {\n resolve: (vectors: number[][]) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\n\n/** The text an embedding represents for a node — mirrors the in-process indexer. */\nfunction nodeText(node: GraphNode): string {\n const parts = [node.qualifiedName || node.name, node.kind, node.file, node.doc]\n .filter((p): p is string => typeof p === 'string' && p.length > 0);\n return parts.join(' · ').slice(0, 512);\n}\n\nexport class EmbedBroker {\n private child: ChildProcess | null = null;\n private starting = false;\n private gaveUp = false;\n private crashes = 0;\n private reason: string | undefined;\n private model: string | undefined;\n private nextId = 1;\n private buffer = '';\n private readonly pending = new Map<number, Pending>();\n private readonly indexes = new Map<string, SlotIndex>();\n /** Slot keys with a build in flight, so warms are not duplicated. */\n private readonly building = new Set<string>();\n /** The slot most recently made current — logged on change. */\n private currentKey: string | undefined;\n private graphProvider?: (repositoryId: string, gitRef: string) => VgGraph | undefined;\n\n private readonly log: EmbedBrokerLog;\n private readonly spawnWorker: () => ChildProcess;\n private readonly maxCrashes: number;\n private readonly requestTimeoutMs: number;\n private readonly batchSize: number;\n private readonly now: () => number;\n\n constructor(options: EmbedBrokerOptions = {}) {\n this.log = options.log ?? ((): void => {});\n this.spawnWorker = options.spawnWorker ?? defaultSpawnWorker;\n this.maxCrashes = options.maxCrashes ?? 3;\n this.requestTimeoutMs = options.requestTimeoutMs ?? 120_000;\n this.batchSize = options.batchSize ?? 256;\n this.now = options.now ?? ((): number => Date.now());\n }\n\n status(): EmbedBrokerStatus {\n return {\n worker: this.gaveUp ? 'unavailable' : this.child ? 'ready' : this.starting ? 'starting' : 'stopped',\n pid: this.child?.pid,\n model: this.model,\n crashes: this.crashes,\n reason: this.reason,\n slots: this.listSlots(),\n };\n }\n\n listSlots(repositoryId?: string): SlotIndexSummary[] {\n const out: SlotIndexSummary[] = [];\n for (const idx of this.indexes.values()) {\n if (repositoryId && idx.repositoryId !== repositoryId) continue;\n out.push({\n repositoryId: idx.repositoryId,\n gitRef: idx.gitRef,\n state: idx.state,\n vectors: idx.vectors.size,\n nodeCount: idx.nodeCount,\n builtAt: idx.builtAt,\n buildMs: idx.buildMs,\n error: idx.error,\n });\n }\n return out.sort((a, b) => a.repositoryId.localeCompare(b.repositoryId) || a.gitRef.localeCompare(b.gitRef));\n }\n\n slot(repositoryId: string, gitRef: string): SlotIndex | undefined {\n return this.indexes.get(activeGraphSlotKey(repositoryId, gitRef));\n }\n\n /** True once the broker has stopped trying — callers should go lexical. */\n unavailable(): boolean {\n return this.gaveUp;\n }\n\n /**\n * A graph slot was published or replaced. The vectors for that slot no\n * longer describe its graph, so they are dropped and a rebuild is queued.\n * Called from the same funnel that stores the graph, so the two can never\n * disagree about which ref they belong to.\n */\n onGraphPut(repositoryId: string, gitRef: string, graph: VgGraph): void {\n const key = activeGraphSlotKey(repositoryId, gitRef);\n const existing = this.indexes.get(key);\n const nodeCount = graph.nodes?.length ?? 0;\n if (existing && existing.state === 'ready') {\n this.log(`semantic: ${repositoryId}@${gitRef} graph republished — index stale (${existing.vectors.size} vectors dropped)`);\n }\n this.indexes.set(key, {\n repositoryId,\n gitRef,\n state: 'stale',\n vectors: new Map(),\n nodeCount,\n });\n }\n\n /**\n * Supplies the graph for a slot so a select can warm without the caller\n * threading it through. Set by the daemon to read its own cache.\n */\n setGraphProvider(provider: (repositoryId: string, gitRef: string) => VgGraph | undefined): void {\n this.graphProvider = provider;\n }\n\n /**\n * A slot became current — a branch switch, a new repo, a fresh publish.\n * The matching index is swapped in, and warmed in the background if it is\n * not ready, so the first Ask after a switch is not the one that pays.\n */\n onGraphSelect(repositoryId: string, gitRef: string): void {\n const key = activeGraphSlotKey(repositoryId, gitRef);\n if (this.currentKey !== key) {\n this.currentKey = key;\n const idx = this.indexes.get(key);\n this.log(\n `semantic: current slot → ${repositoryId}@${gitRef} · index ${idx ? `${idx.state} (${idx.vectors.size} vectors)` : 'absent'}`,\n );\n }\n if (this.gaveUp) return;\n const idx = this.indexes.get(key);\n if (idx?.state === 'ready' || this.building.has(key)) return;\n const graph = this.graphProvider?.(repositoryId, gitRef);\n if (!graph) return;\n // Fire and forget: warming must never block the op that triggered it.\n void this.ensureIndex(repositoryId, gitRef, graph);\n }\n\n /** A graph slot was evicted — its index goes with it, never outliving it. */\n onGraphEvict(repositoryId: string, gitRef: string): void {\n const key = activeGraphSlotKey(repositoryId, gitRef);\n const idx = this.indexes.get(key);\n if (!idx) return;\n this.indexes.delete(key);\n this.log(`semantic: ${repositoryId}@${gitRef} index evicted with its graph slot (${idx.vectors.size} vectors freed)`);\n }\n\n /** Drop everything (daemon shutdown / registry clear). */\n clear(): void {\n this.indexes.clear();\n this.building.clear();\n }\n\n /**\n * Ensure the slot has vectors, building them if needed. Resolves when the\n * index is ready or has definitively failed; never throws.\n */\n async ensureIndex(repositoryId: string, gitRef: string, graph: VgGraph): Promise<SlotIndex> {\n const key = activeGraphSlotKey(repositoryId, gitRef);\n let idx = this.indexes.get(key);\n if (!idx) {\n idx = { repositoryId, gitRef, state: 'stale', vectors: new Map(), nodeCount: graph.nodes?.length ?? 0 };\n this.indexes.set(key, idx);\n }\n if (idx.state === 'ready') return idx;\n if (this.gaveUp) {\n idx.state = 'failed';\n idx.error = this.reason ?? 'embedding worker unavailable';\n return idx;\n }\n if (this.building.has(key)) return idx;\n\n this.building.add(key);\n idx.state = 'building';\n const nodes = (graph.nodes ?? []).filter((n) => !!n?.id);\n const started = this.now();\n this.log(`semantic: building index for ${repositoryId}@${gitRef} (${nodes.length} nodes)…`);\n\n try {\n const vectors = new Map<string, number[]>();\n for (let i = 0; i < nodes.length; i += this.batchSize) {\n const batch = nodes.slice(i, i + this.batchSize);\n const out = await this.embed(batch.map((n) => nodeText(n)));\n batch.forEach((n, j) => {\n const v = out[j];\n if (v) vectors.set(n.id, v);\n });\n // A slot evicted or republished mid-build must not be resurrected with\n // vectors describing the graph it no longer has.\n const live = this.indexes.get(key);\n if (!live || live !== idx) {\n this.log(`semantic: index build for ${repositoryId}@${gitRef} abandoned — slot changed underneath it`);\n return idx;\n }\n }\n idx.vectors = vectors;\n idx.nodeCount = nodes.length;\n idx.state = 'ready';\n idx.builtAt = this.now();\n idx.buildMs = idx.builtAt - started;\n idx.error = undefined;\n this.log(`semantic: index ready for ${repositoryId}@${gitRef} — ${vectors.size} vectors in ${idx.buildMs}ms`);\n } catch (err) {\n idx.state = 'failed';\n idx.error = err instanceof Error ? err.message : String(err);\n this.log(`semantic: index build failed for ${repositoryId}@${gitRef} — ${idx.error}; callers fall back to lexical`);\n } finally {\n this.building.delete(key);\n }\n return idx;\n }\n\n /** Embed one query string. Returns null when semantic is not available. */\n async embedQuery(text: string): Promise<number[] | null> {\n if (this.gaveUp) return null;\n try {\n const [vector] = await this.embed([text], true);\n return vector ?? null;\n } catch (err) {\n this.log(`semantic: query embedding failed — ${err instanceof Error ? err.message : String(err)}; using lexical`);\n return null;\n }\n }\n\n /** Stop the worker (daemon shutdown). Safe to call when already stopped. */\n stop(): void {\n const child = this.child;\n this.child = null;\n this.starting = false;\n for (const [, p] of this.pending) {\n clearTimeout(p.timer);\n p.reject(new Error('embedding worker stopped'));\n }\n this.pending.clear();\n if (child) {\n try {\n child.kill();\n } catch {\n /* already gone */\n }\n }\n }\n\n // ── worker plumbing ────────────────────────────────────────────────────\n\n private ensureWorker(): ChildProcess {\n if (this.child) return this.child;\n this.starting = true;\n const child = this.spawnWorker();\n this.child = child;\n this.starting = false;\n this.buffer = '';\n this.log(`semantic: embedding worker started (pid ${child.pid ?? '?'})`);\n\n child.stdout?.setEncoding('utf8');\n child.stdout?.on('data', (chunk: string) => this.onData(chunk));\n // The worker's stderr is diagnostic only; surface it so a failing backend\n // is visible in the daemon log rather than silently swallowed.\n child.stderr?.setEncoding('utf8');\n child.stderr?.on('data', (chunk: string) => {\n const text = String(chunk).trim();\n if (text) this.log(`semantic worker: ${text.slice(0, 500)}`);\n });\n child.on('exit', (code, signal) => this.onExit(code, signal));\n child.on('error', (err: Error) => {\n this.log(`semantic: embedding worker could not start — ${err.message}`);\n this.onExit(null, null);\n });\n return child;\n }\n\n private onData(chunk: string): void {\n this.buffer += chunk;\n let nl: number;\n while ((nl = this.buffer.indexOf('\\n')) >= 0) {\n const line = this.buffer.slice(0, nl).trim();\n this.buffer = this.buffer.slice(nl + 1);\n if (!line) continue;\n let res: { id?: number; ok?: boolean; vectors?: number[][]; error?: string; model?: string };\n try {\n res = JSON.parse(line) as typeof res;\n } catch {\n continue; // a corrupt frame is not fatal to the stream\n }\n if (typeof res.model === 'string') this.model = res.model;\n const id = res.id;\n if (typeof id !== 'number') continue;\n const p = this.pending.get(id);\n if (!p) continue;\n this.pending.delete(id);\n clearTimeout(p.timer);\n if (res.ok && Array.isArray(res.vectors)) p.resolve(res.vectors);\n else p.reject(new Error(res.error || 'embedding worker returned no vectors'));\n }\n }\n\n private onExit(code: number | null, signal: NodeJS.Signals | null): void {\n const wasRunning = !!this.child;\n this.child = null;\n if (!wasRunning) return;\n\n this.crashes++;\n const how = signal ? `signal ${signal}` : `code ${code ?? 'null'}`;\n // Fail every in-flight request rather than letting callers hang: each one\n // has a lexical fallback waiting.\n for (const [, p] of this.pending) {\n clearTimeout(p.timer);\n p.reject(new Error(`embedding worker exited (${how})`));\n }\n this.pending.clear();\n\n if (this.crashes >= this.maxCrashes) {\n this.gaveUp = true;\n this.reason =\n `the embedding worker exited (${how}) ${this.crashes} times — semantic search is off for this daemon; ` +\n `everything falls back to lexical. A native backend that aborts like this is usually a blocked ` +\n `onnxruntime-node postinstall (see \\`vg embed --where\\`).`;\n this.log(`semantic: ${this.reason}`);\n return;\n }\n this.log(`semantic: embedding worker exited (${how}) — restarting on next use (${this.crashes}/${this.maxCrashes})`);\n }\n\n private embed(texts: string[], query = false): Promise<number[][]> {\n if (this.gaveUp) return Promise.reject(new Error(this.reason ?? 'embedding worker unavailable'));\n if (!texts.length) return Promise.resolve([]);\n let child: ChildProcess;\n try {\n child = this.ensureWorker();\n } catch (err) {\n // A worker that cannot even be spawned counts against the crash budget,\n // so a permanently broken install settles into \"lexical\" instead of\n // retrying (and re-logging) on every request.\n const error = err instanceof Error ? err : new Error(String(err));\n this.crashes++;\n if (this.crashes >= this.maxCrashes) {\n this.gaveUp = true;\n this.reason = `the embedding worker could not start (${error.message}) — semantic search is off for this daemon`;\n this.log(`semantic: ${this.reason}`);\n } else {\n this.log(`semantic: embedding worker could not start — ${error.message} (${this.crashes}/${this.maxCrashes})`);\n }\n return Promise.reject(error);\n }\n const id = this.nextId++;\n return new Promise<number[][]>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(new Error(`embedding request timed out after ${this.requestTimeoutMs}ms`));\n }, this.requestTimeoutMs);\n // Do not hold the daemon open on this timer.\n (timer as unknown as { unref?: () => void }).unref?.();\n this.pending.set(id, { resolve, reject, timer });\n try {\n child.stdin?.write(JSON.stringify({ id, op: 'embed', texts, query }) + '\\n');\n } catch (err) {\n this.pending.delete(id);\n clearTimeout(timer);\n reject(err instanceof Error ? err : new Error(String(err)));\n }\n });\n }\n\n /** A successful exchange clears the crash streak — used after a good build. */\n noteHealthy(): void {\n this.crashes = 0;\n }\n}\n\n/**\n * Spawn the real worker: the compiled sibling entry (a tsup entry point, like\n * `parse-worker`), run by the same Node binary. Under a TS-only runner the\n * compiled file does not exist — the same situation `engine/pool.ts` handles —\n * so this throws rather than spawning something that cannot start, and the\n * broker reports the failure like any other and callers go lexical.\n */\nfunction defaultSpawnWorker(): ChildProcess {\n const here = path.dirname(fileURLToPath(import.meta.url));\n const entry = path.join(here, 'embed-worker-main.js');\n if (!fs.existsSync(entry)) {\n throw new Error(`embedding worker not found at ${entry} — semantic runs lexically`);\n }\n return spawn(process.execPath, [entry], {\n stdio: ['pipe', 'pipe', 'pipe'],\n // Never inherit loader flags or a debugger port: this child exists to be\n // expendable, and anything that changes how it loads defeats the point.\n env: { ...process.env, NODE_OPTIONS: '' },\n });\n}\n","import * as fs from 'node:fs';\nimport * as net from 'node:net';\nimport * as path from 'node:path';\nimport { VGD_PROTOCOL_VERSION, parseRequest, type VgdResponse } from './protocol.js';\nimport { WorkspaceRegistry } from './registry.js';\nimport { vgdPidPath, vgdSocketPath } from './paths.js';\nimport { queryGraph } from '../../engine/query.js';\nimport { loadGraph } from '../../engine/load.js';\nimport { impactOf } from '../../engine/impact.js';\nimport { resolveOne } from '../../engine/lookup.js';\nimport { getVgdHostBroker, type VgdHostBroker } from './host-broker.js';\nimport { EmbedBroker } from './embed-broker.js';\nimport type { VgGraph } from '../../schema.js';\n\nexport interface VgdServerOptions {\n /** Override socket path (tests). */\n socketPath?: string;\n /** Override PID path (tests). */\n pidPath?: string;\n registry?: WorkspaceRegistry;\n now?: () => Date;\n /** Process id recorded in status / pid file (tests). */\n pid?: number;\n /** Inject host broker (tests); default process-wide broker. */\n hostBroker?: VgdHostBroker;\n /** Inject the semantic broker (tests); default owns a worker child. */\n embedBroker?: EmbedBroker;\n /**\n * Diagnostic sink. `vg daemon start` points this at stdout so the daemon's\n * work — graph publishes, branch switches, index builds — is visible while\n * it happens instead of being inferred after the fact.\n */\n log?: (message: string) => void;\n /**\n * Invoked (shortly after the reply is written) when a client sends the\n * `shutdown` op. Only a standalone `vg daemon start` passes this — an\n * in-process vgd (e.g. inside `vg code`) leaves it unset, and the op is\n * refused so another process can never take down the owning session.\n */\n onShutdownRequest?: () => void;\n}\n\nexport interface VgdServer {\n readonly socketPath: string;\n readonly registry: WorkspaceRegistry;\n /** Wall time when the server started listening. */\n readonly startedAt: number;\n close(): Promise<void>;\n}\n\n/**\n * Start a line-delimited JSON daemon on the local vgd socket.\n * Creates the daemon directory; removes a stale Unix socket file if present.\n */\nexport async function startVgdServer(options: VgdServerOptions = {}): Promise<VgdServer> {\n const socketPath = options.socketPath ?? vgdSocketPath();\n const pidPath = options.pidPath ?? vgdPidPath();\n const registry = options.registry ?? new WorkspaceRegistry();\n const hostBroker = options.hostBroker ?? getVgdHostBroker();\n const log = options.log ?? ((): void => {});\n // Semantic warm: the index is slot-scoped like the graph, so it attaches to\n // the registry's lifecycle rather than being managed alongside it by hand.\n const embedBroker = options.embedBroker ?? new EmbedBroker({ log });\n embedBroker.setGraphProvider((repositoryId, gitRef) => registry.graphs.get(repositoryId, gitRef)?.graph);\n registry.setSlotListener(embedBroker);\n const onShutdownRequest = options.onShutdownRequest;\n const now = options.now ?? (() => new Date());\n const pid = options.pid ?? process.pid;\n const startedAt = Date.now();\n\n // Unix sockets need a free path; named pipes on Windows are cleaned by the OS.\n if (!socketPath.startsWith('\\\\\\\\.\\\\pipe')) {\n fs.mkdirSync(path.dirname(socketPath), { recursive: true });\n try {\n fs.unlinkSync(socketPath);\n } catch {\n /* nothing to remove */\n }\n } else {\n fs.mkdirSync(path.dirname(pidPath), { recursive: true });\n }\n\n const server = net.createServer((socket) => {\n let buffer = '';\n socket.setEncoding('utf8');\n socket.on('data', (chunk: string) => {\n buffer += chunk;\n let nl: number;\n while ((nl = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.slice(0, nl).trim();\n buffer = buffer.slice(nl + 1);\n if (!line) continue;\n void Promise.resolve(\n handleLine(line, { registry, hostBroker, embedBroker, now, pid, startedAt, socketPath, onShutdownRequest, log }),\n ).then(\n (response) => {\n socket.write(JSON.stringify(response) + '\\n');\n },\n );\n }\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once('error', reject);\n server.listen(socketPath, () => {\n server.off('error', reject);\n resolve();\n });\n });\n\n try {\n fs.mkdirSync(path.dirname(pidPath), { recursive: true });\n fs.writeFileSync(pidPath, `${pid}\\n`, 'utf8');\n } catch {\n /* pid file is best-effort */\n }\n\n return {\n socketPath,\n registry,\n startedAt,\n async close() {\n // The worker is a child of this process — never leave it orphaned.\n embedBroker.stop();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n try {\n fs.unlinkSync(pidPath);\n } catch {\n /* gone */\n }\n if (!socketPath.startsWith('\\\\\\\\.\\\\pipe')) {\n try {\n fs.unlinkSync(socketPath);\n } catch {\n /* gone */\n }\n }\n },\n };\n}\n\nasync function handleLine(\n line: string,\n ctx: {\n registry: WorkspaceRegistry;\n hostBroker: VgdHostBroker;\n embedBroker: EmbedBroker;\n log: (message: string) => void;\n now: () => Date;\n pid: number;\n startedAt: number;\n socketPath: string;\n onShutdownRequest?: () => void;\n },\n): Promise<VgdResponse> {\n const req = parseRequest(line);\n if ('error' in req) return { ok: false, error: req.error, code: 'bad_request' };\n\n switch (req.op) {\n case 'ping':\n return { ok: true, pong: true, version: VGD_PROTOCOL_VERSION };\n case 'status':\n return {\n ok: true,\n pid: ctx.pid,\n uptimeMs: Date.now() - ctx.startedAt,\n workspaces: ctx.registry.size(),\n graphSlots: ctx.registry.graphs.size(),\n version: VGD_PROTOCOL_VERSION,\n socketPath: ctx.socketPath,\n };\n case 'shutdown': {\n if (!ctx.onShutdownRequest) {\n return {\n ok: false,\n error:\n 'this vgd is embedded in another process (e.g. vg code) and cannot be stopped remotely — stop the owning process instead',\n code: 'shutdown_unsupported',\n };\n }\n // Let the reply flush to the client before the listener goes away.\n const hook = ctx.onShutdownRequest;\n setTimeout(() => hook(), 150);\n return { ok: true, stopping: true };\n }\n case 'embed-status':\n return { ok: true, semantic: ctx.embedBroker.status() };\n case 'embed-query': {\n const vector = await ctx.embedBroker.embedQuery(req.text);\n if (!vector) {\n return {\n ok: false,\n error: 'semantic unavailable — rank lexically',\n code: 'semantic_unavailable',\n };\n }\n return { ok: true, vector, model: ctx.embedBroker.status().model };\n }\n case 'embed-index': {\n const gitRef = req.gitRef ?? ctx.registry.graphs.selectedRef(req.repositoryId);\n if (!gitRef) return { ok: false, error: 'no current gitRef for this repository', code: 'no_slot' };\n const slot = ctx.registry.graphs.get(req.repositoryId, gitRef);\n if (!slot) {\n return { ok: false, error: `no graph slot for ${req.repositoryId}@${gitRef} — publish the map first`, code: 'no_slot' };\n }\n const idx = await ctx.embedBroker.ensureIndex(req.repositoryId, gitRef, slot.graph);\n return {\n ok: true,\n indexed: true,\n repositoryId: req.repositoryId,\n gitRef,\n state: idx.state,\n vectors: idx.vectors.size,\n buildMs: idx.buildMs,\n };\n }\n case 'host-status':\n return { ok: true, host: ctx.hostBroker.status() };\n case 'host-load': {\n const r = await ctx.hostBroker.load(req.modelPath);\n if (!r.ok) return { ok: false, error: r.error, code: 'host_error' };\n return { ok: true, hostLoaded: true, modelPath: r.modelPath };\n }\n case 'host-unload': {\n const r = await ctx.hostBroker.unload(req.modelPath);\n return { ok: true, hostUnloaded: true, cleared: r.cleared };\n }\n case 'host-generate': {\n const r = await ctx.hostBroker.generate(\n req.modelPath,\n req.messages.map((m) => ({\n role: (m.role === 'system' || m.role === 'assistant' ? m.role : 'user') as 'system' | 'user' | 'assistant',\n content: m.content,\n })),\n {\n grammar: req.grammar,\n requireGrammar: req.requireGrammar,\n maxTokens: req.maxTokens,\n temperature: req.temperature,\n },\n );\n if (!r.ok) return { ok: false, error: r.error, code: 'host_error' };\n return {\n ok: true,\n hostGenerated: true,\n text: r.result.text,\n model: r.result.model,\n constrained: r.result.constrained,\n grammarApplied: r.result.grammarApplied,\n draftAcceptedChars: r.result.draftAcceptedChars,\n latencyMs: r.result.latencyMs,\n unknownIdentifiers: r.result.unknownIdentifiers,\n };\n }\n case 'list':\n return { ok: true, workspaces: ctx.registry.list() };\n case 'register': {\n const known = ctx.registry.size();\n const workspace = ctx.registry.register(req.root, ctx.now, { label: req.label, role: req.role });\n // A repo the daemon has not seen before is the interesting case — that is\n // when a warm daemon still has cold work to do.\n if (ctx.registry.size() > known) {\n ctx.log(`register: new workspace ${workspace.id} (${workspace.root}${workspace.gitRef ? ` @${workspace.gitRef}` : ''})`);\n }\n return { ok: true, workspace };\n }\n case 'unregister':\n return { ok: true, removed: ctx.registry.unregister(req.root) };\n case 'register-federation': {\n const workspaces = ctx.registry.registerFederation(req.members, ctx.now);\n return { ok: true, workspaces, federation: true };\n }\n case 'list-graph-slots': {\n ctx.registry.graphs.evictIdle();\n return { ok: true, slots: ctx.registry.graphs.list(req.repositoryId) };\n }\n case 'select-git-ref': {\n const before = ctx.registry.graphs.selectedRef(req.repositoryId);\n if (before !== req.gitRef) {\n ctx.log(`select-git-ref: ${req.repositoryId} ${before ?? '(none)'} → ${req.gitRef}`);\n }\n ctx.registry.selectGitRef(req.repositoryId, req.gitRef);\n return { ok: true, selected: true, repositoryId: req.repositoryId, gitRef: req.gitRef };\n }\n case 'put-graph': {\n try {\n // The wire line was already JSON.parse'd by parseRequest — re-encoding a\n // large repo's graph (`parseGraph(JSON.stringify(...))`) blocked the\n // daemon's event loop for seconds, timing out every concurrent client.\n const graph = req.graph as VgGraph;\n ctx.log(`put-graph: ${req.repositoryId}@${req.gitRef} · ${graph.nodes?.length ?? 0} nodes`);\n ctx.registry.putGraph(req.repositoryId, req.gitRef, graph);\n return {\n ok: true,\n stored: true,\n repositoryId: req.repositoryId,\n gitRef: req.gitRef,\n nodeCount: graph.nodes?.length ?? 0,\n };\n } catch (e) {\n return { ok: false, error: e instanceof Error ? e.message : 'invalid graph', code: 'bad_graph' };\n }\n }\n case 'load-graph': {\n // Load from disk inside the daemon: the snapshot-first loader decodes\n // the binary sidecar (msgpack) when fresh — no multi-MB JSON line ever\n // crosses the socket, which is what made put-graph publishes slow on\n // large repos.\n const record = ctx.registry.register(req.root, ctx.now, { gitRef: req.gitRef });\n const gitRef = req.gitRef ?? record.gitRef ?? 'HEAD';\n ctx.log(`load-graph: ${record.id}@${gitRef} from ${req.root}`);\n const graph = loadGraph(req.root, req.graphPath);\n if (!graph) {\n return {\n ok: false,\n error: `no code map found for ${req.root} — run \\`vg build\\` (or bare \\`vg\\`) first`,\n code: 'no_map',\n };\n }\n ctx.registry.putGraph(record.id, gitRef, graph);\n return {\n ok: true,\n stored: true,\n repositoryId: record.id,\n gitRef,\n nodeCount: graph.nodes?.length ?? 0,\n };\n }\n case 'query-graph': {\n const resolved = ctx.registry.resolveGraph(req.repositoryId, req.gitRef);\n if (!resolved) {\n return { ok: false, error: 'no ActiveGraph loaded for repository — put-graph first', code: 'no_graph' };\n }\n const result = queryGraph(resolved.graph, req.query, { limit: req.limit ?? 12, budget: 2000 });\n return {\n ok: true,\n query: req.query,\n repositoryId: req.repositoryId,\n gitRef: resolved.gitRef,\n matches: result.matches.slice(0, req.limit ?? 12).map((m) => ({\n id: m.node.id,\n qualifiedName: m.node.qualifiedName,\n kind: m.node.kind,\n file: m.node.file,\n line: m.node.span?.start ?? 0,\n score: m.score,\n why: m.why,\n })),\n tokensEstimate: result.tokensEstimate,\n };\n }\n case 'impact-of': {\n const resolved = ctx.registry.resolveGraph(req.repositoryId, req.gitRef);\n if (!resolved) {\n return { ok: false, error: 'no ActiveGraph loaded for repository — put-graph first', code: 'no_graph' };\n }\n const node = resolveSymbol(resolved.graph, req.symbol);\n if (!node) {\n return { ok: false, error: `symbol not found: ${req.symbol}`, code: 'not_found' };\n }\n const impact = impactOf(resolved.graph, node.id, { depth: req.depth ?? 4 });\n return {\n ok: true,\n repositoryId: req.repositoryId,\n gitRef: resolved.gitRef,\n symbol: req.symbol,\n root: impact.root,\n depth: impact.depth,\n affected: impact.affected.slice(0, 40).map((a) => ({\n id: a.id,\n name: a.name,\n kind: a.kind,\n file: a.file,\n line: a.line,\n depth: a.depth,\n confidence: a.confidence,\n })),\n direct: impact.direct,\n transitive: impact.transitive,\n };\n }\n case 'graph-summary': {\n const resolved = ctx.registry.resolveGraph(req.repositoryId, req.gitRef);\n if (!resolved) {\n return { ok: false, error: 'no ActiveGraph loaded for repository — put-graph first', code: 'no_graph' };\n }\n const g = resolved.graph;\n return {\n ok: true,\n repositoryId: req.repositoryId,\n gitRef: resolved.gitRef,\n summary: {\n nodeCount: g.nodes?.length ?? 0,\n edgeCount: g.edges?.length ?? 0,\n languages: g.meta?.languages ?? [],\n corpusHash: g.provenance?.corpusHash ?? null,\n root: g.meta?.root ?? null,\n },\n };\n }\n }\n}\n\nfunction resolveSymbol(graph: VgGraph, symbol: string): { id: string } | null {\n // Prefer exact id, then qualified-name / short-name lookup.\n if (graph.nodes.some((n) => n.id === symbol)) return { id: symbol };\n const hit = resolveOne(graph, symbol);\n if (hit.node?.id) return { id: hit.node.id };\n if (hit.candidates.length === 1 && hit.candidates[0]?.id) return { id: hit.candidates[0].id };\n const q = symbol.toLowerCase();\n const byQn = graph.nodes.find((n) => n.qualifiedName?.toLowerCase() === q || n.name?.toLowerCase() === q);\n return byQn ? { id: byQn.id } : null;\n}\n","/**\n * Branch-aware graph loading for a single repository worktree (Fusion §4.1.1).\n *\n * Combines {@link detectGitRef}, disk load via {@link loadGraph}, and an\n * {@link ActiveGraphCache} so checkout A → B → A reuses a warm in-memory map\n * when the branch is still resident (LILO idle eviction applies).\n */\n\nimport { loadGraph } from '../engine/load.js';\nimport { repositoryIdFromRoot } from './paths.js';\nimport { detectGitRef, type GitRunner } from './git-ref.js';\nimport { ActiveGraphCache } from './active-graph-cache.js';\nimport type { VgGraph } from '../schema.js';\n\nexport interface BranchGraphLoadResult {\n graph: VgGraph | null;\n gitRef: string;\n kind: 'branch' | 'detached' | 'none';\n /** True when the selected ActiveGraph slot changed since the previous ensure. */\n switched: boolean;\n /** True when the graph was served from the in-memory cache. */\n fromCache: boolean;\n repositoryId: string;\n}\n\nexport interface BranchGraphSessionOptions {\n root: string;\n cache?: ActiveGraphCache;\n /** Optional explicit graph path (CLI `--graph`); bypasses branch keying for disk. */\n graphPath?: string;\n detectGit?: typeof detectGitRef;\n load?: typeof loadGraph;\n gitRun?: GitRunner;\n}\n\n/**\n * Stateful helper: call {@link ensureCurrent} at session start and before each\n * agent turn so a mid-session `git checkout` picks up the correct map.\n */\nexport class BranchGraphSession {\n readonly root: string;\n readonly repositoryId: string;\n readonly cache: ActiveGraphCache;\n private readonly graphPath?: string;\n private readonly detectGit: typeof detectGitRef;\n private readonly load: typeof loadGraph;\n private readonly gitRun?: GitRunner;\n private lastRef = '';\n\n constructor(options: BranchGraphSessionOptions) {\n this.root = options.root;\n this.repositoryId = repositoryIdFromRoot(options.root);\n this.cache = options.cache ?? new ActiveGraphCache();\n this.graphPath = options.graphPath;\n this.detectGit = options.detectGit ?? detectGitRef;\n this.load = options.load ?? loadGraph;\n this.gitRun = options.gitRun;\n }\n\n /**\n * Resolve HEAD, activate the matching cache slot (or load from disk), and\n * run idle eviction. Returns null graph when no map exists for this ref.\n */\n ensureCurrent(): BranchGraphLoadResult {\n this.cache.evictIdle();\n const info = this.gitRun ? this.detectGit(this.root, this.gitRun) : this.detectGit(this.root);\n const gitRef = info.ref || 'unknown';\n const switched = this.lastRef !== '' && this.lastRef !== gitRef;\n this.lastRef = gitRef;\n\n // Explicit --graph path: still track ref for cache identity but load that file.\n if (this.graphPath) {\n const graph = this.load(this.root, this.graphPath);\n if (graph) {\n this.cache.put(this.repositoryId, gitRef, graph);\n this.cache.select(this.repositoryId, gitRef);\n }\n return {\n graph,\n gitRef,\n kind: info.kind,\n switched,\n fromCache: false,\n repositoryId: this.repositoryId,\n };\n }\n\n const warm = this.cache.get(this.repositoryId, gitRef);\n if (warm) {\n this.cache.select(this.repositoryId, gitRef);\n return {\n graph: warm.graph,\n gitRef,\n kind: info.kind,\n switched,\n fromCache: true,\n repositoryId: this.repositoryId,\n };\n }\n\n const graph = this.load(this.root);\n if (graph) {\n this.cache.put(this.repositoryId, gitRef, graph);\n this.cache.select(this.repositoryId, gitRef);\n }\n return {\n graph,\n gitRef,\n kind: info.kind,\n switched,\n fromCache: false,\n repositoryId: this.repositoryId,\n };\n }\n\n /** Diagnostics for daemon status / tests. */\n listSlots() {\n return this.cache.list(this.repositoryId);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { loadGraphFileWithSnapshot, resolveGraphPath } from './chunk-N4IDP2M2.js';
2
- import { cacheDir } from './chunk-AJ2KE3NT.js';
1
+ import { loadGraphFileWithSnapshot, resolveGraphPath } from './chunk-7TOIESUT.js';
2
+ import { cacheDir } from './chunk-RBMKBYGV.js';
3
3
  import { __require } from './chunk-Z6ZWNWWR.js';
4
4
  import * as fs from 'fs';
5
5
  import * as path from 'path';
@@ -199,5 +199,5 @@ function loadGraph(root, graphPath) {
199
199
  }
200
200
 
201
201
  export { SCHEMA_VERSION, loadGraph, loadGraphPreferIndex, writeGraphIndex };
202
- //# sourceMappingURL=chunk-DIU3MXB3.js.map
203
- //# sourceMappingURL=chunk-DIU3MXB3.js.map
202
+ //# sourceMappingURL=chunk-537JBQVB.js.map
203
+ //# sourceMappingURL=chunk-537JBQVB.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/engine/index-db.ts","../src/engine/load.ts"],"names":[],"mappings":";;;;;;;AASO,IAAM,cAAA,GAAiB;;;AC2BvB,SAAS,YAAY,IAAA,EAAsB;AAChD,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA,EAAG,UAAU,CAAA;AAC7C;AAGO,SAAS,eAAA,CAAgB,MAAc,KAAA,EAAkC;AAC9E,EAAA,MAAM,IAAA,GAAO,YAAY,IAAI,CAAA;AAC7B,EAAA,IAAI;AAEF,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,SAAA,CAAQ,QAAa,CAA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C","file":"chunk-DIU3MXB3.js","sourcesContent":["/**\n * The `vg-graph/1.0` on-disk schema.\n *\n * This is vg's own open schema (VG-PACKAGE-AND-SCHEMA.md §4) — informed by good\n * ideas (content-hashed ids, epistemic typing of facts) but standalone and\n * self-contained. Every collection is deterministically serialized\n * (sorted keys, stable element order). These TypeScript shapes are normative.\n */\n\nexport const SCHEMA_VERSION = 'vg-graph/1.0' as const;\n\nexport type ResolverKind = 'scip' | 'stackgraph' | 'tsc' | 'heuristic';\n\n/** Coarse, honest resolution tier for an edge (see engine/epistemic.ts). */\nexport type EpistemicTier = 'observed' | 'name-matched' | 'declared';\n\n/**\n * The toolchain that produced this graph — the reproducibility fingerprint.\n * Everything here deterministically affects graph *content* (parse trees change\n * between grammar releases; resolvers change which edges resolve), so a CI run\n * and a laptop run that disagree can be caught by comparing `fingerprint`.\n * Deliberately excludes the Node/OS version so the graph stays byte-stable\n * across host runtimes; `fingerprint` pins the parse/resolve toolchain only.\n */\nexport interface Toolchain {\n schema: string; // SCHEMA_VERSION\n tool: string; // vg calendar version\n grammars: string; // tree-sitter grammar set version string\n resolvers: ResolverKind[]; // resolver kinds available, sorted\n fingerprint: string; // shortId over the fields above — the value `vg attest` signs\n}\n\nexport interface Provenance {\n tool: 'vg';\n version: string; // calendar version\n grammars: Record<string, string>; // lang → grammar version (determinism input)\n resolver: ResolverKind[];\n deep: boolean; // did the heavier open passes run\n semanticModel?: string; // embedding model id+version if --deep semantic links\n corpusHash: string; // blake3 over the included file set + hashes\n toolchain?: Toolchain; // reproducibility fingerprint (checked by `vg verify`)\n}\n\n/** Analysis cost tier — auto-selected by node count (or forced). Reported honestly. */\nexport type AnalysisTier = 'full' | 'large' | 'xl';\n\nexport interface GraphMeta {\n root: string; // relative; portable across machines\n languages: string[];\n counts: {\n nodes: number;\n edges: number;\n areas: number;\n tests: number;\n untested: number;\n };\n cluster: 'leiden' | 'louvain' | 'none';\n /** Auto-selected (or forced) analysis tier for large maps. */\n analysisTier?: AnalysisTier;\n edgeKinds: EdgeKind[];\n}\n\nexport type NodeKind =\n | 'file'\n | 'module'\n | 'package'\n | 'class'\n | 'interface'\n | 'function'\n | 'method'\n | 'property'\n | 'test'\n | 'route'\n | 'component'\n /** Documentation / config text ingested for semantic ask (markdown, txt, env examples). */\n | 'document'\n | 'external';\n\nexport interface Span {\n start: number; // 1-based start line\n end: number; // 1-based end line\n}\n\nexport interface Centrality {\n degree: number;\n pagerank: number;\n betweenness: number;\n eigenvector: number;\n}\n\nexport interface GraphNode {\n id: string; // blake3(canonical(kind, qualifiedName, file, signature))\n kind: NodeKind;\n name: string; // short name\n qualifiedName: string;\n file: string; // relative path\n span: Span; // line range (excluded from id hash)\n lang: string;\n visibility?: 'public' | 'private' | 'protected' | 'internal';\n signature?: string;\n doc?: string; // short leading doc-comment / docstring summary (deterministic; not a full body)\n importance: number; // 0..1 blended centrality\n centrality: Centrality;\n area: number; // area id (the node's community); -1 = unassigned (cluster \"none\")\n isHub: boolean; // centrality outlier — surfaced by `vg hubs`\n tested: boolean | null; // null = not analyzable (e.g. external)\n coverage?: number; // 0..1 line coverage if a coverage report was ingested\n changeCoupling?: string[]; // node ids that historically change together\n}\n\nexport type EdgeKind =\n | 'call'\n | 'import'\n | 'contains'\n | 'extends'\n | 'implements'\n | 'references'\n | 'test'\n | 'coverage';\n\nexport interface GraphEdge {\n id: string; // blake3(canonical(kind, src, dst))\n kind: EdgeKind;\n src: string; // node id\n dst: string; // node id\n resolution: ResolverKind; // how the edge was resolved\n confidence: number; // 0..1 (1.0 for scip/declared; lower for heuristic/dynamic)\n epistemic?: EpistemicTier; // coarse honesty tier derived from resolution+kind\n surprise?: number; // 0..1 improbability under the area model (`vg oddities`)\n count?: number; // call-site multiplicity\n}\n\nexport interface Area {\n id: number; // stable across runs (remapped to previous committed map)\n label: string; // most-central member's name (editable via `vg label`)\n size: number;\n members: string[]; // node ids, sorted\n cohesion: number; // 0..1\n externalEdges: number; // cross-area edge count\n}\n\nexport type FactKind = 'contract' | 'invariant' | 'characterization';\nexport type DerivedBy = 'declared' | 'static';\nexport type FactConfidence = 'Observed' | 'Derived';\n\nexport interface Fact {\n id: string; // blake3(canonical(kind, subjectIds, predicate))\n kind: FactKind;\n subjectIds: string[]; // node ids this fact constrains\n predicate: unknown; // the constraint\n derivedBy: DerivedBy;\n confidence: FactConfidence;\n evidence: { file: string; span: Span }[];\n}\n\n/**\n * A reference the graph could not resolve — surfaced by `vg unknowns`. Reporting\n * what it *cannot* connect (ranked by blast radius) is the honest inverse of a\n * scanner that hides its unknowns. Only unknowns the precise rungs (tsc/scip)\n * did not supersede are recorded, so a compiler-resolved file never shows here.\n */\nexport interface Unknown {\n from: string; // node id where the unresolved reference occurs\n name: string; // the callee/type name that could not be resolved\n kind: 'call' | 'extends' | 'implements';\n count: number; // occurrences at this site\n}\n\nexport type GroundingKind = 'should_follow' | 'smells_like' | 'relevant_to';\n\nexport interface GroundingEdge {\n src: string; // node id\n packEntryId: string;\n kind: GroundingKind;\n confidence: number; // 0..1\n rationale: 'recommended' | 'conjectured';\n citation: { title: string; url: string };\n}\n\n/** Precomputed hub blast-radius counts for fast agent answers (optional). */\nexport interface HubBlastSummary {\n id: string;\n name: string;\n kind: string;\n file: string;\n importance: number;\n direct: number;\n depth2: number;\n files: number;\n tested: boolean | null;\n}\n\nexport interface GraphSummaries {\n hubs: HubBlastSummary[];\n}\n\nexport interface VgGraph {\n schemaVersion: typeof SCHEMA_VERSION;\n generatedAt: string; // ISO; the ONLY nondeterministic field (pinned by --generated-at)\n provenance: Provenance;\n meta: GraphMeta;\n nodes: GraphNode[]; // sorted by id\n edges: GraphEdge[]; // sorted by (kind, src, dst)\n areas: Area[]; // sorted by id\n facts?: Fact[]; // open facts (contract/invariant/characterization); sorted by id\n grounding?: GroundingEdge[]; // free-pack grounding (default on; omit with --no-ground)\n unknowns?: Unknown[]; // heuristic references left unresolved; sorted by (from, kind, name)\n /** Build-time hub blast-radius summaries (always on; tiny). */\n summaries?: GraphSummaries;\n}\n","/**\n * SQLite serve index for large maps (scale past flat-JSON-only serve).\n *\n * The canonical artifact remains `graph.json` (determinism / git). The index\n * at `.vibgrate/cache/graph.db` is a derived, gitignored structure built after\n * every successful build:\n * - denormalized name/edge columns for O(log n) lookup\n * - full node/edge/area JSON for reconstructing a `VgGraph` without parsing\n * the pretty-printed graph.json (faster cold serve on XL maps)\n *\n * Uses Node's built-in `node:sqlite` (Node ≥22) — no native npm dependency.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { cacheDir } from './cache.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport type {\n Area,\n EpistemicTier,\n GraphEdge,\n GraphNode,\n ResolverKind,\n VgGraph,\n} from '../schema.js';\nimport { SCHEMA_VERSION } from '../schema.js';\n\nexport interface IndexWriteResult {\n path: string;\n nodes: number;\n edges: number;\n /** False when node:sqlite is unavailable — callers should not fail the build. */\n ok: boolean;\n reason?: string;\n}\n\nexport function indexDbPath(root: string): string {\n return path.join(cacheDir(root), 'graph.db');\n}\n\n/** Write (replace) the SQLite index from a built graph. Never throws to callers. */\nexport function writeGraphIndex(root: string, graph: VgGraph): IndexWriteResult {\n const file = indexDbPath(root);\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const tmp = `${file}.${process.pid}.tmp`;\n try {\n if (fs.existsSync(tmp)) fs.unlinkSync(tmp);\n } catch {\n /* ignore */\n }\n\n const db = new DatabaseSync(tmp);\n db.exec(`\n PRAGMA journal_mode = OFF;\n PRAGMA synchronous = OFF;\n CREATE TABLE meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE nodes (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n kind TEXT NOT NULL,\n file TEXT NOT NULL,\n line INTEGER NOT NULL,\n importance REAL NOT NULL,\n area INTEGER NOT NULL,\n is_hub INTEGER NOT NULL,\n lang TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE edges (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n src TEXT NOT NULL,\n dst TEXT NOT NULL,\n resolution TEXT NOT NULL,\n confidence REAL NOT NULL,\n epistemic TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE areas (\n id INTEGER PRIMARY KEY,\n json TEXT NOT NULL\n );\n CREATE INDEX idx_nodes_name ON nodes(name);\n CREATE INDEX idx_nodes_qn ON nodes(qualified_name);\n CREATE INDEX idx_nodes_file ON nodes(file);\n CREATE INDEX idx_edges_src ON edges(src);\n CREATE INDEX idx_edges_dst ON edges(dst);\n CREATE INDEX idx_edges_kind ON edges(kind);\n `);\n\n const insMeta = db.prepare('INSERT INTO meta(key, value) VALUES (?, ?)');\n insMeta.run('corpusHash', graph.provenance.corpusHash);\n insMeta.run('schemaVersion', graph.schemaVersion);\n insMeta.run('generatedAt', graph.generatedAt);\n insMeta.run('nodeCount', String(graph.nodes.length));\n insMeta.run('edgeCount', String(graph.edges.length));\n insMeta.run('analysisTier', graph.meta.analysisTier ?? 'full');\n insMeta.run('indexVersion', 'vg-graph-index/2');\n // Full meta + provenance for reconstruct without graph.json parse.\n insMeta.run('graphMeta', JSON.stringify(graph.meta));\n insMeta.run('graphProvenance', JSON.stringify(graph.provenance));\n if (graph.facts) insMeta.run('factsJson', JSON.stringify(graph.facts));\n if (graph.grounding) insMeta.run('groundingJson', JSON.stringify(graph.grounding));\n if (graph.summaries) insMeta.run('summariesJson', JSON.stringify(graph.summaries));\n if (graph.unknowns) insMeta.run('unknownsJson', JSON.stringify(graph.unknowns));\n\n const insNode = db.prepare(\n `INSERT INTO nodes(id, name, qualified_name, kind, file, line, importance, area, is_hub, lang, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const n of graph.nodes) {\n insNode.run(\n n.id,\n n.name,\n n.qualifiedName,\n n.kind,\n n.file,\n n.span.start,\n n.importance,\n n.area,\n n.isHub ? 1 : 0,\n n.lang,\n JSON.stringify(n),\n );\n }\n\n const insEdge = db.prepare(\n `INSERT INTO edges(id, kind, src, dst, resolution, confidence, epistemic, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const e of graph.edges) {\n insEdge.run(\n e.id,\n e.kind,\n e.src,\n e.dst,\n e.resolution,\n e.confidence,\n e.epistemic ?? 'observed',\n JSON.stringify(e),\n );\n }\n\n const insArea = db.prepare('INSERT INTO areas(id, json) VALUES (?, ?)');\n for (const a of graph.areas) {\n insArea.run(a.id, JSON.stringify(a));\n }\n\n db.close();\n fs.renameSync(tmp, file);\n return { path: file, nodes: graph.nodes.length, edges: graph.edges.length, ok: true };\n } catch (err) {\n return {\n path: file,\n nodes: 0,\n edges: 0,\n ok: false,\n reason: (err as Error).message,\n };\n }\n}\n\nexport interface NameHit {\n id: string;\n name: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n importance: number;\n}\n\n/** Fast name / prefix lookup against the index. Empty if index missing. */\nexport function lookupNameIndex(root: string, query: string, limit = 20): NameHit[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !query.trim()) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const q = query.trim();\n const rows = db\n .prepare(\n `SELECT id, name, qualified_name, kind, file, line, importance\n FROM nodes\n WHERE name = ? OR qualified_name = ? OR name LIKE ? OR qualified_name LIKE ?\n ORDER BY\n CASE WHEN name = ? OR qualified_name = ? THEN 0\n WHEN name LIKE ? THEN 1\n ELSE 2 END,\n importance DESC\n LIMIT ?`,\n )\n .all(q, q, `${q}%`, `%${q}%`, q, q, `${q}%`, limit) as Record<string, unknown>[];\n db.close();\n return rows.map((r) => ({\n id: String(r.id),\n name: String(r.name),\n qualifiedName: String(r.qualified_name),\n kind: String(r.kind),\n file: String(r.file),\n line: Number(r.line),\n importance: Number(r.importance),\n }));\n } catch {\n return [];\n }\n}\n\n/** Neighbor edges for a node id (src or dst). Empty if index missing. */\nexport function lookupNeighbors(\n root: string,\n nodeId: string,\n direction: 'out' | 'in' | 'both' = 'both',\n limit = 50,\n): GraphEdge[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !nodeId) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n let rows: Record<string, unknown>[] = [];\n if (direction === 'out' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE src = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n if (direction === 'in' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE dst = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n db.close();\n const byId = new Map<string, GraphEdge>();\n for (const r of rows) {\n try {\n const e = JSON.parse(String(r.json)) as GraphEdge;\n byId.set(e.id, e);\n } catch {\n /* skip bad row */\n }\n }\n return [...byId.values()];\n } catch {\n return [];\n }\n}\n\n/** Read index meta (corpusHash etc.) or null if missing. */\nexport function readIndexMeta(root: string): Record<string, string> | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const rows = db.prepare('SELECT key, value FROM meta').all() as { key: string; value: string }[];\n db.close();\n const out: Record<string, string> = {};\n for (const r of rows) out[r.key] = r.value;\n return out;\n } catch {\n return null;\n }\n}\n\n/**\n * Reconstruct a full `VgGraph` from the SQLite index (indexVersion ≥ 2).\n * Returns null if the index is missing, stale schema, or incomplete.\n * Prefer this over JSON.parse of pretty graph.json for cold serve on large maps.\n */\nexport function loadGraphFromIndex(root: string): VgGraph | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const metaRows = db.prepare('SELECT key, value FROM meta').all() as {\n key: string;\n value: string;\n }[];\n const meta: Record<string, string> = {};\n for (const r of metaRows) meta[r.key] = r.value;\n\n if (meta.indexVersion !== 'vg-graph-index/2' || !meta.graphMeta || !meta.graphProvenance) {\n db.close();\n return null;\n }\n\n const nodeRows = db.prepare('SELECT json FROM nodes ORDER BY id').all() as {\n json: string;\n }[];\n const edgeRows = db.prepare('SELECT json FROM edges ORDER BY id').all() as {\n json: string;\n }[];\n const areaRows = db.prepare('SELECT json FROM areas ORDER BY id').all() as {\n json: string;\n }[];\n db.close();\n\n const nodes = nodeRows.map((r) => JSON.parse(r.json) as GraphNode);\n const edges = edgeRows.map((r) => JSON.parse(r.json) as GraphEdge);\n const areas = areaRows.map((r) => JSON.parse(r.json) as Area);\n\n // Stable sorts match serialize contract (ids already ordered by SQL, re-sort for safety).\n nodes.sort((a, b) => a.id.localeCompare(b.id));\n edges.sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n areas.sort((a, b) => a.id - b.id);\n\n const graph: VgGraph = {\n schemaVersion: (meta.schemaVersion as typeof SCHEMA_VERSION) || SCHEMA_VERSION,\n generatedAt: meta.generatedAt ?? new Date(0).toISOString(),\n provenance: JSON.parse(meta.graphProvenance),\n meta: JSON.parse(meta.graphMeta),\n nodes,\n edges,\n areas,\n };\n if (meta.factsJson) graph.facts = JSON.parse(meta.factsJson);\n if (meta.groundingJson) graph.grounding = JSON.parse(meta.groundingJson);\n if (meta.summariesJson) graph.summaries = JSON.parse(meta.summariesJson);\n if (meta.unknownsJson) graph.unknowns = JSON.parse(meta.unknownsJson);\n\n // Lightweight integrity: edge resolution types stay valid.\n for (const e of edges) {\n if (!e.resolution) e.resolution = 'heuristic' as ResolverKind;\n if (!e.epistemic) e.epistemic = 'observed' as EpistemicTier;\n }\n return graph;\n } catch {\n return null;\n }\n}\n\n/**\n * Load the graph preferring the SQLite index when its corpusHash matches the\n * committed graph.json provenance (or when only the index exists). Falls back\n * to graph.json. Returns null if neither is usable.\n */\nexport function loadGraphPreferIndex(\n root: string,\n graphJsonPath: string,\n): { graph: VgGraph; source: 'index' | 'json' } | null {\n // Snapshot-first: skips the large-string JSON.parse when a fresh binary\n // snapshot exists (sidecar or store-mode standalone), and self-heals the\n // sidecar when not (see engine/snapshot.ts).\n const jsonGraph: VgGraph | null = loadGraphFileWithSnapshot(graphJsonPath);\n\n const fromIndex = loadGraphFromIndex(root);\n if (fromIndex) {\n if (!jsonGraph || fromIndex.provenance.corpusHash === jsonGraph.provenance.corpusHash) {\n return { graph: fromIndex, source: 'index' };\n }\n // Index stale vs graph.json — prefer canonical JSON and let next build refresh.\n }\n if (jsonGraph) return { graph: jsonGraph, source: 'json' };\n return null;\n}\n","import * as fs from 'node:fs';\nimport { resolveGraphPath } from './artifacts.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport { loadGraphPreferIndex } from './index-db.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Load the code map for a repository.\n *\n * When `graphPath` is omitted, prefers an existing global-store snapshot, then\n * the legacy `.vibgrate/graph.json`, matching {@link resolveGraphPath}.\n * Prefers the SQLite index when its corpusHash matches the committed map\n * (faster cold serve on large repos). Returns null if none exists.\n */\nexport function loadGraph(root: string, graphPath?: string): VgGraph | null {\n const file = resolveGraphPath(root, graphPath);\n // Index is always rooted at the project root; only use it when loading the\n // default map for that root (not an arbitrary --graph path).\n if (!graphPath) {\n const preferred = loadGraphPreferIndex(root, file);\n if (preferred) return preferred.graph;\n }\n return loadGraphFileWithSnapshot(file);\n}\n"]}
1
+ {"version":3,"sources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AA,EAAO,SAAA,EAAW,QAAQ,MAAA,EAAO;AACzD,EAAA,OAAO,IAAA;AACT;;;ACvWO,SAAS,SAAA,CAAU,MAAc,SAAA,EAAoC;AAC1E,EAAA,MAAM,IAAA,GAAO,gBAAA,CAAiB,IAAA,EAAM,SAAS,CAAA;AAG7C,EAAA,IAAI,CAAC,SAAA,EAAW;AACd,IAAA,MAAM,SAAA,GAAY,oBAAA,CAAqB,IAAA,EAAM,IAAI,CAAA;AACjD,IAAA,IAAI,SAAA,SAAkB,SAAA,CAAU,KAAA;AAAA,EAClC;AACA,EAAA,OAAO,0BAA0B,IAAI,CAAA;AACvC","file":"chunk-537JBQVB.js","sourcesContent":["/**\n * The `vg-graph/1.0` on-disk schema.\n *\n * This is vg's own open schema (VG-PACKAGE-AND-SCHEMA.md §4) — informed by good\n * ideas (content-hashed ids, epistemic typing of facts) but standalone and\n * self-contained. Every collection is deterministically serialized\n * (sorted keys, stable element order). These TypeScript shapes are normative.\n */\n\nexport const SCHEMA_VERSION = 'vg-graph/1.0' as const;\n\nexport type ResolverKind = 'scip' | 'stackgraph' | 'tsc' | 'heuristic';\n\n/** Coarse, honest resolution tier for an edge (see engine/epistemic.ts). */\nexport type EpistemicTier = 'observed' | 'name-matched' | 'declared';\n\n/**\n * The toolchain that produced this graph — the reproducibility fingerprint.\n * Everything here deterministically affects graph *content* (parse trees change\n * between grammar releases; resolvers change which edges resolve), so a CI run\n * and a laptop run that disagree can be caught by comparing `fingerprint`.\n * Deliberately excludes the Node/OS version so the graph stays byte-stable\n * across host runtimes; `fingerprint` pins the parse/resolve toolchain only.\n */\nexport interface Toolchain {\n schema: string; // SCHEMA_VERSION\n tool: string; // vg calendar version\n grammars: string; // tree-sitter grammar set version string\n resolvers: ResolverKind[]; // resolver kinds available, sorted\n fingerprint: string; // shortId over the fields above — the value `vg attest` signs\n}\n\nexport interface Provenance {\n tool: 'vg';\n version: string; // calendar version\n grammars: Record<string, string>; // lang → grammar version (determinism input)\n resolver: ResolverKind[];\n deep: boolean; // did the heavier open passes run\n semanticModel?: string; // embedding model id+version if --deep semantic links\n corpusHash: string; // blake3 over the included file set + hashes\n toolchain?: Toolchain; // reproducibility fingerprint (checked by `vg verify`)\n}\n\n/** Analysis cost tier — auto-selected by node count (or forced). Reported honestly. */\nexport type AnalysisTier = 'full' | 'large' | 'xl';\n\nexport interface GraphMeta {\n root: string; // relative; portable across machines\n languages: string[];\n counts: {\n nodes: number;\n edges: number;\n areas: number;\n tests: number;\n untested: number;\n };\n cluster: 'leiden' | 'louvain' | 'none';\n /** Auto-selected (or forced) analysis tier for large maps. */\n analysisTier?: AnalysisTier;\n edgeKinds: EdgeKind[];\n}\n\nexport type NodeKind =\n | 'file'\n | 'module'\n | 'package'\n | 'class'\n | 'interface'\n | 'function'\n | 'method'\n | 'property'\n | 'test'\n | 'route'\n | 'component'\n /** Documentation / config text ingested for semantic ask (markdown, txt, env examples). */\n | 'document'\n | 'external';\n\nexport interface Span {\n start: number; // 1-based start line\n end: number; // 1-based end line\n}\n\nexport interface Centrality {\n degree: number;\n pagerank: number;\n betweenness: number;\n eigenvector: number;\n}\n\nexport interface GraphNode {\n id: string; // blake3(canonical(kind, qualifiedName, file, signature))\n kind: NodeKind;\n name: string; // short name\n qualifiedName: string;\n file: string; // relative path\n span: Span; // line range (excluded from id hash)\n lang: string;\n visibility?: 'public' | 'private' | 'protected' | 'internal';\n signature?: string;\n doc?: string; // short leading doc-comment / docstring summary (deterministic; not a full body)\n importance: number; // 0..1 blended centrality\n centrality: Centrality;\n area: number; // area id (the node's community); -1 = unassigned (cluster \"none\")\n isHub: boolean; // centrality outlier — surfaced by `vg hubs`\n tested: boolean | null; // null = not analyzable (e.g. external)\n coverage?: number; // 0..1 line coverage if a coverage report was ingested\n changeCoupling?: string[]; // node ids that historically change together\n}\n\nexport type EdgeKind =\n | 'call'\n | 'import'\n | 'contains'\n | 'extends'\n | 'implements'\n | 'references'\n | 'test'\n | 'coverage';\n\nexport interface GraphEdge {\n id: string; // blake3(canonical(kind, src, dst))\n kind: EdgeKind;\n src: string; // node id\n dst: string; // node id\n resolution: ResolverKind; // how the edge was resolved\n confidence: number; // 0..1 (1.0 for scip/declared; lower for heuristic/dynamic)\n epistemic?: EpistemicTier; // coarse honesty tier derived from resolution+kind\n surprise?: number; // 0..1 improbability under the area model (`vg oddities`)\n count?: number; // call-site multiplicity\n}\n\nexport interface Area {\n id: number; // stable across runs (remapped to previous committed map)\n label: string; // most-central member's name (editable via `vg label`)\n size: number;\n members: string[]; // node ids, sorted\n cohesion: number; // 0..1\n externalEdges: number; // cross-area edge count\n}\n\nexport type FactKind = 'contract' | 'invariant' | 'characterization';\nexport type DerivedBy = 'declared' | 'static';\nexport type FactConfidence = 'Observed' | 'Derived';\n\nexport interface Fact {\n id: string; // blake3(canonical(kind, subjectIds, predicate))\n kind: FactKind;\n subjectIds: string[]; // node ids this fact constrains\n predicate: unknown; // the constraint\n derivedBy: DerivedBy;\n confidence: FactConfidence;\n evidence: { file: string; span: Span }[];\n}\n\n/**\n * A reference the graph could not resolve — surfaced by `vg unknowns`. Reporting\n * what it *cannot* connect (ranked by blast radius) is the honest inverse of a\n * scanner that hides its unknowns. Only unknowns the precise rungs (tsc/scip)\n * did not supersede are recorded, so a compiler-resolved file never shows here.\n */\nexport interface Unknown {\n from: string; // node id where the unresolved reference occurs\n name: string; // the callee/type name that could not be resolved\n kind: 'call' | 'extends' | 'implements';\n count: number; // occurrences at this site\n}\n\nexport type GroundingKind = 'should_follow' | 'smells_like' | 'relevant_to';\n\nexport interface GroundingEdge {\n src: string; // node id\n packEntryId: string;\n kind: GroundingKind;\n confidence: number; // 0..1\n rationale: 'recommended' | 'conjectured';\n citation: { title: string; url: string };\n}\n\n/** Precomputed hub blast-radius counts for fast agent answers (optional). */\nexport interface HubBlastSummary {\n id: string;\n name: string;\n kind: string;\n file: string;\n importance: number;\n direct: number;\n depth2: number;\n files: number;\n tested: boolean | null;\n}\n\nexport interface GraphSummaries {\n hubs: HubBlastSummary[];\n}\n\nexport interface VgGraph {\n schemaVersion: typeof SCHEMA_VERSION;\n generatedAt: string; // ISO; the ONLY nondeterministic field (pinned by --generated-at)\n provenance: Provenance;\n meta: GraphMeta;\n nodes: GraphNode[]; // sorted by id\n edges: GraphEdge[]; // sorted by (kind, src, dst)\n areas: Area[]; // sorted by id\n facts?: Fact[]; // open facts (contract/invariant/characterization); sorted by id\n grounding?: GroundingEdge[]; // free-pack grounding (default on; omit with --no-ground)\n unknowns?: Unknown[]; // heuristic references left unresolved; sorted by (from, kind, name)\n /** Build-time hub blast-radius summaries (always on; tiny). */\n summaries?: GraphSummaries;\n}\n","/**\n * SQLite serve index for large maps (scale past flat-JSON-only serve).\n *\n * The canonical artifact remains `graph.json` (determinism / git). The index\n * at `.vibgrate/cache/graph.db` is a derived, gitignored structure built after\n * every successful build:\n * - denormalized name/edge columns for O(log n) lookup\n * - full node/edge/area JSON for reconstructing a `VgGraph` without parsing\n * the pretty-printed graph.json (faster cold serve on XL maps)\n *\n * Uses Node's built-in `node:sqlite` (Node ≥22) — no native npm dependency.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { cacheDir } from './cache.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport type {\n Area,\n EpistemicTier,\n GraphEdge,\n GraphNode,\n ResolverKind,\n VgGraph,\n} from '../schema.js';\nimport { SCHEMA_VERSION } from '../schema.js';\n\nexport interface IndexWriteResult {\n path: string;\n nodes: number;\n edges: number;\n /** False when node:sqlite is unavailable — callers should not fail the build. */\n ok: boolean;\n reason?: string;\n}\n\nexport function indexDbPath(root: string): string {\n return path.join(cacheDir(root), 'graph.db');\n}\n\n/** Write (replace) the SQLite index from a built graph. Never throws to callers. */\nexport function writeGraphIndex(root: string, graph: VgGraph): IndexWriteResult {\n const file = indexDbPath(root);\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const tmp = `${file}.${process.pid}.tmp`;\n try {\n if (fs.existsSync(tmp)) fs.unlinkSync(tmp);\n } catch {\n /* ignore */\n }\n\n const db = new DatabaseSync(tmp);\n db.exec(`\n PRAGMA journal_mode = OFF;\n PRAGMA synchronous = OFF;\n CREATE TABLE meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n );\n CREATE TABLE nodes (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL,\n kind TEXT NOT NULL,\n file TEXT NOT NULL,\n line INTEGER NOT NULL,\n importance REAL NOT NULL,\n area INTEGER NOT NULL,\n is_hub INTEGER NOT NULL,\n lang TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE edges (\n id TEXT PRIMARY KEY,\n kind TEXT NOT NULL,\n src TEXT NOT NULL,\n dst TEXT NOT NULL,\n resolution TEXT NOT NULL,\n confidence REAL NOT NULL,\n epistemic TEXT NOT NULL,\n json TEXT NOT NULL\n );\n CREATE TABLE areas (\n id INTEGER PRIMARY KEY,\n json TEXT NOT NULL\n );\n CREATE INDEX idx_nodes_name ON nodes(name);\n CREATE INDEX idx_nodes_qn ON nodes(qualified_name);\n CREATE INDEX idx_nodes_file ON nodes(file);\n CREATE INDEX idx_edges_src ON edges(src);\n CREATE INDEX idx_edges_dst ON edges(dst);\n CREATE INDEX idx_edges_kind ON edges(kind);\n `);\n\n const insMeta = db.prepare('INSERT INTO meta(key, value) VALUES (?, ?)');\n insMeta.run('corpusHash', graph.provenance.corpusHash);\n insMeta.run('schemaVersion', graph.schemaVersion);\n insMeta.run('generatedAt', graph.generatedAt);\n insMeta.run('nodeCount', String(graph.nodes.length));\n insMeta.run('edgeCount', String(graph.edges.length));\n insMeta.run('analysisTier', graph.meta.analysisTier ?? 'full');\n insMeta.run('indexVersion', 'vg-graph-index/2');\n // Full meta + provenance for reconstruct without graph.json parse.\n insMeta.run('graphMeta', JSON.stringify(graph.meta));\n insMeta.run('graphProvenance', JSON.stringify(graph.provenance));\n if (graph.facts) insMeta.run('factsJson', JSON.stringify(graph.facts));\n if (graph.grounding) insMeta.run('groundingJson', JSON.stringify(graph.grounding));\n if (graph.summaries) insMeta.run('summariesJson', JSON.stringify(graph.summaries));\n if (graph.unknowns) insMeta.run('unknownsJson', JSON.stringify(graph.unknowns));\n\n const insNode = db.prepare(\n `INSERT INTO nodes(id, name, qualified_name, kind, file, line, importance, area, is_hub, lang, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const n of graph.nodes) {\n insNode.run(\n n.id,\n n.name,\n n.qualifiedName,\n n.kind,\n n.file,\n n.span.start,\n n.importance,\n n.area,\n n.isHub ? 1 : 0,\n n.lang,\n JSON.stringify(n),\n );\n }\n\n const insEdge = db.prepare(\n `INSERT INTO edges(id, kind, src, dst, resolution, confidence, epistemic, json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n );\n for (const e of graph.edges) {\n insEdge.run(\n e.id,\n e.kind,\n e.src,\n e.dst,\n e.resolution,\n e.confidence,\n e.epistemic ?? 'observed',\n JSON.stringify(e),\n );\n }\n\n const insArea = db.prepare('INSERT INTO areas(id, json) VALUES (?, ?)');\n for (const a of graph.areas) {\n insArea.run(a.id, JSON.stringify(a));\n }\n\n db.close();\n fs.renameSync(tmp, file);\n return { path: file, nodes: graph.nodes.length, edges: graph.edges.length, ok: true };\n } catch (err) {\n return {\n path: file,\n nodes: 0,\n edges: 0,\n ok: false,\n reason: (err as Error).message,\n };\n }\n}\n\nexport interface NameHit {\n id: string;\n name: string;\n qualifiedName: string;\n kind: string;\n file: string;\n line: number;\n importance: number;\n}\n\n/** Fast name / prefix lookup against the index. Empty if index missing. */\nexport function lookupNameIndex(root: string, query: string, limit = 20): NameHit[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !query.trim()) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const q = query.trim();\n const rows = db\n .prepare(\n `SELECT id, name, qualified_name, kind, file, line, importance\n FROM nodes\n WHERE name = ? OR qualified_name = ? OR name LIKE ? OR qualified_name LIKE ?\n ORDER BY\n CASE WHEN name = ? OR qualified_name = ? THEN 0\n WHEN name LIKE ? THEN 1\n ELSE 2 END,\n importance DESC\n LIMIT ?`,\n )\n .all(q, q, `${q}%`, `%${q}%`, q, q, `${q}%`, limit) as Record<string, unknown>[];\n db.close();\n return rows.map((r) => ({\n id: String(r.id),\n name: String(r.name),\n qualifiedName: String(r.qualified_name),\n kind: String(r.kind),\n file: String(r.file),\n line: Number(r.line),\n importance: Number(r.importance),\n }));\n } catch {\n return [];\n }\n}\n\n/** Neighbor edges for a node id (src or dst). Empty if index missing. */\nexport function lookupNeighbors(\n root: string,\n nodeId: string,\n direction: 'out' | 'in' | 'both' = 'both',\n limit = 50,\n): GraphEdge[] {\n const file = indexDbPath(root);\n if (!fs.existsSync(file) || !nodeId) return [];\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n let rows: Record<string, unknown>[] = [];\n if (direction === 'out' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE src = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n if (direction === 'in' || direction === 'both') {\n rows = rows.concat(\n db\n .prepare(`SELECT json FROM edges WHERE dst = ? LIMIT ?`)\n .all(nodeId, limit) as Record<string, unknown>[],\n );\n }\n db.close();\n const byId = new Map<string, GraphEdge>();\n for (const r of rows) {\n try {\n const e = JSON.parse(String(r.json)) as GraphEdge;\n byId.set(e.id, e);\n } catch {\n /* skip bad row */\n }\n }\n return [...byId.values()];\n } catch {\n return [];\n }\n}\n\n/** Read index meta (corpusHash etc.) or null if missing. */\nexport function readIndexMeta(root: string): Record<string, string> | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const rows = db.prepare('SELECT key, value FROM meta').all() as { key: string; value: string }[];\n db.close();\n const out: Record<string, string> = {};\n for (const r of rows) out[r.key] = r.value;\n return out;\n } catch {\n return null;\n }\n}\n\n/**\n * Reconstruct a full `VgGraph` from the SQLite index (indexVersion ≥ 2).\n * Returns null if the index is missing, stale schema, or incomplete.\n * Prefer this over JSON.parse of pretty graph.json for cold serve on large maps.\n */\nexport function loadGraphFromIndex(root: string): VgGraph | null {\n const file = indexDbPath(root);\n if (!fs.existsSync(file)) return null;\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const { DatabaseSync } = require('node:sqlite') as typeof import('node:sqlite');\n const db = new DatabaseSync(file, { readOnly: true });\n const metaRows = db.prepare('SELECT key, value FROM meta').all() as {\n key: string;\n value: string;\n }[];\n const meta: Record<string, string> = {};\n for (const r of metaRows) meta[r.key] = r.value;\n\n if (meta.indexVersion !== 'vg-graph-index/2' || !meta.graphMeta || !meta.graphProvenance) {\n db.close();\n return null;\n }\n\n const nodeRows = db.prepare('SELECT json FROM nodes ORDER BY id').all() as {\n json: string;\n }[];\n const edgeRows = db.prepare('SELECT json FROM edges ORDER BY id').all() as {\n json: string;\n }[];\n const areaRows = db.prepare('SELECT json FROM areas ORDER BY id').all() as {\n json: string;\n }[];\n db.close();\n\n const nodes = nodeRows.map((r) => JSON.parse(r.json) as GraphNode);\n const edges = edgeRows.map((r) => JSON.parse(r.json) as GraphEdge);\n const areas = areaRows.map((r) => JSON.parse(r.json) as Area);\n\n // Stable sorts match serialize contract (ids already ordered by SQL, re-sort for safety).\n nodes.sort((a, b) => a.id.localeCompare(b.id));\n edges.sort(\n (a, b) =>\n a.kind.localeCompare(b.kind) || a.src.localeCompare(b.src) || a.dst.localeCompare(b.dst),\n );\n areas.sort((a, b) => a.id - b.id);\n\n const graph: VgGraph = {\n schemaVersion: (meta.schemaVersion as typeof SCHEMA_VERSION) || SCHEMA_VERSION,\n generatedAt: meta.generatedAt ?? new Date(0).toISOString(),\n provenance: JSON.parse(meta.graphProvenance),\n meta: JSON.parse(meta.graphMeta),\n nodes,\n edges,\n areas,\n };\n if (meta.factsJson) graph.facts = JSON.parse(meta.factsJson);\n if (meta.groundingJson) graph.grounding = JSON.parse(meta.groundingJson);\n if (meta.summariesJson) graph.summaries = JSON.parse(meta.summariesJson);\n if (meta.unknownsJson) graph.unknowns = JSON.parse(meta.unknownsJson);\n\n // Lightweight integrity: edge resolution types stay valid.\n for (const e of edges) {\n if (!e.resolution) e.resolution = 'heuristic' as ResolverKind;\n if (!e.epistemic) e.epistemic = 'observed' as EpistemicTier;\n }\n return graph;\n } catch {\n return null;\n }\n}\n\n/**\n * Load the graph preferring the SQLite index when its corpusHash matches the\n * committed graph.json provenance (or when only the index exists). Falls back\n * to graph.json. Returns null if neither is usable.\n */\nexport function loadGraphPreferIndex(\n root: string,\n graphJsonPath: string,\n): { graph: VgGraph; source: 'index' | 'json' } | null {\n // Snapshot-first: skips the large-string JSON.parse when a fresh binary\n // snapshot exists (sidecar or store-mode standalone), and self-heals the\n // sidecar when not (see engine/snapshot.ts).\n const jsonGraph: VgGraph | null = loadGraphFileWithSnapshot(graphJsonPath);\n\n const fromIndex = loadGraphFromIndex(root);\n if (fromIndex) {\n if (!jsonGraph || fromIndex.provenance.corpusHash === jsonGraph.provenance.corpusHash) {\n return { graph: fromIndex, source: 'index' };\n }\n // Index stale vs graph.json — prefer canonical JSON and let next build refresh.\n }\n if (jsonGraph) return { graph: jsonGraph, source: 'json' };\n return null;\n}\n","import * as fs from 'node:fs';\nimport { resolveGraphPath } from './artifacts.js';\nimport { loadGraphFileWithSnapshot } from './snapshot.js';\nimport { loadGraphPreferIndex } from './index-db.js';\nimport type { VgGraph } from '../schema.js';\n\n/**\n * Load the code map for a repository.\n *\n * When `graphPath` is omitted, prefers an existing global-store snapshot, then\n * the legacy `.vibgrate/graph.json`, matching {@link resolveGraphPath}.\n * Prefers the SQLite index when its corpusHash matches the committed map\n * (faster cold serve on large repos). Returns null if none exists.\n */\nexport function loadGraph(root: string, graphPath?: string): VgGraph | null {\n const file = resolveGraphPath(root, graphPath);\n // Index is always rooted at the project root; only use it when loading the\n // default map for that root (not an arbitrary --graph path).\n if (!graphPath) {\n const preferred = loadGraphPreferIndex(root, file);\n if (preferred) return preferred.graph;\n }\n return loadGraphFileWithSnapshot(file);\n}\n"]}
@@ -1,8 +1,8 @@
1
+ import { lookupModelCapabilities } from './chunk-7BU7CWXC.js';
1
2
  import { resolveGgufPath } from './chunk-7AVYKZEM.js';
2
3
  import { managerFromProviderId, formatManagerBadgeLine } from './chunk-WHJMS7XC.js';
3
- import { lookupModelCapabilities } from './chunk-536J6HUR.js';
4
- import { MockProvider, LocalLlamaProvider, OPENAI_COMPATIBLE, OllamaProvider, OpenAiCompatibleProvider } from './chunk-SJFBXCII.js';
5
- import { CliError, ExitCode } from './chunk-FKFRASAB.js';
4
+ import { MockProvider, LocalLlamaProvider, OPENAI_COMPATIBLE, OllamaProvider, OpenAiCompatibleProvider } from './chunk-QUI3E3TQ.js';
5
+ import { CliError, ExitCode } from './chunk-23UPIFRU.js';
6
6
  import { discoverModels } from './chunk-CQDUBAQY.js';
7
7
  import * as fs from 'fs';
8
8
  import * as os from 'os';
@@ -148,6 +148,49 @@ function titleCase(id) {
148
148
  // src/code/text-tool-protocol.ts
149
149
  var TAG_RE = /<tool_call>\s*([\s\S]*?)\s*<\/tool_call>/g;
150
150
  var FENCE_RE = /```(?:tool_call|tool|json)?\s*\n?([\s\S]*?)```/g;
151
+ var CALL_SYNTAX_RE = /^([A-Za-z_][\w]*)\s*\(([\s\S]*)\)\s*;?$/;
152
+ function toCallSyntaxToolCall(blob, index, tools) {
153
+ if (!tools.length) return null;
154
+ const m = CALL_SYNTAX_RE.exec(blob.trim());
155
+ if (!m) return null;
156
+ const [, name, rawArgs] = m;
157
+ const spec = tools.find((t) => t.name === name);
158
+ if (!spec) return null;
159
+ const args = rawArgs.trim();
160
+ if (!args) return { id: `text_${index}`, name, arguments: {} };
161
+ if (args.startsWith("{")) {
162
+ try {
163
+ const parsed = JSON.parse(args);
164
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
165
+ return { id: `text_${index}`, name, arguments: parsed };
166
+ }
167
+ } catch {
168
+ return null;
169
+ }
170
+ return null;
171
+ }
172
+ const required = Array.isArray(spec.parameters?.required) ? spec.parameters.required : [];
173
+ if (required.length !== 1) return null;
174
+ const literal = parseStringLiteral(args);
175
+ if (literal === null) return null;
176
+ return { id: `text_${index}`, name, arguments: { [required[0]]: literal } };
177
+ }
178
+ function parseStringLiteral(src) {
179
+ const s = src.trim();
180
+ if (s.length < 2) return null;
181
+ const quote = s[0];
182
+ if (quote !== '"' && quote !== "'" && quote !== "`" || s[s.length - 1] !== quote) return null;
183
+ const inner = s.slice(1, -1);
184
+ if (new RegExp(`(?<!\\\\)${quote === "`" ? "`" : quote}`).test(inner)) return null;
185
+ if (quote === '"') {
186
+ try {
187
+ return JSON.parse(s);
188
+ } catch {
189
+ return null;
190
+ }
191
+ }
192
+ return inner.replace(/\\n/g, "\n").replace(/\\t/g, " ").replace(new RegExp(`\\\\${quote}`, "g"), quote);
193
+ }
151
194
  function toToolCall(blob, index) {
152
195
  let parsed;
153
196
  try {
@@ -163,7 +206,7 @@ function toToolCall(blob, index) {
163
206
  arguments: args && typeof args === "object" && !Array.isArray(args) ? args : {}
164
207
  };
165
208
  }
166
- function parseTextToolCalls(text) {
209
+ function parseTextToolCalls(text, tools = []) {
167
210
  const calls = [];
168
211
  let cleaned = text ?? "";
169
212
  cleaned = cleaned.replace(TAG_RE, (whole, body) => {
@@ -174,7 +217,8 @@ function parseTextToolCalls(text) {
174
217
  });
175
218
  if (calls.length === 0) {
176
219
  cleaned = cleaned.replace(FENCE_RE, (whole, body) => {
177
- const call = toToolCall(body.trim(), calls.length);
220
+ const blob = body.trim();
221
+ const call = toToolCall(blob, calls.length) ?? toCallSyntaxToolCall(blob, calls.length, tools);
178
222
  if (!call) return whole;
179
223
  calls.push(call);
180
224
  return "";
@@ -188,6 +232,12 @@ function parseTextToolCalls(text) {
188
232
  calls.push(call);
189
233
  cleaned = "";
190
234
  }
235
+ } else {
236
+ const call = toCallSyntaxToolCall(t, 0, tools);
237
+ if (call) {
238
+ calls.push(call);
239
+ cleaned = "";
240
+ }
191
241
  }
192
242
  }
193
243
  return { calls, text: cleaned.trim() };
@@ -233,7 +283,7 @@ function withToolCallFallback(provider, caps) {
233
283
  if (native || !opts.tools?.length) {
234
284
  const result2 = await provider.chat(messages, opts);
235
285
  if ((!result2.toolCalls || result2.toolCalls.length === 0) && result2.text) {
236
- const rescued = parseTextToolCalls(result2.text);
286
+ const rescued = parseTextToolCalls(result2.text, opts.tools ?? []);
237
287
  if (rescued.calls.length) return { ...result2, text: rescued.text, toolCalls: rescued.calls };
238
288
  }
239
289
  return result2;
@@ -247,7 +297,7 @@ function withToolCallFallback(provider, caps) {
247
297
  withProtocol.unshift({ role: "system", content: instruction });
248
298
  }
249
299
  const result = await provider.chat(withProtocol, { ...opts, tools: void 0 });
250
- const parsed = parseTextToolCalls(result.text ?? "");
300
+ const parsed = parseTextToolCalls(result.text ?? "", opts.tools);
251
301
  if (parsed.calls.length) return { ...result, text: parsed.text, toolCalls: parsed.calls };
252
302
  return result;
253
303
  }
@@ -433,5 +483,5 @@ function basename(p) {
433
483
  }
434
484
 
435
485
  export { fetchCatalog, resolveProviders, topProviders };
436
- //# sourceMappingURL=chunk-4HFSUIIN.js.map
437
- //# sourceMappingURL=chunk-4HFSUIIN.js.map
486
+ //# sourceMappingURL=chunk-5TS7N7J2.js.map
487
+ //# sourceMappingURL=chunk-5TS7N7J2.js.map