@vibgrate/cli 2026.818.2 → 2026.819.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/DOCS.md +3 -3
  2. package/dist/agent-ZJRWCMR6.js +30 -0
  3. package/dist/{agent-X6VYCE63.js.map → agent-ZJRWCMR6.js.map} +1 -1
  4. package/dist/{approvals-TPQFQSWG.js → approvals-YTUXBZWQ.js} +7 -7
  5. package/dist/{approvals-TPQFQSWG.js.map → approvals-YTUXBZWQ.js.map} +1 -1
  6. package/dist/attach-WOA25VNH.js +10 -0
  7. package/dist/{attach-G5JUIWIT.js.map → attach-WOA25VNH.js.map} +1 -1
  8. package/dist/baseline-TVRRUZGA.js +9 -0
  9. package/dist/{baseline-DXI64VLW.js.map → baseline-TVRRUZGA.js.map} +1 -1
  10. package/dist/{chunk-V6WONSIK.js → chunk-24HKTTFV.js} +5 -5
  11. package/dist/{chunk-V6WONSIK.js.map → chunk-24HKTTFV.js.map} +1 -1
  12. package/dist/{chunk-VMAIDM4K.js → chunk-2C4QT5D7.js} +5 -5
  13. package/dist/{chunk-VMAIDM4K.js.map → chunk-2C4QT5D7.js.map} +1 -1
  14. package/dist/{chunk-JGA63RGF.js → chunk-2ZBLZ2S3.js} +13 -13
  15. package/dist/{chunk-JGA63RGF.js.map → chunk-2ZBLZ2S3.js.map} +1 -1
  16. package/dist/{chunk-OV4KGXPD.js → chunk-57ZRSCHY.js} +3 -3
  17. package/dist/{chunk-OV4KGXPD.js.map → chunk-57ZRSCHY.js.map} +1 -1
  18. package/dist/{chunk-NDNNOAS6.js → chunk-6H2QV5DR.js} +3 -3
  19. package/dist/{chunk-NDNNOAS6.js.map → chunk-6H2QV5DR.js.map} +1 -1
  20. package/dist/{chunk-2C33WR5O.js → chunk-7BSUPHX6.js} +3 -3
  21. package/dist/{chunk-2C33WR5O.js.map → chunk-7BSUPHX6.js.map} +1 -1
  22. package/dist/{chunk-LJSJX6U4.js → chunk-A3WWRW7U.js} +3 -3
  23. package/dist/{chunk-LJSJX6U4.js.map → chunk-A3WWRW7U.js.map} +1 -1
  24. package/dist/{chunk-X2MQ7UFL.js → chunk-AP3JN33O.js} +12 -12
  25. package/dist/{chunk-X2MQ7UFL.js.map → chunk-AP3JN33O.js.map} +1 -1
  26. package/dist/{chunk-O5IJDMTB.js → chunk-AQZYDFEK.js} +4 -4
  27. package/dist/{chunk-O5IJDMTB.js.map → chunk-AQZYDFEK.js.map} +1 -1
  28. package/dist/{chunk-VQ5KMHW6.js → chunk-BQ6NTRRK.js} +44 -15
  29. package/dist/chunk-BQ6NTRRK.js.map +1 -0
  30. package/dist/{chunk-HF6R73UC.js → chunk-C2EZIAA3.js} +27 -13
  31. package/dist/chunk-C2EZIAA3.js.map +1 -0
  32. package/dist/{chunk-MRZHNUN7.js → chunk-CA4YQBA7.js} +4 -4
  33. package/dist/{chunk-MRZHNUN7.js.map → chunk-CA4YQBA7.js.map} +1 -1
  34. package/dist/{chunk-YF54UMOU.js → chunk-CBL3VY7J.js} +3 -3
  35. package/dist/{chunk-YF54UMOU.js.map → chunk-CBL3VY7J.js.map} +1 -1
  36. package/dist/{chunk-PRHH4DVO.js → chunk-FCMWHSQ6.js} +3 -3
  37. package/dist/{chunk-PRHH4DVO.js.map → chunk-FCMWHSQ6.js.map} +1 -1
  38. package/dist/{chunk-V2UGRUTL.js → chunk-GBXOAO5V.js} +176 -37
  39. package/dist/chunk-GBXOAO5V.js.map +1 -0
  40. package/dist/{chunk-JFE7XCAE.js → chunk-IASO2HCI.js} +3 -3
  41. package/dist/{chunk-JFE7XCAE.js.map → chunk-IASO2HCI.js.map} +1 -1
  42. package/dist/{chunk-ZUOBPKVK.js → chunk-IMI2VHHZ.js} +3 -3
  43. package/dist/{chunk-ZUOBPKVK.js.map → chunk-IMI2VHHZ.js.map} +1 -1
  44. package/dist/{chunk-NKLYDSB7.js → chunk-JPOYXG7Z.js} +10 -10
  45. package/dist/{chunk-NKLYDSB7.js.map → chunk-JPOYXG7Z.js.map} +1 -1
  46. package/dist/{chunk-L2OS4WHT.js → chunk-MMJFHEZ4.js} +4 -4
  47. package/dist/{chunk-L2OS4WHT.js.map → chunk-MMJFHEZ4.js.map} +1 -1
  48. package/dist/{chunk-E3O5UKNA.js → chunk-NKKOGJ63.js} +35 -17
  49. package/dist/chunk-NKKOGJ63.js.map +1 -0
  50. package/dist/{chunk-7AVYKZEM.js → chunk-NV7XNBX4.js} +4 -4
  51. package/dist/{chunk-7AVYKZEM.js.map → chunk-NV7XNBX4.js.map} +1 -1
  52. package/dist/{chunk-NJQZRM55.js → chunk-OGFOJG4H.js} +6 -6
  53. package/dist/{chunk-NJQZRM55.js.map → chunk-OGFOJG4H.js.map} +1 -1
  54. package/dist/{chunk-NZELMYT4.js → chunk-OLIMW4PQ.js} +8 -56
  55. package/dist/chunk-OLIMW4PQ.js.map +1 -0
  56. package/dist/{chunk-B4EXD5LK.js → chunk-PJRPSYFQ.js} +9 -7
  57. package/dist/chunk-PJRPSYFQ.js.map +1 -0
  58. package/dist/{chunk-NG4KIJW6.js → chunk-PVNALGTG.js} +10 -6
  59. package/dist/chunk-PVNALGTG.js.map +1 -0
  60. package/dist/{chunk-BMOFJIMG.js → chunk-QE6F62FR.js} +3 -3
  61. package/dist/{chunk-BMOFJIMG.js.map → chunk-QE6F62FR.js.map} +1 -1
  62. package/dist/{chunk-6ABMV74F.js → chunk-R5TQBIR6.js} +4 -4
  63. package/dist/{chunk-6ABMV74F.js.map → chunk-R5TQBIR6.js.map} +1 -1
  64. package/dist/{chunk-5I4VSBWQ.js → chunk-RTURQXQL.js} +372 -113
  65. package/dist/chunk-RTURQXQL.js.map +1 -0
  66. package/dist/{chunk-74UBGF4P.js → chunk-SHD5TCZ5.js} +3 -3
  67. package/dist/{chunk-74UBGF4P.js.map → chunk-SHD5TCZ5.js.map} +1 -1
  68. package/dist/{chunk-KU7FI5EV.js → chunk-USPMMVNH.js} +3 -3
  69. package/dist/{chunk-KU7FI5EV.js.map → chunk-USPMMVNH.js.map} +1 -1
  70. package/dist/{chunk-E53WBVUQ.js → chunk-VHRSG6CF.js} +3 -3
  71. package/dist/{chunk-E53WBVUQ.js.map → chunk-VHRSG6CF.js.map} +1 -1
  72. package/dist/{chunk-I5LP55B6.js → chunk-W44THEXF.js} +3 -3
  73. package/dist/{chunk-I5LP55B6.js.map → chunk-W44THEXF.js.map} +1 -1
  74. package/dist/{chunk-AEJYA6HZ.js → chunk-W6ASIMG5.js} +7 -7
  75. package/dist/{chunk-AEJYA6HZ.js.map → chunk-W6ASIMG5.js.map} +1 -1
  76. package/dist/{chunk-CQDUBAQY.js → chunk-WNKGRXUA.js} +3 -3
  77. package/dist/{chunk-CQDUBAQY.js.map → chunk-WNKGRXUA.js.map} +1 -1
  78. package/dist/{chunk-RHKOUPWT.js → chunk-WPLOEFZU.js} +7 -5
  79. package/dist/chunk-WPLOEFZU.js.map +1 -0
  80. package/dist/{chunk-FJG5AXKZ.js → chunk-WUFIXAEJ.js} +22 -6
  81. package/dist/chunk-WUFIXAEJ.js.map +1 -0
  82. package/dist/{chunk-6PFHDHOL.js → chunk-XLQ4YHS3.js} +16 -14
  83. package/dist/chunk-XLQ4YHS3.js.map +1 -0
  84. package/dist/{chunk-BWPBB45M.js → chunk-XP6UUCZZ.js} +3 -3
  85. package/dist/{chunk-BWPBB45M.js.map → chunk-XP6UUCZZ.js.map} +1 -1
  86. package/dist/{chunk-BPF3YX2U.js → chunk-XQNKCA2J.js} +6 -3
  87. package/dist/chunk-XQNKCA2J.js.map +1 -0
  88. package/dist/{chunk-FFXGWFAE.js → chunk-XW2XQM3C.js} +7 -7
  89. package/dist/{chunk-FFXGWFAE.js.map → chunk-XW2XQM3C.js.map} +1 -1
  90. package/dist/{chunk-7N4Y3E47.js → chunk-YJYEPYB2.js} +13 -18
  91. package/dist/chunk-YJYEPYB2.js.map +1 -0
  92. package/dist/chunk-ZUZHYAJK.js +6 -0
  93. package/dist/{chunk-4NTNMT6T.js.map → chunk-ZUZHYAJK.js.map} +1 -1
  94. package/dist/cli.js +112 -108
  95. package/dist/cli.js.map +1 -1
  96. package/dist/client-P5XSRFV4.js +8 -0
  97. package/dist/{client-UQIELEEZ.js.map → client-P5XSRFV4.js.map} +1 -1
  98. package/dist/daemon-YKOEP3XA.js +30 -0
  99. package/dist/{daemon-GUMWMKCA.js.map → daemon-YKOEP3XA.js.map} +1 -1
  100. package/dist/embed-worker-main.js +5 -5
  101. package/dist/ensure-map-BLRJDO2Y.js +40 -0
  102. package/dist/{ensure-map-FHDJTO7Y.js.map → ensure-map-BLRJDO2Y.js.map} +1 -1
  103. package/dist/federation-M4ZNXOPX.js +8 -0
  104. package/dist/{federation-MDQPO3PW.js.map → federation-M4ZNXOPX.js.map} +1 -1
  105. package/dist/fs-FO3NQHPT.js +4 -0
  106. package/dist/fs-FO3NQHPT.js.map +1 -0
  107. package/dist/git-ref-LMT3EXYY.js +4 -0
  108. package/dist/{git-ref-RSRAN4OH.js.map → git-ref-LMT3EXYY.js.map} +1 -1
  109. package/dist/graph-backend-NTYONTWW.js +16 -0
  110. package/dist/{graph-backend-W2D3HRRD.js.map → graph-backend-NTYONTWW.js.map} +1 -1
  111. package/dist/index.d.ts +1 -1
  112. package/dist/index.js +24 -25
  113. package/dist/index.js.map +1 -1
  114. package/dist/{interactive-2MK4TLRD.js → interactive-B3WTC7LB.js} +41 -42
  115. package/dist/interactive-B3WTC7LB.js.map +1 -0
  116. package/dist/{llm-host-XFYFOAAX.js → llm-host-QVTJJVER.js} +5 -5
  117. package/dist/{llm-host-XFYFOAAX.js.map → llm-host-QVTJJVER.js.map} +1 -1
  118. package/dist/load-AJROS77R.js +11 -0
  119. package/dist/{load-4R4HYMBB.js.map → load-AJROS77R.js.map} +1 -1
  120. package/dist/local-runtime-GA43KYS5.js +6 -0
  121. package/dist/{local-runtime-6SNWKSA7.js.map → local-runtime-GA43KYS5.js.map} +1 -1
  122. package/dist/model-manager-6H3TMZKK.js +10 -0
  123. package/dist/{model-manager-SXHZ5VD4.js.map → model-manager-6H3TMZKK.js.map} +1 -1
  124. package/dist/{model-orchestrator-LHYPJBFH.js → model-orchestrator-X3NE3Y2G.js} +6 -6
  125. package/dist/{model-orchestrator-LHYPJBFH.js.map → model-orchestrator-X3NE3Y2G.js.map} +1 -1
  126. package/dist/parse-worker.js +2 -2
  127. package/dist/{paths-62AKTFSR.js → paths-RVK6FKRN.js} +4 -4
  128. package/dist/{paths-62AKTFSR.js.map → paths-RVK6FKRN.js.map} +1 -1
  129. package/dist/publish-27S66NOW.js +9 -0
  130. package/dist/{publish-7YHRTBRA.js.map → publish-27S66NOW.js.map} +1 -1
  131. package/dist/resolve-gguf-WVKVDN45.js +9 -0
  132. package/dist/{resolve-gguf-SDIYGGI6.js.map → resolve-gguf-WVKVDN45.js.map} +1 -1
  133. package/dist/{run-outcome-H5GVDDZJ.js → run-outcome-SBBSTSH3.js} +7 -7
  134. package/dist/{run-outcome-H5GVDDZJ.js.map → run-outcome-SBBSTSH3.js.map} +1 -1
  135. package/dist/runtime-session-JYYKQVDX.js +26 -0
  136. package/dist/{runtime-session-JBIHHH5N.js.map → runtime-session-JYYKQVDX.js.map} +1 -1
  137. package/dist/session-2ZMHZ2O6.js +17 -0
  138. package/dist/{session-N5IU4K5Q.js.map → session-2ZMHZ2O6.js.map} +1 -1
  139. package/dist/{slot-subscription-25GOARW5.js → slot-subscription-C2ZUJED6.js} +5 -5
  140. package/dist/{slot-subscription-25GOARW5.js.map → slot-subscription-C2ZUJED6.js.map} +1 -1
  141. package/dist/{stream-json-4WLSUF6I.js → stream-json-ZWGB4C47.js} +17 -17
  142. package/dist/{stream-json-4WLSUF6I.js.map → stream-json-ZWGB4C47.js.map} +1 -1
  143. package/dist/version-5QIEUXU6.js +4 -0
  144. package/dist/{version-DTEU3SQD.js.map → version-5QIEUXU6.js.map} +1 -1
  145. package/dist/{vg-mcp-bridge-KDVYIMFX.js → vg-mcp-bridge-4FETMJ6M.js} +16 -15
  146. package/dist/vg-mcp-bridge-4FETMJ6M.js.map +1 -0
  147. package/dist/{vgd-M7UOPWLB.js → vgd-R524P5BJ.js} +13 -14
  148. package/dist/vgd-R524P5BJ.js.map +1 -0
  149. package/package.json +1 -1
  150. package/dist/agent-X6VYCE63.js +0 -30
  151. package/dist/attach-G5JUIWIT.js +0 -10
  152. package/dist/baseline-DXI64VLW.js +0 -9
  153. package/dist/chunk-4NTNMT6T.js +0 -6
  154. package/dist/chunk-5I4VSBWQ.js.map +0 -1
  155. package/dist/chunk-6PFHDHOL.js.map +0 -1
  156. package/dist/chunk-7N4Y3E47.js.map +0 -1
  157. package/dist/chunk-B4EXD5LK.js.map +0 -1
  158. package/dist/chunk-BPF3YX2U.js.map +0 -1
  159. package/dist/chunk-E3O5UKNA.js.map +0 -1
  160. package/dist/chunk-FJG5AXKZ.js.map +0 -1
  161. package/dist/chunk-HF6R73UC.js.map +0 -1
  162. package/dist/chunk-NG4KIJW6.js.map +0 -1
  163. package/dist/chunk-NZELMYT4.js.map +0 -1
  164. package/dist/chunk-POOL355F.js +0 -237
  165. package/dist/chunk-POOL355F.js.map +0 -1
  166. package/dist/chunk-RHKOUPWT.js.map +0 -1
  167. package/dist/chunk-V2UGRUTL.js.map +0 -1
  168. package/dist/chunk-VQ5KMHW6.js.map +0 -1
  169. package/dist/client-UQIELEEZ.js +0 -8
  170. package/dist/daemon-GUMWMKCA.js +0 -31
  171. package/dist/ensure-map-FHDJTO7Y.js +0 -41
  172. package/dist/federation-MDQPO3PW.js +0 -7
  173. package/dist/fs-TLPOWC2D.js +0 -4
  174. package/dist/fs-TLPOWC2D.js.map +0 -1
  175. package/dist/git-ref-RSRAN4OH.js +0 -4
  176. package/dist/graph-backend-W2D3HRRD.js +0 -16
  177. package/dist/interactive-2MK4TLRD.js.map +0 -1
  178. package/dist/load-4R4HYMBB.js +0 -11
  179. package/dist/local-runtime-6SNWKSA7.js +0 -6
  180. package/dist/model-manager-SXHZ5VD4.js +0 -10
  181. package/dist/publish-7YHRTBRA.js +0 -9
  182. package/dist/resolve-gguf-SDIYGGI6.js +0 -9
  183. package/dist/runtime-session-JBIHHH5N.js +0 -27
  184. package/dist/session-N5IU4K5Q.js +0 -17
  185. package/dist/version-DTEU3SQD.js +0 -4
  186. package/dist/vg-mcp-bridge-KDVYIMFX.js.map +0 -1
  187. package/dist/vgd-M7UOPWLB.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schema.ts","../src/engine/index-db.ts","../src/engine/load.ts"],"names":[],"mappings":";;;;;;;AAoBO,IAAM,cAAA,GAAiB;AAQvB,IAAM,yBAAA,GAA4B,CAAC,cAAA,EAAgB,cAAc;;;ACQjE,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,CAAA;AAC9C,IAAG,aAAe,IAAA,CAAA,OAAA,CAAQ,IAAI,GAAG,EAAE,SAAA,EAAW,MAAM,CAAA;AACpD,IAAA,MAAM,GAAA,GAAM,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,QAAQ,GAAG,CAAA,IAAA,CAAA;AAClC,IAAA,IAAI;AACF,MAAA,IAAO,EAAA,CAAA,UAAA,CAAW,GAAG,CAAA,EAAM,cAAW,GAAG,CAAA;AAAA,IAC3C,CAAA,CAAA,MAAQ;AAAA,IAER;AAEA,IAAA,MAAM,EAAA,GAAK,IAAI,YAAA,CAAa,GAAG,CAAA;AAC/B,IAAA,EAAA,CAAG,IAAA,CAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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a,CAAA;AAEzE,EAAA,MAAM,SAAA,GAAY,mBAAmB,IAAI,CAAA;AACzC,EAAA,IAAI,SAAA,EAAW;AACb,IAAA,IAAI,CAAC,SAAA,IAAa,SAAA,CAAU,WAAW,UAAA,KAAe,SAAA,CAAU,WAAW,UAAA,EAAY;AACrF,MAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,MAAA,EAAQ,OAAA,EAAQ;AAAA,IAC7C;AAAA,EAEF;AACA,EAAA,IAAI,WAAW,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,QAAQ,MAAA,EAAO;AACzD,EAAA,OAAO,IAAA;AACT;;;ACxWO,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-KU7FI5EV.js","sourcesContent":["/**\n * The `vg-graph/1.1` 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 * ## Version history\n *\n * - `vg-graph/1.0` — code-only vocabulary.\n * - `vg-graph/1.1` — **additive**: toolchain node kinds (`resource`, `workload`,\n * `job`, `step`, `image`, `chart`) and toolchain edge kinds (`depends_on`,\n * `provisions`, `deploys`, `triggers`, `exposes`, `mounts`, `builds_from`),\n * produced by `engine/toolchain/`. Nothing was removed or renamed, so a 1.0\n * reader that tolerates unknown kinds reads a 1.1 graph correctly; readers\n * that hard-match the version string need widening (see\n * `SUPPORTED_SCHEMA_VERSIONS`).\n */\n\nexport const SCHEMA_VERSION = 'vg-graph/1.1' as const;\n\n/**\n * Schema versions a reader should accept. The toolchain vocabulary added in 1.1\n * is purely additive, so a 1.0 artifact still loads — only the newer kinds are\n * absent from it. Readers must prefer this over an equality check on\n * {@link SCHEMA_VERSION}, which rejects perfectly readable older graphs.\n */\nexport const SUPPORTED_SCHEMA_VERSIONS = ['vg-graph/1.0', 'vg-graph/1.1'] as const;\n\nexport type SupportedSchemaVersion = (typeof SUPPORTED_SCHEMA_VERSIONS)[number];\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 // ── Toolchain kinds (engine/toolchain/) ──────────────────────────────────\n // Structural extraction of the infrastructure/CI corpus. These sit alongside\n // the code kinds above and never replace the `document` node for the same\n // file: the document node stays the semantic-ask surface, these carry the\n // structure. Additive — consumers must tolerate unknown kinds.\n /** A declared infrastructure object: Terraform resource/data, K8s object, Compose service. */\n | 'resource'\n /** A deployable unit that runs containers (Deployment, StatefulSet, DaemonSet, Job, CronJob). */\n | 'workload'\n /** A CI job (GitHub Actions job, GitLab CI job). */\n | 'job'\n /** A single step within a CI job. */\n | 'step'\n /** A container image reference (`ghcr.io/acme/web:1.2.3`) or a Dockerfile build stage. */\n | 'image'\n /** A Helm chart (from `Chart.yaml`). */\n | 'chart';\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 // ── Toolchain edge kinds (engine/toolchain/) ─────────────────────────────\n // Every edge below is produced by structural extraction or by the\n // cross-domain linker. Linker-produced edges are always\n // `resolution: 'heuristic'` with a calibrated confidence — an inferred\n // `deploys` is not a declared `import` and must never claim to be.\n /** Declared ordering/reference dependency (Terraform `depends_on` + interpolation, Compose `depends_on`, CI `needs`). */\n | 'depends_on'\n /** An IaC declaration creates infrastructure (Terraform module → resource, chart → workload). */\n | 'provisions'\n /** A CI job or IaC declaration puts a workload/image into an environment. */\n | 'deploys'\n /** An event or upstream job causes a workflow/job to run. */\n | 'triggers'\n /** A workload/service publishes a port or endpoint. */\n | 'exposes'\n /** A workload/service consumes a volume, config map, or secret *by reference*. */\n | 'mounts'\n /** A build stage or workload is derived from a container image. */\n | 'builds_from';\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 /**\n * The schema this artifact was written against. A freshly built graph always\n * carries {@link SCHEMA_VERSION}; a graph *loaded* from disk may carry any\n * member of {@link SUPPORTED_SCHEMA_VERSIONS}, since older artifacts stay\n * readable (the 1.1 additions are additive).\n */\n schemaVersion: SupportedSchemaVersion;\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 \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 \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 \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 \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 \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 { 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":["../src/schema.ts","../src/engine/index-db.ts","../src/engine/load.ts"],"names":[],"mappings":";;;;;;;AAoBO,IAAM,cAAA,GAAiB;AAQvB,IAAM,yBAAA,GAA4B,CAAC,cAAA,EAAgB,cAAc;;;ACQjE,SAAS,YAAY,IAAA,EAAsB;AAChD,EAAA,OAAY,IAAA,CAAA,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA,EAAG,UAAU,CAAA;AA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,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-USPMMVNH.js","sourcesContent":["/**\n * The `vg-graph/1.1` 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 * ## Version history\n *\n * - `vg-graph/1.0` — code-only vocabulary.\n * - `vg-graph/1.1` — **additive**: toolchain node kinds (`resource`, `workload`,\n * `job`, `step`, `image`, `chart`) and toolchain edge kinds (`depends_on`,\n * `provisions`, `deploys`, `triggers`, `exposes`, `mounts`, `builds_from`),\n * produced by `engine/toolchain/`. Nothing was removed or renamed, so a 1.0\n * reader that tolerates unknown kinds reads a 1.1 graph correctly; readers\n * that hard-match the version string need widening (see\n * `SUPPORTED_SCHEMA_VERSIONS`).\n */\n\nexport const SCHEMA_VERSION = 'vg-graph/1.1' as const;\n\n/**\n * Schema versions a reader should accept. The toolchain vocabulary added in 1.1\n * is purely additive, so a 1.0 artifact still loads — only the newer kinds are\n * absent from it. Readers must prefer this over an equality check on\n * {@link SCHEMA_VERSION}, which rejects perfectly readable older graphs.\n */\nexport const SUPPORTED_SCHEMA_VERSIONS = ['vg-graph/1.0', 'vg-graph/1.1'] as const;\n\nexport type SupportedSchemaVersion = (typeof SUPPORTED_SCHEMA_VERSIONS)[number];\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 // ── Toolchain kinds (engine/toolchain/) ──────────────────────────────────\n // Structural extraction of the infrastructure/CI corpus. These sit alongside\n // the code kinds above and never replace the `document` node for the same\n // file: the document node stays the semantic-ask surface, these carry the\n // structure. Additive — consumers must tolerate unknown kinds.\n /** A declared infrastructure object: Terraform resource/data, K8s object, Compose service. */\n | 'resource'\n /** A deployable unit that runs containers (Deployment, StatefulSet, DaemonSet, Job, CronJob). */\n | 'workload'\n /** A CI job (GitHub Actions job, GitLab CI job). */\n | 'job'\n /** A single step within a CI job. */\n | 'step'\n /** A container image reference (`ghcr.io/acme/web:1.2.3`) or a Dockerfile build stage. */\n | 'image'\n /** A Helm chart (from `Chart.yaml`). */\n | 'chart';\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 // ── Toolchain edge kinds (engine/toolchain/) ─────────────────────────────\n // Every edge below is produced by structural extraction or by the\n // cross-domain linker. Linker-produced edges are always\n // `resolution: 'heuristic'` with a calibrated confidence — an inferred\n // `deploys` is not a declared `import` and must never claim to be.\n /** Declared ordering/reference dependency (Terraform `depends_on` + interpolation, Compose `depends_on`, CI `needs`). */\n | 'depends_on'\n /** An IaC declaration creates infrastructure (Terraform module → resource, chart → workload). */\n | 'provisions'\n /** A CI job or IaC declaration puts a workload/image into an environment. */\n | 'deploys'\n /** An event or upstream job causes a workflow/job to run. */\n | 'triggers'\n /** A workload/service publishes a port or endpoint. */\n | 'exposes'\n /** A workload/service consumes a volume, config map, or secret *by reference*. */\n | 'mounts'\n /** A build stage or workload is derived from a container image. */\n | 'builds_from';\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 /**\n * The schema this artifact was written against. A freshly built graph always\n * carries {@link SCHEMA_VERSION}; a graph *loaded* from disk may carry any\n * member of {@link SUPPORTED_SCHEMA_VERSIONS}, since older artifacts stay\n * readable (the 1.1 additions are additive).\n */\n schemaVersion: SupportedSchemaVersion;\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 \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 \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 \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 \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 \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 { 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,4 +1,4 @@
1
- import { vgdSocketPath } from './chunk-NDNNOAS6.js';
1
+ import { vgdSocketPath } from './chunk-6H2QV5DR.js';
2
2
  import * as net from 'net';
3
3
 
4
4
  function defaultVgdTimeoutMs(op) {
@@ -69,5 +69,5 @@ async function vgdIsRunning(options = {}) {
69
69
  }
70
70
 
71
71
  export { defaultVgdTimeoutMs, vgdIsRunning, vgdRequest };
72
- //# sourceMappingURL=chunk-E53WBVUQ.js.map
73
- //# sourceMappingURL=chunk-E53WBVUQ.js.map
72
+ //# sourceMappingURL=chunk-VHRSG6CF.js.map
73
+ //# sourceMappingURL=chunk-VHRSG6CF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/vgd/client.ts"],"names":[],"mappings":";;;AAoBO,SAAS,oBAAoB,EAAA,EAA8B;AAChE,EAAA,QAAQ,EAAA;AAAI,IACV,KAAK,MAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,OAAO,GAAA;AAAA;AAAA,IACT,KAAK,WAAA;AAAA,IACL,KAAK,YAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,IAAA;AAAA;AAAA,IACT,KAAK,eAAA;AACH,MAAA,OAAO,GAAA;AAAA;AAAA,IACT,KAAK,aAAA;AAAA,IACL,KAAK,YAAA;AAIH,MAAA,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AO,OAAA,CAAQ,IAAI,CAAA;AAC9B,MAAA,IAAI,KAAK,CAAA,EAAG;AACZ,MAAA,MAAM,OAAO,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,EAAE,EAAE,IAAA,EAAK;AACtC,MAAA,IAAI;AACF,QAAA,MAAA,CAAO,KAAA,CAAA,EAAW,IAAA,CAAK,KAAA,CAAM,IAAI,CAAgB,CAAA;AAAA,MACnD,SAAS,CAAA,EAAG;AACV,QAAA,MAAA,CAAO,CAAA,YAAa,QAAQ,CAAA,GAAI,IAAI,MAAM,MAAA,CAAO,CAAC,CAAC,CAAC,CAAA;AAAA,MACtD;AAAA,IACF,CAAC,CAAA;AACD,IAAA,MAAA,CAAO,GAAG,OAAA,EAAS,CAAC,GAAA,KAAQ,MAAA,CAAO,GAAG,CAAC,CAAA;AACvC,IAAA,MAAA,CAAO,EAAA,CAAG,OAAO,MAAM;AACrB,MAAA,IAAI,CAAC,OAAA,EAAS,MAAA,CAAO,IAAI,KAAA,CAAM,6CAA6C,CAAC,CAAA;AAAA,IAC/E,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AACH;AAGA,eAAsB,YAAA,CAAa,OAAA,GAA4B,EAAC,EAAqB;AACnF,EAAA,IAAI;AACF,IAAA,MAAM,MAAM,MAAM,UAAA,CAAW,EAAE,EAAA,EAAI,MAAA,IAAU,OAAO,CAAA;AACpD,IAAA,OAAO,IAAI,EAAA,KAAO,IAAA,IAAQ,MAAA,IAAU,GAAA,IAAO,IAAI,IAAA,KAAS,IAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-E53WBVUQ.js","sourcesContent":["import * as net from 'node:net';\nimport type { VgdRequest, VgdResponse } from './protocol.js';\nimport { vgdSocketPath } from './paths.js';\n\nexport interface VgdClientOptions {\n socketPath?: string;\n /** End-to-end response timeout in ms (default: per-op, see {@link defaultVgdTimeoutMs}). */\n timeoutMs?: number;\n}\n\n/**\n * Default response timeout per operation.\n *\n * The timer spans the whole round trip — writing the request, the daemon\n * handling it, and the reply. Liveness probes must fail fast, but a flat 2s\n * default guaranteed false \"vgd did not respond\" failures on large repos:\n * `put-graph` ships the entire code map as one JSON line (tens of MB for a\n * 40k-file workspace), and the single-threaded daemon needs seconds to read\n * and store it. Ops that ride on a busy daemon's event loop get headroom too.\n */\nexport function defaultVgdTimeoutMs(op: VgdRequest['op']): number {\n switch (op) {\n case 'ping':\n case 'status':\n return 2000; // liveness probes — fail fast\n case 'put-graph':\n case 'load-graph':\n case 'host-load':\n return 120_000; // large payload / disk load / model load\n case 'host-generate':\n return 300_000; // local model generation\n case 'embed-index':\n case 'embed-rank':\n // First ask on a large repo may have to wait for the slot index (or for\n // a `vg embed` child that already holds the cache lock). 10s made\n // `vg ask` give up and re-embed tens of thousands of nodes in-process.\n return 600_000;\n default:\n return 10_000; // registry + graph queries — may queue behind a put-graph\n }\n}\n\n/**\n * Send one request to a running vgd and return the parsed response.\n * Rejects if the daemon is not reachable.\n */\nexport function vgdRequest(request: VgdRequest, options: VgdClientOptions = {}): Promise<VgdResponse> {\n const socketPath = options.socketPath ?? vgdSocketPath();\n const timeoutMs = options.timeoutMs ?? defaultVgdTimeoutMs(request.op);\n\n return new Promise((resolve, reject) => {\n const socket = net.createConnection(socketPath);\n let settled = false;\n let buffer = '';\n\n const finish = (err?: Error, value?: VgdResponse): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n socket.destroy();\n if (err) reject(err);\n else resolve(value!);\n };\n\n const timer = setTimeout(() => finish(new Error(`vgd did not respond within ${timeoutMs}ms`)), timeoutMs);\n\n socket.setEncoding('utf8');\n socket.on('connect', () => {\n socket.write(JSON.stringify(request) + '\\n');\n });\n socket.on('data', (chunk: string) => {\n buffer += chunk;\n const nl = buffer.indexOf('\\n');\n if (nl < 0) return;\n const line = buffer.slice(0, nl).trim();\n try {\n finish(undefined, JSON.parse(line) as VgdResponse);\n } catch (e) {\n finish(e instanceof Error ? e : new Error(String(e)));\n }\n });\n socket.on('error', (err) => finish(err));\n socket.on('end', () => {\n if (!settled) finish(new Error('vgd closed the connection before responding'));\n });\n });\n}\n\n/** True when a local vgd answers ping. */\nexport async function vgdIsRunning(options: VgdClientOptions = {}): Promise<boolean> {\n try {\n const res = await vgdRequest({ op: 'ping' }, options);\n return res.ok === true && 'pong' in res && res.pong === true;\n } catch {\n return false;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/runtime/vgd/client.ts"],"names":[],"mappings":";;;AAoBO,SAAS,oBAAoB,EAAA,EAA8B;AAChE,EAAA,QAAQ,EAAA;AAAI,IACV,KAAK,MAAA;AAAA,IACL,KAAK,QAAA;AACH,MAAA,OAAO,GAAA;AAAA;AAAA,IACT,KAAK,WAAA;AAAA,IACL,KAAK,YAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,IAAA;AAAA;AAAA,IACT,KAAK,eAAA;AACH,MAAA,OAAO,GAAA;AAAA;AAAA,IACT,KAAK,aAAA;AAAA,IACL,KAAK,YAAA;AAIH,MAAA,OAAO,GAAA;AAAA,IACT;AACE,MAAA,OAAO,GAAA;AAAA;AAEb;AAMO,SAAS,UAAA,CAAW,OAAA,EAAqB,OAAA,GAA4B,EAAC,EAAyB;AACpG,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,UAAA,IAAc,aAAA,EAAc;AACvD,EAAA,MAAM,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,mBAAA,CAAoB,QAAQ,EAAE,CAAA;AAErE,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,MAAM,MAAA,GAAa,qBAAiB,UAAU,CAAA;AAC9C,IAAA,IAAI,OAAA,GAAU,KAAA;AACd,IAAA,IAAI,MAAA,GAAS,EAAA;AAEb,IAAA,MAAM,MAAA,GAAS,CAAC,GAAA,EAAa,KAAA,KAA8B;AACzD,MAAA,IAAI,OAAA,EAAS;AACb,MAAA,OA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AI,CAAC,OAAA,EAAS,MAAA,CAAO,IAAI,KAAA,CAAM,6CAA6C,CAAC,CAAA;AAAA,IAC/E,CAAC,CAAA;AAAA,EACH,CAAC,CAAA;AACH;AAGA,eAAsB,YAAA,CAAa,OAAA,GAA4B,EAAC,EAAqB;AACnF,EAAA,IAAI;AACF,IAAA,MAAM,MAAM,MAAM,UAAA,CAAW,EAAE,EAAA,EAAI,MAAA,IAAU,OAAO,CAAA;AACpD,IAAA,OAAO,IAAI,EAAA,KAAO,IAAA,IAAQ,MAAA,IAAU,GAAA,IAAO,IAAI,IAAA,KAAS,IAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF","file":"chunk-VHRSG6CF.js","sourcesContent":["import * as net from 'node:net';\nimport type { VgdRequest, VgdResponse } from './protocol.js';\nimport { vgdSocketPath } from './paths.js';\n\nexport interface VgdClientOptions {\n socketPath?: string;\n /** End-to-end response timeout in ms (default: per-op, see {@link defaultVgdTimeoutMs}). */\n timeoutMs?: number;\n}\n\n/**\n * Default response timeout per operation.\n *\n * The timer spans the whole round trip — writing the request, the daemon\n * handling it, and the reply. Liveness probes must fail fast, but a flat 2s\n * default guaranteed false \"vgd did not respond\" failures on large repos:\n * `put-graph` ships the entire code map as one JSON line (tens of MB for a\n * 40k-file workspace), and the single-threaded daemon needs seconds to read\n * and store it. Ops that ride on a busy daemon's event loop get headroom too.\n */\nexport function defaultVgdTimeoutMs(op: VgdRequest['op']): number {\n switch (op) {\n case 'ping':\n case 'status':\n return 2000; // liveness probes — fail fast\n case 'put-graph':\n case 'load-graph':\n case 'host-load':\n return 120_000; // large payload / disk load / model load\n case 'host-generate':\n return 300_000; // local model generation\n case 'embed-index':\n case 'embed-rank':\n // First ask on a large repo may have to wait for the slot index (or for\n // a `vg embed` child that already holds the cache lock). 10s made\n // `vg ask` give up and re-embed tens of thousands of nodes in-process.\n return 600_000;\n default:\n return 10_000; // registry + graph queries — may queue behind a put-graph\n }\n}\n\n/**\n * Send one request to a running vgd and return the parsed response.\n * Rejects if the daemon is not reachable.\n */\nexport function vgdRequest(request: VgdRequest, options: VgdClientOptions = {}): Promise<VgdResponse> {\n const socketPath = options.socketPath ?? vgdSocketPath();\n const timeoutMs = options.timeoutMs ?? defaultVgdTimeoutMs(request.op);\n\n return new Promise((resolve, reject) => {\n const socket = net.createConnection(socketPath);\n let settled = false;\n let buffer = '';\n\n const finish = (err?: Error, value?: VgdResponse): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n socket.destroy();\n if (err) reject(err);\n else resolve(value!);\n };\n\n const timer = setTimeout(() => finish(new Error(`vgd did not respond within ${timeoutMs}ms`)), timeoutMs);\n\n socket.setEncoding('utf8');\n socket.on('connect', () => {\n socket.write(JSON.stringify(request) + '\\n');\n });\n socket.on('data', (chunk: string) => {\n buffer += chunk;\n const nl = buffer.indexOf('\\n');\n if (nl < 0) return;\n const line = buffer.slice(0, nl).trim();\n try {\n finish(undefined, JSON.parse(line) as VgdResponse);\n } catch (e) {\n finish(e instanceof Error ? e : new Error(String(e)));\n }\n });\n socket.on('error', (err) => finish(err));\n socket.on('end', () => {\n if (!settled) finish(new Error('vgd closed the connection before responding'));\n });\n });\n}\n\n/** True when a local vgd answers ping. */\nexport async function vgdIsRunning(options: VgdClientOptions = {}): Promise<boolean> {\n try {\n const res = await vgdRequest({ op: 'ping' }, options);\n return res.ok === true && 'pong' in res && res.pong === true;\n } catch {\n return false;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { isPackageInstalled, ensurePackage } from './chunk-3HNPVXUK.js';
2
- import { isWeightCached, lookupCatalog } from './chunk-OV4KGXPD.js';
2
+ import { isWeightCached, lookupCatalog } from './chunk-57ZRSCHY.js';
3
3
  import { spawnSync } from 'child_process';
4
4
 
5
5
  // src/runtime/model-install-plan.ts
@@ -352,5 +352,5 @@ async function ensureManagerRuntime(opts) {
352
352
  }
353
353
 
354
354
  export { buildModelInstallPlan, ensureManagerRuntime, formatManagerBadgeLine, managerBadge, managerFromProviderId };
355
- //# sourceMappingURL=chunk-I5LP55B6.js.map
356
- //# sourceMappingURL=chunk-I5LP55B6.js.map
355
+ //# sourceMappingURL=chunk-W44THEXF.js.map
356
+ //# sourceMappingURL=chunk-W44THEXF.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/runtime/model-install-plan.ts","../src/runtime/model-manager.ts"],"names":[],"mappings":";;;;;AAaO,IAAM,iCAAA,GAAoC,sBAAA;AAkF1C,SAAS,sBAAsB,OAAA,EAAuC;AAC3E,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,KAAM,WAAA,IAAe,CAAA,KAAM,WAAA,IAAe,MAAM,UAAA,EAAY;AAC9D,IAAA,OAAO;AAAA,MACL;AAAA,QACE,EAAA,EAAI,gBAAA;AAAA,QACJ,IAAA,EAAM,aAAA;AAAA,QACN,IAAA,EAAM,mBAAA;AAAA,QACN,MAAA,EAAQ;AAAA;AACV,KACF;AAAA,EACF;AACA,EAAA,IAAI,MAAM,QAAA,EAAU;AAClB,IAAA,OAAO;AAAA,MACL;AAAA,QACE,EAAA,EAAI,QAAA;AAAA,QACJ,IAAA,EAAM,eAAA;AAAA,QACN,MAAA,EAAQ,QAAA;AAAA,QACR,MAAA,EAAQ;AAAA;AACV,KACF;AAAA,EACF;AAEA,EAAA,OAAO,EAAC;AACV;AAEO,SAAS,wBAAA,CACd,SACA,IAAA,EACwC;AACxC,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,KAAM,UAAU,OAAO,QAAA;AAC3B,EAAA,IAAI,CAAA,KAAM,WAAA,IAAe,CAAA,KAAM,WAAA,IAAe,MAAM,UAAA,EAAY;AAE9D,IAAA,IAAI,IAAA,EAAM,eAAgB,IAAA,EAAM,UAAA,IAAc,cAAc,IAAA,CAAK,UAAU,GAAI,OAAO,UAAA;AACtF,IAAA,OAAO,YAAA;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ency closure for a provider + pack/weights.\n *\n * Used by `vg models install` / `pull` (and hosts that mirror them). Planning is\n * side-effect free; execution lives in `model-install.ts`.\n *\n * schemaVersion: model-install-plan/0\n */\n\nimport { isPackageInstalled } from '../code/ensure.js';\nimport type { PackWeightsRef } from './model-orchestrator.js';\nimport { isWeightCached, lookupCatalog } from './weight-store.js';\n\nexport const MODEL_INSTALL_PLAN_SCHEMA_VERSION = 'model-install-plan/0' as const;\n\nexport type RuntimeDepKind = 'npm-runtime' | 'native-binary' | 'weights';\n\n/** Dep/weight readiness: `manual` = user must supply path/app (we do not auto-fetch). */\nexport type DepStatus = 'satisfied' | 'missing' | 'unmanaged' | 'manual';\n\nexport interface ProviderRuntimeDep {\n id: string;\n kind: RuntimeDepKind;\n /** npm install spec, e.g. `node-llama-cpp@^3`. */\n spec?: string;\n /** PATH binary name for native-binary deps. */\n binary?: string;\n /** One-line human reason. */\n reason: string;\n /** When true, npm install may need scripts (surfaced in plan only). */\n requiresInstallScripts?: boolean;\n}\n\nexport interface PlannedDep extends ProviderRuntimeDep {\n status: DepStatus;\n}\n\nexport interface ModelInstallPlan {\n schemaVersion: typeof MODEL_INSTALL_PLAN_SCHEMA_VERSION;\n provider: string;\n backend: string;\n model: string;\n mode?: string;\n packId?: string;\n license?: string;\n promise?: string;\n fit?: string;\n runtimeDeps: PlannedDep[];\n weights: {\n channel: 'ollama' | 'local-path' | 'manual' | 'vibgrate';\n ref: string;\n status: DepStatus;\n /** First-party or pack download URL when channel is vibgrate. */\n downloadUrl?: string;\n };\n /** Ids already present (runtime + weights). */\n alreadySatisfied: string[];\n /** npm specs / binary ids we will install (never third-party apps). */\n willInstall: string[];\n /** Weight refs we will download via the backend channel. */\n willDownload: string[];\n /** Things the user must fix outside vg (e.g. install Ollama.app). */\n blocked: Array<{ id: string; reason: string }>;\n offlineBlocked: boolean;\n /** True when nothing remains to install/download and nothing is blocked. */\n ready: boolean;\n}\n\nexport interface BuildInstallPlanInput {\n backend: PackWeightsRef['backend'] | string;\n weightsRef: string;\n license?: string;\n mode?: string;\n packId?: string;\n promise?: string;\n fit?: string;\n /** Discovered local model names (Ollama / LM Studio / gguf). */\n installedNames?: string[];\n /** When true, network install/download is forbidden. */\n offline?: boolean;\n /** Injectable binary probe (defaults: which/where style via injected map). */\n hasBinary?: (name: string) => boolean;\n /** Injectable npm package probe. */\n isPackageInstalled?: (spec: string) => boolean;\n /** Optional local GGUF path (llama.cpp) — when set, weights are satisfied. */\n modelPath?: string;\n /** Pack/catalog HTTPS URL for first-party GGUF download. */\n downloadUrl?: string;\n /** Optional sha256 for first-party download. */\n sha256?: string;\n /** Injectable weight-cache probe (tests). */\n isWeightCached?: (ref: string) => boolean;\n}\n\n/** Runtime deps declared per backend (not third-party app installers). */\nexport function runtimeDepsForBackend(backend: string): ProviderRuntimeDep[] {\n const b = backend.toLowerCase();\n if (b === 'llama.cpp' || b === 'llama-cpp' || b === 'vibgrate') {\n return [\n {\n id: 'node-llama-cpp',\n kind: 'npm-runtime',\n spec: 'node-llama-cpp@^3',\n reason: 'in-process llama.cpp binding for the first-party / llama-cpp provider',\n },\n ];\n }\n if (b === 'ollama') {\n return [\n {\n id: 'ollama',\n kind: 'native-binary',\n binary: 'ollama',\n reason: 'Ollama on PATH (install from https://ollama.com — third-party apps are not auto-installed)',\n },\n ];\n }\n // LM Studio / Foundry / other: weights managed externally; no auto deps.\n return [];\n}\n\nexport function weightsChannelForBackend(\n backend: string,\n opts?: { downloadUrl?: string; weightsRef?: string },\n): ModelInstallPlan['weights']['channel'] {\n const b = backend.toLowerCase();\n if (b === 'ollama') return 'ollama';\n if (b === 'llama.cpp' || b === 'llama-cpp' || b === 'vibgrate') {\n // Prefer first-party store when we have a catalog/pack URL for this ref.\n if (opts?.downloadUrl || (opts?.weightsRef && lookupCatalog(opts.weightsRef))) return 'vibgrate';\n return 'local-path';\n }\n if (b === 'lm-studio' || b === 'lmstudio' || b === 'foundry-local') return 'manual';\n return 'manual';\n}\n\nfunction weightsInstalled(ref: string, installedNames: string[]): boolean {\n const want = ref.toLowerCase();\n return installedNames.some((n) => {\n const have = n.toLowerCase();\n return have === want || have.includes(want) || want.includes(have);\n });\n}\n\n/**\n * Build a side-effect-free install plan for a backend + weight ref.\n */\nexport function buildModelInstallPlan(input: BuildInstallPlanInput): ModelInstallPlan {\n const hasBinary = input.hasBinary ?? (() => false);\n const pkgInstalled = input.isPackageInstalled ?? isPackageInstalled;\n const installedNames = input.installedNames ?? [];\n const offline = !!input.offline;\n const backend = input.backend;\n const provider = providerLabel(backend);\n\n const runtimeDeps: PlannedDep[] = runtimeDepsForBackend(backend).map((dep) => {\n if (dep.kind === 'npm-runtime' && dep.spec) {\n return { ...dep, status: pkgInstalled(dep.spec) ? 'satisfied' : 'missing' };\n }\n if (dep.kind === 'native-binary' && dep.binary) {\n // Present → satisfied; absent → unmanaged (we never install third-party apps).\n return { ...dep, status: hasBinary(dep.binary) ? 'satisfied' : 'unmanaged' };\n }\n return { ...dep, status: 'unmanaged' as const };\n });\n\n const channel = weightsChannelForBackend(backend, {\n downloadUrl: input.downloadUrl,\n weightsRef: input.weightsRef,\n });\n const weightCached = (input.isWeightCached ?? isWeightCached)(input.weightsRef);\n const catalog = lookupCatalog(input.weightsRef);\n const downloadUrl = input.downloadUrl ?? catalog?.url;\n\n let weightsStatus: DepStatus = 'missing';\n if (channel === 'ollama') {\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) ? 'satisfied' : 'missing';\n } else if (channel === 'vibgrate') {\n weightsStatus =\n weightCached || weightsInstalled(input.weightsRef, installedNames) || !!input.modelPath ? 'satisfied' : 'missing';\n } else if (channel === 'local-path') {\n // Satisfied only when caller reports the model (path) already discoverable.\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) || !!input.modelPath || weightCached ? 'satisfied' : 'manual';\n } else {\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) ? 'satisfied' : 'manual';\n }\n\n const alreadySatisfied: string[] = [];\n const willInstall: string[] = [];\n const willDownload: string[] = [];\n const blocked: Array<{ id: string; reason: string }> = [];\n\n for (const dep of runtimeDeps) {\n if (dep.status === 'satisfied') {\n alreadySatisfied.push(dep.id);\n continue;\n }\n if (dep.kind === 'npm-runtime' && dep.spec && dep.status === 'missing') {\n if (offline) {\n blocked.push({ id: dep.id, reason: `${dep.spec} needed but --local/offline forbids install` });\n } else {\n willInstall.push(dep.spec);\n }\n continue;\n }\n if (dep.kind === 'native-binary' && dep.status === 'unmanaged') {\n blocked.push({\n id: dep.id,\n reason: dep.reason,\n });\n }\n }\n\n if (weightsStatus === 'satisfied') {\n alreadySatisfied.push(`weights:${input.weightsRef}`);\n } else if (weightsStatus === 'missing' && (channel === 'ollama' || channel === 'vibgrate')) {\n if (offline) {\n blocked.push({ id: `weights:${input.weightsRef}`, reason: 'weights missing and --local/offline forbids download' });\n } else if (channel === 'ollama' && runtimeDeps.some((d) => d.id === 'ollama' && d.status === 'unmanaged')) {\n willDownload.push(input.weightsRef);\n } else if (channel === 'vibgrate' && !downloadUrl) {\n blocked.push({\n id: `weights:${input.weightsRef}`,\n reason: `no first-party download URL for ${input.weightsRef} — place a gguf in the weight store or pass --model-path`,\n });\n } else {\n willDownload.push(input.weightsRef);\n }\n } else if (weightsStatus === 'manual' || weightsStatus === 'missing') {\n blocked.push({\n id: `weights:${input.weightsRef}`,\n reason:\n channel === 'local-path'\n ? `point --model-path at a local gguf for ${input.weightsRef}, or run install when a first-party URL is catalogued`\n : `install or link weights for ${input.weightsRef} via the backend app`,\n });\n }\n\n // Under offline, do not claim we will download/install — those land in blocked.\n const effectiveWillInstall = offline ? [] : willInstall;\n const effectiveWillDownload = offline ? [] : willDownload;\n const offlineBlocked = offline && blocked.some((b) => /offline|forbids/i.test(b.reason));\n\n const allRuntimeOk = runtimeDeps.every((d) => d.status === 'satisfied');\n const fullyReady = allRuntimeOk && weightsStatus === 'satisfied' && blocked.length === 0;\n\n return {\n schemaVersion: MODEL_INSTALL_PLAN_SCHEMA_VERSION,\n provider,\n backend,\n model: input.weightsRef,\n mode: input.mode,\n packId: input.packId,\n license: input.license,\n promise: input.promise,\n fit: input.fit,\n runtimeDeps,\n weights: {\n channel,\n ref: input.weightsRef,\n status: weightsStatus,\n downloadUrl: channel === 'vibgrate' ? downloadUrl : undefined,\n },\n alreadySatisfied,\n willInstall: effectiveWillInstall,\n willDownload: effectiveWillDownload,\n blocked,\n offlineBlocked,\n ready: fullyReady,\n };\n}\n\nfunction providerLabel(backend: string): string {\n const b = backend.toLowerCase();\n if (b === 'llama.cpp' || b === 'llama-cpp') return 'llama-cpp';\n if (b === 'vibgrate') return 'vibgrate';\n if (b === 'lm-studio' || b === 'lmstudio') return 'lmstudio';\n if (b === 'foundry-local') return 'foundry-local';\n return b === 'ollama' ? 'ollama' : backend;\n}\n","/**\n * Model manager identity + runtime ensure.\n *\n * **Code Modes** always use the first-party **Vibgrate** manager (embedded\n * llama.cpp / vgd host-broker + weight store). Custom local/hosted backends\n * (Ollama, LM Studio, OpenRouter, …) are explicit user choices; when chosen we\n * silently install *our* installable runtime packages for that path (npm\n * bindings), never third-party desktop apps. The user sees a short badge for\n * which manager ran.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { ensurePackage, isPackageInstalled, type EnsureOptions } from '../code/ensure.js';\nimport { runtimeDepsForBackend } from './model-install-plan.js';\n\n/** Durable manager ids surfaced in badges and JSON. */\nexport type ModelManagerId =\n | 'vibgrate'\n | 'ollama'\n | 'lmstudio'\n | 'foundry-local'\n | 'openrouter'\n | 'litellm'\n | 'openai'\n | 'together'\n | 'mock'\n | 'other';\n\nexport interface ManagerBadge {\n id: ModelManagerId;\n /** Short product label, e.g. \"Vibgrate\". */\n label: string;\n /** Compact badge for CLI/UI, e.g. \"[Vibgrate]\". */\n badge: string;\n /** One-line after-run note. */\n note: string;\n}\n\nconst LABELS: Record<ModelManagerId, { label: string; note: string }> = {\n vibgrate: {\n label: 'Vibgrate',\n note: 'Code Mode · first-party model manager (embedded inference)',\n },\n ollama: {\n label: 'Ollama',\n note: 'Custom local · Ollama',\n },\n lmstudio: {\n label: 'LM Studio',\n note: 'Custom local · LM Studio',\n },\n 'foundry-local': {\n label: 'Foundry Local',\n note: 'Custom local · Foundry Local',\n },\n openrouter: {\n label: 'OpenRouter',\n note: 'Custom hosted · OpenRouter',\n },\n litellm: {\n label: 'LiteLLM',\n note: 'Custom hosted · LiteLLM',\n },\n openai: {\n label: 'OpenAI',\n note: 'Custom hosted · OpenAI',\n },\n together: {\n label: 'Together',\n note: 'Custom hosted · Together',\n },\n mock: {\n label: 'Mock',\n note: 'Scripted offline provider',\n },\n other: {\n label: 'Custom',\n note: 'Custom model backend',\n },\n};\n\n/** Map a provider id (`llama-cpp`, `ollama`, …) to a manager badge. */\nexport function managerFromProviderId(providerId: string | undefined | null): ModelManagerId {\n const id = (providerId ?? '').toLowerCase().trim();\n if (id === 'llama-cpp' || id === 'llama.cpp' || id === 'vibgrate' || id === 'vibgrate-store') return 'vibgrate';\n if (id === 'ollama') return 'ollama';\n if (id === 'lmstudio' || id === 'lm-studio') return 'lmstudio';\n if (id === 'foundry-local' || id === 'foundry') return 'foundry-local';\n if (id === 'openrouter') return 'openrouter';\n if (id === 'litellm') return 'litellm';\n if (id === 'openai') return 'openai';\n if (id === 'together') return 'together';\n if (id === 'mock' || id === 'scripted') return 'mock';\n return 'other';\n}\n\nexport function managerBadge(id: ModelManagerId): ManagerBadge {\n const meta = LABELS[id] ?? LABELS.other;\n return {\n id,\n label: meta.label,\n badge: `[${meta.label}]`,\n note: meta.note,\n };\n}\n\nexport function formatManagerBadgeLine(id: ModelManagerId, model?: string): string {\n const b = managerBadge(id);\n const modelPart = model ? ` · ${model}` : '';\n return `${b.badge} ${b.note}${modelPart}`;\n}\n\nexport interface EnsureManagerRuntimeOptions {\n /** Provider id that will run (llama-cpp, ollama, …). */\n providerId: string;\n /** Model id for weight pull when the backend supports it. */\n model?: string;\n /** `--local` / offline — no network install. */\n offline?: boolean;\n /**\n * Consent to install npm runtime packages (and ollama pull when binary is\n * present). True when the user chose a custom provider/model or passed --yes.\n */\n consent?: boolean;\n /** Injectable ensure (tests). */\n ensurePackage?: typeof ensurePackage;\n /** Injectable PATH binary probe. */\n hasBinary?: (name: string) => boolean;\n /** Injectable ollama pull. */\n ollamaPull?: (name: string) => number;\n onProgress?: (line: string) => void;\n}\n\nexport interface EnsureManagerRuntimeResult {\n ok: boolean;\n manager: ModelManagerId;\n badge: ManagerBadge;\n /** npm specs installed this call. */\n installed: string[];\n /** Weight refs pulled (e.g. ollama pull). */\n pulled: string[];\n /** Non-fatal notes (e.g. app already present). */\n messages: string[];\n error?: string;\n}\n\nfunction defaultHasBinary(name: string): boolean {\n const res = spawnSync(name, ['--version'], { stdio: 'ignore', encoding: 'utf8' });\n // Some CLIs use subcommands; try bare which-style.\n if (res.status === 0) return true;\n const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], {\n stdio: 'ignore',\n encoding: 'utf8',\n });\n return which.status === 0;\n}\n\n/**\n * Silently install *installable* runtime deps for the chosen manager.\n * Never installs third-party desktop apps (Ollama.app, LM Studio) — those\n * remain user-managed; we only install npm packages into the Vibgrate runtime\n * cache and pull weights when the backend binary is already on PATH.\n */\nexport async function ensureManagerRuntime(\n opts: EnsureManagerRuntimeOptions,\n): Promise<EnsureManagerRuntimeResult> {\n const manager = managerFromProviderId(opts.providerId);\n const badge = managerBadge(manager);\n const installed: string[] = [];\n const pulled: string[] = [];\n const messages: string[] = [];\n const ensure = opts.ensurePackage ?? ensurePackage;\n const hasBinary = opts.hasBinary ?? defaultHasBinary;\n\n // Hosted OpenAI-compatible backends: no local packages.\n if (\n manager === 'openrouter' ||\n manager === 'litellm' ||\n manager === 'openai' ||\n manager === 'together' ||\n manager === 'mock'\n ) {\n return { ok: true, manager, badge, installed, pulled, messages };\n }\n\n // LM Studio / Foundry: HTTP clients only — no auto app install (ADR-005).\n if (manager === 'lmstudio' || manager === 'foundry-local') {\n messages.push(\n manager === 'lmstudio'\n ? 'LM Studio must already be running with a model loaded (we never install the app)'\n : 'Foundry Local must already be running (we never install the app)',\n );\n return { ok: true, manager, badge, installed, pulled, messages };\n }\n\n const backend =\n manager === 'vibgrate' ? 'llama.cpp' : manager === 'ollama' ? 'ollama' : opts.providerId;\n const deps = runtimeDepsForBackend(backend);\n\n for (const dep of deps) {\n if (dep.kind === 'npm-runtime' && dep.spec) {\n if (isPackageInstalled(dep.spec)) {\n messages.push(`${dep.id} already installed`);\n continue;\n }\n if (opts.offline) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `${dep.spec} needed but offline/--local forbids install`,\n };\n }\n if (!opts.consent) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `${dep.spec} needed — pass --yes or run \\`vg models install\\` once`,\n };\n }\n opts.onProgress?.(`installing ${dep.spec}`);\n const ensureOpts: EnsureOptions = {\n consent: true,\n local: false,\n interactive: false,\n };\n const res = await ensure(dep.spec, ensureOpts);\n if (!res.module) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `couldn't install ${dep.spec}`,\n };\n }\n installed.push(dep.spec);\n continue;\n }\n if (dep.kind === 'native-binary' && dep.binary) {\n if (!hasBinary(dep.binary)) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error:\n dep.reason ||\n `${dep.binary} is not on PATH — install it once, then re-run (vg never auto-installs third-party apps)`,\n };\n }\n messages.push(`${dep.binary} on PATH`);\n }\n }\n\n // Optional: when user chose a custom Ollama model, pull weights if missing.\n if (manager === 'ollama' && opts.model && opts.consent && !opts.offline) {\n const list = spawnSync('ollama', ['list'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });\n const have =\n list.status === 0 &&\n (list.stdout ?? '')\n .split('\\n')\n .slice(1)\n .some((line) => {\n const name = line.trim().split(/\\s+/)[0]?.toLowerCase();\n return name === opts.model!.toLowerCase() || name?.startsWith(`${opts.model!.toLowerCase()}:`);\n });\n if (!have) {\n opts.onProgress?.(`pulling ${opts.model}`);\n const pull = opts.ollamaPull ?? ((name: string) => spawnSync('ollama', ['pull', name], { stdio: 'ignore' }).status ?? 1);\n const status = pull(opts.model);\n if (status !== 0) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `ollama pull ${opts.model} failed (exit ${status})`,\n };\n }\n pulled.push(opts.model);\n }\n }\n\n return { ok: true, manager, badge, installed, pulled, messages };\n}\n"]}
1
+ {"version":3,"sources":["../src/runtime/model-install-plan.ts","../src/runtime/model-manager.ts"],"names":[],"mappings":";;;;;AAaO,IAAM,iCAAA,GAAoC,sBAAA;AAkF1C,SAAS,sBAAsB,OAAA,EAAuC;AAC3E,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,KAAM,WAAA,IAAe,CAAA,KAAM,WAAA,IAAe,MAAM,UAAA,EAAY;AAC9D,IAAA,OAAO;AAAA,MACL;AAAA,QACE,EAAA,EAAI,gBAAA;AAAA,QACJ,IAAA,EAAM,aAAA;AAAA,QACN,IAAA,EAAM,mBAAA;AAAA,QACN,MAAA,EAAQ;AAAA;AACV,KACF;AAAA,EACF;AACA,EAAA,IAAI,MAAM,QAAA,EAAU;AAClB,IAAA,OAAO;AAAA,MACL;AAAA,QACE,EAAA,EAAI,QAAA;AAAA,QACJ,IAAA,EAAM,eAAA;AAAA,QACN,MAAA,EAAQ,QAAA;AAAA,QACR,MAAA,EAAQ;AAAA;AACV,KACF;AAAA,EACF;AAEA,EAAA,OAAO,EAAC;AACV;AAEO,SAAS,wBAAA,CACd,SACA,IAAA,EACwC;AACxC,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,KAAM,UAAU,OAAO,QAAA;AAC3B,EAAA,IAAI,CAAA,KAAM,WAAA,IAAe,CAAA,KAAM,WAAA,IAAe,MAAM,UAAA,EAAY;AAE9D,IAAA,IAAI,IAAA,EAAM,eAAgB,IAAA,EAAM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EAAW,QAAQ,QAAA,EAAS;AACjE","file":"chunk-W44THEXF.js","sourcesContent":["/**\n * Model install plan — pure dependency closure for a provider + pack/weights.\n *\n * Used by `vg models install` / `pull` (and hosts that mirror them). Planning is\n * side-effect free; execution lives in `model-install.ts`.\n *\n * schemaVersion: model-install-plan/0\n */\n\nimport { isPackageInstalled } from '../code/ensure.js';\nimport type { PackWeightsRef } from './model-orchestrator.js';\nimport { isWeightCached, lookupCatalog } from './weight-store.js';\n\nexport const MODEL_INSTALL_PLAN_SCHEMA_VERSION = 'model-install-plan/0' as const;\n\nexport type RuntimeDepKind = 'npm-runtime' | 'native-binary' | 'weights';\n\n/** Dep/weight readiness: `manual` = user must supply path/app (we do not auto-fetch). */\nexport type DepStatus = 'satisfied' | 'missing' | 'unmanaged' | 'manual';\n\nexport interface ProviderRuntimeDep {\n id: string;\n kind: RuntimeDepKind;\n /** npm install spec, e.g. `node-llama-cpp@^3`. */\n spec?: string;\n /** PATH binary name for native-binary deps. */\n binary?: string;\n /** One-line human reason. */\n reason: string;\n /** When true, npm install may need scripts (surfaced in plan only). */\n requiresInstallScripts?: boolean;\n}\n\nexport interface PlannedDep extends ProviderRuntimeDep {\n status: DepStatus;\n}\n\nexport interface ModelInstallPlan {\n schemaVersion: typeof MODEL_INSTALL_PLAN_SCHEMA_VERSION;\n provider: string;\n backend: string;\n model: string;\n mode?: string;\n packId?: string;\n license?: string;\n promise?: string;\n fit?: string;\n runtimeDeps: PlannedDep[];\n weights: {\n channel: 'ollama' | 'local-path' | 'manual' | 'vibgrate';\n ref: string;\n status: DepStatus;\n /** First-party or pack download URL when channel is vibgrate. */\n downloadUrl?: string;\n };\n /** Ids already present (runtime + weights). */\n alreadySatisfied: string[];\n /** npm specs / binary ids we will install (never third-party apps). */\n willInstall: string[];\n /** Weight refs we will download via the backend channel. */\n willDownload: string[];\n /** Things the user must fix outside vg (e.g. install Ollama.app). */\n blocked: Array<{ id: string; reason: string }>;\n offlineBlocked: boolean;\n /** True when nothing remains to install/download and nothing is blocked. */\n ready: boolean;\n}\n\nexport interface BuildInstallPlanInput {\n backend: PackWeightsRef['backend'] | string;\n weightsRef: string;\n license?: string;\n mode?: string;\n packId?: string;\n promise?: string;\n fit?: string;\n /** Discovered local model names (Ollama / LM Studio / gguf). */\n installedNames?: string[];\n /** When true, network install/download is forbidden. */\n offline?: boolean;\n /** Injectable binary probe (defaults: which/where style via injected map). */\n hasBinary?: (name: string) => boolean;\n /** Injectable npm package probe. */\n isPackageInstalled?: (spec: string) => boolean;\n /** Optional local GGUF path (llama.cpp) — when set, weights are satisfied. */\n modelPath?: string;\n /** Pack/catalog HTTPS URL for first-party GGUF download. */\n downloadUrl?: string;\n /** Optional sha256 for first-party download. */\n sha256?: string;\n /** Injectable weight-cache probe (tests). */\n isWeightCached?: (ref: string) => boolean;\n}\n\n/** Runtime deps declared per backend (not third-party app installers). */\nexport function runtimeDepsForBackend(backend: string): ProviderRuntimeDep[] {\n const b = backend.toLowerCase();\n if (b === 'llama.cpp' || b === 'llama-cpp' || b === 'vibgrate') {\n return [\n {\n id: 'node-llama-cpp',\n kind: 'npm-runtime',\n spec: 'node-llama-cpp@^3',\n reason: 'in-process llama.cpp binding for the first-party / llama-cpp provider',\n },\n ];\n }\n if (b === 'ollama') {\n return [\n {\n id: 'ollama',\n kind: 'native-binary',\n binary: 'ollama',\n reason: 'Ollama on PATH (install from https://ollama.com — third-party apps are not auto-installed)',\n },\n ];\n }\n // LM Studio / Foundry / other: weights managed externally; no auto deps.\n return [];\n}\n\nexport function weightsChannelForBackend(\n backend: string,\n opts?: { downloadUrl?: string; weightsRef?: string },\n): ModelInstallPlan['weights']['channel'] {\n const b = backend.toLowerCase();\n if (b === 'ollama') return 'ollama';\n if (b === 'llama.cpp' || b === 'llama-cpp' || b === 'vibgrate') {\n // Prefer first-party store when we have a catalog/pack URL for this ref.\n if (opts?.downloadUrl || (opts?.weightsRef && lookupCatalog(opts.weightsRef))) return 'vibgrate';\n return 'local-path';\n }\n if (b === 'lm-studio' || b === 'lmstudio' || b === 'foundry-local') return 'manual';\n return 'manual';\n}\n\nfunction weightsInstalled(ref: string, installedNames: string[]): boolean {\n const want = ref.toLowerCase();\n return installedNames.some((n) => {\n const have = n.toLowerCase();\n return have === want || have.includes(want) || want.includes(have);\n });\n}\n\n/**\n * Build a side-effect-free install plan for a backend + weight ref.\n */\nexport function buildModelInstallPlan(input: BuildInstallPlanInput): ModelInstallPlan {\n const hasBinary = input.hasBinary ?? (() => false);\n const pkgInstalled = input.isPackageInstalled ?? isPackageInstalled;\n const installedNames = input.installedNames ?? [];\n const offline = !!input.offline;\n const backend = input.backend;\n const provider = providerLabel(backend);\n\n const runtimeDeps: PlannedDep[] = runtimeDepsForBackend(backend).map((dep) => {\n if (dep.kind === 'npm-runtime' && dep.spec) {\n return { ...dep, status: pkgInstalled(dep.spec) ? 'satisfied' : 'missing' };\n }\n if (dep.kind === 'native-binary' && dep.binary) {\n // Present → satisfied; absent → unmanaged (we never install third-party apps).\n return { ...dep, status: hasBinary(dep.binary) ? 'satisfied' : 'unmanaged' };\n }\n return { ...dep, status: 'unmanaged' as const };\n });\n\n const channel = weightsChannelForBackend(backend, {\n downloadUrl: input.downloadUrl,\n weightsRef: input.weightsRef,\n });\n const weightCached = (input.isWeightCached ?? isWeightCached)(input.weightsRef);\n const catalog = lookupCatalog(input.weightsRef);\n const downloadUrl = input.downloadUrl ?? catalog?.url;\n\n let weightsStatus: DepStatus = 'missing';\n if (channel === 'ollama') {\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) ? 'satisfied' : 'missing';\n } else if (channel === 'vibgrate') {\n weightsStatus =\n weightCached || weightsInstalled(input.weightsRef, installedNames) || !!input.modelPath ? 'satisfied' : 'missing';\n } else if (channel === 'local-path') {\n // Satisfied only when caller reports the model (path) already discoverable.\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) || !!input.modelPath || weightCached ? 'satisfied' : 'manual';\n } else {\n weightsStatus = weightsInstalled(input.weightsRef, installedNames) ? 'satisfied' : 'manual';\n }\n\n const alreadySatisfied: string[] = [];\n const willInstall: string[] = [];\n const willDownload: string[] = [];\n const blocked: Array<{ id: string; reason: string }> = [];\n\n for (const dep of runtimeDeps) {\n if (dep.status === 'satisfied') {\n alreadySatisfied.push(dep.id);\n continue;\n }\n if (dep.kind === 'npm-runtime' && dep.spec && dep.status === 'missing') {\n if (offline) {\n blocked.push({ id: dep.id, reason: `${dep.spec} needed but --local/offline forbids install` });\n } else {\n willInstall.push(dep.spec);\n }\n continue;\n }\n if (dep.kind === 'native-binary' && dep.status === 'unmanaged') {\n blocked.push({\n id: dep.id,\n reason: dep.reason,\n });\n }\n }\n\n if (weightsStatus === 'satisfied') {\n alreadySatisfied.push(`weights:${input.weightsRef}`);\n } else if (weightsStatus === 'missing' && (channel === 'ollama' || channel === 'vibgrate')) {\n if (offline) {\n blocked.push({ id: `weights:${input.weightsRef}`, reason: 'weights missing and --local/offline forbids download' });\n } else if (channel === 'ollama' && runtimeDeps.some((d) => d.id === 'ollama' && d.status === 'unmanaged')) {\n willDownload.push(input.weightsRef);\n } else if (channel === 'vibgrate' && !downloadUrl) {\n blocked.push({\n id: `weights:${input.weightsRef}`,\n reason: `no first-party download URL for ${input.weightsRef} — place a gguf in the weight store or pass --model-path`,\n });\n } else {\n willDownload.push(input.weightsRef);\n }\n } else if (weightsStatus === 'manual' || weightsStatus === 'missing') {\n blocked.push({\n id: `weights:${input.weightsRef}`,\n reason:\n channel === 'local-path'\n ? `point --model-path at a local gguf for ${input.weightsRef}, or run install when a first-party URL is catalogued`\n : `install or link weights for ${input.weightsRef} via the backend app`,\n });\n }\n\n // Under offline, do not claim we will download/install — those land in blocked.\n const effectiveWillInstall = offline ? [] : willInstall;\n const effectiveWillDownload = offline ? [] : willDownload;\n const offlineBlocked = offline && blocked.some((b) => /offline|forbids/i.test(b.reason));\n\n const allRuntimeOk = runtimeDeps.every((d) => d.status === 'satisfied');\n const fullyReady = allRuntimeOk && weightsStatus === 'satisfied' && blocked.length === 0;\n\n return {\n schemaVersion: MODEL_INSTALL_PLAN_SCHEMA_VERSION,\n provider,\n backend,\n model: input.weightsRef,\n mode: input.mode,\n packId: input.packId,\n license: input.license,\n promise: input.promise,\n fit: input.fit,\n runtimeDeps,\n weights: {\n channel,\n ref: input.weightsRef,\n status: weightsStatus,\n downloadUrl: channel === 'vibgrate' ? downloadUrl : undefined,\n },\n alreadySatisfied,\n willInstall: effectiveWillInstall,\n willDownload: effectiveWillDownload,\n blocked,\n offlineBlocked,\n ready: fullyReady,\n };\n}\n\nfunction providerLabel(backend: string): string {\n const b = backend.toLowerCase();\n if (b === 'llama.cpp' || b === 'llama-cpp') return 'llama-cpp';\n if (b === 'vibgrate') return 'vibgrate';\n if (b === 'lm-studio' || b === 'lmstudio') return 'lmstudio';\n if (b === 'foundry-local') return 'foundry-local';\n return b === 'ollama' ? 'ollama' : backend;\n}\n","/**\n * Model manager identity + runtime ensure.\n *\n * **Code Modes** always use the first-party **Vibgrate** manager (embedded\n * llama.cpp / vgd host-broker + weight store). Custom local/hosted backends\n * (Ollama, LM Studio, OpenRouter, …) are explicit user choices; when chosen we\n * silently install *our* installable runtime packages for that path (npm\n * bindings), never third-party desktop apps. The user sees a short badge for\n * which manager ran.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { ensurePackage, isPackageInstalled, type EnsureOptions } from '../code/ensure.js';\nimport { runtimeDepsForBackend } from './model-install-plan.js';\n\n/** Durable manager ids surfaced in badges and JSON. */\nexport type ModelManagerId =\n | 'vibgrate'\n | 'ollama'\n | 'lmstudio'\n | 'foundry-local'\n | 'openrouter'\n | 'litellm'\n | 'openai'\n | 'together'\n | 'mock'\n | 'other';\n\nexport interface ManagerBadge {\n id: ModelManagerId;\n /** Short product label, e.g. \"Vibgrate\". */\n label: string;\n /** Compact badge for CLI/UI, e.g. \"[Vibgrate]\". */\n badge: string;\n /** One-line after-run note. */\n note: string;\n}\n\nconst LABELS: Record<ModelManagerId, { label: string; note: string }> = {\n vibgrate: {\n label: 'Vibgrate',\n note: 'Code Mode · first-party model manager (embedded inference)',\n },\n ollama: {\n label: 'Ollama',\n note: 'Custom local · Ollama',\n },\n lmstudio: {\n label: 'LM Studio',\n note: 'Custom local · LM Studio',\n },\n 'foundry-local': {\n label: 'Foundry Local',\n note: 'Custom local · Foundry Local',\n },\n openrouter: {\n label: 'OpenRouter',\n note: 'Custom hosted · OpenRouter',\n },\n litellm: {\n label: 'LiteLLM',\n note: 'Custom hosted · LiteLLM',\n },\n openai: {\n label: 'OpenAI',\n note: 'Custom hosted · OpenAI',\n },\n together: {\n label: 'Together',\n note: 'Custom hosted · Together',\n },\n mock: {\n label: 'Mock',\n note: 'Scripted offline provider',\n },\n other: {\n label: 'Custom',\n note: 'Custom model backend',\n },\n};\n\n/** Map a provider id (`llama-cpp`, `ollama`, …) to a manager badge. */\nexport function managerFromProviderId(providerId: string | undefined | null): ModelManagerId {\n const id = (providerId ?? '').toLowerCase().trim();\n if (id === 'llama-cpp' || id === 'llama.cpp' || id === 'vibgrate' || id === 'vibgrate-store') return 'vibgrate';\n if (id === 'ollama') return 'ollama';\n if (id === 'lmstudio' || id === 'lm-studio') return 'lmstudio';\n if (id === 'foundry-local' || id === 'foundry') return 'foundry-local';\n if (id === 'openrouter') return 'openrouter';\n if (id === 'litellm') return 'litellm';\n if (id === 'openai') return 'openai';\n if (id === 'together') return 'together';\n if (id === 'mock' || id === 'scripted') return 'mock';\n return 'other';\n}\n\nexport function managerBadge(id: ModelManagerId): ManagerBadge {\n const meta = LABELS[id] ?? LABELS.other;\n return {\n id,\n label: meta.label,\n badge: `[${meta.label}]`,\n note: meta.note,\n };\n}\n\nexport function formatManagerBadgeLine(id: ModelManagerId, model?: string): string {\n const b = managerBadge(id);\n const modelPart = model ? ` · ${model}` : '';\n return `${b.badge} ${b.note}${modelPart}`;\n}\n\nexport interface EnsureManagerRuntimeOptions {\n /** Provider id that will run (llama-cpp, ollama, …). */\n providerId: string;\n /** Model id for weight pull when the backend supports it. */\n model?: string;\n /** `--local` / offline — no network install. */\n offline?: boolean;\n /**\n * Consent to install npm runtime packages (and ollama pull when binary is\n * present). True when the user chose a custom provider/model or passed --yes.\n */\n consent?: boolean;\n /** Injectable ensure (tests). */\n ensurePackage?: typeof ensurePackage;\n /** Injectable PATH binary probe. */\n hasBinary?: (name: string) => boolean;\n /** Injectable ollama pull. */\n ollamaPull?: (name: string) => number;\n onProgress?: (line: string) => void;\n}\n\nexport interface EnsureManagerRuntimeResult {\n ok: boolean;\n manager: ModelManagerId;\n badge: ManagerBadge;\n /** npm specs installed this call. */\n installed: string[];\n /** Weight refs pulled (e.g. ollama pull). */\n pulled: string[];\n /** Non-fatal notes (e.g. app already present). */\n messages: string[];\n error?: string;\n}\n\nfunction defaultHasBinary(name: string): boolean {\n const res = spawnSync(name, ['--version'], { stdio: 'ignore', encoding: 'utf8' });\n // Some CLIs use subcommands; try bare which-style.\n if (res.status === 0) return true;\n const which = spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], {\n stdio: 'ignore',\n encoding: 'utf8',\n });\n return which.status === 0;\n}\n\n/**\n * Silently install *installable* runtime deps for the chosen manager.\n * Never installs third-party desktop apps (Ollama.app, LM Studio) — those\n * remain user-managed; we only install npm packages into the Vibgrate runtime\n * cache and pull weights when the backend binary is already on PATH.\n */\nexport async function ensureManagerRuntime(\n opts: EnsureManagerRuntimeOptions,\n): Promise<EnsureManagerRuntimeResult> {\n const manager = managerFromProviderId(opts.providerId);\n const badge = managerBadge(manager);\n const installed: string[] = [];\n const pulled: string[] = [];\n const messages: string[] = [];\n const ensure = opts.ensurePackage ?? ensurePackage;\n const hasBinary = opts.hasBinary ?? defaultHasBinary;\n\n // Hosted OpenAI-compatible backends: no local packages.\n if (\n manager === 'openrouter' ||\n manager === 'litellm' ||\n manager === 'openai' ||\n manager === 'together' ||\n manager === 'mock'\n ) {\n return { ok: true, manager, badge, installed, pulled, messages };\n }\n\n // LM Studio / Foundry: HTTP clients only — no auto app install (ADR-005).\n if (manager === 'lmstudio' || manager === 'foundry-local') {\n messages.push(\n manager === 'lmstudio'\n ? 'LM Studio must already be running with a model loaded (we never install the app)'\n : 'Foundry Local must already be running (we never install the app)',\n );\n return { ok: true, manager, badge, installed, pulled, messages };\n }\n\n const backend =\n manager === 'vibgrate' ? 'llama.cpp' : manager === 'ollama' ? 'ollama' : opts.providerId;\n const deps = runtimeDepsForBackend(backend);\n\n for (const dep of deps) {\n if (dep.kind === 'npm-runtime' && dep.spec) {\n if (isPackageInstalled(dep.spec)) {\n messages.push(`${dep.id} already installed`);\n continue;\n }\n if (opts.offline) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `${dep.spec} needed but offline/--local forbids install`,\n };\n }\n if (!opts.consent) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `${dep.spec} needed — pass --yes or run \\`vg models install\\` once`,\n };\n }\n opts.onProgress?.(`installing ${dep.spec}`);\n const ensureOpts: EnsureOptions = {\n consent: true,\n local: false,\n interactive: false,\n };\n const res = await ensure(dep.spec, ensureOpts);\n if (!res.module) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `couldn't install ${dep.spec}`,\n };\n }\n installed.push(dep.spec);\n continue;\n }\n if (dep.kind === 'native-binary' && dep.binary) {\n if (!hasBinary(dep.binary)) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error:\n dep.reason ||\n `${dep.binary} is not on PATH — install it once, then re-run (vg never auto-installs third-party apps)`,\n };\n }\n messages.push(`${dep.binary} on PATH`);\n }\n }\n\n // Optional: when user chose a custom Ollama model, pull weights if missing.\n if (manager === 'ollama' && opts.model && opts.consent && !opts.offline) {\n const list = spawnSync('ollama', ['list'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });\n const have =\n list.status === 0 &&\n (list.stdout ?? '')\n .split('\\n')\n .slice(1)\n .some((line) => {\n const name = line.trim().split(/\\s+/)[0]?.toLowerCase();\n return name === opts.model!.toLowerCase() || name?.startsWith(`${opts.model!.toLowerCase()}:`);\n });\n if (!have) {\n opts.onProgress?.(`pulling ${opts.model}`);\n const pull = opts.ollamaPull ?? ((name: string) => spawnSync('ollama', ['pull', name], { stdio: 'ignore' }).status ?? 1);\n const status = pull(opts.model);\n if (status !== 0) {\n return {\n ok: false,\n manager,\n badge,\n installed,\n pulled,\n messages,\n error: `ollama pull ${opts.model} failed (exit ${status})`,\n };\n }\n pulled.push(opts.model);\n }\n }\n\n return { ok: true, manager, badge, installed, pulled, messages };\n}\n"]}
@@ -1,8 +1,8 @@
1
- import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-74UBGF4P.js';
2
- import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-YF54UMOU.js';
3
- import { userAskFromInstruction } from './chunk-MRZHNUN7.js';
4
- import { analyzeQuestion, loadTopicTags } from './chunk-VMAIDM4K.js';
5
- import { repositoryIdFromRoot } from './chunk-BWPBB45M.js';
1
+ import { buildMessages, parseEdits, applyEdits, unifiedDiff, redactSecrets } from './chunk-SHD5TCZ5.js';
2
+ import { recordCliCall, CLI_TOOL_ALIASES, buildCodeContext, buildTaskCapsule, capsuleToCodeContext } from './chunk-CBL3VY7J.js';
3
+ import { userAskFromInstruction } from './chunk-CA4YQBA7.js';
4
+ import { analyzeQuestion, loadTopicTags } from './chunk-2C4QT5D7.js';
5
+ import { repositoryIdFromRoot } from './chunk-XP6UUCZZ.js';
6
6
  import * as fs from 'fs';
7
7
  import * as path from 'path';
8
8
 
@@ -259,5 +259,5 @@ function shortId() {
259
259
  }
260
260
 
261
261
  export { commitChanges, nodeCodeFs, runCodeSession, undoChanges };
262
- //# sourceMappingURL=chunk-AEJYA6HZ.js.map
263
- //# sourceMappingURL=chunk-AEJYA6HZ.js.map
262
+ //# sourceMappingURL=chunk-W6ASIMG5.js.map
263
+ //# sourceMappingURL=chunk-W6ASIMG5.js.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W,MAAM,CAAA;AACrC,MAAG,kBAAoB,IAAA,CAAA,IAAA,CAAK,GAAA,EAAK,kBAAkB,CAAA,EAAG,OAAO,IAAI,CAAA;AAAA,IACnE;AAAA,GACF;AACF;AAGA,SAAS,OAAA,GAAkB;AACzB,EAAA,IAAI,CAAA,GAAI,EAAA;AACR,EAAA,MAAM,QAAA,GAAW,sCAAA;AACjB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,KAAK,CAAA,IAAK,QAAA,CAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-AEJYA6HZ.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { analyzeQuestion, type RelevanceAnalysis } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // Optional relevance provider: widens capsule seed vocabulary when\n // installed; null (the default) changes nothing.\n const relevance = await analyzeQuestion(userAskFromInstruction(instruction));\n const topicTags = relevance ? await loadTopicTags(graph, root) : null;\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n relevance,\n topicTags,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; relevance?: RelevanceAnalysis | null; topicTags?: Map<string, readonly string[]> | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, relevance: opts.relevance, topicTags: opts.topicTags });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n relevance: opts.relevance,\n topicTags: opts.topicTags,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}
1
+ {"version":3,"sources":["../src/code/session.ts"],"names":["resolve"],"mappings":";;;;;;;;AAsFA,eAAsB,eAAe,OAAA,EAAwD;AAC3F,EAAA,MAAM;AAAA,IACJ,KAAA;AAAA,IACA,IAAA;AAAA,IACA,WAAA;AAAA,IACA,SAAA;AAAA,IACA,K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A,MAAM,QAAA,GAAW,sCAAA;AACjB,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,CAAA,EAAG,KAAK,CAAA,IAAK,QAAA,CAAS,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,MAAA,EAAO,GAAI,QAAA,CAAS,MAAM,CAAC,CAAA;AACrF,EAAA,OAAO,CAAA;AACT","file":"chunk-W6ASIMG5.js","sourcesContent":["/**\n * The `vg code` governance session (VG-CLI-CODE §7).\n *\n * This is the load-bearing rule the whole platform is built on, applied to code\n * edits: a state-altering change goes **through** the lifecycle, never around it\n * (GUARDRAILS §5). One run walks inspect → assess → dry-run → approve → execute\n * → verify → log:\n *\n * inspect build the graph-grounded context for the instruction\n * assess ask the routed model for a terse edit; apply it deterministically\n * (in memory); compute the diff and the blast radius\n * dry-run the DEFAULT terminal state — propose the change, write nothing\n * approve writing requires explicit consent; without it we stop at dry-run\n * execute write the approved changes to disk\n * verify confirm the files on disk match what was approved (+ optional cmd)\n * log append an immutable, secret-free audit record with a correlation id\n *\n * Everything is deterministic except the single model call, which is isolated\n * behind the provider list (tried in order, falling back on transport failure).\n * The filesystem and clock are injectable so the whole session is testable\n * offline with no writes escaping a temp dir.\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { buildCodeContext } from './context.js';\nimport { analyzeQuestion, type RelevanceAnalysis } from '../engine/relevance-provider.js';\nimport { loadTopicTags } from '../engine/relevance-enrich.js';\nimport { userAskFromInstruction } from '../engine/user-ask.js';\nimport { buildTaskCapsule, capsuleToCodeContext } from './capsule.js';\nimport { recordCliCall, CLI_TOOL_ALIASES } from '../engine/savings.js';\nimport { repositoryIdFromRoot } from '../runtime/paths.js';\nimport { parseEdits, applyEdits, type SymbolSpan } from './apply.js';\nimport { unifiedDiff } from './diff.js';\nimport { buildMessages } from './prompt.js';\nimport { redactSecrets } from './providers.js';\nimport type { ChatOptions, CodeContext, CodeSessionResult, FileChange, LifecyclePhase, Provider, ProviderResult } from './types.js';\nimport type { VgGraph } from '../schema.js';\n\n/** Minimal filesystem seam so the session is testable without touching real disk. */\nexport interface CodeFs {\n read(file: string): string | null;\n write(file: string, content: string): void;\n remove(file: string): void;\n appendAudit(line: string): void;\n}\n\nexport interface RunSessionOptions {\n graph: VgGraph;\n root: string;\n instruction: string;\n /** Providers to try in order (from the router); the first that answers wins. */\n providers: Provider[];\n /** Write to disk? Default false — dry-run is the safe default (GUARDRAILS §3.2). */\n apply?: boolean;\n /** Explicit consent for the write (`--yes`); without it, a requested apply stops at dry-run. */\n consent?: boolean;\n /** Restrict the edit surface to these files. */\n files?: string[];\n /** Context token budget. */\n budget?: number;\n chatOptions?: ChatOptions;\n /** Injectable filesystem (defaults to a real, root-scoped fs). */\n fsImpl?: CodeFs;\n /** Injectable clock (ms) for the audit timestamp. */\n now?: () => number;\n /** Injectable correlation id (defaults to a random short id). */\n correlationId?: string;\n /** Progress callback per phase. */\n onPhase?: (phase: LifecyclePhase, detail: string) => void;\n /** Skip appending to the audit log (used by tests/dry programmatic calls). */\n noAudit?: boolean;\n /**\n * Who is making the graph-backed call, for per-model savings auditing. When\n * `client` is set, the context-assembly step (a `query_graph`-equivalent) is\n * recorded to the local savings ledger tagged with the provider + model, so\n * `vg savings` can break usage down per model. VG Code always sets this.\n */\n attribution?: { client: string; provider?: string; model?: string };\n /**\n * Use a source-bearing Task Capsule for the inspect context (Fusion Runtime\n * Phase 0 A/B). Default false keeps the metadata-only path.\n */\n capsule?: boolean;\n}\n\nexport async function runCodeSession(options: RunSessionOptions): Promise<CodeSessionResult> {\n const {\n graph,\n root,\n instruction,\n providers,\n apply = false,\n consent = false,\n files,\n budget,\n chatOptions,\n now = () => 0,\n onPhase = () => {},\n } = options;\n const fsImpl = options.fsImpl ?? nodeCodeFs(root);\n const correlationId = options.correlationId ?? shortId();\n const phasesRun: LifecyclePhase[] = [];\n const phase = (p: LifecyclePhase, detail: string): void => {\n phasesRun.push(p);\n onPhase(p, detail);\n };\n\n // ── inspect ──────────────────────────────────────────────────────────────\n phase('inspect', options.capsule ? 'building source-bearing task capsule' : 'building graph-grounded context');\n // Optional relevance provider: widens capsule seed vocabulary when\n // installed; null (the default) changes nothing.\n const relevance = await analyzeQuestion(userAskFromInstruction(instruction));\n const topicTags = relevance ? await loadTopicTags(graph, root) : null;\n const context = buildSessionContext(graph, instruction, {\n budget,\n files,\n capsule: options.capsule,\n root,\n fsImpl,\n relevance,\n topicTags,\n });\n\n // Per-model savings: the context build is VG Code's `query_graph`-equivalent.\n // Record it (counts only — never code or the instruction) tagged with the\n // model, so `vg savings` audits usage per model. Local-only, best-effort.\n if (options.attribution?.client) {\n const seedFiles = new Set(context.seeds.map((s) => s.node.file).filter(Boolean));\n recordCliCall(\n root,\n {\n tool: CLI_TOOL_ALIASES.ask,\n client: options.attribution.client,\n provider: options.attribution.provider,\n model: options.attribution.model,\n outcome: context.seeds.length ? 'complete' : 'miss',\n vgTokens: context.tokensEstimate,\n baselineFiles: seedFiles.size,\n },\n now(),\n );\n }\n\n // ── assess ──────────────────────────────────────────────────────────────\n phase('assess', 'asking the routed model for a minimal edit');\n const messages = buildMessages(context);\n const { result, provider, fellBack } = await complete(providers, messages, chatOptions, correlationId);\n\n const edits = parseEdits(result.text);\n const spans = spanIndex(graph);\n const applied = applyEdits(\n edits,\n (file) => fsImpl.read(file),\n (file) => spans.get(normalize(file)) ?? [],\n );\n\n const changes: FileChange[] = [];\n for (const [file, entry] of [...applied.entries()].sort((a, b) => a[0].localeCompare(b[0]))) {\n changes.push({\n file,\n before: entry.before,\n after: entry.after,\n outcomes: entry.outcomes,\n diff: unifiedDiff(entry.before, entry.after, file),\n });\n }\n\n // ── dry-run (always produced) ─────────────────────────────────────────────\n phase('dry-run', `${changes.length} file(s) would change`);\n\n const anyApplicable = changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n const base: CodeSessionResult = {\n instruction,\n provider: { id: provider.id, model: provider.model, local: provider.local, fellBack },\n phasesRun,\n changes,\n applied: false,\n verification: { ran: false, ok: false, detail: 'dry-run — no changes written' },\n correlationId,\n };\n\n // ── approve ───────────────────────────────────────────────────────────────\n // Writing is opt-in AND consent-gated. A requested apply without consent is\n // not an error — it degrades to a dry-run so the caller can review, then\n // re-run with --yes. This is the \"never destructive-by-default\" guardrail.\n if (!apply) {\n if (!options.noAudit) writeAudit(fsImpl, base, now());\n return base;\n }\n if (!consent) {\n const stopped = { ...base, verification: { ran: false, ok: false, detail: 'apply requested without consent — re-run with --yes to write these changes' } };\n if (!options.noAudit) writeAudit(fsImpl, stopped, now());\n return stopped;\n }\n if (!anyApplicable) {\n const nothing = { ...base, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n if (!options.noAudit) writeAudit(fsImpl, nothing, now());\n return nothing;\n }\n phase('approve', 'consent given (--yes)');\n\n // ── execute ───────────────────────────────────────────────────────────────\n phase('execute', 'writing approved changes');\n for (const change of changes) {\n if (change.diff === '') continue; // no-op file\n if (!change.outcomes.some((o) => o.status === 'applied')) continue; // nothing applied cleanly here\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n\n // ── verify ────────────────────────────────────────────────────────────────\n phase('verify', 'confirming on-disk content matches the approved change');\n const verification = verifyWrites(fsImpl, changes);\n\n // ── log ───────────────────────────────────────────────────────────────────\n phase('log', 'recording an audit entry');\n const final: CodeSessionResult = { ...base, applied: true, verification };\n if (!options.noAudit) writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Commit an already-computed dry-run result: write the cleanly-applied changes,\n * verify them on disk, and append the audit record — the \"approve → execute →\n * verify → log\" tail of the lifecycle, run against a proposal the caller has\n * already shown and had approved (the interactive REPL uses this so it never\n * calls the model twice or writes something different from what was reviewed).\n */\nexport function commitChanges(result: CodeSessionResult, fsImpl: CodeFs, now: () => number = () => 0): CodeSessionResult {\n const anyApplicable = result.changes.some((c) => c.diff !== '' && c.outcomes.some((o) => o.status === 'applied'));\n if (!anyApplicable) {\n return { ...result, applied: false, verification: { ran: false, ok: false, detail: 'nothing to write — no edit applied cleanly' } };\n }\n for (const change of result.changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n if (change.after === null) fsImpl.remove(change.file);\n else fsImpl.write(change.file, change.after);\n }\n const verification = verifyWrites(fsImpl, result.changes);\n const final: CodeSessionResult = { ...result, applied: true, verification, phasesRun: [...result.phasesRun, 'approve', 'execute', 'verify', 'log'] };\n writeAudit(fsImpl, final, now());\n return final;\n}\n\n/**\n * Undo a set of applied changes by restoring each file's prior content — the\n * `/undo` command. A created file (before === null) is removed; an edited or\n * deleted file is restored to its `before`. Only cleanly-applied changes are\n * reverted. Returns the files it restored.\n */\nexport function undoChanges(changes: FileChange[], fsImpl: CodeFs): string[] {\n const restored: string[] = [];\n for (const ch of changes) {\n if (!ch.outcomes.some((o) => o.status === 'applied')) continue;\n if (ch.before === null) fsImpl.remove(ch.file);\n else fsImpl.write(ch.file, ch.before);\n restored.push(ch.file);\n }\n return restored;\n}\n\nfunction buildSessionContext(\n graph: VgGraph,\n instruction: string,\n opts: { budget?: number; files?: string[]; capsule?: boolean; root: string; fsImpl: CodeFs; relevance?: RelevanceAnalysis | null; topicTags?: Map<string, readonly string[]> | null },\n): CodeContext {\n const budget = opts.budget;\n const files = opts.files;\n if (!opts.capsule) {\n return buildCodeContext(graph, instruction, { budget, files, relevance: opts.relevance, topicTags: opts.topicTags });\n }\n const capsule = buildTaskCapsule(graph, instruction, {\n budget,\n files,\n readFile: (rel) => opts.fsImpl.read(rel),\n repositoryId: repositoryIdFromRoot(opts.root),\n relevance: opts.relevance,\n topicTags: opts.topicTags,\n });\n return capsuleToCodeContext(capsule);\n}\n\n/** Try each provider in order; fall back on transport failure. Throws the last actionable error. */\nasync function complete(\n providers: Provider[],\n messages: ReturnType<typeof buildMessages>,\n chatOptions: ChatOptions | undefined,\n correlationId: string,\n): Promise<{ result: ProviderResult; provider: Provider; fellBack: boolean }> {\n if (providers.length === 0) throw new Error(`no model provider available (ref ${correlationId})`);\n let lastErr: unknown;\n for (let i = 0; i < providers.length; i++) {\n const provider = providers[i];\n try {\n const result = await provider.chat(messages, { temperature: 0, ...chatOptions });\n return { result, provider, fellBack: i > 0 };\n } catch (e) {\n lastErr = e;\n }\n }\n const message = lastErr instanceof Error ? redactSecrets(lastErr.message) : String(lastErr);\n throw new Error(`${message} (ref ${correlationId})`);\n}\n\n/** Confirm each written file's on-disk content equals what we approved. */\nfunction verifyWrites(fsImpl: CodeFs, changes: FileChange[]): { ran: boolean; ok: boolean; detail: string } {\n let checked = 0;\n const mismatches: string[] = [];\n for (const change of changes) {\n if (change.diff === '' || !change.outcomes.some((o) => o.status === 'applied')) continue;\n checked++;\n const onDisk = fsImpl.read(change.file);\n if (onDisk !== change.after) mismatches.push(change.file);\n }\n if (mismatches.length) return { ran: true, ok: false, detail: `on-disk content differs for: ${mismatches.join(', ')}` };\n return { ran: true, ok: true, detail: `wrote and verified ${checked} file(s)` };\n}\n\n/** An append-only, secret-free audit record (GUARDRAILS §2.6 / §5). No file contents, no keys. */\nfunction writeAudit(fsImpl: CodeFs, r: CodeSessionResult, ts: number): void {\n const record = {\n ts,\n correlationId: r.correlationId,\n instruction: r.instruction.slice(0, 500),\n provider: r.provider.id,\n model: r.provider.model,\n local: r.provider.local,\n applied: r.applied,\n files: r.changes.map((c) => ({ file: c.file, statuses: c.outcomes.map((o) => o.status) })),\n verification: r.verification,\n phases: r.phasesRun,\n };\n try {\n fsImpl.appendAudit(JSON.stringify(record));\n } catch {\n /* audit is best-effort; never fail the run on a logging problem */\n }\n}\n\n/** Build a per-file map of symbol spans for graph-scoped edit disambiguation. */\nfunction spanIndex(graph: VgGraph): Map<string, SymbolSpan[]> {\n const map = new Map<string, SymbolSpan[]>();\n for (const n of graph.nodes) {\n if (n.kind === 'file' || n.kind === 'external') continue;\n const file = normalize(n.file);\n const list = map.get(file) ?? [];\n list.push({ qualifiedName: n.qualifiedName, file, start: n.span.start, end: n.span.end });\n map.set(file, list);\n }\n return map;\n}\n\nfunction normalize(file: string): string {\n return file.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n}\n\n/** Default filesystem impl, scoped to `root`. Refuses paths that escape the root. */\nexport function nodeCodeFs(root: string): CodeFs {\n const resolve = (file: string): string => {\n const abs = path.resolve(root, file);\n const rel = path.relative(root, abs);\n if (rel.startsWith('..') || path.isAbsolute(rel)) {\n throw new Error(`edit path escapes the project root: ${file} — refusing to touch files outside ${root}`);\n }\n return abs;\n };\n return {\n read(file) {\n try {\n return fs.readFileSync(resolve(file), 'utf8');\n } catch {\n return null;\n }\n },\n write(file, content) {\n const abs = resolve(file);\n fs.mkdirSync(path.dirname(abs), { recursive: true });\n fs.writeFileSync(abs, content);\n },\n remove(file) {\n try {\n fs.rmSync(resolve(file));\n } catch {\n /* already gone */\n }\n },\n appendAudit(line) {\n const dir = path.join(root, '.vibgrate');\n fs.mkdirSync(dir, { recursive: true });\n fs.appendFileSync(path.join(dir, 'code-audit.jsonl'), line + '\\n');\n },\n };\n}\n\n/** Short, URL-safe correlation id. Not a graph artifact, so runtime randomness is fine here. */\nfunction shortId(): string {\n let s = '';\n const alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789';\n for (let i = 0; i < 8; i++) s += alphabet[Math.floor(Math.random() * alphabet.length)];\n return s;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { listCachedWeights } from './chunk-OV4KGXPD.js';
1
+ import { listCachedWeights } from './chunk-57ZRSCHY.js';
2
2
  import * as fs from 'fs';
3
3
  import * as os from 'os';
4
4
  import * as path from 'path';
@@ -74,5 +74,5 @@ function dedupe(models) {
74
74
  }
75
75
 
76
76
  export { discoverModels };
77
- //# sourceMappingURL=chunk-CQDUBAQY.js.map
78
- //# sourceMappingURL=chunk-CQDUBAQY.js.map
77
+ //# sourceMappingURL=chunk-WNKGRXUA.js.map
78
+ //# sourceMappingURL=chunk-WNKGRXUA.js.map