@hawkeyexl/manni 4.16.0 → 4.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/README.md +1 -1
  2. package/dist/{batch-L5W4JS7A.js → batch-5TPNK5BQ.js} +14 -14
  3. package/dist/{build-GNZUVDZX.js → build-GGKCRWKH.js} +15 -14
  4. package/dist/{calibrate-2LYIDN6U.js → calibrate-OGOLLGXY.js} +15 -15
  5. package/dist/{capture-OEDMFU5Z.js → capture-CNHRHTA7.js} +14 -14
  6. package/dist/{check-NLLFHNWG.js → check-BAMOJMOJ.js} +16 -15
  7. package/dist/{check-Z5VGDSDT.js → check-XLIS5A7G.js} +13 -14
  8. package/dist/check-XYGABPXI.js +47 -0
  9. package/dist/{check-JR2TYL2Y.js → check-ZFI7H7LS.js} +15 -15
  10. package/dist/{cli-THEU2QG2.js → chunk-245W2Q7C.js} +133 -365
  11. package/dist/chunk-245W2Q7C.js.map +1 -0
  12. package/dist/{chunk-OJ7FEM2G.js → chunk-27FP4KKD.js} +47 -10
  13. package/dist/chunk-27FP4KKD.js.map +1 -0
  14. package/dist/{chunk-GQQ2AX63.js → chunk-2QZCPPVE.js} +38 -432
  15. package/dist/chunk-2QZCPPVE.js.map +1 -0
  16. package/dist/{chunk-BMYCLTFK.js → chunk-327CWO33.js} +3 -3
  17. package/dist/{chunk-WT3AATHC.js → chunk-33FIOHJ4.js} +252 -425
  18. package/dist/chunk-33FIOHJ4.js.map +1 -0
  19. package/dist/{chunk-ZJZQPOJO.js → chunk-3COYAAR7.js} +2 -2
  20. package/dist/{chunk-6ANTGYNT.js → chunk-3LZ6AYB4.js} +2 -2
  21. package/dist/{chunk-2AUULNIJ.js → chunk-4A445ALG.js} +3 -3
  22. package/dist/{chunk-L3YGGYBG.js → chunk-4KY2RUXQ.js} +3 -3
  23. package/dist/{chunk-NDBISART.js → chunk-5VA3ZOB7.js} +3 -3
  24. package/dist/{chunk-4LLYPDNG.js → chunk-6E6Z6UQL.js} +7 -7
  25. package/dist/{chunk-CSLJMML4.js → chunk-6ZYXK3JT.js} +4 -4
  26. package/dist/chunk-7RZQAMA2.js +314 -0
  27. package/dist/chunk-7RZQAMA2.js.map +1 -0
  28. package/dist/{chunk-NH6B6DDI.js → chunk-CWVL7XZR.js} +4 -4
  29. package/dist/{chunk-DTG6S2UG.js → chunk-E3YXGLEU.js} +2 -2
  30. package/dist/{chunk-5PO2BWZF.js → chunk-E76WPNYO.js} +2 -2
  31. package/dist/{chunk-F4GXZMEO.js → chunk-EITEHOSX.js} +12 -7
  32. package/dist/{chunk-F4GXZMEO.js.map → chunk-EITEHOSX.js.map} +1 -1
  33. package/dist/{chunk-DSTRT6YD.js → chunk-EU5QLSNN.js} +3 -3
  34. package/dist/{chunk-F6B2TNXU.js → chunk-F7GYY373.js} +6 -6
  35. package/dist/{chunk-6NTNLKNQ.js → chunk-FE3US7FR.js} +6 -5
  36. package/dist/{chunk-6NTNLKNQ.js.map → chunk-FE3US7FR.js.map} +1 -1
  37. package/dist/{chunk-IL62WATF.js → chunk-FNQE3RAW.js} +2 -2
  38. package/dist/chunk-FO6MNXOF.js +580 -0
  39. package/dist/chunk-FO6MNXOF.js.map +1 -0
  40. package/dist/{chunk-5D24C6WM.js → chunk-GMOAW2EG.js} +6 -2
  41. package/dist/chunk-GMOAW2EG.js.map +1 -0
  42. package/dist/chunk-GNZKLUZW.js +459 -0
  43. package/dist/chunk-GNZKLUZW.js.map +1 -0
  44. package/dist/{chunk-LEOQO3S6.js → chunk-ICRYIYMJ.js} +7 -7
  45. package/dist/{chunk-GR6QQ7GM.js → chunk-IIBVQCCR.js} +4 -4
  46. package/dist/{chunk-O6YTTBSN.js → chunk-JFB45L7D.js} +2 -2
  47. package/dist/chunk-JFPCDIES.js +1338 -0
  48. package/dist/chunk-JFPCDIES.js.map +1 -0
  49. package/dist/{chunk-2XRET3ZG.js → chunk-JHUEACRT.js} +31 -47
  50. package/dist/chunk-JHUEACRT.js.map +1 -0
  51. package/dist/{chunk-7UC55CAU.js → chunk-JS5NCZYC.js} +187 -159
  52. package/dist/chunk-JS5NCZYC.js.map +1 -0
  53. package/dist/{chunk-63GILHR5.js → chunk-KRQTN5KE.js} +4 -4
  54. package/dist/{chunk-WDENIUC7.js → chunk-MDZXRHIJ.js} +1 -1
  55. package/dist/chunk-MDZXRHIJ.js.map +1 -0
  56. package/dist/{chunk-3GLDB7MZ.js → chunk-MH5MX4B3.js} +1311 -18
  57. package/dist/chunk-MH5MX4B3.js.map +1 -0
  58. package/dist/{chunk-IGRXQC3H.js → chunk-N25KDXOV.js} +2 -2
  59. package/dist/{chunk-DW22KCLN.js → chunk-NPZWOPOH.js} +3 -3
  60. package/dist/{chunk-4L3JBAW4.js → chunk-NUAVQQMC.js} +2 -2
  61. package/dist/{chunk-PBZZUNDV.js → chunk-O2TE5X25.js} +7 -7
  62. package/dist/{chunk-EOSQENQF.js → chunk-OVQDZOMU.js} +2 -2
  63. package/dist/{chunk-WD33LE5A.js → chunk-OZWV27SE.js} +1313 -127
  64. package/dist/chunk-OZWV27SE.js.map +1 -0
  65. package/dist/{chunk-5OOQ3HQ3.js → chunk-PCTJ7P6U.js} +11 -2
  66. package/dist/chunk-PCTJ7P6U.js.map +1 -0
  67. package/dist/{chunk-EZCJPF72.js → chunk-PLN2LJDM.js} +3 -3
  68. package/dist/{chunk-D4ANAOY7.js → chunk-QGJA43DX.js} +20 -6
  69. package/dist/chunk-QGJA43DX.js.map +1 -0
  70. package/dist/{chunk-6YFEV7CM.js → chunk-QWYE3S3U.js} +5 -5
  71. package/dist/{chunk-GC47NBGO.js → chunk-QXTL5MGT.js} +4 -4
  72. package/dist/{chunk-AWAXAJ6R.js → chunk-RCWP63XT.js} +2 -2
  73. package/dist/{chunk-IM67NRUW.js → chunk-RMKMJ43W.js} +2 -2
  74. package/dist/{chunk-EA5KKIFG.js → chunk-RVSUMNCR.js} +3 -3
  75. package/dist/{chunk-NFJGIBES.js → chunk-SVB45M54.js} +82 -238
  76. package/dist/chunk-SVB45M54.js.map +1 -0
  77. package/dist/{chunk-4HEEXPVX.js → chunk-T3VFO2LO.js} +6 -6
  78. package/dist/{chunk-FU3OCYYH.js → chunk-TFTGMYDR.js} +2 -2
  79. package/dist/chunk-UP6NBQ62.js +2 -0
  80. package/dist/{chunk-LPBVWUKS.js → chunk-V2IP2ZMD.js} +2 -2
  81. package/dist/{chunk-PHNAQ4QX.js → chunk-V5QTIP2M.js} +182 -94
  82. package/dist/chunk-V5QTIP2M.js.map +1 -0
  83. package/dist/{chunk-B3XXCDYW.js → chunk-VV4YM6VM.js} +2385 -2061
  84. package/dist/chunk-VV4YM6VM.js.map +1 -0
  85. package/dist/{chunk-7GB3KEEM.js → chunk-XKZZRG3Z.js} +24 -460
  86. package/dist/chunk-XKZZRG3Z.js.map +1 -0
  87. package/dist/{chunk-ZT5NUSZA.js → chunk-XTQTA262.js} +146 -27
  88. package/dist/chunk-XTQTA262.js.map +1 -0
  89. package/dist/chunk-YLU4H2H3.js +545 -0
  90. package/dist/chunk-YLU4H2H3.js.map +1 -0
  91. package/dist/{chunk-YF6IZXAC.js → chunk-ZLOLC6WD.js} +7 -7
  92. package/dist/{cli-RWRYV5FB.js → cli-6UQ3QV2G.js} +9 -9
  93. package/dist/{cli-LZW6Z33F.js → cli-GH42HLFK.js} +42 -24
  94. package/dist/cli-GH42HLFK.js.map +1 -0
  95. package/dist/{cli-5QTSTGTX.js → cli-GND6TVRG.js} +18 -18
  96. package/dist/{cli-4Y2XY52B.js → cli-JHULEOH2.js} +2 -2
  97. package/dist/cli-LVHZCC2O.js +379 -0
  98. package/dist/cli-LVHZCC2O.js.map +1 -0
  99. package/dist/{cli-2EKRURBU.js → cli-NWU77YRZ.js} +15 -15
  100. package/dist/{cli-2SDBEUER.js → cli-PUO75R3L.js} +21 -21
  101. package/dist/{cli-TZ2OHF3H.js → cli-Q2RJMCVE.js} +28 -20
  102. package/dist/cli-Q2RJMCVE.js.map +1 -0
  103. package/dist/{cli-DBMPGGOV.js → cli-RUNYBUIV.js} +38 -38
  104. package/dist/{cli-BXUZ3KEQ.js → cli-T7UJF3BF.js} +634 -36
  105. package/dist/cli-T7UJF3BF.js.map +1 -0
  106. package/dist/{cli-KAUXC7EZ.js → cli-WUFQGIUG.js} +9 -9
  107. package/dist/cli.js +14 -14
  108. package/dist/docmeta.js +8 -8
  109. package/dist/{github-UR6LMUMW.js → github-BV42LSW2.js} +13 -14
  110. package/dist/github-XZ7OLATY.js +35 -0
  111. package/dist/graph/runtime.d.ts +633 -217
  112. package/dist/graph/runtime.js +1001 -370
  113. package/dist/graph/runtime.js.map +1 -1
  114. package/dist/index.d.ts +2734 -1977
  115. package/dist/index.js +109 -65
  116. package/dist/index.js.map +1 -1
  117. package/dist/{json-QTYN2JQB.js → json-LEEXKSGP.js} +13 -14
  118. package/dist/{json-5EQCGVCV.js → json-YTKUFNO3.js} +2 -2
  119. package/dist/{labels-UM2AFR5S.js → labels-E256WRAI.js} +12 -13
  120. package/dist/{labels-UM2AFR5S.js.map → labels-E256WRAI.js.map} +1 -1
  121. package/dist/{lint-LOFNZZPR.js → lint-W4CM3EIO.js} +13 -13
  122. package/dist/{list-GU7S6KEX.js → list-TB4R6AP4.js} +13 -14
  123. package/dist/{list-EPMHOU7T.js → list-UDDGL2OI.js} +15 -15
  124. package/dist/{page-25CN3AFY.js → page-L64NO57W.js} +13 -14
  125. package/dist/{prepare-5GYMBF4P.js → prepare-GFTAYDTP.js} +13 -13
  126. package/dist/{pretty-52Z74O6F.js → pretty-HYCYKYHB.js} +14 -15
  127. package/dist/{pretty-QW6OSYRS.js → pretty-Q43TCD6D.js} +13 -14
  128. package/dist/{reporters-WT53GD4P.js → reporters-4HRBSMUF.js} +4 -4
  129. package/dist/{reporters-FSXJ42EB.js → reporters-6TEJDXXO.js} +4 -4
  130. package/dist/{reporters-3FXX2W4X.js → reporters-E3FUVBQ6.js} +12 -12
  131. package/dist/{run-H7XJMUWK.js → run-UDX2C54M.js} +16 -16
  132. package/dist/{sarif-C427U3NA.js → sarif-WL353VTA.js} +11 -11
  133. package/dist/sarif-XZFJ5VIJ.js +36 -0
  134. package/dist/site/rehype.d.ts +33 -0
  135. package/dist/site/rehype.js +49 -0
  136. package/dist/site/rehype.js.map +1 -0
  137. package/dist/{term-VG65JRNR.js → term-OZ7ZR5KB.js} +18 -19
  138. package/dist/{term-VG65JRNR.js.map → term-OZ7ZR5KB.js.map} +1 -1
  139. package/dist/{types-VMOT7RAL.js → types-7N7ETP3W.js} +2 -2
  140. package/dist/{validate-K36F54UB.js → validate-CR3TI7GP.js} +5 -5
  141. package/package.json +10 -1
  142. package/plugin/manni/.claude-plugin/plugin.json +1 -1
  143. package/shapes/graph/shapes-1.2.0.ttl +1161 -0
  144. package/dist/check-LVO4HZ3F.js +0 -36
  145. package/dist/chunk-2XRET3ZG.js.map +0 -1
  146. package/dist/chunk-3GLDB7MZ.js.map +0 -1
  147. package/dist/chunk-3WZQ2FR3.js +0 -236
  148. package/dist/chunk-3WZQ2FR3.js.map +0 -1
  149. package/dist/chunk-5D24C6WM.js.map +0 -1
  150. package/dist/chunk-5OOQ3HQ3.js.map +0 -1
  151. package/dist/chunk-7GB3KEEM.js.map +0 -1
  152. package/dist/chunk-7UC55CAU.js.map +0 -1
  153. package/dist/chunk-B3XXCDYW.js.map +0 -1
  154. package/dist/chunk-D4ANAOY7.js.map +0 -1
  155. package/dist/chunk-GQQ2AX63.js.map +0 -1
  156. package/dist/chunk-IKEWBMCN.js +0 -98
  157. package/dist/chunk-IKEWBMCN.js.map +0 -1
  158. package/dist/chunk-NFJGIBES.js.map +0 -1
  159. package/dist/chunk-OJ7FEM2G.js.map +0 -1
  160. package/dist/chunk-PHNAQ4QX.js.map +0 -1
  161. package/dist/chunk-WD33LE5A.js.map +0 -1
  162. package/dist/chunk-WDENIUC7.js.map +0 -1
  163. package/dist/chunk-WT3AATHC.js.map +0 -1
  164. package/dist/chunk-YUTVAMWW.js +0 -2
  165. package/dist/chunk-ZT5NUSZA.js.map +0 -1
  166. package/dist/cli-BXUZ3KEQ.js.map +0 -1
  167. package/dist/cli-LZW6Z33F.js.map +0 -1
  168. package/dist/cli-THEU2QG2.js.map +0 -1
  169. package/dist/cli-TZ2OHF3H.js.map +0 -1
  170. package/dist/github-ICZ5UDGX.js +0 -36
  171. package/dist/sarif-UVAFWZKS.js +0 -37
  172. /package/dist/{batch-L5W4JS7A.js.map → batch-5TPNK5BQ.js.map} +0 -0
  173. /package/dist/{build-GNZUVDZX.js.map → build-GGKCRWKH.js.map} +0 -0
  174. /package/dist/{calibrate-2LYIDN6U.js.map → calibrate-OGOLLGXY.js.map} +0 -0
  175. /package/dist/{capture-OEDMFU5Z.js.map → capture-CNHRHTA7.js.map} +0 -0
  176. /package/dist/{check-LVO4HZ3F.js.map → check-BAMOJMOJ.js.map} +0 -0
  177. /package/dist/{check-NLLFHNWG.js.map → check-XLIS5A7G.js.map} +0 -0
  178. /package/dist/{check-Z5VGDSDT.js.map → check-XYGABPXI.js.map} +0 -0
  179. /package/dist/{check-JR2TYL2Y.js.map → check-ZFI7H7LS.js.map} +0 -0
  180. /package/dist/{chunk-BMYCLTFK.js.map → chunk-327CWO33.js.map} +0 -0
  181. /package/dist/{chunk-ZJZQPOJO.js.map → chunk-3COYAAR7.js.map} +0 -0
  182. /package/dist/{chunk-6ANTGYNT.js.map → chunk-3LZ6AYB4.js.map} +0 -0
  183. /package/dist/{chunk-2AUULNIJ.js.map → chunk-4A445ALG.js.map} +0 -0
  184. /package/dist/{chunk-L3YGGYBG.js.map → chunk-4KY2RUXQ.js.map} +0 -0
  185. /package/dist/{chunk-NDBISART.js.map → chunk-5VA3ZOB7.js.map} +0 -0
  186. /package/dist/{chunk-4LLYPDNG.js.map → chunk-6E6Z6UQL.js.map} +0 -0
  187. /package/dist/{chunk-CSLJMML4.js.map → chunk-6ZYXK3JT.js.map} +0 -0
  188. /package/dist/{chunk-NH6B6DDI.js.map → chunk-CWVL7XZR.js.map} +0 -0
  189. /package/dist/{chunk-DTG6S2UG.js.map → chunk-E3YXGLEU.js.map} +0 -0
  190. /package/dist/{chunk-5PO2BWZF.js.map → chunk-E76WPNYO.js.map} +0 -0
  191. /package/dist/{chunk-DSTRT6YD.js.map → chunk-EU5QLSNN.js.map} +0 -0
  192. /package/dist/{chunk-F6B2TNXU.js.map → chunk-F7GYY373.js.map} +0 -0
  193. /package/dist/{chunk-IL62WATF.js.map → chunk-FNQE3RAW.js.map} +0 -0
  194. /package/dist/{chunk-LEOQO3S6.js.map → chunk-ICRYIYMJ.js.map} +0 -0
  195. /package/dist/{chunk-GR6QQ7GM.js.map → chunk-IIBVQCCR.js.map} +0 -0
  196. /package/dist/{chunk-O6YTTBSN.js.map → chunk-JFB45L7D.js.map} +0 -0
  197. /package/dist/{chunk-63GILHR5.js.map → chunk-KRQTN5KE.js.map} +0 -0
  198. /package/dist/{chunk-IGRXQC3H.js.map → chunk-N25KDXOV.js.map} +0 -0
  199. /package/dist/{chunk-DW22KCLN.js.map → chunk-NPZWOPOH.js.map} +0 -0
  200. /package/dist/{chunk-4L3JBAW4.js.map → chunk-NUAVQQMC.js.map} +0 -0
  201. /package/dist/{chunk-PBZZUNDV.js.map → chunk-O2TE5X25.js.map} +0 -0
  202. /package/dist/{chunk-EOSQENQF.js.map → chunk-OVQDZOMU.js.map} +0 -0
  203. /package/dist/{chunk-EZCJPF72.js.map → chunk-PLN2LJDM.js.map} +0 -0
  204. /package/dist/{chunk-6YFEV7CM.js.map → chunk-QWYE3S3U.js.map} +0 -0
  205. /package/dist/{chunk-GC47NBGO.js.map → chunk-QXTL5MGT.js.map} +0 -0
  206. /package/dist/{chunk-AWAXAJ6R.js.map → chunk-RCWP63XT.js.map} +0 -0
  207. /package/dist/{chunk-IM67NRUW.js.map → chunk-RMKMJ43W.js.map} +0 -0
  208. /package/dist/{chunk-EA5KKIFG.js.map → chunk-RVSUMNCR.js.map} +0 -0
  209. /package/dist/{chunk-4HEEXPVX.js.map → chunk-T3VFO2LO.js.map} +0 -0
  210. /package/dist/{chunk-FU3OCYYH.js.map → chunk-TFTGMYDR.js.map} +0 -0
  211. /package/dist/{chunk-YUTVAMWW.js.map → chunk-UP6NBQ62.js.map} +0 -0
  212. /package/dist/{chunk-LPBVWUKS.js.map → chunk-V2IP2ZMD.js.map} +0 -0
  213. /package/dist/{chunk-YF6IZXAC.js.map → chunk-ZLOLC6WD.js.map} +0 -0
  214. /package/dist/{cli-RWRYV5FB.js.map → cli-6UQ3QV2G.js.map} +0 -0
  215. /package/dist/{cli-5QTSTGTX.js.map → cli-GND6TVRG.js.map} +0 -0
  216. /package/dist/{cli-4Y2XY52B.js.map → cli-JHULEOH2.js.map} +0 -0
  217. /package/dist/{cli-2EKRURBU.js.map → cli-NWU77YRZ.js.map} +0 -0
  218. /package/dist/{cli-2SDBEUER.js.map → cli-PUO75R3L.js.map} +0 -0
  219. /package/dist/{cli-DBMPGGOV.js.map → cli-RUNYBUIV.js.map} +0 -0
  220. /package/dist/{cli-KAUXC7EZ.js.map → cli-WUFQGIUG.js.map} +0 -0
  221. /package/dist/{github-ICZ5UDGX.js.map → github-BV42LSW2.js.map} +0 -0
  222. /package/dist/{github-UR6LMUMW.js.map → github-XZ7OLATY.js.map} +0 -0
  223. /package/dist/{json-5EQCGVCV.js.map → json-LEEXKSGP.js.map} +0 -0
  224. /package/dist/{json-QTYN2JQB.js.map → json-YTKUFNO3.js.map} +0 -0
  225. /package/dist/{lint-LOFNZZPR.js.map → lint-W4CM3EIO.js.map} +0 -0
  226. /package/dist/{list-EPMHOU7T.js.map → list-TB4R6AP4.js.map} +0 -0
  227. /package/dist/{list-GU7S6KEX.js.map → list-UDDGL2OI.js.map} +0 -0
  228. /package/dist/{page-25CN3AFY.js.map → page-L64NO57W.js.map} +0 -0
  229. /package/dist/{prepare-5GYMBF4P.js.map → prepare-GFTAYDTP.js.map} +0 -0
  230. /package/dist/{pretty-52Z74O6F.js.map → pretty-HYCYKYHB.js.map} +0 -0
  231. /package/dist/{pretty-QW6OSYRS.js.map → pretty-Q43TCD6D.js.map} +0 -0
  232. /package/dist/{reporters-3FXX2W4X.js.map → reporters-4HRBSMUF.js.map} +0 -0
  233. /package/dist/{reporters-FSXJ42EB.js.map → reporters-6TEJDXXO.js.map} +0 -0
  234. /package/dist/{reporters-WT53GD4P.js.map → reporters-E3FUVBQ6.js.map} +0 -0
  235. /package/dist/{run-H7XJMUWK.js.map → run-UDX2C54M.js.map} +0 -0
  236. /package/dist/{sarif-C427U3NA.js.map → sarif-WL353VTA.js.map} +0 -0
  237. /package/dist/{sarif-UVAFWZKS.js.map → sarif-XZFJ5VIJ.js.map} +0 -0
  238. /package/dist/{types-VMOT7RAL.js.map → types-7N7ETP3W.js.map} +0 -0
  239. /package/dist/{validate-K36F54UB.js.map → validate-CR3TI7GP.js.map} +0 -0
@@ -1,35 +1,65 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ GraphIndex,
4
+ VectorIndexError,
5
+ VectorMismatchError,
6
+ createLexicalIndex,
7
+ createVectorIndex,
8
+ decodeVectorIndex,
9
+ findEntry,
10
+ impact,
11
+ range,
12
+ resolveSubject,
13
+ resolveVariant,
14
+ traverse,
15
+ withholds
16
+ } from "./chunk-JFPCDIES.js";
2
17
  import {
3
18
  COPIED_SHARE,
19
+ copiedPairs,
20
+ deliveredFields,
21
+ mergePage,
22
+ openMetaView,
23
+ questionKey,
24
+ readQuestionFile,
25
+ readSampleQuestions,
26
+ withExternalMetadata
27
+ } from "./chunk-7RZQAMA2.js";
28
+ import {
4
29
  DEFAULT_MODEL,
5
30
  GraphError,
6
31
  LOCALIZATIONS_FILENAME,
7
32
  NS,
8
33
  PREFIXES,
9
34
  RDF_TYPE,
35
+ SOFTWARE_SUBJECT_IRIS,
10
36
  STDIN_PATH,
11
37
  UNDETERMINED,
38
+ analyzeDoc,
12
39
  byCodeUnit,
13
40
  canonicalLanguageTag,
14
- copiedPairs,
41
+ documentBase,
15
42
  formatOf,
43
+ isLanguageTag,
16
44
  isTreeFormat,
17
45
  loadRunConfig,
18
- mergePage,
19
46
  metadataOf,
20
47
  mintTreeSections,
21
- openMetaView,
22
48
  parseLocalizations,
23
49
  parseTree,
24
50
  profileFor,
25
- questionKey,
26
- readQuestionFile,
27
- readSampleQuestions,
51
+ routesFrom,
28
52
  withPrefix
29
- } from "./chunk-NFJGIBES.js";
53
+ } from "./chunk-SVB45M54.js";
54
+ import {
55
+ runCheck
56
+ } from "./chunk-XTQTA262.js";
30
57
  import {
31
58
  packageRoot
32
59
  } from "./chunk-TIUTIOFB.js";
60
+ import {
61
+ runDerive
62
+ } from "./chunk-27FP4KKD.js";
33
63
  import {
34
64
  bodyLineOf,
35
65
  findWindows,
@@ -37,10 +67,11 @@ import {
37
67
  spellLines,
38
68
  splitLines,
39
69
  toFileLines
40
- } from "./chunk-3GLDB7MZ.js";
70
+ } from "./chunk-MH5MX4B3.js";
41
71
  import {
72
+ integrityOf,
42
73
  locateFrontmatter
43
- } from "./chunk-WD33LE5A.js";
74
+ } from "./chunk-OZWV27SE.js";
44
75
  import {
45
76
  warn
46
77
  } from "./chunk-HX44GB4Z.js";
@@ -105,2246 +136,2543 @@ function compactIri(iri) {
105
136
  return iri;
106
137
  }
107
138
 
108
- // src/graph/core/pkg.ts
109
- import { join } from "node:path";
110
- function bundledShapesPath(moduleUrl) {
111
- return join(packageRoot(moduleUrl), "shapes", "graph", "shapes-1.1.1.ttl");
112
- }
139
+ // src/graph/commands/search.ts
140
+ import { createHash } from "node:crypto";
141
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
142
+ import { dirname, join, resolve } from "node:path";
113
143
 
114
- // src/graph/core/shacl.ts
115
- import { readFileSync as readFileSync2 } from "node:fs";
116
- import { DataFactory, Parser as Parser2, Store as Store2 } from "n3";
117
- import SHACLValidator from "rdf-validate-shacl";
118
- var SH = "http://www.w3.org/ns/shacl#";
119
- var OWL_ONTOLOGY = "http://www.w3.org/2002/07/owl#Ontology";
120
- var RDFS_SEE_ALSO = "http://www.w3.org/2000/01/rdf-schema#seeAlso";
121
- var FAMILY_SEVERITY = {
122
- violation: "error",
123
- warning: "warning",
124
- info: "notice"
125
- };
126
- function finding(shaclSeverity, rest) {
127
- return { severity: FAMILY_SEVERITY[shaclSeverity], shaclSeverity, ...rest };
128
- }
129
- var SEVERITY_RANK = {
130
- error: 0,
131
- warning: 1,
132
- notice: 2
144
+ // src/graph/embed/local.ts
145
+ var EmbedderUnavailableError = class extends Error {
146
+ constructor(detail) {
147
+ super(
148
+ `Local embeddings need @huggingface/transformers, which is an optional peer dependency.
149
+ Install it: npm install @huggingface/transformers
150
+ (${detail})`
151
+ );
152
+ this.name = "EmbedderUnavailableError";
153
+ }
133
154
  };
134
- function compareFindings(a, b) {
135
- return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || byCodeUnit(a.focusNode, b.focusNode) || byCodeUnit(a.path ?? "", b.path ?? "") || byCodeUnit(a.message, b.message);
136
- }
137
- function readShapesFile(source) {
138
- const { path, label } = typeof source === "string" ? { path: source, label: source } : source;
139
- let text;
155
+ async function loadTransformers(injected) {
156
+ if (injected) return injected;
140
157
  try {
141
- text = readFileSync2(path, "utf8");
158
+ return await import("@huggingface/transformers");
142
159
  } catch (e) {
143
- if (e.code === "ENOENT") {
144
- throw new GraphError(
145
- `Shapes file not found: ${path}. Fix the path in --shapes or graph.check.shapes. Leave both unset to use the bundled shapes.`
146
- );
147
- }
148
- throw new GraphError(`Failed to read shapes ${path}: ${errorMessage(e)}`);
160
+ throw new EmbedderUnavailableError(
161
+ errorMessage(e)
162
+ );
149
163
  }
150
- let quads;
151
- try {
152
- quads = new Parser2({ format: "text/turtle" }).parse(text);
153
- } catch (e) {
154
- throw new GraphError(`Failed to parse shapes ${path}: ${errorMessage(e)}`);
164
+ }
165
+ async function createLocalEmbedder(options = {}) {
166
+ const model = options.model ?? DEFAULT_MODEL;
167
+ const dtype = options.dtype ?? "q8";
168
+ const role = options.role ?? "passage";
169
+ const profile = profileFor(model);
170
+ const transformers = await loadTransformers(options.transformers);
171
+ if (transformers.env?.backends?.onnx?.wasm) {
172
+ transformers.env.backends.onnx.wasm.numThreads = 1;
155
173
  }
156
- const header = new Store2(quads);
157
- const ontology = header.getSubjects(DataFactory.namedNode(`${NS.rdf}type`), DataFactory.namedNode(OWL_ONTOLOGY), null).map((s) => s.value).sort(byCodeUnit)[0];
158
- const first = (predicate) => ontology === void 0 ? void 0 : header.getObjects(DataFactory.namedNode(ontology), DataFactory.namedNode(predicate), null).map((o) => o.value).sort(byCodeUnit)[0];
159
- const seeAlso = first(RDFS_SEE_ALSO);
174
+ const extractor = await transformers.pipeline("feature-extraction", model, {
175
+ // No `device`: its accepted values are disjoint across platforms, so any
176
+ // hardcoded choice throws on one of them (ADR 01025).
177
+ ...options.device === void 0 ? {} : { device: options.device },
178
+ dtype
179
+ });
180
+ let dims = 0;
160
181
  return {
161
- label,
162
- id: first(`${NS.dcterms}identifier`) ?? label,
163
- guide: seeAlso !== void 0 && /^https?:\/\//.test(seeAlso) ? seeAlso : null,
164
- quads
182
+ model,
183
+ dtype,
184
+ get dims() {
185
+ return dims;
186
+ },
187
+ async embed(text) {
188
+ const output = await extractor(withPrefix(profile, role, text), {
189
+ pooling: "mean",
190
+ normalize: true
191
+ });
192
+ const data = Float32Array.from(output.data);
193
+ dims = data.length;
194
+ return data;
195
+ }
165
196
  };
166
197
  }
167
- function loadShapes(sources) {
168
- const store = new Store2();
169
- const files = [];
170
- const fileOf = /* @__PURE__ */ new Map();
171
- for (const source of sources) {
172
- const file = readShapesFile(source);
173
- files.push(file);
174
- store.addQuads(file.quads);
175
- for (const q of file.quads) {
176
- if (!fileOf.has(q.subject.value)) fileOf.set(q.subject.value, file);
177
- }
198
+
199
+ // src/graph/embed/mock.ts
200
+ function fnv1a(text, seed) {
201
+ let hash = (2166136261 ^ seed) >>> 0;
202
+ for (let i = 0; i < text.length; i++) {
203
+ hash = (hash ^ text.charCodeAt(i)) >>> 0;
204
+ hash = hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)) >>> 0;
178
205
  }
179
- return { store, files, fileOf };
180
- }
181
- function localName(iri) {
182
- const hash = iri.lastIndexOf("#");
183
- return iri.slice((hash === -1 ? iri.lastIndexOf("/") : hash) + 1);
184
- }
185
- function shapeText(store, shape, predicate) {
186
- const subject = shape.termType === "BlankNode" ? DataFactory.blankNode(shape.value) : DataFactory.namedNode(shape.value);
187
- return preferredLiteral(store.getObjects(subject, DataFactory.namedNode(predicate), null));
188
- }
189
- function preferredLiteral(terms) {
190
- const literals = terms.flatMap(
191
- (t) => t.termType === "Literal" ? [{ value: t.value, language: t.language }] : []
192
- );
193
- const rank = (lang) => lang === "" ? 0 : lang.startsWith("en") ? 1 : 2;
194
- literals.sort(
195
- (a, b) => rank(a.language) - rank(b.language) || byCodeUnit(a.language, b.language) || byCodeUnit(a.value, b.value)
196
- );
197
- return literals[0]?.value ?? null;
198
- }
199
- function labelOf(store, iri) {
200
- return preferredLiteral(
201
- store.getObjects(DataFactory.namedNode(iri), DataFactory.namedNode(`${NS.skos}prefLabel`), null)
202
- ) ?? compactIri(iri);
203
- }
204
- function quotedList(values) {
205
- const quoted = values.map((v) => `"${v}"`);
206
- const last = quoted.pop();
207
- if (last === void 0) return "";
208
- return quoted.length === 0 ? last : `${quoted.join(", ")} and ${last}`;
206
+ return hash >>> 0;
209
207
  }
210
- function shapeGuidance(loaded, shape) {
211
- if (shape === null) return null;
212
- const file = loaded.fileOf.get(shape.value);
213
- if (file === void 0) return null;
214
- const named = shape.termType === "NamedNode";
208
+ function createMockEmbedder(options = {}) {
209
+ const dims = options.dims ?? 8;
210
+ const model = options.model ?? "mock";
211
+ const dtype = options.dtype ?? "mock";
215
212
  return {
216
- id: file.id,
217
- rule: named ? localName(shape.value) : null,
218
- description: named ? shapeText(loaded.store, shape, `${SH}description`) : null,
219
- guide: file.guide
220
- };
221
- }
222
- var bundled;
223
- function coreGuidance(rule) {
224
- bundled ??= loadShapes([bundledShapesPath(import.meta.url)]);
225
- const shape = bundled.store.getSubjects(DataFactory.namedNode(`${NS.rdf}type`), DataFactory.namedNode(`${SH}PropertyShape`), null).find((s) => localName(s.value) === rule);
226
- return shape === void 0 ? null : shapeGuidance(bundled, shape);
227
- }
228
- function blameDocs(store, focus) {
229
- const pathPred = DataFactory.namedNode(`${NS.graph}path`);
230
- const pathOf = (iri) => store.getQuads(DataFactory.namedNode(iri), pathPred, null, null)[0]?.object.value;
231
- const found = /* @__PURE__ */ new Set();
232
- const visited = /* @__PURE__ */ new Set();
233
- const walk = (iri, depth) => {
234
- if (visited.has(iri)) return;
235
- visited.add(iri);
236
- const own = pathOf(iri);
237
- if (own !== void 0) {
238
- found.add(own);
239
- return;
240
- }
241
- const hash = iri.indexOf("#");
242
- if (hash !== -1) {
243
- const base = pathOf(iri.slice(0, hash));
244
- if (base !== void 0) {
245
- found.add(base);
246
- return;
247
- }
248
- }
249
- if (depth === 0) return;
250
- for (const quad of store.getQuads(null, null, DataFactory.namedNode(iri), null)) {
251
- if (quad.subject.termType === "NamedNode") {
252
- walk(quad.subject.value, depth - 1);
213
+ model,
214
+ dtype,
215
+ dims,
216
+ embed(text) {
217
+ const vector = new Float32Array(dims);
218
+ for (let i = 0; i < dims; i++) {
219
+ vector[i] = fnv1a(text, i) / 4294967296 * 2 - 1;
253
220
  }
221
+ return Promise.resolve(vector);
254
222
  }
255
223
  };
256
- walk(focus, 2);
257
- return [...found].sort();
258
224
  }
259
- function broaderEdges(store) {
260
- const edges2 = [];
261
- for (const q of store.getQuads(
262
- null,
263
- DataFactory.namedNode(`${NS.skos}broader`),
264
- null,
265
- null
266
- )) {
267
- if (q.object.termType === "NamedNode") {
268
- edges2.push({ s: q.subject.value, o: q.object.value });
269
- }
225
+
226
+ // src/graph/commands/search.ts
227
+ var SEARCH_MODES = ["lexical", "hybrid", "vector"];
228
+ function loadSearchIndex(indexPath) {
229
+ const raw = readFileSync2(indexPath, "utf8");
230
+ let parsed;
231
+ try {
232
+ parsed = JSON.parse(raw);
233
+ } catch (e) {
234
+ throw new GraphError(
235
+ `Failed to parse ${indexPath}: ${errorMessage(e)} \u2014 re-run \`manni graph export search\`.`
236
+ );
270
237
  }
271
- for (const q of store.getQuads(
272
- null,
273
- DataFactory.namedNode(`${NS.skos}narrower`),
274
- null,
275
- null
276
- )) {
277
- if (q.object.termType === "NamedNode") {
278
- edges2.push({ s: q.object.value, o: q.subject.value });
279
- }
238
+ const entries = parsed?.entries;
239
+ if (!Array.isArray(entries)) {
240
+ throw new GraphError(
241
+ `Not a manni graph search index: ${indexPath} \u2014 expected an \`entries\` array; re-run \`manni graph export search\`.`
242
+ );
280
243
  }
281
- return edges2;
282
- }
283
- function broaderCycles(store) {
284
- const adjacency = /* @__PURE__ */ new Map();
285
- const selfLoops = /* @__PURE__ */ new Set();
286
- for (const { s, o } of broaderEdges(store)) {
287
- if (s === o) selfLoops.add(s);
288
- const list = adjacency.get(s);
289
- if (list) list.push(o);
290
- else adjacency.set(s, [o]);
291
- if (!adjacency.has(o)) adjacency.set(o, []);
292
- }
293
- for (const list of adjacency.values()) list.sort();
294
- const index = /* @__PURE__ */ new Map();
295
- const lowlink = /* @__PURE__ */ new Map();
296
- const onStack = /* @__PURE__ */ new Set();
297
- const stack = [];
298
- const components = [];
299
- let counter = 0;
300
- const numberOf = (map, node) => {
301
- const value = map.get(node);
302
- if (value === void 0) {
303
- throw new GraphError(
304
- `internal: ${node} was visited before it was numbered`
305
- );
306
- }
307
- return value;
244
+ return {
245
+ doc: parsed,
246
+ // Same recipe `manni graph embed` uses, so the two digests are comparable.
247
+ source: `sha256:${createHash("sha256").update(raw, "utf8").digest("hex")}`
308
248
  };
309
- const nodes = [...adjacency.keys()].sort();
310
- for (const root of nodes) {
311
- if (index.has(root)) continue;
312
- const frames = [[root, 0]];
313
- for (let frame = frames.at(-1); frame !== void 0; frame = frames.at(-1)) {
314
- const [node, childIdx] = frame;
315
- if (childIdx === 0) {
316
- index.set(node, counter);
317
- lowlink.set(node, counter);
318
- counter += 1;
319
- stack.push(node);
320
- onStack.add(node);
321
- }
322
- const children = adjacency.get(node) ?? [];
323
- const child = children[childIdx];
324
- if (child !== void 0) {
325
- frame[1] += 1;
326
- if (!index.has(child)) {
327
- frames.push([child, 0]);
328
- } else if (onStack.has(child)) {
329
- lowlink.set(
330
- node,
331
- Math.min(numberOf(lowlink, node), numberOf(index, child))
332
- );
333
- }
334
- } else {
335
- if (lowlink.get(node) === index.get(node)) {
336
- const component = [];
337
- let member;
338
- do {
339
- member = stack.pop();
340
- if (member === void 0) break;
341
- onStack.delete(member);
342
- component.push(member);
343
- } while (member !== node);
344
- if (component.length > 1 || selfLoops.has(node)) {
345
- components.push(component.sort());
346
- }
347
- }
348
- frames.pop();
349
- const parent = frames.at(-1);
350
- if (parent) {
351
- lowlink.set(
352
- parent[0],
353
- Math.min(numberOf(lowlink, parent[0]), numberOf(lowlink, node))
354
- );
355
- }
356
- }
249
+ }
250
+ function noIndexFor(lang, available) {
251
+ return `No index for language "${lang}" \u2014 this corpus has ${available.join(", ") || "none"}.`;
252
+ }
253
+ function langRequired(available) {
254
+ return `This corpus has more than one localization (${available.join(", ")}) \u2014 pass --lang to choose one.`;
255
+ }
256
+ function resolveLocalization(indexDir, lang) {
257
+ const manifestPath = join(indexDir, LOCALIZATIONS_FILENAME);
258
+ if (!existsSync2(manifestPath)) {
259
+ throw new GraphError(
260
+ `Localization manifest not found: ${manifestPath} \u2014 run \`manni graph export search\` first.`
261
+ );
262
+ }
263
+ const manifest = parseLocalizations(readFileSync2(manifestPath, "utf8"));
264
+ if (!manifest) {
265
+ throw new GraphError(
266
+ `Not a manni graph localization manifest: ${manifestPath} \u2014 re-run \`manni graph export search\`.`
267
+ );
268
+ }
269
+ const available = manifest.languages.map((l) => l.language);
270
+ if (lang !== void 0) {
271
+ const wanted = canonicalLanguageTag(lang);
272
+ const hit = manifest.languages.find(
273
+ (l) => canonicalLanguageTag(l.language) === wanted
274
+ );
275
+ if (!hit) {
276
+ throw new GraphError(noIndexFor(lang, available));
357
277
  }
278
+ return hit;
358
279
  }
359
- return components.sort((a, b) => (a[0] ?? "") < (b[0] ?? "") ? -1 : 1);
360
- }
361
- function broaderClosure(edges2, start) {
362
- const adjacency = /* @__PURE__ */ new Map();
363
- for (const { s, o } of edges2) {
364
- const list = adjacency.get(s);
365
- if (list) list.push(o);
366
- else adjacency.set(s, [o]);
280
+ const only = manifest.languages[0];
281
+ if (!only) {
282
+ throw new GraphError(
283
+ `The localization manifest lists no languages: ${manifestPath} \u2014 re-run \`manni graph export search\`.`
284
+ );
367
285
  }
368
- const seen = /* @__PURE__ */ new Set();
369
- const queue = [...adjacency.get(start) ?? []];
370
- for (let node = queue.shift(); node !== void 0; node = queue.shift()) {
371
- if (seen.has(node)) continue;
372
- seen.add(node);
373
- queue.push(...adjacency.get(node) ?? []);
286
+ if (manifest.languages.length > 1) {
287
+ throw new GraphError(langRequired(available));
374
288
  }
375
- return seen;
289
+ return only;
376
290
  }
377
- function relatedConflicts(store) {
378
- const edges2 = broaderEdges(store);
379
- const related = `${NS.skos}related`;
380
- const has = (index2, a, b) => index2.get(a)?.has(b) ?? false;
381
- const put = (index2, a, b) => {
382
- const targets = index2.get(a);
383
- if (targets) targets.add(b);
384
- else index2.set(a, /* @__PURE__ */ new Set([b]));
385
- };
386
- const index = (predicate) => {
387
- const out = /* @__PURE__ */ new Map();
388
- for (const q of store.getQuads(null, DataFactory.namedNode(predicate), null, null)) {
389
- if (q.object.termType === "NamedNode") put(out, q.subject.value, q.object.value);
390
- }
391
- return out;
392
- };
393
- const relatedIndex = index(related);
394
- const broaderIndex = index(`${NS.skos}broader`);
395
- const disjointFires = (a, b) => has(relatedIndex, a, b) && has(broaderIndex, a, b) || has(relatedIndex, b, a) && has(broaderIndex, b, a);
396
- const closures = /* @__PURE__ */ new Map();
397
- const ancestors = (node) => {
398
- let found = closures.get(node);
399
- if (found === void 0) {
400
- found = broaderClosure(edges2, node);
401
- closures.set(node, found);
291
+ async function runSearch(opts) {
292
+ const cwd = opts.cwd ?? process.cwd();
293
+ const config = loadRunConfig(
294
+ {
295
+ ...opts.config === void 0 ? {} : { configPath: opts.config },
296
+ ...opts.noConfig === void 0 ? {} : { noConfig: opts.noConfig }
297
+ },
298
+ cwd
299
+ );
300
+ const graphPath = resolve(cwd, opts.graph ?? config.out);
301
+ const indexDir = opts.index ? resolve(cwd, opts.index) : dirname(graphPath);
302
+ const localization = resolveLocalization(indexDir, opts.lang);
303
+ const indexPath = join(indexDir, localization.search.path);
304
+ if (!existsSync2(indexPath)) {
305
+ throw new GraphError(
306
+ `Search index not found: ${indexPath} \u2014 the manifest names it; re-run \`manni graph export search\`.`
307
+ );
308
+ }
309
+ const { doc, source } = loadSearchIndex(indexPath);
310
+ if (localization.search.digest !== source) {
311
+ throw new GraphError(
312
+ `Stale manifest: ${localization.search.path} does not match the digest recorded for "${localization.language}". Re-run \`manni graph export search\`.`
313
+ );
314
+ }
315
+ const lexical = createLexicalIndex(doc);
316
+ const explicitVectors = opts.vectors !== void 0 && opts.vectors !== "" ? opts.vectors : void 0;
317
+ const wantsVector = opts.mode === "vector" || opts.mode === "hybrid" || explicitVectors !== void 0 && opts.mode !== "lexical";
318
+ const vectorsPath = explicitVectors ? resolve(cwd, explicitVectors) : localization.vectors ? resolve(indexDir, localization.vectors.path) : void 0;
319
+ let vectors;
320
+ if (opts.mode !== "lexical" && vectorsPath !== void 0 && existsSync2(vectorsPath)) {
321
+ try {
322
+ vectors = createVectorIndex(readFileSync2(vectorsPath));
323
+ } catch (e) {
324
+ if (e instanceof VectorIndexError) {
325
+ throw new GraphError(
326
+ `${e.message} (${vectorsPath}) \u2014 re-run \`manni graph embed\`, or use \`--mode lexical\`.`
327
+ );
328
+ }
329
+ throw e;
402
330
  }
403
- return found;
404
- };
405
- const seen = /* @__PURE__ */ new Map();
406
- const findings = [];
407
- for (const [s, targets] of [...relatedIndex].sort(([a], [b]) => byCodeUnit(a, b))) {
408
- for (const o of [...targets].sort(byCodeUnit)) {
409
- const [a, b] = byCodeUnit(s, o) <= 0 ? [s, o] : [o, s];
410
- if (has(seen, a, b)) continue;
411
- put(seen, a, b);
412
- if (disjointFires(a, b)) continue;
413
- const bAboveA = ancestors(a).has(b);
414
- if (!bAboveA && !ancestors(b).has(a)) continue;
415
- const [descendant, ancestor] = bAboveA ? [a, b] : [b, a];
416
- findings.push(
417
- finding("violation", {
418
- message: `"${labelOf(store, ancestor)}" is both related to "${labelOf(store, descendant)}" and one of its ancestors. Remove one link: from \`related-concepts\` or \`related-terms\`, or from the \`broader\` chain between them.`,
419
- focusNode: descendant,
420
- path: related,
421
- docs: [
422
- .../* @__PURE__ */ new Set([...blameDocs(store, descendant), ...blameDocs(store, ancestor)])
423
- ].sort(byCodeUnit),
424
- guidance: coreGuidance("Concept-related")
425
- })
426
- );
331
+ const stale = vectors.check({ source });
332
+ if (stale && wantsVector) throw new GraphError(stale.detail);
333
+ if (stale) {
334
+ warn(`${stale.detail} Falling back to lexical.`);
335
+ vectors = void 0;
427
336
  }
337
+ } else if (wantsVector) {
338
+ const named = vectorsPath ?? `no sidecar recorded for "${localization.language}"`;
339
+ throw new GraphError(
340
+ `Vector index not found: ${named} \u2014 run \`manni graph embed\` first, or use \`--mode lexical\`.`
341
+ );
428
342
  }
429
- return findings;
430
- }
431
- function cycleFindings(store) {
432
- return broaderCycles(store).map((members) => {
433
- const labels = members.map((m) => labelOf(store, m));
434
- return finding("violation", {
435
- message: labels.length === 1 ? `${quotedList(labels)} forms a broader cycle with itself, so it is its own ancestor. Remove the \`broader\` or \`narrower\` value that names it.` : `${quotedList(labels)} form a broader cycle, so each is its own ancestor. Remove one \`broader\` or \`narrower\` value on the cycle.`,
436
- // `broaderCycles` returns only components of at least one member, so
437
- // the first is there; `?? ""` says that without asserting it.
438
- focusNode: members[0] ?? "",
439
- path: `${NS.skos}broader`,
440
- docs: [...new Set(members.flatMap((m) => blameDocs(store, m)))].sort(),
441
- guidance: coreGuidance("Concept-broader")
442
- });
443
- });
444
- }
445
- var SHAPES_1_0_0_COLLISION = "concept carries multiple prefLabels (same slug, different spellings) \u2014 settle on one spelling";
446
- function untaggedPrefLabelFindings(store) {
447
- const prefLabel = `${NS.skos}prefLabel`;
448
- const untagged = /* @__PURE__ */ new Map();
449
- for (const q of store.getQuads(null, DataFactory.namedNode(prefLabel), null, null)) {
450
- if (q.object.termType !== "Literal" || q.object.language !== "") continue;
451
- const spellings = untagged.get(q.subject.value);
452
- if (spellings) spellings.add(q.object.value);
453
- else untagged.set(q.subject.value, /* @__PURE__ */ new Set([q.object.value]));
343
+ let embedder;
344
+ if (vectors) {
345
+ const requireEmbedder = opts.mode === "vector" || opts.mode === "hybrid";
346
+ embedder = await resolveEmbedder(opts.embedder, vectors, requireEmbedder);
454
347
  }
455
- return [...untagged].filter(([, spellings]) => spellings.size > 1).map(
456
- ([focusNode, spellings]) => finding("warning", {
457
- message: `Pages spell this concept ${spellings.size === 2 ? "two" : String(spellings.size)} ways: ${quotedList([...spellings].sort(byCodeUnit))}. Use one spelling on every page that names it.`,
458
- focusNode,
459
- path: prefLabel,
460
- docs: blameDocs(store, focusNode),
461
- guidance: coreGuidance("Concept-prefLabel-collision")
462
- })
463
- );
464
- }
465
- var MAPPINGS = [
466
- ["exactMatch", "exact-matches"],
467
- ["closeMatch", "close-matches"],
468
- ["broadMatch", "broad-matches"],
469
- ["narrowMatch", "narrow-matches"],
470
- ["relatedMatch", "related-matches"]
471
- ];
472
- function inSchemeMappingFindings(store) {
473
- const inScheme = DataFactory.namedNode(`${NS.skos}inScheme`);
474
- const findings = [];
475
- for (const [mapping, key] of MAPPINGS) {
476
- const path = `${NS.skos}${mapping}`;
477
- for (const q of store.getQuads(null, DataFactory.namedNode(path), null, null)) {
478
- if (q.object.termType !== "NamedNode") continue;
479
- const schemes = new Set(store.getObjects(q.subject, inScheme, null).map((o) => o.value));
480
- const shared = store.getObjects(q.object, inScheme, null).some((o) => schemes.has(o.value));
481
- if (!shared) continue;
482
- findings.push(
483
- finding("violation", {
484
- message: `\`${key}\` names "${labelOf(store, q.object.value)}", a concept in this glossary. Use \`broader\`, \`narrower\` or \`related-terms\` for it instead.`,
485
- focusNode: q.subject.value,
486
- path,
487
- docs: blameDocs(store, q.subject.value),
488
- guidance: coreGuidance(`Concept-${mapping}`)
489
- })
490
- );
348
+ const entry2 = await findEntry(opts.query, {
349
+ lexical,
350
+ // Pass the embedder, not a bare function: findEntry then verifies it
351
+ // against the index itself rather than trusting the CLI to have done so.
352
+ ...embedder && vectors ? { vectors, embedder } : {},
353
+ limit: opts.limit
354
+ }).catch((e) => {
355
+ if (e instanceof VectorMismatchError) {
356
+ throw new GraphError(`${e.message} Re-run \`manni graph embed\`.`);
491
357
  }
358
+ throw e;
359
+ });
360
+ const decorate = (c) => {
361
+ const found = lexical.entry(c.iri);
362
+ return {
363
+ iri: c.iri,
364
+ score: c.score,
365
+ via: c.via,
366
+ ...found?.type === void 0 ? {} : { type: found.type },
367
+ ...found?.title === void 0 ? {} : { title: found.title }
368
+ };
369
+ };
370
+ const mode = opts.mode ?? (embedder && vectors ? "hybrid" : "lexical");
371
+ const results = opts.mode === "vector" ? entry2.vector : entry2.candidates;
372
+ if (opts.mode === "vector") {
373
+ entry2.trace.entry.length = 0;
374
+ entry2.trace.entry.push(...entry2.vector);
492
375
  }
493
- return findings;
494
- }
495
- var CURATED_FIELDS = /* @__PURE__ */ new Set(["sections", "revision-of", "derived-from"]);
496
- var GRAPH_FILL_FRAGMENT = "#prov.graph-fill.";
497
- function curatedFieldFindings(store) {
498
- const filledField = `${NS.graph}filledField`;
499
- const pathPred = DataFactory.namedNode(`${NS.graph}path`);
500
- const findings = [];
501
- for (const q of store.getQuads(null, DataFactory.namedNode(filledField), null, null)) {
502
- if (q.object.termType !== "Literal") continue;
503
- const field = q.object.value;
504
- if (!CURATED_FIELDS.has(field)) continue;
505
- const node = q.subject.value;
506
- const at = node.indexOf(GRAPH_FILL_FRAGMENT);
507
- const fieldAt = node.lastIndexOf(".field.");
508
- if (at === -1 || fieldAt <= at) continue;
509
- const activity = node.slice(0, fieldAt);
510
- const model = node.slice(at + GRAPH_FILL_FRAGMENT.length, fieldAt);
511
- const docIri = activity.slice(0, activity.indexOf("#"));
512
- const path = store.getQuads(DataFactory.namedNode(docIri), pathPred, null, null)[0]?.object.value;
513
- findings.push(
514
- finding("violation", {
515
- message: `\`meta-provenance\` credits ${model} with /graph/${field}, a field only a person writes. Check the value, then delete that entry.`,
516
- focusNode: activity,
517
- path: filledField,
518
- docs: path === void 0 ? blameDocs(store, activity) : [path],
519
- guidance: coreGuidance("FilledFieldEntry-name")
520
- })
521
- );
522
- }
523
- return findings;
524
- }
525
- function severityOf(iri) {
526
- if (iri === "http://www.w3.org/ns/shacl#Warning") return "warning";
527
- if (iri === "http://www.w3.org/ns/shacl#Info") return "info";
528
- return "violation";
376
+ return {
377
+ query: opts.query,
378
+ mode,
379
+ results: results.map(decorate),
380
+ lexical: entry2.lexical.map(decorate),
381
+ vector: entry2.vector.map(decorate),
382
+ trace: entry2.trace
383
+ };
529
384
  }
530
- async function validateGraph(store, shapesPaths) {
531
- const shapes = loadShapes(shapesPaths);
532
- const validator = new SHACLValidator(shapes.store);
533
- let report;
385
+ async function resolveEmbedder(override, vectors, required) {
386
+ const { model, dtype } = vectors;
534
387
  try {
535
- report = await validator.validate(store);
388
+ const embedder = override ?? (model === "mock" ? createMockEmbedder({ dtype }) : await createLocalEmbedder({ model, dtype, role: "query" }));
389
+ const mismatch = vectors.check({
390
+ model: embedder.model,
391
+ dtype: embedder.dtype,
392
+ // Defense in depth: a future model that changes output size without
393
+ // changing its id would otherwise only surface deep inside search().
394
+ ...embedder.dims > 0 ? { dims: embedder.dims } : {}
395
+ });
396
+ if (mismatch) throw new GraphError(mismatch.detail);
397
+ return embedder;
536
398
  } catch (e) {
399
+ if (e instanceof GraphError) throw e;
400
+ if (e instanceof EmbedderUnavailableError) {
401
+ if (required) throw new GraphError(e.message);
402
+ return void 0;
403
+ }
537
404
  throw new GraphError(
538
- `SHACL validation failed: ${errorMessage(e)}`
405
+ `Failed to load embedding model ${model}: ${errorMessage(e)}`
539
406
  );
540
407
  }
541
- const merged = /* @__PURE__ */ new Map();
542
- const groups = [];
543
- for (const result of report.results) {
544
- const focus = result.focusNode?.value ?? "";
545
- const path = result.path?.value;
546
- const messages = result.message.map((m) => m.value).filter((m) => m.length > 0);
547
- const declared = result.sourceShape === null ? null : shapeText(shapes.store, result.sourceShape, `${SH}message`);
548
- const message = declared !== null && !/\{[$?]/.test(declared) ? declared : messages.length > 0 ? messages.join("; ") : `constraint violated${path ? ` on ${compactIri(path)}` : ""}`;
549
- const byFocus = merged.get(result.sourceShape?.value ?? "") ?? /* @__PURE__ */ new Map();
550
- merged.set(result.sourceShape?.value ?? "", byFocus);
551
- const byPath = byFocus.get(focus) ?? /* @__PURE__ */ new Map();
552
- byFocus.set(focus, byPath);
553
- const earlier = byPath.get(path ?? "");
554
- if (earlier !== void 0) {
555
- if (!earlier.messages.includes(message)) earlier.messages.push(message);
556
- continue;
557
- }
558
- const found = finding(severityOf(result.severity?.value), {
559
- message,
560
- focusNode: focus,
561
- ...path !== void 0 ? { path } : {},
562
- docs: blameDocs(store, focus),
563
- guidance: shapeGuidance(shapes, result.sourceShape)
564
- });
565
- const group = { found, messages: [message] };
566
- byPath.set(path ?? "", group);
567
- groups.push(group);
408
+ }
409
+ function renderSearch(report, format) {
410
+ if (format === "json") return JSON.stringify(report, null, 2);
411
+ const lines = [];
412
+ for (const r of report.results) {
413
+ const label = r.title ? ` \u2014 ${r.title}` : "";
414
+ const type = r.type ? ` [${r.type}]` : "";
415
+ lines.push(`${r.score.toFixed(4)} ${compactIri(r.iri)}${type}${label}`);
568
416
  }
569
- const findings = groups.map(({ found, messages }) => ({ ...found, message: messages.join("; ") }));
570
- const said = new Set(
571
- findings.filter((f) => f.message === SHAPES_1_0_0_COLLISION).map((f) => f.focusNode)
572
- );
573
- findings.push(
574
- ...cycleFindings(store),
575
- ...relatedConflicts(store),
576
- ...curatedFieldFindings(store),
577
- ...inSchemeMappingFindings(store),
578
- ...untaggedPrefLabelFindings(store).filter((f) => !said.has(f.focusNode))
417
+ if (report.results.length === 0) {
418
+ lines.push("(no matches)");
419
+ }
420
+ lines.push("");
421
+ lines.push(
422
+ `${report.results.length} result${report.results.length === 1 ? "" : "s"} (${report.mode})`
579
423
  );
580
- findings.sort(compareFindings);
581
- return findings;
424
+ return lines.join("\n");
582
425
  }
583
426
 
584
- // src/graph/commands/search.ts
585
- import { createHash } from "node:crypto";
586
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
587
- import { dirname, join as join2, resolve } from "node:path";
427
+ // src/graph/commands/questions.ts
428
+ import { createHash as createHash2 } from "node:crypto";
429
+ import { existsSync as existsSync4, readFileSync as readFileSync4 } from "node:fs";
430
+ import { join as join2, resolve as resolve3 } from "node:path";
431
+ import GithubSlugger from "github-slugger";
588
432
 
589
- // src/graph/core/vector-index.ts
590
- var MAGIC = new Uint8Array([77, 71, 82, 86]);
591
- var FORMAT_VERSION = 2;
592
- var HEADER_OFFSET = 12;
593
- var VectorIndexError = class extends Error {
594
- constructor(message) {
595
- super(message);
596
- this.name = "VectorIndexError";
597
- }
598
- };
599
- function normalize(vector) {
600
- let sum = 0;
601
- for (const value of vector) sum += value * value;
602
- if (sum === 0) return vector;
603
- const inv = 1 / Math.sqrt(sum);
604
- vector.set(vector.map((value) => value * inv));
605
- return vector;
606
- }
607
- function encodeVectorIndex(entries, meta) {
608
- const sorted = [...entries].sort((a, b) => byCodeUnit(a.id, b.id));
609
- const dims = sorted[0]?.vector.length ?? 0;
610
- for (const entry2 of sorted) {
611
- if (entry2.vector.length !== dims) {
612
- throw new VectorIndexError(
613
- `Inconsistent vector dimensions: ${entry2.id} has ${entry2.vector.length}, expected ${dims}.`
614
- );
433
+ // src/graph/core/search-index.ts
434
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
435
+ import { resolve as resolve2 } from "node:path";
436
+
437
+ // src/graph/runtime/resolve.ts
438
+ var GRAPH_PATH = `${NS.graph}path`;
439
+ var DCTERMS_TITLE = `${NS.dcterms}title`;
440
+ var DCTERMS_HAS_PART = `${NS.dcterms}hasPart`;
441
+ var GRAPH_LEVEL = `${NS.graph}level`;
442
+ var GRAPH_ORDER = `${NS.graph}order`;
443
+ var GRAPH_BLOCK = `${NS.graph}Block`;
444
+ function splitFragment(iri) {
445
+ const hash = iri.indexOf("#");
446
+ return hash < 0 ? { doc: iri } : { doc: iri.slice(0, hash), fragment: iri.slice(hash + 1) };
447
+ }
448
+ function fencedLines(lines) {
449
+ const mask = new Array(lines.length).fill(false);
450
+ let open;
451
+ for (const [i, line] of lines.entries()) {
452
+ const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
453
+ const delimiter = m?.[1];
454
+ const info = m?.[2];
455
+ const isFence = delimiter !== void 0 && info !== void 0;
456
+ if (open === void 0) {
457
+ if (isFence && !(delimiter.startsWith("`") && info.includes("`"))) {
458
+ open = delimiter;
459
+ mask[i] = true;
460
+ }
461
+ continue;
615
462
  }
616
- }
617
- const header = {
618
- model: meta.model,
619
- dtype: meta.dtype,
620
- dims,
621
- count: sorted.length,
622
- ids: sorted.map((e) => e.id),
623
- source: meta.source,
624
- language: meta.language
625
- };
626
- const headerBytes = new TextEncoder().encode(JSON.stringify(header));
627
- const payloadBytes = sorted.length * dims * 4;
628
- const out = new Uint8Array(HEADER_OFFSET + headerBytes.length + payloadBytes);
629
- const view = new DataView(out.buffer);
630
- out.set(MAGIC, 0);
631
- view.setUint32(4, FORMAT_VERSION, true);
632
- view.setUint32(8, headerBytes.length, true);
633
- out.set(headerBytes, HEADER_OFFSET);
634
- let offset = HEADER_OFFSET + headerBytes.length;
635
- for (const entry2 of sorted) {
636
- const vector = normalize(Float32Array.from(entry2.vector));
637
- for (const value of vector) {
638
- view.setFloat32(offset, value, true);
639
- offset += 4;
463
+ mask[i] = true;
464
+ if (isFence && delimiter[0] === open[0] && delimiter.length >= open.length && info.trim() === "") {
465
+ open = void 0;
640
466
  }
641
467
  }
642
- return out;
468
+ return mask;
643
469
  }
644
- function decodeVectorIndex(bytes) {
645
- if (bytes.length < HEADER_OFFSET) {
646
- throw new VectorIndexError("Not a manni graph vector index: file is too short.");
647
- }
648
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
649
- if (!MAGIC.every((byte, i) => bytes[i] === byte)) {
650
- throw new VectorIndexError(
651
- "Not a manni graph vector index: bad magic \u2014 is this the right file?"
652
- );
653
- }
654
- const version = view.getUint32(4, true);
655
- if (version !== FORMAT_VERSION) {
656
- throw new VectorIndexError(
657
- `Unsupported vector index version ${version} (this build reads ${FORMAT_VERSION}) \u2014 re-run \`manni graph embed\`.`
658
- );
659
- }
660
- const headerLength = view.getUint32(8, true);
661
- if (HEADER_OFFSET + headerLength > bytes.length) {
662
- throw new VectorIndexError("Vector index is truncated: header overruns.");
663
- }
664
- let header;
665
- try {
666
- header = JSON.parse(
667
- new TextDecoder().decode(
668
- bytes.subarray(HEADER_OFFSET, HEADER_OFFSET + headerLength)
669
- )
670
- );
671
- } catch {
672
- throw new VectorIndexError("Vector index header is not valid JSON.");
673
- }
674
- if (!Array.isArray(header.ids) || typeof header.dims !== "number" || header.ids.length !== header.count) {
675
- throw new VectorIndexError("Vector index header is malformed.");
676
- }
677
- const start = HEADER_OFFSET + headerLength;
678
- const expected = header.count * header.dims * 4;
679
- if (bytes.length - start !== expected) {
680
- throw new VectorIndexError(
681
- `Vector index is truncated: expected ${expected} payload bytes, found ${bytes.length - start}.`
682
- );
683
- }
684
- const vectors = new Float32Array(header.count * header.dims);
685
- for (let i = 0; i < vectors.length; i++) {
686
- vectors[i] = view.getFloat32(start + i * 4, true);
687
- }
688
- return { header, vectors };
470
+ var ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
471
+ var SETEXT_UNDERLINE = /^ {0,3}(=+|-+)[ \t]*$/;
472
+ function isParagraphLine(line) {
473
+ if (line.trim() === "") return false;
474
+ if (ATX.test(line)) return false;
475
+ if (/^ {0,3}([-+*]|\d{1,9}[.)])([ \t]|$)/.test(line)) return false;
476
+ if (/^ {0,3}>/.test(line)) return false;
477
+ if (/^ {0,3}([-*_])([ \t]*\1){2,}[ \t]*$/.test(line)) return false;
478
+ return !/^ {4}/.test(line);
689
479
  }
690
-
691
- // src/graph/runtime/vector.ts
692
- var VectorMismatchError = class extends Error {
693
- reason;
694
- constructor(mismatch) {
695
- super(mismatch.detail);
696
- this.name = "VectorMismatchError";
697
- this.reason = mismatch.reason;
480
+ function frontmatterLength(lines) {
481
+ if (lines[0]?.trim() !== "---") return 0;
482
+ for (let i = 1; i < lines.length; i++) {
483
+ const line = lines[i]?.trim();
484
+ if (line === "---" || line === "...") return i + 1;
698
485
  }
699
- };
700
- async function searchIndexDigest(raw) {
701
- const webCrypto = globalThis.crypto;
702
- const subtle = webCrypto?.subtle;
703
- if (!subtle) {
704
- throw new Error(
705
- "searchIndexDigest needs Web Crypto (globalThis.crypto.subtle), which is unavailable here \u2014 a page served over plain HTTP does not get it."
706
- );
486
+ return 0;
487
+ }
488
+ function sourceHeadings(lines) {
489
+ const fenced = fencedLines(lines);
490
+ const skip = frontmatterLength(lines);
491
+ const headings = [];
492
+ let paragraph = -1;
493
+ for (const [i, line] of lines.entries()) {
494
+ if (i < skip || fenced[i]) {
495
+ paragraph = -1;
496
+ continue;
497
+ }
498
+ const atx = ATX.exec(line);
499
+ const hashes = atx?.[1];
500
+ if (hashes !== void 0) {
501
+ const text = (atx?.[2] ?? "").replace(/(^|[ \t]+)#+$/, "");
502
+ headings.push({ start: i, level: hashes.length, text });
503
+ paragraph = -1;
504
+ continue;
505
+ }
506
+ const underline = SETEXT_UNDERLINE.exec(line)?.[1];
507
+ if (underline !== void 0 && paragraph >= 0) {
508
+ headings.push({
509
+ start: paragraph,
510
+ level: underline.startsWith("=") ? 1 : 2,
511
+ text: lines.slice(paragraph, i).join("\n")
512
+ });
513
+ paragraph = -1;
514
+ continue;
515
+ }
516
+ if (isParagraphLine(line)) {
517
+ if (paragraph < 0) paragraph = i;
518
+ } else {
519
+ paragraph = -1;
520
+ }
707
521
  }
708
- const digest = await subtle.digest("SHA-256", new TextEncoder().encode(raw));
709
- const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
710
- return `sha256:${hex}`;
522
+ return headings;
711
523
  }
712
- function createVectorIndex(bytes) {
713
- const { header, vectors } = decodeVectorIndex(bytes);
714
- const { dims, ids } = header;
715
- return {
716
- model: header.model,
717
- dtype: header.dtype,
718
- dims,
719
- source: header.source,
720
- size: () => ids.length,
721
- idAt: (row) => ids[row],
722
- check(expected) {
723
- if (expected.model !== void 0 && expected.model !== header.model) {
724
- return {
725
- reason: "model",
726
- detail: `Vector index was built with ${header.model}, but the embedder is ${expected.model}. Re-run \`manni graph embed\`.`
727
- };
728
- }
729
- if (expected.dtype !== void 0 && expected.dtype !== header.dtype) {
730
- return {
731
- reason: "dtype",
732
- detail: `Vector index was built at dtype ${header.dtype}, but the embedder is at ${expected.dtype} \u2014 different weights are a different function. Re-run \`manni graph embed\`.`
733
- };
734
- }
735
- if (expected.dims !== void 0 && expected.dims !== dims) {
736
- return {
737
- reason: "dims",
738
- detail: `Vector index has ${dims} dimensions, but the embedder produces ${expected.dims}.`
739
- };
740
- }
741
- if (expected.source !== void 0 && expected.source !== header.source) {
742
- return {
743
- reason: "stale-source",
744
- detail: "Vector index was built from a different search index \u2014 the corpus changed. Re-run `manni graph embed`."
745
- };
746
- }
747
- return void 0;
748
- },
749
- search(query, options = {}) {
750
- if (dims === 0 || ids.length === 0) return [];
751
- if (query.length !== dims) {
752
- throw new VectorMismatchError({
753
- reason: "dims",
754
- detail: `Query vector has ${query.length} dimensions, but the index has ${dims}.`
755
- });
756
- }
757
- const limit = normalizeLimit(options.limit);
758
- if (limit === 0) return [];
759
- const minScore = options.minScore ?? 0;
760
- const q = normalize(Float32Array.from(query));
761
- const scored = [];
762
- for (const [row, iri] of ids.entries()) {
763
- const stored = vectors.subarray(row * dims, (row + 1) * dims);
764
- let score = 0;
765
- for (const [i, value] of q.entries()) score += value * (stored[i] ?? 0);
766
- if (score >= minScore) {
767
- scored.push({ iri, score, via: "vector" });
768
- }
524
+ var ENTITIES = {
525
+ amp: "&",
526
+ lt: "<",
527
+ gt: ">",
528
+ quot: '"',
529
+ apos: "'",
530
+ nbsp: "\xA0"
531
+ };
532
+ function decodeEntities(text) {
533
+ return text.replace(
534
+ /&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi,
535
+ (whole, name) => {
536
+ if (name.startsWith("#")) {
537
+ const hex = name[1] === "x" || name[1] === "X";
538
+ const code = Number.parseInt(name.slice(hex ? 2 : 1), hex ? 16 : 10);
539
+ return Number.isNaN(code) || code > 1114111 ? whole : String.fromCodePoint(code);
769
540
  }
770
- scored.sort(
771
- (a, b) => a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score
772
- );
773
- return scored.slice(0, limit);
541
+ return ENTITIES[name.toLowerCase()] ?? whole;
774
542
  }
775
- };
776
- }
777
- function normalizeLimit(limit) {
778
- return typeof limit === "number" && Number.isInteger(limit) && limit >= 0 ? limit : 10;
779
- }
780
-
781
- // src/graph/runtime/trace.ts
782
- function createTrace() {
783
- return { entry: [], hops: [], exclusions: [], resolutions: [] };
543
+ );
784
544
  }
785
- function reachedNodes(trace) {
786
- const reached = /* @__PURE__ */ new Set();
787
- for (const e of trace.entry) reached.add(e.iri);
788
- for (const h of trace.hops) reached.add(h.to);
789
- return reached;
545
+ function headingKey(text) {
546
+ return text.replace(/[`*_~\\[\]]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
790
547
  }
791
-
792
- // src/graph/runtime/entry.ts
793
- function rrfMerge(rankings, k = 60) {
794
- const fused = /* @__PURE__ */ new Map();
795
- for (const ranking of rankings) {
796
- ranking.forEach((candidate, i) => {
797
- const current = fused.get(candidate.iri) ?? {
798
- score: 0,
799
- vias: /* @__PURE__ */ new Set()
800
- };
801
- current.score += 1 / (k + i + 1);
802
- current.vias.add(candidate.via);
803
- fused.set(candidate.iri, current);
804
- });
805
- }
806
- return [...fused.entries()].map(([iri, { score, vias }]) => {
807
- const [only] = vias;
808
- return {
809
- iri,
810
- score,
811
- via: vias.size === 1 && only !== void 0 ? only : "hybrid"
812
- };
813
- }).sort(
814
- (a, b) => a.score === b.score ? byCodeUnit(a.iri, b.iri) : b.score - a.score
548
+ function stripInline(raw) {
549
+ return decodeEntities(
550
+ raw.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, "$1").replace(/!?\[([^\]]*)\]\[[^\]]*\]/g, "$1").replace(/<((?:https?|mailto):[^>\s]+)>/gi, "$1")
815
551
  );
816
552
  }
817
- async function findEntry(query, options) {
818
- const trace = options.trace ?? createTrace();
819
- const limit = typeof options.limit === "number" && Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : 10;
820
- const lexical = options.lexical.search(query, { limit });
821
- const embedder = options.embedder;
822
- const embed = embedder ? (q) => embedder.embed(q) : options.embedQuery;
823
- let vector = [];
824
- if (options.vectors && embed && query.trim() !== "") {
825
- const mismatch = options.vectors.check({
826
- ...options.embedder ? { model: options.embedder.model, dtype: options.embedder.dtype } : {},
827
- // Staleness is checked whichever way the query is embedded — it is a
828
- // property of the corpus, not of the embedder, so even the unverified
829
- // `embedQuery` path gets it when the caller supplies a digest.
830
- ...options.source === void 0 ? {} : { source: options.source }
831
- });
832
- if (mismatch) throw new VectorMismatchError(mismatch);
833
- const queryVector = await embed(query);
834
- vector = options.vectors.search(queryVector, { limit });
835
- }
836
- const rankings = vector.length > 0 ? [lexical, vector] : [lexical];
837
- const candidates = rrfMerge(rankings).slice(0, limit);
838
- for (const candidate of candidates) trace.entry.push(candidate);
839
- return { candidates, lexical, vector, trace };
840
- }
841
-
842
- // src/graph/runtime/lexical.ts
843
- import MiniSearch from "minisearch";
844
- function createLexicalIndex(input) {
845
- const doc = typeof input === "string" ? JSON.parse(input) : input;
846
- const entries = Array.isArray(doc?.entries) ? doc.entries : [];
847
- const mini = new MiniSearch({
848
- fields: ["title", "labels", "description", "text"],
849
- storeFields: ["id"],
850
- idField: "id",
851
- // Titles and labels are the strongest signal that a node *is* the subject;
852
- // body text is evidence it merely mentions it.
853
- searchOptions: {
854
- boost: { title: 3, labels: 2, description: 1.5 },
855
- prefix: true,
856
- fuzzy: 0.2
553
+ function documentSectionOrder(graph, docIri) {
554
+ const ordered = [];
555
+ const seen = /* @__PURE__ */ new Set();
556
+ const childrenOf = (iri) => graph.out(iri, DCTERMS_HAS_PART).map((e) => e.target).filter((target) => !graph.types(target).includes(GRAPH_BLOCK)).sort((a, b) => {
557
+ const oa = Number.parseInt(graph.literal(a, GRAPH_ORDER) ?? "", 10);
558
+ const ob = Number.parseInt(graph.literal(b, GRAPH_ORDER) ?? "", 10);
559
+ if (Number.isNaN(oa) || Number.isNaN(ob) || oa === ob) {
560
+ return a < b ? -1 : a > b ? 1 : 0;
857
561
  }
562
+ return oa - ob;
858
563
  });
859
- mini.addAll(entries);
860
- const byIri = new Map(entries.map((e) => [e.id, e]));
861
- return {
862
- size: () => entries.length,
863
- entry: (iri) => byIri.get(iri),
864
- search(query, options = {}) {
865
- const trimmed = query.trim();
866
- if (trimmed === "") return [];
867
- const hits = mini.search(trimmed);
868
- hits.sort(
869
- (a, b) => a.score === b.score ? byCodeUnit(String(a.id), String(b.id)) : b.score - a.score
870
- );
871
- return hits.slice(0, options.limit ?? 10).map((h) => ({ iri: String(h.id), score: h.score, via: "lexical" }));
564
+ const walk = (iri) => {
565
+ for (const child of childrenOf(iri)) {
566
+ if (seen.has(child)) continue;
567
+ seen.add(child);
568
+ ordered.push(child);
569
+ walk(child);
872
570
  }
873
571
  };
572
+ walk(docIri);
573
+ return ordered;
874
574
  }
875
-
876
- // src/graph/embed/local.ts
877
- var EmbedderUnavailableError = class extends Error {
878
- constructor(detail) {
879
- super(
880
- `Local embeddings need @huggingface/transformers, which is an optional peer dependency.
881
- Install it: npm install @huggingface/transformers
882
- (${detail})`
883
- );
884
- this.name = "EmbedderUnavailableError";
885
- }
886
- };
887
- async function loadTransformers(injected) {
888
- if (injected) return injected;
889
- try {
890
- return await import("@huggingface/transformers");
891
- } catch (e) {
892
- throw new EmbedderUnavailableError(
893
- errorMessage(e)
894
- );
575
+ function sectionOccurrences(graph, docIri) {
576
+ const occurrences = /* @__PURE__ */ new Map();
577
+ const counts = /* @__PURE__ */ new Map();
578
+ for (const section of documentSectionOrder(graph, docIri)) {
579
+ const rawTitle = graph.literal(section, DCTERMS_TITLE);
580
+ if (rawTitle === void 0) {
581
+ occurrences.set(section, 0);
582
+ continue;
583
+ }
584
+ const title = headingKey(rawTitle);
585
+ const level = graph.literal(section, GRAPH_LEVEL) ?? "";
586
+ let byLevel = counts.get(title);
587
+ if (!byLevel) {
588
+ byLevel = /* @__PURE__ */ new Map();
589
+ counts.set(title, byLevel);
590
+ }
591
+ const seen = byLevel.get(level) ?? 0;
592
+ occurrences.set(section, seen);
593
+ byLevel.set(level, seen + 1);
895
594
  }
595
+ return occurrences;
896
596
  }
897
- async function createLocalEmbedder(options = {}) {
898
- const model = options.model ?? DEFAULT_MODEL;
899
- const dtype = options.dtype ?? "q8";
900
- const role = options.role ?? "passage";
901
- const profile = profileFor(model);
902
- const transformers = await loadTransformers(options.transformers);
903
- if (transformers.env?.backends?.onnx?.wasm) {
904
- transformers.env.backends.onnx.wasm.numThreads = 1;
905
- }
906
- const extractor = await transformers.pipeline("feature-extraction", model, {
907
- // No `device`: its accepted values are disjoint across platforms, so any
908
- // hardcoded choice throws on one of them (ADR 01025).
909
- ...options.device === void 0 ? {} : { device: options.device },
910
- dtype
911
- });
912
- let dims = 0;
913
- return {
914
- model,
915
- dtype,
916
- get dims() {
917
- return dims;
918
- },
919
- async embed(text) {
920
- const output = await extractor(withPrefix(profile, role, text), {
921
- pooling: "mean",
922
- normalize: true
923
- });
924
- const data = Float32Array.from(output.data);
925
- dims = data.length;
926
- return data;
597
+ function sectionOccurrence(graph, sectionIri) {
598
+ const { doc } = splitFragment(sectionIri);
599
+ return sectionOccurrences(graph, doc).get(sectionIri) ?? 0;
600
+ }
601
+ function documentPreamble(markdown) {
602
+ const lines = markdown.split(/\r?\n/);
603
+ const end = sourceHeadings(lines)[0]?.start ?? lines.length;
604
+ const text = lines.slice(0, end).join("\n").trim();
605
+ return text === "" ? void 0 : text;
606
+ }
607
+ function sliceSection(markdown, title, level, occurrence = 0) {
608
+ return slice(markdown, title, level, occurrence, false);
609
+ }
610
+ function sectionOwnText(markdown, title, level, occurrence = 0) {
611
+ return slice(markdown, title, level, occurrence, true);
612
+ }
613
+ function sectionOwnLines(markdown, title, level, occurrence = 0) {
614
+ const span = locate(markdown.split(/\r?\n/), title, level, occurrence, true);
615
+ return span === void 0 ? void 0 : { start: span.start + 1, end: span.end };
616
+ }
617
+ function sectionLines(markdown, title, level, occurrence = 0) {
618
+ const text = sliceSection(markdown, title, level, occurrence);
619
+ if (text === void 0) return void 0;
620
+ const span = locate(markdown.split(/\r?\n/), title, level, occurrence, false);
621
+ if (span === void 0) return void 0;
622
+ return { start: span.start + 1, end: span.start + text.split("\n").length };
623
+ }
624
+ function slice(markdown, title, level, occurrence, ownTextOnly) {
625
+ const lines = markdown.split(/\r?\n/);
626
+ const span = locate(lines, title, level, occurrence, ownTextOnly);
627
+ if (span === void 0) return void 0;
628
+ return lines.slice(span.start, span.end).join("\n").trimEnd();
629
+ }
630
+ function locate(lines, title, level, occurrence, ownTextOnly) {
631
+ const headings = sourceHeadings(lines);
632
+ const wanted = headingKey(title);
633
+ let remaining = occurrence;
634
+ let found = -1;
635
+ for (const [n, heading] of headings.entries()) {
636
+ if (level !== void 0 && heading.level !== level) continue;
637
+ if (headingKey(stripInline(heading.text)) !== wanted) continue;
638
+ if (remaining > 0) {
639
+ remaining -= 1;
640
+ continue;
927
641
  }
928
- };
929
- }
930
-
931
- // src/graph/embed/mock.ts
932
- function fnv1a(text, seed) {
933
- let hash = (2166136261 ^ seed) >>> 0;
934
- for (let i = 0; i < text.length; i++) {
935
- hash = (hash ^ text.charCodeAt(i)) >>> 0;
936
- hash = hash + ((hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24)) >>> 0;
642
+ found = n;
643
+ break;
937
644
  }
938
- return hash >>> 0;
645
+ const match = headings[found];
646
+ if (match === void 0) return void 0;
647
+ const next = headings.slice(found + 1).find((h) => ownTextOnly || h.level <= match.level);
648
+ return { start: match.start, end: next?.start ?? lines.length };
939
649
  }
940
- function createMockEmbedder(options = {}) {
941
- const dims = options.dims ?? 8;
942
- const model = options.model ?? "mock";
943
- const dtype = options.dtype ?? "mock";
650
+ function createFetchResolver(graph, options = {}) {
651
+ const doFetch = options.fetch ?? ((url) => globalThis.fetch(url));
652
+ const toUrl = options.pathToUrl ?? ((path) => `${options.baseUrl ?? ""}${path}`);
653
+ const cache = /* @__PURE__ */ new Map();
654
+ const occurrenceCache = /* @__PURE__ */ new Map();
655
+ const occurrenceOf = (docIri, sectionIri) => {
656
+ let map = occurrenceCache.get(docIri);
657
+ if (!map) {
658
+ map = sectionOccurrences(graph, docIri);
659
+ occurrenceCache.set(docIri, map);
660
+ }
661
+ return map.get(sectionIri) ?? 0;
662
+ };
663
+ const fetchDoc = (url) => {
664
+ let pending = cache.get(url);
665
+ if (!pending) {
666
+ pending = doFetch(url).then((r) => r.ok ? r.text() : void 0).catch(() => void 0);
667
+ cache.set(url, pending);
668
+ }
669
+ return pending;
670
+ };
944
671
  return {
945
- model,
946
- dtype,
947
- dims,
948
- embed(text) {
949
- const vector = new Float32Array(dims);
950
- for (let i = 0; i < dims; i++) {
951
- vector[i] = fnv1a(text, i) / 4294967296 * 2 - 1;
672
+ async resolve(iri) {
673
+ const { doc, fragment } = splitFragment(iri);
674
+ const path = graph.literal(doc, GRAPH_PATH);
675
+ if (!path) return void 0;
676
+ const sourceUrl = toUrl(path);
677
+ const body = await fetchDoc(sourceUrl);
678
+ const title = graph.literal(iri, DCTERMS_TITLE);
679
+ if (body === void 0) {
680
+ options.trace?.resolutions.push({
681
+ iri,
682
+ sourceUrl,
683
+ ok: false,
684
+ error: "fetch failed"
685
+ });
686
+ return void 0;
952
687
  }
953
- return Promise.resolve(vector);
688
+ let text = body;
689
+ if (fragment) {
690
+ const levelText = graph.literal(iri, GRAPH_LEVEL);
691
+ const level = levelText ? Number.parseInt(levelText, 10) : void 0;
692
+ const slice2 = title === void 0 ? void 0 : sliceSection(
693
+ body,
694
+ title,
695
+ Number.isNaN(level) ? void 0 : level,
696
+ occurrenceOf(doc, iri)
697
+ );
698
+ if (slice2 === void 0) {
699
+ options.trace?.resolutions.push({
700
+ iri,
701
+ sourceUrl,
702
+ ok: false,
703
+ error: "section heading not found"
704
+ });
705
+ return void 0;
706
+ }
707
+ text = slice2;
708
+ }
709
+ options.trace?.resolutions.push({ iri, sourceUrl, ok: true });
710
+ return { iri, text, sourceUrl, title };
954
711
  }
955
712
  };
956
713
  }
957
714
 
958
- // src/graph/commands/search.ts
959
- var SEARCH_MODES = ["lexical", "hybrid", "vector"];
960
- function loadSearchIndex(indexPath) {
961
- const raw = readFileSync3(indexPath, "utf8");
962
- let parsed;
963
- try {
964
- parsed = JSON.parse(raw);
965
- } catch (e) {
966
- throw new GraphError(
967
- `Failed to parse ${indexPath}: ${errorMessage(e)} \u2014 re-run \`manni graph export search\`.`
968
- );
969
- }
970
- const entries = parsed?.entries;
971
- if (!Array.isArray(entries)) {
972
- throw new GraphError(
973
- `Not a manni graph search index: ${indexPath} \u2014 expected an \`entries\` array; re-run \`manni graph export search\`.`
974
- );
715
+ // src/graph/core/search-index.ts
716
+ var GRAPH_DOCUMENT = `${NS.graph}Document`;
717
+ var GRAPH_SECTION = `${NS.graph}Section`;
718
+ var SKOS_CONCEPT = `${NS.skos}Concept`;
719
+ var GRAPH_PATH2 = `${NS.graph}path`;
720
+ var GRAPH_LEVEL2 = `${NS.graph}level`;
721
+ var DCTERMS_TITLE2 = `${NS.dcterms}title`;
722
+ var DCTERMS_DESCRIPTION = `${NS.dcterms}description`;
723
+ var SKOS_PREF_LABEL = `${NS.skos}prefLabel`;
724
+ var SKOS_ALT_LABEL = `${NS.skos}altLabel`;
725
+ var DCTERMS_LANGUAGE = `${NS.dcterms}language`;
726
+ function joinLabels(values) {
727
+ const seen = /* @__PURE__ */ new Map();
728
+ for (const v of values) {
729
+ const key = v.trim().toLowerCase();
730
+ if (key && !seen.has(key)) seen.set(key, v.trim());
975
731
  }
976
- return {
977
- doc: parsed,
978
- // Same recipe `manni graph embed` uses, so the two digests are comparable.
979
- source: `sha256:${createHash("sha256").update(raw, "utf8").digest("hex")}`
980
- };
732
+ const out = [...seen.values()].sort(byCodeUnit);
733
+ return out.length > 0 ? out.join(" ") : void 0;
981
734
  }
982
- function resolveLocalization(indexDir, lang) {
983
- const manifestPath = join2(indexDir, LOCALIZATIONS_FILENAME);
984
- if (!existsSync2(manifestPath)) {
985
- throw new GraphError(
986
- `Localization manifest not found: ${manifestPath} \u2014 run \`manni graph export search\` first.`
987
- );
988
- }
989
- const manifest = parseLocalizations(readFileSync3(manifestPath, "utf8"));
990
- if (!manifest) {
991
- throw new GraphError(
992
- `Not a manni graph localization manifest: ${manifestPath} \u2014 re-run \`manni graph export search\`.`
993
- );
994
- }
995
- const available = manifest.languages.map((l) => l.language);
996
- if (lang !== void 0) {
997
- const wanted = canonicalLanguageTag(lang);
998
- const hit = manifest.languages.find(
999
- (l) => canonicalLanguageTag(l.language) === wanted
1000
- );
1001
- if (!hit) {
1002
- throw new GraphError(
1003
- `No index for language "${lang}" \u2014 this corpus has ${available.join(", ") || "none"}.`
1004
- );
1005
- }
1006
- return hit;
1007
- }
1008
- const only = manifest.languages[0];
1009
- if (!only) {
1010
- throw new GraphError(
1011
- `The localization manifest lists no languages: ${manifestPath} \u2014 re-run \`manni graph export search\`.`
1012
- );
1013
- }
1014
- if (manifest.languages.length > 1) {
1015
- throw new GraphError(
1016
- `This corpus has more than one localization (${available.join(", ")}) \u2014 pass --lang to choose one.`
1017
- );
1018
- }
1019
- return only;
735
+ var FRONTMATTER = /^---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?(?:---|\.\.\.)[ \t]*(?:\r?\n|$)(?:\r?\n)*/;
736
+ function stripFrontmatter(markdown) {
737
+ return markdown.replace(FRONTMATTER, "");
1020
738
  }
1021
- async function runSearch(opts) {
1022
- const cwd = opts.cwd ?? process.cwd();
1023
- const config = loadRunConfig(
1024
- {
1025
- ...opts.config === void 0 ? {} : { configPath: opts.config },
1026
- ...opts.noConfig === void 0 ? {} : { noConfig: opts.noConfig }
1027
- },
1028
- cwd
1029
- );
1030
- const graphPath = resolve(cwd, opts.graph ?? config.out);
1031
- const indexDir = opts.index ? resolve(cwd, opts.index) : dirname(graphPath);
1032
- const localization = resolveLocalization(indexDir, opts.lang);
1033
- const indexPath = join2(indexDir, localization.search.path);
1034
- if (!existsSync2(indexPath)) {
1035
- throw new GraphError(
1036
- `Search index not found: ${indexPath} \u2014 the manifest names it; re-run \`manni graph export search\`.`
1037
- );
739
+ function plainText(nodes) {
740
+ return nodes.map((n) => n.text.replace(/\r\n/g, "\n").trim()).filter((t) => t !== "");
741
+ }
742
+ function treeText(source, path) {
743
+ const format = formatOf(path);
744
+ if (format === "markdown" || format === "mdx") return void 0;
745
+ const minted = mintTreeSections(parseTree(source, path, format).sections);
746
+ const sections = /* @__PURE__ */ new Map();
747
+ for (const [n, section] of minted.sections.entries()) {
748
+ const own = plainText(minted.owned[n] ?? []);
749
+ sections.set(section.slug, [section.title, ...own].join("\n\n"));
1038
750
  }
1039
- const { doc, source } = loadSearchIndex(indexPath);
1040
- if (localization.search.digest !== source) {
1041
- throw new GraphError(
1042
- `Stale manifest: ${localization.search.path} does not match the digest recorded for "${localization.language}". Re-run \`manni graph export search\`.`
1043
- );
751
+ const lead = plainText(minted.unowned);
752
+ return { doc: lead.length > 0 ? lead.join("\n\n") : void 0, sections };
753
+ }
754
+ function entry(id, type, fields) {
755
+ const out = { id, type };
756
+ if (fields.title !== void 0) out.title = fields.title;
757
+ if (fields.labels !== void 0) out.labels = fields.labels;
758
+ if (fields.description !== void 0) out.description = fields.description;
759
+ if (fields.text !== void 0) out.text = fields.text;
760
+ return out;
761
+ }
762
+ function buildSearchIndex(graph, cwd, options = {}) {
763
+ const warnings = options.warnings ?? [];
764
+ const readDoc = options.readDoc ?? ((path) => {
765
+ const abs = resolve2(cwd, path);
766
+ return existsSync3(abs) ? readFileSync3(abs, "utf8") : void 0;
767
+ });
768
+ const entries = [];
769
+ const sourceOf = /* @__PURE__ */ new Map();
770
+ const treeTextOf = /* @__PURE__ */ new Map();
771
+ const allSections = graph.instancesOf(GRAPH_SECTION);
772
+ const sectionsOf = /* @__PURE__ */ new Map();
773
+ for (const section of allSections) {
774
+ const hash = section.indexOf("#");
775
+ if (hash < 0) continue;
776
+ const doc = section.slice(0, hash);
777
+ const siblings = sectionsOf.get(doc);
778
+ if (siblings) siblings.push(section);
779
+ else sectionsOf.set(doc, [section]);
1044
780
  }
1045
- const lexical = createLexicalIndex(doc);
1046
- const explicitVectors = opts.vectors !== void 0 && opts.vectors !== "" ? opts.vectors : void 0;
1047
- const wantsVector = opts.mode === "vector" || opts.mode === "hybrid" || explicitVectors !== void 0 && opts.mode !== "lexical";
1048
- const vectorsPath = explicitVectors ? resolve(cwd, explicitVectors) : localization.vectors ? resolve(indexDir, localization.vectors.path) : void 0;
1049
- let vectors;
1050
- if (opts.mode !== "lexical" && vectorsPath !== void 0 && existsSync2(vectorsPath)) {
1051
- try {
1052
- vectors = createVectorIndex(readFileSync3(vectorsPath));
1053
- } catch (e) {
1054
- if (e instanceof VectorIndexError) {
1055
- throw new GraphError(
1056
- `${e.message} (${vectorsPath}) \u2014 re-run \`manni graph embed\`, or use \`--mode lexical\`.`
1057
- );
1058
- }
1059
- throw e;
1060
- }
1061
- const stale = vectors.check({ source });
1062
- if (stale && wantsVector) throw new GraphError(stale.detail);
1063
- if (stale) {
1064
- warn(`${stale.detail} Falling back to lexical.`);
1065
- vectors = void 0;
781
+ for (const doc of graph.instancesOf(GRAPH_DOCUMENT)) {
782
+ const path = graph.literal(doc, GRAPH_PATH2);
783
+ const source = path === void 0 ? void 0 : readDoc(path);
784
+ sourceOf.set(doc, source);
785
+ if (path !== void 0 && source === void 0) {
786
+ warnings.push(
787
+ `Source not found for ${path} \u2014 indexed without body text.`
788
+ );
1066
789
  }
1067
- } else if (wantsVector) {
1068
- const named = vectorsPath ?? `no sidecar recorded for "${localization.language}"`;
1069
- throw new GraphError(
1070
- `Vector index not found: ${named} \u2014 run \`manni graph embed\` first, or use \`--mode lexical\`.`
790
+ const tree = source === void 0 || path === void 0 ? void 0 : treeText(source, path);
791
+ if (tree) treeTextOf.set(doc, tree);
792
+ const body = source === void 0 ? void 0 : stripFrontmatter(source).replace(/\r\n/g, "\n");
793
+ const text = tree ? tree.doc : body === void 0 ? void 0 : (sectionsOf.get(doc)?.length ?? 0) > 0 ? documentPreamble(body) : body;
794
+ entries.push(
795
+ entry(doc, compactIri(GRAPH_DOCUMENT), {
796
+ title: graph.literal(doc, DCTERMS_TITLE2),
797
+ description: graph.literal(doc, DCTERMS_DESCRIPTION),
798
+ text
799
+ })
1071
800
  );
1072
801
  }
1073
- let embedder;
1074
- if (vectors) {
1075
- const requireEmbedder = opts.mode === "vector" || opts.mode === "hybrid";
1076
- embedder = await resolveEmbedder(opts.embedder, vectors, requireEmbedder);
1077
- }
1078
- const entry2 = await findEntry(opts.query, {
1079
- lexical,
1080
- // Pass the embedder, not a bare function: findEntry then verifies it
1081
- // against the index itself rather than trusting the CLI to have done so.
1082
- ...embedder && vectors ? { vectors, embedder } : {},
1083
- limit: opts.limit
1084
- }).catch((e) => {
1085
- if (e instanceof VectorMismatchError) {
1086
- throw new GraphError(`${e.message} Re-run \`manni graph embed\`.`);
802
+ const occurrencesOf = /* @__PURE__ */ new Map();
803
+ for (const section of allSections) {
804
+ const hash = section.indexOf("#");
805
+ const doc = hash < 0 ? section : section.slice(0, hash);
806
+ const title = graph.literal(section, DCTERMS_TITLE2);
807
+ const source = sourceOf.get(doc);
808
+ const levelText = graph.literal(section, GRAPH_LEVEL2);
809
+ const parsed = levelText === void 0 ? NaN : Number.parseInt(levelText, 10);
810
+ const level = Number.isNaN(parsed) ? void 0 : parsed;
811
+ let occurrences = occurrencesOf.get(doc);
812
+ if (!occurrences) {
813
+ occurrences = sectionOccurrences(graph, doc);
814
+ occurrencesOf.set(doc, occurrences);
1087
815
  }
1088
- throw e;
1089
- });
1090
- const decorate = (c) => {
1091
- const found = lexical.entry(c.iri);
1092
- return {
1093
- iri: c.iri,
1094
- score: c.score,
1095
- via: c.via,
1096
- ...found?.type === void 0 ? {} : { type: found.type },
1097
- ...found?.title === void 0 ? {} : { title: found.title }
1098
- };
1099
- };
1100
- const mode = opts.mode ?? (embedder && vectors ? "hybrid" : "lexical");
1101
- const results = opts.mode === "vector" ? entry2.vector : entry2.candidates;
1102
- if (opts.mode === "vector") {
1103
- entry2.trace.entry.length = 0;
1104
- entry2.trace.entry.push(...entry2.vector);
816
+ const tree = treeTextOf.get(doc);
817
+ const text = tree ? tree.sections.get(section.slice(hash + 1)) : source !== void 0 && title !== void 0 ? sectionOwnText(source, title, level, occurrences.get(section) ?? 0) : void 0;
818
+ entries.push(entry(section, compactIri(GRAPH_SECTION), { title, text }));
1105
819
  }
1106
- return {
1107
- query: opts.query,
1108
- mode,
1109
- results: results.map(decorate),
1110
- lexical: entry2.lexical.map(decorate),
1111
- vector: entry2.vector.map(decorate),
1112
- trace: entry2.trace
1113
- };
820
+ for (const concept of graph.instancesOf(SKOS_CONCEPT)) {
821
+ const pref = graph.literals(concept, SKOS_PREF_LABEL);
822
+ const alt = graph.literals(concept, SKOS_ALT_LABEL);
823
+ entries.push(
824
+ entry(concept, compactIri(SKOS_CONCEPT), {
825
+ title: pref[0],
826
+ labels: joinLabels([...pref, ...alt])
827
+ })
828
+ );
829
+ }
830
+ entries.sort((a, b) => byCodeUnit(a.id, b.id));
831
+ return { version: 1, entries };
1114
832
  }
1115
- async function resolveEmbedder(override, vectors, required) {
1116
- const { model, dtype } = vectors;
1117
- try {
1118
- const embedder = override ?? (model === "mock" ? createMockEmbedder({ dtype }) : await createLocalEmbedder({ model, dtype, role: "query" }));
1119
- const mismatch = vectors.check({
1120
- model: embedder.model,
1121
- dtype: embedder.dtype,
1122
- // Defense in depth: a future model that changes output size without
1123
- // changing its id would otherwise only surface deep inside search().
1124
- ...embedder.dims > 0 ? { dims: embedder.dims } : {}
1125
- });
1126
- if (mismatch) throw new GraphError(mismatch.detail);
1127
- return embedder;
1128
- } catch (e) {
1129
- if (e instanceof GraphError) throw e;
1130
- if (e instanceof EmbedderUnavailableError) {
1131
- if (required) throw new GraphError(e.message);
833
+ function emitSearchIndex(doc) {
834
+ return `${JSON.stringify(doc, null, 2)}
835
+ `;
836
+ }
837
+ function partitionByLanguage(graph, index) {
838
+ const documentType = compactIri(GRAPH_DOCUMENT);
839
+ const sectionType = compactIri(GRAPH_SECTION);
840
+ const languageOf2 = (entry2) => {
841
+ if (entry2.type !== documentType && entry2.type !== sectionType) {
1132
842
  return void 0;
1133
843
  }
1134
- throw new GraphError(
1135
- `Failed to load embedding model ${model}: ${errorMessage(e)}`
1136
- );
844
+ const hash = entry2.id.indexOf("#");
845
+ const doc = hash === -1 ? entry2.id : entry2.id.slice(0, hash);
846
+ return languageOfDocument(graph, doc);
847
+ };
848
+ const out = /* @__PURE__ */ new Map();
849
+ const shared = [];
850
+ for (const entry2 of index.entries) {
851
+ const language = languageOf2(entry2);
852
+ if (language === void 0) {
853
+ shared.push(entry2);
854
+ continue;
855
+ }
856
+ const bucket = out.get(language);
857
+ if (bucket) bucket.entries.push(entry2);
858
+ else out.set(language, { version: 1, entries: [entry2] });
1137
859
  }
1138
- }
1139
- function renderSearch(report, format) {
1140
- if (format === "json") return JSON.stringify(report, null, 2);
1141
- const lines = [];
1142
- for (const r of report.results) {
1143
- const label = r.title ? ` \u2014 ${r.title}` : "";
1144
- const type = r.type ? ` [${r.type}]` : "";
1145
- lines.push(`${r.score.toFixed(4)} ${compactIri(r.iri)}${type}${label}`);
860
+ if (out.size === 0 && shared.length > 0) {
861
+ out.set(UNDETERMINED, { version: 1, entries: [] });
1146
862
  }
1147
- if (report.results.length === 0) {
1148
- lines.push("(no matches)");
863
+ for (const bucket of out.values()) {
864
+ bucket.entries.push(...shared);
865
+ bucket.entries.sort((a, b) => byCodeUnit(a.id, b.id));
1149
866
  }
1150
- lines.push("");
1151
- lines.push(
1152
- `${report.results.length} result${report.results.length === 1 ? "" : "s"} (${report.mode})`
1153
- );
1154
- return lines.join("\n");
867
+ return out;
1155
868
  }
1156
-
1157
- // src/graph/commands/questions.ts
1158
- import { createHash as createHash2 } from "node:crypto";
1159
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "node:fs";
1160
- import { join as join3, resolve as resolve3 } from "node:path";
1161
- import GithubSlugger from "github-slugger";
1162
-
1163
- // src/graph/core/search-index.ts
1164
- import { existsSync as existsSync3, readFileSync as readFileSync4 } from "node:fs";
1165
- import { resolve as resolve2 } from "node:path";
1166
-
1167
- // src/graph/runtime/resolve.ts
1168
- var GRAPH_PATH = `${NS.graph}path`;
1169
- var DCTERMS_TITLE = `${NS.dcterms}title`;
1170
- var DCTERMS_HAS_PART = `${NS.dcterms}hasPart`;
1171
- var GRAPH_LEVEL = `${NS.graph}level`;
1172
- var GRAPH_ORDER = `${NS.graph}order`;
1173
- function splitFragment(iri) {
1174
- const hash = iri.indexOf("#");
1175
- return hash < 0 ? { doc: iri } : { doc: iri.slice(0, hash), fragment: iri.slice(hash + 1) };
869
+ function languageOfDocument(graph, doc) {
870
+ const tag = graph.literal(doc, DCTERMS_LANGUAGE);
871
+ return tag === void 0 ? UNDETERMINED : canonicalLanguageTag(tag);
1176
872
  }
1177
- function fencedLines(lines) {
1178
- const mask = new Array(lines.length).fill(false);
1179
- let open;
1180
- for (const [i, line] of lines.entries()) {
1181
- const m = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
1182
- const delimiter = m?.[1];
1183
- const info = m?.[2];
1184
- const isFence = delimiter !== void 0 && info !== void 0;
1185
- if (open === void 0) {
1186
- if (isFence && !(delimiter.startsWith("`") && info.includes("`"))) {
1187
- open = delimiter;
1188
- mask[i] = true;
1189
- }
1190
- continue;
1191
- }
1192
- mask[i] = true;
1193
- if (isFence && delimiter[0] === open[0] && delimiter.length >= open.length && info.trim() === "") {
1194
- open = void 0;
1195
- }
873
+ function documentsByLanguage(graph) {
874
+ const out = /* @__PURE__ */ new Map();
875
+ for (const doc of graph.instancesOf(GRAPH_DOCUMENT)) {
876
+ const language = languageOfDocument(graph, doc);
877
+ out.set(language, (out.get(language) ?? 0) + 1);
1196
878
  }
1197
- return mask;
1198
- }
1199
- var ATX = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*$/;
1200
- var SETEXT_UNDERLINE = /^ {0,3}(=+|-+)[ \t]*$/;
1201
- function isParagraphLine(line) {
1202
- if (line.trim() === "") return false;
1203
- if (ATX.test(line)) return false;
1204
- if (/^ {0,3}([-+*]|\d{1,9}[.)])([ \t]|$)/.test(line)) return false;
1205
- if (/^ {0,3}>/.test(line)) return false;
1206
- if (/^ {0,3}([-*_])([ \t]*\1){2,}[ \t]*$/.test(line)) return false;
1207
- return !/^ {4}/.test(line);
879
+ return out;
1208
880
  }
1209
- function frontmatterLength(lines) {
1210
- if (lines[0]?.trim() !== "---") return 0;
1211
- for (let i = 1; i < lines.length; i++) {
1212
- const line = lines[i]?.trim();
1213
- if (line === "---" || line === "...") return i + 1;
881
+
882
+ // src/graph/commands/questions.ts
883
+ var DOCUMENT = `${NS.graph}Document`;
884
+ var SECTION = `${NS.graph}Section`;
885
+ var PATH = `${NS.graph}path`;
886
+ var LEVEL = `${NS.graph}level`;
887
+ var TITLE = `${NS.dcterms}title`;
888
+ var LANGUAGE = `${NS.dcterms}language`;
889
+ var SAMPLE_QUESTION = `${NS.graph}sampleQuestion`;
890
+ var DOCUMENT_TYPE = compactIri(DOCUMENT);
891
+ var SECTION_TYPE = compactIri(SECTION);
892
+ function readManifest(indexDir) {
893
+ const path = join2(indexDir, LOCALIZATIONS_FILENAME);
894
+ if (!existsSync4(path)) return [];
895
+ const manifest = parseLocalizations(readFileSync4(path, "utf8"));
896
+ if (!manifest) {
897
+ throw new GraphError(
898
+ `Not a manni graph localization manifest: ${path} \u2014 re-run \`manni graph export search\`.`
899
+ );
1214
900
  }
1215
- return 0;
901
+ return manifest.languages;
1216
902
  }
1217
- function sourceHeadings(lines) {
1218
- const fenced = fencedLines(lines);
1219
- const skip = frontmatterLength(lines);
1220
- const headings = [];
1221
- let paragraph = -1;
1222
- for (const [i, line] of lines.entries()) {
1223
- if (i < skip || fenced[i]) {
1224
- paragraph = -1;
1225
- continue;
1226
- }
1227
- const atx = ATX.exec(line);
1228
- const hashes = atx?.[1];
1229
- if (hashes !== void 0) {
1230
- const text = (atx?.[2] ?? "").replace(/(^|[ \t]+)#+$/, "");
1231
- headings.push({ start: i, level: hashes.length, text });
1232
- paragraph = -1;
1233
- continue;
1234
- }
1235
- const underline = SETEXT_UNDERLINE.exec(line)?.[1];
1236
- if (underline !== void 0 && paragraph >= 0) {
1237
- headings.push({
1238
- start: paragraph,
1239
- level: underline.startsWith("=") ? 1 : 2,
1240
- text: lines.slice(paragraph, i).join("\n")
1241
- });
1242
- paragraph = -1;
1243
- continue;
1244
- }
1245
- if (isParagraphLine(line)) {
1246
- if (paragraph < 0) paragraph = i;
1247
- } else {
1248
- paragraph = -1;
903
+ async function openRetriever(doc, entry2, indexDir) {
904
+ const lexical = createLexicalIndex(doc);
905
+ if (!entry2?.vectors) return { lexical };
906
+ const path = resolve3(indexDir, entry2.vectors.path);
907
+ if (!existsSync4(path)) return { lexical };
908
+ let vectors;
909
+ try {
910
+ vectors = createVectorIndex(readFileSync4(path));
911
+ } catch (e) {
912
+ if (e instanceof VectorIndexError) {
913
+ throw new GraphError(`${e.message} (${path}) \u2014 re-run \`manni graph embed\`.`);
1249
914
  }
915
+ throw e;
1250
916
  }
1251
- return headings;
917
+ const source = `sha256:${createHash2("sha256").update(emitSearchIndex(doc), "utf8").digest("hex")}`;
918
+ const stale = vectors.check({ source });
919
+ if (stale) {
920
+ warn(`${stale.detail} Falling back to lexical.`);
921
+ return { lexical };
922
+ }
923
+ const embedder = await resolveEmbedder(void 0, vectors, false);
924
+ return embedder ? { lexical, vectors, embedder } : { lexical };
1252
925
  }
1253
- var ENTITIES = {
1254
- amp: "&",
1255
- lt: "<",
1256
- gt: ">",
1257
- quot: '"',
1258
- apos: "'",
1259
- nbsp: "\xA0"
1260
- };
1261
- function decodeEntities(text) {
1262
- return text.replace(
1263
- /&(#x[0-9a-f]+|#[0-9]+|[a-z]+);/gi,
1264
- (whole, name) => {
1265
- if (name.startsWith("#")) {
1266
- const hex = name[1] === "x" || name[1] === "X";
1267
- const code = Number.parseInt(name.slice(hex ? 2 : 1), hex ? 16 : 10);
1268
- return Number.isNaN(code) || code > 1114111 ? whole : String.fromCodePoint(code);
1269
- }
1270
- return ENTITIES[name.toLowerCase()] ?? whole;
926
+ async function rankNodes(question, r) {
927
+ const entry2 = await findEntry(question, {
928
+ lexical: r.lexical,
929
+ ...r.vectors && r.embedder ? { vectors: r.vectors, embedder: r.embedder } : {},
930
+ limit: r.lexical.size()
931
+ }).catch((e) => {
932
+ if (e instanceof VectorMismatchError) {
933
+ throw new GraphError(`${e.message} Re-run \`manni graph embed\`.`);
1271
934
  }
1272
- );
1273
- }
1274
- function headingKey(text) {
1275
- return text.replace(/[`*_~\\[\]]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
935
+ throw e;
936
+ });
937
+ return entry2.candidates.flatMap((c) => {
938
+ const type = r.lexical.entry(c.iri)?.type;
939
+ return type === DOCUMENT_TYPE || type === SECTION_TYPE ? [c.iri] : [];
940
+ });
1276
941
  }
1277
- function stripInline(raw) {
1278
- return decodeEntities(
1279
- raw.replace(/!?\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/g, "$1").replace(/!?\[([^\]]*)\]\[[^\]]*\]/g, "$1").replace(/<((?:https?|mailto):[^>\s]+)>/gi, "$1")
1280
- );
942
+ function pageOf(iri) {
943
+ const hash = iri.indexOf("#");
944
+ return hash < 0 ? iri : iri.slice(0, hash);
1281
945
  }
1282
- function documentSectionOrder(graph, docIri) {
1283
- const ordered = [];
1284
- const seen = /* @__PURE__ */ new Set();
1285
- const childrenOf = (iri) => graph.out(iri, DCTERMS_HAS_PART).map((e) => e.target).sort((a, b) => {
1286
- const oa = Number.parseInt(graph.literal(a, GRAPH_ORDER) ?? "", 10);
1287
- const ob = Number.parseInt(graph.literal(b, GRAPH_ORDER) ?? "", 10);
1288
- if (Number.isNaN(oa) || Number.isNaN(ob) || oa === ob) {
1289
- return a < b ? -1 : a > b ? 1 : 0;
1290
- }
1291
- return oa - ob;
1292
- });
1293
- const walk = (iri) => {
1294
- for (const child of childrenOf(iri)) {
1295
- if (seen.has(child)) continue;
1296
- seen.add(child);
1297
- ordered.push(child);
1298
- walk(child);
1299
- }
1300
- };
1301
- walk(docIri);
1302
- return ordered;
946
+ function lastLine(position) {
947
+ const { start, end } = position;
948
+ return end.column <= 1 && end.line > start.line ? end.line - 1 : end.line;
1303
949
  }
1304
- function sectionOccurrences(graph, docIri) {
1305
- const occurrences = /* @__PURE__ */ new Map();
1306
- const counts = /* @__PURE__ */ new Map();
1307
- for (const section of documentSectionOrder(graph, docIri)) {
1308
- const rawTitle = graph.literal(section, DCTERMS_TITLE);
1309
- if (rawTitle === void 0) {
1310
- occurrences.set(section, 0);
1311
- continue;
1312
- }
1313
- const title = headingKey(rawTitle);
1314
- const level = graph.literal(section, GRAPH_LEVEL) ?? "";
1315
- let byLevel = counts.get(title);
1316
- if (!byLevel) {
1317
- byLevel = /* @__PURE__ */ new Map();
1318
- counts.set(title, byLevel);
950
+ function sectionSpans(graph, doc, path, content, sections) {
951
+ const format = formatOf(path);
952
+ const out = [];
953
+ if (isTreeFormat(format)) {
954
+ const known = new Set(sections);
955
+ const minted = mintTreeSections(parseTree(content, path, format).sections);
956
+ for (const [n, section] of minted.sections.entries()) {
957
+ const iri = `${doc}#${section.slug}`;
958
+ const node = minted.nodes[n];
959
+ if (!known.has(iri) || node === void 0) continue;
960
+ const head = node.titlePosition ?? node.position;
961
+ const end = Math.max(
962
+ lastLine(head),
963
+ ...(minted.owned[n] ?? []).map((c) => lastLine(c.position))
964
+ );
965
+ out.push({ iri, span: { start: head.start.line, end } });
1319
966
  }
1320
- const seen = byLevel.get(level) ?? 0;
1321
- occurrences.set(section, seen);
1322
- byLevel.set(level, seen + 1);
967
+ return out;
1323
968
  }
1324
- return occurrences;
1325
- }
1326
- function sectionOccurrence(graph, sectionIri) {
1327
- const { doc } = splitFragment(sectionIri);
1328
- return sectionOccurrences(graph, doc).get(sectionIri) ?? 0;
1329
- }
1330
- function documentPreamble(markdown) {
1331
- const lines = markdown.split(/\r?\n/);
1332
- const end = sourceHeadings(lines)[0]?.start ?? lines.length;
1333
- const text = lines.slice(0, end).join("\n").trim();
1334
- return text === "" ? void 0 : text;
1335
- }
1336
- function sliceSection(markdown, title, level, occurrence = 0) {
1337
- return slice(markdown, title, level, occurrence, false);
969
+ const occurrences = sectionOccurrences(graph, doc);
970
+ for (const iri of sections) {
971
+ const title = graph.literal(iri, TITLE);
972
+ if (title === void 0) continue;
973
+ const level = Number.parseInt(graph.literal(iri, LEVEL) ?? "", 10);
974
+ const span = sectionOwnLines(
975
+ content,
976
+ title,
977
+ Number.isNaN(level) ? void 0 : level,
978
+ occurrences.get(iri) ?? 0
979
+ );
980
+ if (span) out.push({ iri, span });
981
+ }
982
+ return out;
1338
983
  }
1339
- function sectionOwnText(markdown, title, level, occurrence = 0) {
1340
- return slice(markdown, title, level, occurrence, true);
984
+ function bodyOf(content, format) {
985
+ const bodyLine = format === "html" || format === "xml" ? 1 : bodyLineOf(content, locateFrontmatter(content)?.closeEnd ?? 0);
986
+ return { bodyLine, body: splitLines(content).slice(bodyLine - 1) };
1341
987
  }
1342
- function sectionOwnLines(markdown, title, level, occurrence = 0) {
1343
- const span = locate(markdown.split(/\r?\n/), title, level, occurrence, true);
1344
- return span === void 0 ? void 0 : { start: span.start + 1, end: span.end };
988
+ function freshness(body, pin) {
989
+ const { lines, integrity } = pin;
990
+ if (integrity === void 0) {
991
+ return lines.end <= body.length ? { state: "current", ranges: [lines] } : { state: "changed" };
992
+ }
993
+ if (pinOfLines(body, lines) === integrity) return { state: "current", ranges: [lines] };
994
+ const length = lines.end - lines.start + 1;
995
+ const { starts } = findWindows(body, length, integrity, void 0, { around: lines.start });
996
+ const ranges = starts.map((start) => ({ start, end: start + length - 1 }));
997
+ if (ranges.length === 0) return { state: "changed" };
998
+ return { state: ranges.length === 1 ? "moved" : "ambiguous", ranges };
1345
999
  }
1346
- function slice(markdown, title, level, occurrence, ownTextOnly) {
1347
- const lines = markdown.split(/\r?\n/);
1348
- const span = locate(lines, title, level, occurrence, ownTextOnly);
1349
- if (span === void 0) return void 0;
1350
- return lines.slice(span.start, span.end).join("\n").trimEnd();
1000
+ function matchList(ranges) {
1001
+ const spelled = ranges.map(spellLines);
1002
+ const head = spelled.slice(0, -1);
1003
+ const last = spelled[spelled.length - 1] ?? "";
1004
+ if (head.length === 0) return `lines ${last} match`;
1005
+ const both = head.length === 1 ? "both" : "all";
1006
+ return `lines ${head.join(", ")} and ${last} ${both} match`;
1351
1007
  }
1352
- function locate(lines, title, level, occurrence, ownTextOnly) {
1353
- const headings = sourceHeadings(lines);
1354
- const wanted = headingKey(title);
1355
- let remaining = occurrence;
1356
- let found = -1;
1357
- for (const [n, heading] of headings.entries()) {
1358
- if (level !== void 0 && heading.level !== level) continue;
1359
- if (headingKey(stripInline(heading.text)) !== wanted) continue;
1360
- if (remaining > 0) {
1361
- remaining -= 1;
1008
+ async function readPages(graph, sources, view, verb) {
1009
+ const contents = /* @__PURE__ */ new Map();
1010
+ const onDisk = [];
1011
+ const byAbs = /* @__PURE__ */ new Map();
1012
+ let missing = 0;
1013
+ for (const doc of graph.instancesOf(DOCUMENT)) {
1014
+ const path = graph.literal(doc, PATH);
1015
+ if (path === void 0 || path === STDIN_PATH) continue;
1016
+ const abs = resolve3(sources, path);
1017
+ if (!existsSync4(abs)) {
1018
+ missing += 1;
1362
1019
  continue;
1363
1020
  }
1364
- found = n;
1365
- break;
1021
+ contents.set(path, readFileSync4(abs, "utf8"));
1022
+ onDisk.push({ doc, path });
1023
+ byAbs.set(abs, { doc, path });
1366
1024
  }
1367
- const match = headings[found];
1368
- if (match === void 0) return void 0;
1369
- const next = headings.slice(found + 1).find((h) => ownTextOnly || h.level <= match.level);
1370
- return { start: match.start, end: next?.start ?? lines.length };
1371
- }
1372
- function createFetchResolver(graph, options = {}) {
1373
- const doFetch = options.fetch ?? ((url) => globalThis.fetch(url));
1374
- const toUrl = options.pathToUrl ?? ((path) => `${options.baseUrl ?? ""}${path}`);
1375
- const cache = /* @__PURE__ */ new Map();
1376
- const occurrenceCache = /* @__PURE__ */ new Map();
1377
- const occurrenceOf = (docIri, sectionIri) => {
1378
- let map = occurrenceCache.get(docIri);
1379
- if (!map) {
1380
- map = sectionOccurrences(graph, docIri);
1381
- occurrenceCache.set(docIri, map);
1382
- }
1383
- return map.get(sectionIri) ?? 0;
1384
- };
1385
- const fetchDoc = (url) => {
1386
- let pending = cache.get(url);
1387
- if (!pending) {
1388
- pending = doFetch(url).then((r) => r.ok ? r.text() : void 0).catch(() => void 0);
1389
- cache.set(url, pending);
1390
- }
1391
- return pending;
1025
+ if (missing > 0) {
1026
+ warn(
1027
+ missing === 1 ? `1 page in the graph is not on disk, so its questions were not ${verb}; run manni graph build.` : `${String(missing)} pages in the graph are not on disk, so their questions were not ${verb}; run manni graph build.`
1028
+ );
1029
+ }
1030
+ const sectionsOf = /* @__PURE__ */ new Map();
1031
+ for (const section of graph.instancesOf(SECTION)) {
1032
+ const doc = pageOf(section);
1033
+ const siblings = sectionsOf.get(doc);
1034
+ if (siblings) siblings.push(section);
1035
+ else sectionsOf.set(doc, [section]);
1036
+ }
1037
+ const records = /* @__PURE__ */ new Map();
1038
+ const record = (doc, path, questions) => {
1039
+ const known = records.get(doc);
1040
+ if (known) return known;
1041
+ const content = contents.get(path) ?? "";
1042
+ const { bodyLine, body } = bodyOf(content, formatOf(path));
1043
+ const tag = graph.literal(doc, LANGUAGE);
1044
+ const page = {
1045
+ doc,
1046
+ path,
1047
+ language: tag === void 0 ? UNDETERMINED : canonicalLanguageTag(tag),
1048
+ bodyLine,
1049
+ body,
1050
+ sections: sectionSpans(graph, doc, path, content, sectionsOf.get(doc) ?? []),
1051
+ questions
1052
+ };
1053
+ records.set(doc, page);
1054
+ return page;
1392
1055
  };
1056
+ const meta = await openMetaView(view.source, view.cwd, onDisk.map((p) => p.path), sources);
1057
+ const pages = [];
1058
+ for (const { doc, path } of onDisk) {
1059
+ const content = contents.get(path) ?? "";
1060
+ const format = formatOf(path);
1061
+ const own = metadataOf(content, path, format);
1062
+ const { data } = await mergePage(meta, path, own.data, own.present, format);
1063
+ const questions = readSampleQuestions(data["sample-questions"]);
1064
+ if (questions.length > 0) pages.push(record(doc, path, questions));
1065
+ }
1066
+ pages.sort((a, b) => byCodeUnit(a.path, b.path));
1393
1067
  return {
1394
- async resolve(iri) {
1395
- const { doc, fragment } = splitFragment(iri);
1396
- const path = graph.literal(doc, GRAPH_PATH);
1397
- if (!path) return void 0;
1398
- const sourceUrl = toUrl(path);
1399
- const body = await fetchDoc(sourceUrl);
1400
- const title = graph.literal(iri, DCTERMS_TITLE);
1401
- if (body === void 0) {
1402
- options.trace?.resolutions.push({
1403
- iri,
1404
- sourceUrl,
1405
- ok: false,
1406
- error: "fetch failed"
1407
- });
1408
- return void 0;
1409
- }
1410
- let text = body;
1411
- if (fragment) {
1412
- const levelText = graph.literal(iri, GRAPH_LEVEL);
1413
- const level = levelText ? Number.parseInt(levelText, 10) : void 0;
1414
- const slice2 = title === void 0 ? void 0 : sliceSection(
1415
- body,
1416
- title,
1417
- Number.isNaN(level) ? void 0 : level,
1418
- occurrenceOf(doc, iri)
1419
- );
1420
- if (slice2 === void 0) {
1421
- options.trace?.resolutions.push({
1422
- iri,
1423
- sourceUrl,
1424
- ok: false,
1425
- error: "section heading not found"
1426
- });
1427
- return void 0;
1428
- }
1429
- text = slice2;
1430
- }
1431
- options.trace?.resolutions.push({ iri, sourceUrl, ok: true });
1432
- return { iri, text, sourceUrl, title };
1068
+ pages,
1069
+ contents,
1070
+ pageAt: (abs) => {
1071
+ const hit = byAbs.get(abs);
1072
+ return hit && record(hit.doc, hit.path, []);
1433
1073
  }
1434
1074
  };
1435
1075
  }
1436
-
1437
- // src/graph/core/search-index.ts
1438
- var GRAPH_DOCUMENT = `${NS.graph}Document`;
1439
- var GRAPH_SECTION = `${NS.graph}Section`;
1440
- var SKOS_CONCEPT = `${NS.skos}Concept`;
1441
- var GRAPH_PATH2 = `${NS.graph}path`;
1442
- var GRAPH_LEVEL2 = `${NS.graph}level`;
1443
- var DCTERMS_TITLE2 = `${NS.dcterms}title`;
1444
- var DCTERMS_DESCRIPTION = `${NS.dcterms}description`;
1445
- var SKOS_PREF_LABEL = `${NS.skos}prefLabel`;
1446
- var SKOS_ALT_LABEL = `${NS.skos}altLabel`;
1447
- var DCTERMS_LANGUAGE = `${NS.dcterms}language`;
1448
- function joinLabels(values) {
1449
- const seen = /* @__PURE__ */ new Map();
1450
- for (const v of values) {
1451
- const key = v.trim().toLowerCase();
1452
- if (key && !seen.has(key)) seen.set(key, v.trim());
1076
+ function holdersOf(page, lines) {
1077
+ const out = page.sections.filter(({ span }) => span.start <= lines.end && lines.start <= span.end).map(({ iri }) => iri);
1078
+ for (let line = lines.start; line <= lines.end; line++) {
1079
+ if (!page.sections.some(({ span }) => span.start <= line && line <= span.end)) {
1080
+ return [page.doc, ...out];
1081
+ }
1453
1082
  }
1454
- const out = [...seen.values()].sort(byCodeUnit);
1455
- return out.length > 0 ? out.join(" ") : void 0;
1083
+ return out;
1456
1084
  }
1457
- var FRONTMATTER = /^---[ \t]*\r?\n(?:[\s\S]*?\r?\n)?(?:---|\.\.\.)[ \t]*(?:\r?\n|$)(?:\r?\n)*/;
1458
- function stripFrontmatter(markdown) {
1459
- return markdown.replace(FRONTMATTER, "");
1085
+ function percent(part, of) {
1086
+ return of === 0 ? 0 : Math.floor(part / of * 100);
1460
1087
  }
1461
- function plainText(nodes) {
1462
- return nodes.map((n) => n.text.replace(/\r\n/g, "\n").trim()).filter((t) => t !== "");
1088
+ function plural(n, word) {
1089
+ return `${String(n)} ${word}${n === 1 ? "" : "s"}`;
1463
1090
  }
1464
- function treeText(source, path) {
1465
- const format = formatOf(path);
1466
- if (format === "markdown" || format === "mdx") return void 0;
1467
- const minted = mintTreeSections(parseTree(source, path, format).sections);
1468
- const sections = /* @__PURE__ */ new Map();
1469
- for (const [n, section] of minted.sections.entries()) {
1470
- const own = plainText(minted.owned[n] ?? []);
1471
- sections.set(section.slug, [section.title, ...own].join("\n\n"));
1472
- }
1473
- const lead = plainText(minted.unowned);
1474
- return { doc: lead.length > 0 ? lead.join("\n\n") : void 0, sections };
1091
+ function listOf(items) {
1092
+ const head = items.slice(0, -1);
1093
+ const last = items[items.length - 1] ?? "";
1094
+ return head.length === 0 ? last : `${head.join(", ")} and ${last}`;
1475
1095
  }
1476
- function entry(id, type, fields) {
1477
- const out = { id, type };
1478
- if (fields.title !== void 0) out.title = fields.title;
1479
- if (fields.labels !== void 0) out.labels = fields.labels;
1480
- if (fields.description !== void 0) out.description = fields.description;
1481
- if (fields.text !== void 0) out.text = fields.text;
1482
- return out;
1096
+ function renderQuestionSummary(s) {
1097
+ const homes = [
1098
+ ...s.pages > 0 ? [`on ${plural(s.pages, "page")}`] : [],
1099
+ ...s.files.length > 0 ? [`in ${listOf(s.files)}`] : []
1100
+ ];
1101
+ const { reviewed, drafted } = s.found;
1102
+ const a = s.answers;
1103
+ return [
1104
+ `questions ${String(s.total)}: ${String(s.reviewed)} reviewed, ${String(s.drafted)} drafted${homes.length > 0 ? `, ${homes.join(" and ")}` : ""}`,
1105
+ ` found ${String(reviewed.inTop)} of ${String(reviewed.of)} reviewed in the top ${String(s.top)} (${String(percent(reviewed.inTop, reviewed.of))}%), ${String(reviewed.first)} first (${String(percent(reviewed.first, reviewed.of))}%)`,
1106
+ ...s.cited === void 0 ? [] : [
1107
+ ` cited ${String(s.cited)} of ${String(reviewed.of)} reviewed by graph retrieve (${String(percent(s.cited, reviewed.of))}%)${s.withheld ? `, ${String(s.withheld)} withheld` : ""}`
1108
+ ],
1109
+ ...drafted.of > 0 ? [` drafted ${String(drafted.inTop)} of ${String(drafted.of)} in the top ${String(s.top)}, not counted until reviewed`] : [],
1110
+ ` answers ${String(a.pinned)} pinned, ${String(a.unreviewed)} not reviewed: ${String(a.current)} current, ${String(a.moved)} moved, ${String(a.changed)} changed; ${String(a.unpinned)} not pinned`,
1111
+ ...s.gaps > 0 ? [` gaps ${plural(s.gaps, "question")} the docs don't answer`] : []
1112
+ ];
1483
1113
  }
1484
- function buildSearchIndex(graph, cwd, options = {}) {
1485
- const warnings = options.warnings ?? [];
1486
- const readDoc = options.readDoc ?? ((path) => {
1487
- const abs = resolve2(cwd, path);
1488
- return existsSync3(abs) ? readFileSync4(abs, "utf8") : void 0;
1489
- });
1490
- const entries = [];
1491
- const sourceOf = /* @__PURE__ */ new Map();
1492
- const treeTextOf = /* @__PURE__ */ new Map();
1493
- const allSections = graph.instancesOf(GRAPH_SECTION);
1494
- const sectionsOf = /* @__PURE__ */ new Map();
1495
- for (const section of allSections) {
1496
- const hash = section.indexOf("#");
1497
- if (hash < 0) continue;
1498
- const doc = section.slice(0, hash);
1499
- const siblings = sectionsOf.get(doc);
1500
- if (siblings) siblings.push(section);
1501
- else sectionsOf.set(doc, [section]);
1502
- }
1503
- for (const doc of graph.instancesOf(GRAPH_DOCUMENT)) {
1504
- const path = graph.literal(doc, GRAPH_PATH2);
1505
- const source = path === void 0 ? void 0 : readDoc(path);
1506
- sourceOf.set(doc, source);
1507
- if (path !== void 0 && source === void 0) {
1508
- warnings.push(
1509
- `Source not found for ${path} \u2014 indexed without body text.`
1114
+ async function askSampleQuestions(store, settings, sources, indexDir, view, questionFiles, configDir, cite) {
1115
+ const knob = settings.severity;
1116
+ const top = settings.top;
1117
+ const sets = questionFiles.map((label) => ({
1118
+ label,
1119
+ questions: readQuestionFile(resolve3(configDir, label), label)
1120
+ }));
1121
+ const graph = GraphIndex.fromQuads(storeToQuads(store), Object.fromEntries(PREFIXES));
1122
+ const { pages, contents, pageAt } = await readPages(graph, sources, view, "checked");
1123
+ const total = pages.reduce((n, p) => n + p.questions.length, 0) + sets.reduce((n, f) => n + f.questions.length, 0);
1124
+ if (total === 0) return { findings: [] };
1125
+ let byLanguage;
1126
+ let manifest = [];
1127
+ const retrievers = /* @__PURE__ */ new Map();
1128
+ const ranked = /* @__PURE__ */ new Map();
1129
+ const rank = async (language, question) => {
1130
+ const key = JSON.stringify([language, question]);
1131
+ const cached = ranked.get(key);
1132
+ if (cached) return cached;
1133
+ if (byLanguage === void 0) {
1134
+ byLanguage = partitionByLanguage(
1135
+ graph,
1136
+ buildSearchIndex(graph, sources, { readDoc: (p) => contents.get(p) })
1137
+ );
1138
+ manifest = readManifest(indexDir);
1139
+ }
1140
+ let retriever = retrievers.get(language);
1141
+ if (!retriever) {
1142
+ retriever = await openRetriever(
1143
+ byLanguage.get(language) ?? { version: 1, entries: [] },
1144
+ manifest.find((l) => canonicalLanguageTag(l.language) === language),
1145
+ indexDir
1146
+ );
1147
+ retrievers.set(language, retriever);
1148
+ }
1149
+ const nodes = await rankNodes(question, retriever);
1150
+ ranked.set(key, nodes);
1151
+ return nodes;
1152
+ };
1153
+ const describe = (iri) => {
1154
+ const path = graph.literal(pageOf(iri), PATH) ?? pageOf(iri);
1155
+ const title = iri.includes("#") ? graph.literal(iri, TITLE) : void 0;
1156
+ return title === void 0 ? path : `${path} \xA7 ${title}`;
1157
+ };
1158
+ const where = (position, first) => [
1159
+ position === 0 ? "it is not found" : `it ranks ${String(position)}`,
1160
+ ...first === void 0 ? [] : [`first is ${describe(first)}`]
1161
+ ].join("; ");
1162
+ const findings = [];
1163
+ const reporter = (target) => (kind, message, draft) => {
1164
+ const level = kind === "knob" ? knob : kind;
1165
+ if (level === "off") return;
1166
+ const suffix = draft === "question" ? " (drafted, not reviewed)" : draft === "pin" ? " (answer not reviewed)" : "";
1167
+ findings.push({
1168
+ severity: draft ? "notice" : level,
1169
+ message: `${message}${suffix}`,
1170
+ focusNode: target.focusNode,
1171
+ ...target.path === void 0 ? {} : { path: target.path },
1172
+ docs: target.docs,
1173
+ // A retrieval check judges a question, not a shape.
1174
+ guidance: null
1175
+ });
1176
+ };
1177
+ const empty = () => ({ inTop: 0, first: 0, of: 0 });
1178
+ const summary = {
1179
+ total,
1180
+ reviewed: 0,
1181
+ drafted: 0,
1182
+ pages: pages.length,
1183
+ files: [...questionFiles],
1184
+ top,
1185
+ found: { reviewed: empty(), drafted: empty() },
1186
+ answers: { pinned: 0, unreviewed: 0, current: 0, moved: 0, changed: 0, unpinned: 0 },
1187
+ gaps: 0
1188
+ };
1189
+ const tally = (reviewed, tests) => {
1190
+ if (tests.length === 0) return;
1191
+ const count = reviewed ? summary.found.reviewed : summary.found.drafted;
1192
+ count.of += 1;
1193
+ if (tests.every((p) => p >= 1 && p <= top)) count.inTop += 1;
1194
+ if (tests.every((p) => p === 1)) count.first += 1;
1195
+ };
1196
+ const askPin = async (page, pin, question, language, report, draft, file) => {
1197
+ const fresh = freshness(page.body, pin);
1198
+ if (fresh.state === "changed") {
1199
+ summary.answers.changed += 1;
1200
+ const of2 = file === void 0 ? "" : ` of ${file}`;
1201
+ const fix = file === void 0 ? "re-pair it with manni graph fill --fields sample-questions and review it" : "re-pin it and review it";
1202
+ report(
1203
+ "knob",
1204
+ `lines ${spellLines(pin.lines)}${of2} no longer hold the answer to "${question}" as pinned, so ${fix}.`,
1205
+ draft
1206
+ );
1207
+ return { position: 0, answering: [] };
1208
+ }
1209
+ const [range2] = fresh.ranges;
1210
+ const inFile = file === void 0 ? "" : ` in ${file}`;
1211
+ if (fresh.state === "current") summary.answers.current += 1;
1212
+ else summary.answers.moved += 1;
1213
+ if (fresh.state === "moved" && range2) {
1214
+ report(
1215
+ "notice",
1216
+ `the answer to "${question}"${inFile} moved from lines ${spellLines(pin.lines)} to ${spellLines(range2)}, so manni graph fill --fields sample-questions re-pins it.`,
1217
+ draft
1218
+ );
1219
+ } else if (fresh.state === "ambiguous") {
1220
+ report(
1221
+ "warning",
1222
+ `the answer to "${question}"${inFile} moved, and ${matchList(fresh.ranges)}, so pin one of them by hand.`,
1223
+ draft
1510
1224
  );
1511
1225
  }
1512
- const tree = source === void 0 || path === void 0 ? void 0 : treeText(source, path);
1513
- if (tree) treeTextOf.set(doc, tree);
1514
- const body = source === void 0 ? void 0 : stripFrontmatter(source).replace(/\r\n/g, "\n");
1515
- const text = tree ? tree.doc : body === void 0 ? void 0 : (sectionsOf.get(doc)?.length ?? 0) > 0 ? documentPreamble(body) : body;
1516
- entries.push(
1517
- entry(doc, compactIri(GRAPH_DOCUMENT), {
1518
- title: graph.literal(doc, DCTERMS_TITLE2),
1519
- description: graph.literal(doc, DCTERMS_DESCRIPTION),
1520
- text
1521
- })
1226
+ const text = range2 ? page.body.slice(range2.start - 1, range2.end).join("\n") : void 0;
1227
+ const nodes = await rank(language, question);
1228
+ const answering = fresh.ranges.flatMap((r) => holdersOf(page, toFileLines(r, page.bodyLine)));
1229
+ const positions = answering.map((iri) => nodes.indexOf(iri) + 1);
1230
+ const best = positions.reduce(
1231
+ (b, p, i) => p >= 1 && (b.p === 0 || p < b.p) ? { p, i } : b,
1232
+ { p: 0, i: 0 }
1522
1233
  );
1523
- }
1524
- const occurrencesOf = /* @__PURE__ */ new Map();
1525
- for (const section of allSections) {
1526
- const hash = section.indexOf("#");
1527
- const doc = hash < 0 ? section : section.slice(0, hash);
1528
- const title = graph.literal(section, DCTERMS_TITLE2);
1529
- const source = sourceOf.get(doc);
1530
- const levelText = graph.literal(section, GRAPH_LEVEL2);
1531
- const parsed = levelText === void 0 ? NaN : Number.parseInt(levelText, 10);
1532
- const level = Number.isNaN(parsed) ? void 0 : parsed;
1533
- let occurrences = occurrencesOf.get(doc);
1534
- if (!occurrences) {
1535
- occurrences = sectionOccurrences(graph, doc);
1536
- occurrencesOf.set(doc, occurrences);
1234
+ const found = { position: best.p, answering, ...text === void 0 ? {} : { text } };
1235
+ if (best.p >= 1 && best.p <= top) return found;
1236
+ const holder = answering[best.i];
1237
+ if (holder !== void 0) {
1238
+ const title = holder.includes("#") ? graph.literal(holder, TITLE) : void 0;
1239
+ const target = file !== void 0 ? `does not find ${describe(holder)}` : title === void 0 ? "does not find this page, whose own text answers it," : `does not find the section that answers it, \xA7 ${title},`;
1240
+ report("knob", `"${question}" ${target} in the top ${String(top)} (${where(best.p, nodes[0])})`, draft);
1537
1241
  }
1538
- const tree = treeTextOf.get(doc);
1539
- const text = tree ? tree.sections.get(section.slice(hash + 1)) : source !== void 0 && title !== void 0 ? sectionOwnText(source, title, level, occurrences.get(section) ?? 0) : void 0;
1540
- entries.push(entry(section, compactIri(GRAPH_SECTION), { title, text }));
1541
- }
1542
- for (const concept of graph.instancesOf(SKOS_CONCEPT)) {
1543
- const pref = graph.literals(concept, SKOS_PREF_LABEL);
1544
- const alt = graph.literals(concept, SKOS_ALT_LABEL);
1545
- entries.push(
1546
- entry(concept, compactIri(SKOS_CONCEPT), {
1547
- title: pref[0],
1548
- labels: joinLabels([...pref, ...alt])
1549
- })
1242
+ return found;
1243
+ };
1244
+ const row = { seam: cite ? void 0 : null };
1245
+ let citedCount = 0;
1246
+ let withheldCount = 0;
1247
+ const languageOf2 = (iri) => {
1248
+ const tag = graph.literal(pageOf(iri), LANGUAGE);
1249
+ return tag === void 0 ? void 0 : canonicalLanguageTag(tag);
1250
+ };
1251
+ const askCited = async (question, language, targets, report) => {
1252
+ if (row.seam === void 0 && cite) {
1253
+ try {
1254
+ row.seam = await cite();
1255
+ } catch (e) {
1256
+ if (!(e instanceof GraphError)) throw e;
1257
+ row.seam = null;
1258
+ findings.push({
1259
+ severity: "notice",
1260
+ message: `the cited row did not run: ${e.message}`,
1261
+ focusNode: "questions",
1262
+ docs: [],
1263
+ guidance: null
1264
+ });
1265
+ }
1266
+ }
1267
+ const seam = row.seam;
1268
+ if (!seam) return;
1269
+ const bundle = await seam.retrieve(question, language);
1270
+ const cites = bundle?.citations.map((c) => c.iri) ?? [];
1271
+ const leak = cites.find((iri) => {
1272
+ const l = languageOf2(iri);
1273
+ return l !== void 0 && l !== UNDETERMINED && l !== language;
1274
+ });
1275
+ if (leak !== void 0) {
1276
+ const page = graph.literal(pageOf(leak), PATH) ?? pageOf(leak);
1277
+ report("error", `"${question}" asks in ${language}, and graph retrieve cites ${page}, which is ${languageOf2(leak) ?? ""}.`);
1278
+ return;
1279
+ }
1280
+ if (targets.every((t) => t.some((iri) => cites.includes(iri)))) {
1281
+ citedCount += 1;
1282
+ return;
1283
+ }
1284
+ if (targets.some((t) => t.length === 0)) return;
1285
+ const held = targets.flat().find((iri) => seam.withheld.has(iri));
1286
+ if (held !== void 0) {
1287
+ withheldCount += 1;
1288
+ const title = held.includes("#") ? graph.literal(held, TITLE) : void 0;
1289
+ const what = title === void 0 ? graph.literal(pageOf(held), PATH) ?? pageOf(held) : `\xA7 ${title}`;
1290
+ const because = listOf(seam.withheld.get(held) ?? []);
1291
+ report("knob", `"${question}" is not cited by graph retrieve, because graph.retrieve.withhold left out ${what} as ${because}.`);
1292
+ return;
1293
+ }
1294
+ const first = cites[0];
1295
+ report(
1296
+ "knob",
1297
+ first === void 0 ? `"${question}" is not cited by graph retrieve, which cites nothing for it.` : `"${question}" is not cited by graph retrieve, which cites ${describe(first)} first.`
1550
1298
  );
1551
- }
1552
- entries.sort((a, b) => byCodeUnit(a.id, b.id));
1553
- return { version: 1, entries };
1554
- }
1555
- function emitSearchIndex(doc) {
1556
- return `${JSON.stringify(doc, null, 2)}
1557
- `;
1558
- }
1559
- function partitionByLanguage(graph, index) {
1560
- const documentType = compactIri(GRAPH_DOCUMENT);
1561
- const sectionType = compactIri(GRAPH_SECTION);
1562
- const languageOf = (entry2) => {
1563
- if (entry2.type !== documentType && entry2.type !== sectionType) {
1564
- return void 0;
1299
+ };
1300
+ const copies = (question, said, report, draft) => {
1301
+ const m = said.length === 0 ? void 0 : copiedPairs(question, ...said);
1302
+ if (m && m.copied / m.of > COPIED_SHARE) {
1303
+ report(
1304
+ "notice",
1305
+ `"${question}" repeats ${String(m.copied)} of its ${String(m.of)} word pairs from its answer, so it tests matching words more than finding.`,
1306
+ draft
1307
+ );
1565
1308
  }
1566
- const hash = entry2.id.indexOf("#");
1567
- const doc = hash === -1 ? entry2.id : entry2.id.slice(0, hash);
1568
- return languageOfDocument(graph, doc);
1569
1309
  };
1570
- const out = /* @__PURE__ */ new Map();
1571
- const shared = [];
1572
- for (const entry2 of index.entries) {
1573
- const language = languageOf(entry2);
1574
- if (language === void 0) {
1575
- shared.push(entry2);
1576
- continue;
1310
+ const asked = [];
1311
+ for (const page of pages) {
1312
+ const report = reporter({ focusNode: page.doc, path: SAMPLE_QUESTION, docs: [page.path] });
1313
+ for (const [n, q] of page.questions.entries()) {
1314
+ const drafted = q.reviewed ? void 0 : "question";
1315
+ if (q.reviewed) summary.reviewed += 1;
1316
+ else summary.drafted += 1;
1317
+ asked.push({ key: questionKey(q.question), where: page.path, order: n, text: q.question, report, ...drafted ? { draft: drafted } : {} });
1318
+ if (q.answers.length === 0) summary.answers.unpinned += 1;
1319
+ const tests = [];
1320
+ const targets = [];
1321
+ if (q.answers.length === 0 || q.reviewed && q.answers.every((a) => !a.reviewed)) {
1322
+ targets.push([page.doc, ...page.sections.map((s) => s.iri)]);
1323
+ const nodes = await rank(page.language, q.question);
1324
+ const pagesFound = [...new Set(nodes.map(pageOf))];
1325
+ const position = pagesFound.indexOf(page.doc) + 1;
1326
+ tests.push(position);
1327
+ if (position < 1 || position > top) {
1328
+ report(
1329
+ "knob",
1330
+ `"${q.question}" does not find this page in the top ${String(top)} (${where(position, pagesFound[0])})`,
1331
+ drafted
1332
+ );
1333
+ }
1334
+ }
1335
+ const said = [];
1336
+ for (const pin of q.answers) {
1337
+ const draft = drafted ?? (pin.reviewed ? void 0 : "pin");
1338
+ summary.answers.pinned += 1;
1339
+ if (draft) summary.answers.unreviewed += 1;
1340
+ const { position, text, answering } = await askPin(page, pin, q.question, page.language, report, draft);
1341
+ if (text !== void 0) said.push(text);
1342
+ if (draft !== "pin") {
1343
+ tests.push(position);
1344
+ targets.push(answering);
1345
+ }
1346
+ }
1347
+ copies(q.question, said, report, drafted);
1348
+ tally(q.reviewed, tests);
1349
+ if (q.reviewed && tests.length > 0) await askCited(q.question, page.language, targets, report);
1577
1350
  }
1578
- const bucket = out.get(language);
1579
- if (bucket) bucket.entries.push(entry2);
1580
- else out.set(language, { version: 1, entries: [entry2] });
1581
1351
  }
1582
- if (out.size === 0 && shared.length > 0) {
1583
- out.set(UNDETERMINED, { version: 1, entries: [] });
1352
+ for (const set of sets) {
1353
+ for (const [n, q] of set.questions.entries()) {
1354
+ const report = reporter({ focusNode: `${set.label}:${String(q.line)}`, docs: [set.label] });
1355
+ const drafted = q.reviewed ? void 0 : "question";
1356
+ if (q.reviewed) summary.reviewed += 1;
1357
+ else summary.drafted += 1;
1358
+ asked.push({ key: questionKey(q.question), where: set.label, order: n, text: q.question, report, ...drafted ? { draft: drafted } : {} });
1359
+ if (q.answers.length === 0) {
1360
+ summary.gaps += 1;
1361
+ continue;
1362
+ }
1363
+ const [firstAnswer] = q.answers;
1364
+ const firstPage = firstAnswer && pageAt(resolve3(configDir, firstAnswer.file));
1365
+ const language = q.language !== void 0 ? canonicalLanguageTag(q.language) : firstPage?.language ?? UNDETERMINED;
1366
+ const tests = [];
1367
+ const targets = [];
1368
+ const said = [];
1369
+ for (const pin of q.answers) {
1370
+ const draft = drafted ?? (pin.reviewed ? void 0 : "pin");
1371
+ summary.answers.pinned += 1;
1372
+ if (draft) summary.answers.unreviewed += 1;
1373
+ const abs = resolve3(configDir, pin.file);
1374
+ const page = pageAt(abs);
1375
+ if (page === void 0) {
1376
+ if (existsSync4(abs)) {
1377
+ const nodes = await rank(language, q.question);
1378
+ report("knob", `"${q.question}" does not find ${pin.file} in the top ${String(top)} (${where(0, nodes[0])})`, draft);
1379
+ } else {
1380
+ summary.answers.changed += 1;
1381
+ report(
1382
+ "knob",
1383
+ `${pin.file}, which holds the answer to "${q.question}", does not exist, so re-pin or remove the question.`,
1384
+ draft
1385
+ );
1386
+ }
1387
+ if (draft !== "pin") {
1388
+ tests.push(0);
1389
+ targets.push([]);
1390
+ }
1391
+ continue;
1392
+ }
1393
+ const { position, text, answering } = await askPin(page, pin, q.question, language, report, draft, pin.file);
1394
+ if (text !== void 0) said.push(text);
1395
+ if (draft !== "pin") {
1396
+ tests.push(position);
1397
+ targets.push(answering);
1398
+ }
1399
+ }
1400
+ copies(q.question, said, report, drafted);
1401
+ tally(q.reviewed, tests);
1402
+ if (q.reviewed && tests.length > 0) await askCited(q.question, language, targets, report);
1403
+ }
1584
1404
  }
1585
- for (const bucket of out.values()) {
1586
- bucket.entries.push(...shared);
1587
- bucket.entries.sort((a, b) => byCodeUnit(a.id, b.id));
1405
+ asked.sort((a, b) => byCodeUnit(a.where, b.where) || a.order - b.order);
1406
+ const firstAt = /* @__PURE__ */ new Map();
1407
+ for (const copy of asked) {
1408
+ if (copy.key === "") continue;
1409
+ const first = firstAt.get(copy.key);
1410
+ if (first === void 0) firstAt.set(copy.key, copy.where);
1411
+ else copy.report("knob", `"${copy.text}" is also asked on ${first}, so keep it where it is answered.`, copy.draft);
1588
1412
  }
1589
- return out;
1590
- }
1591
- function languageOfDocument(graph, doc) {
1592
- const tag = graph.literal(doc, DCTERMS_LANGUAGE);
1593
- return tag === void 0 ? UNDETERMINED : canonicalLanguageTag(tag);
1413
+ const threshold = settings.foundThreshold;
1414
+ const { inTop, of } = summary.found.reviewed;
1415
+ if (threshold !== null && of > 0 && inTop / of * 100 < threshold) {
1416
+ findings.push({
1417
+ severity: "error",
1418
+ message: `${String(inTop)} of ${String(of)} reviewed questions are found in the top ${String(top)} (${String(percent(inTop, of))}%), under the ${String(threshold)}% that graph.check.questions.foundThreshold asks for.`,
1419
+ focusNode: "questions",
1420
+ docs: [],
1421
+ guidance: null
1422
+ });
1423
+ }
1424
+ if (row.seam) {
1425
+ summary.cited = citedCount;
1426
+ summary.withheld = withheldCount;
1427
+ const cited = settings.citedThreshold;
1428
+ if (cited !== null && of > 0 && citedCount / of * 100 < cited) {
1429
+ findings.push({
1430
+ severity: "error",
1431
+ message: `${String(citedCount)} of ${String(of)} reviewed questions are cited by graph retrieve (${String(percent(citedCount, of))}%), under the ${String(cited)}% that graph.check.questions.citedThreshold asks for.`,
1432
+ focusNode: "questions",
1433
+ docs: [],
1434
+ guidance: null
1435
+ });
1436
+ }
1437
+ }
1438
+ return { findings, summary };
1594
1439
  }
1595
- function documentsByLanguage(graph) {
1596
- const out = /* @__PURE__ */ new Map();
1597
- for (const doc of graph.instancesOf(GRAPH_DOCUMENT)) {
1598
- const language = languageOfDocument(graph, doc);
1599
- out.set(language, (out.get(language) ?? 0) + 1);
1440
+ async function exportSampleQuestions(store, sources, view, questionFiles, configDir) {
1441
+ const sets = questionFiles.map((label) => ({
1442
+ label,
1443
+ questions: readQuestionFile(resolve3(configDir, label), label)
1444
+ }));
1445
+ const graph = GraphIndex.fromQuads(storeToQuads(store), Object.fromEntries(PREFIXES));
1446
+ const { pages, pageAt } = await readPages(graph, sources, view, "exported");
1447
+ let stale = 0;
1448
+ const pinned = (page, file, pin, reviewed) => {
1449
+ const fresh = freshness(page.body, pin);
1450
+ const range2 = fresh.state === "changed" ? pin.lines : fresh.ranges[0] ?? pin.lines;
1451
+ if (fresh.state === "changed") stale += 1;
1452
+ const first = toFileLines({ start: range2.start, end: range2.start }, page.bodyLine);
1453
+ const text = page.body.slice(range2.start - 1, range2.end).join("\n");
1454
+ return {
1455
+ id: holdersOf(page, first)[0] ?? page.doc,
1456
+ file,
1457
+ lines: spellLines(range2),
1458
+ reviewed,
1459
+ ...fresh.state === "changed" ? { stale: true } : {},
1460
+ ...text === "" ? {} : { text }
1461
+ };
1462
+ };
1463
+ const lines = [];
1464
+ const write = (id, question, language, reviewed, expected) => {
1465
+ lines.push(
1466
+ JSON.stringify({ id, question, language, reviewed, answerable: expected.length > 0, expected })
1467
+ );
1468
+ };
1469
+ for (const page of pages) {
1470
+ const slugger = new GithubSlugger();
1471
+ for (const q of page.questions) {
1472
+ const expected = q.answers.length === 0 ? [{ id: page.doc, file: page.path, reviewed: q.reviewed }] : q.answers.map((pin) => pinned(page, page.path, pin, q.reviewed && pin.reviewed));
1473
+ write(`${page.path}#${slugger.slug(q.question)}`, q.question, page.language, q.reviewed, expected);
1474
+ }
1475
+ }
1476
+ for (const set of sets) {
1477
+ const slugger = new GithubSlugger();
1478
+ for (const q of set.questions) {
1479
+ const expected = q.answers.map((pin) => {
1480
+ const reviewed = q.reviewed && pin.reviewed;
1481
+ const abs = resolve3(configDir, pin.file);
1482
+ const page = pageAt(abs);
1483
+ if (page) return pinned(page, pin.file, pin, reviewed);
1484
+ const gone = !existsSync4(abs);
1485
+ if (gone) stale += 1;
1486
+ return { file: pin.file, lines: spellLines(pin.lines), reviewed, ...gone ? { stale: true } : {} };
1487
+ });
1488
+ const [firstAnswer] = q.answers;
1489
+ const firstPage = firstAnswer && pageAt(resolve3(configDir, firstAnswer.file));
1490
+ const language = q.language !== void 0 ? canonicalLanguageTag(q.language) : firstPage?.language ?? UNDETERMINED;
1491
+ write(`${set.label}#${slugger.slug(q.question)}`, q.question, language, q.reviewed, expected);
1492
+ }
1600
1493
  }
1601
- return out;
1494
+ return { lines, stale };
1602
1495
  }
1603
1496
 
1604
- // src/graph/runtime/graph.ts
1605
- var XSD_STRING2 = "http://www.w3.org/2001/XMLSchema#string";
1606
- function compareValues(a, b) {
1607
- if (a.kind !== b.kind) return a.kind === "iri" ? -1 : 1;
1608
- const v = byCodeUnit(a.value, b.value);
1609
- if (v !== 0) return v;
1610
- const da = a.kind === "literal" ? a.datatype ?? "" : "";
1611
- const db = b.kind === "literal" ? b.datatype ?? "" : "";
1612
- const la = a.kind === "literal" ? a.language ?? "" : "";
1613
- const lb = b.kind === "literal" ? b.language ?? "" : "";
1614
- return byCodeUnit(da, db) || byCodeUnit(la, lb);
1615
- }
1616
- var GraphIndex = class _GraphIndex {
1617
- nodes = /* @__PURE__ */ new Map();
1618
- /** subject → predicate → object IRIs (sorted). */
1619
- outbound = /* @__PURE__ */ new Map();
1620
- /** object → predicate → subject IRIs (sorted). */
1621
- inbound = /* @__PURE__ */ new Map();
1622
- /** class IRI → instance IRIs (sorted). */
1623
- byType = /* @__PURE__ */ new Map();
1624
- /** prefix → namespace, from the artifact's own `@context`. */
1625
- context;
1626
- constructor(context) {
1627
- this.context = context;
1628
- }
1629
- /**
1630
- * Build from a `graph.jsonld` document — a JSON string or the parsed object.
1631
- * CURIE keys and `@type` values are expanded using the document's own
1632
- * `@context`, so the index is self-describing.
1633
- */
1634
- static fromJsonLd(input) {
1635
- const doc = typeof input === "string" ? JSON.parse(input) : input;
1636
- const context = doc["@context"] ?? {};
1637
- const index = new _GraphIndex({ ...context });
1638
- for (const raw of doc["@graph"] ?? []) {
1639
- index.addJsonLdNode(raw);
1640
- }
1641
- index.finalize();
1642
- return index;
1643
- }
1644
- /** Build from dockg's internal quad shape (the Node/CLI path). */
1645
- static fromQuads(quads, context = {}) {
1646
- const index = new _GraphIndex({ ...context });
1647
- for (const q of quads) {
1648
- const o = q.o;
1649
- const value = o.kind === "iri" ? { kind: "iri", value: o.value } : o.language ? { kind: "literal", value: o.value, language: o.language } : o.datatype && o.datatype !== XSD_STRING2 ? { kind: "literal", value: o.value, datatype: o.datatype } : { kind: "literal", value: o.value };
1650
- index.addTriple(q.s, q.p, value);
1651
- }
1652
- index.finalize();
1653
- return index;
1654
- }
1655
- /** Expand a CURIE (`dcterms:title`) to a full IRI using `@context`. */
1656
- expand(term) {
1657
- const colon = term.indexOf(":");
1658
- if (colon <= 0) return term;
1659
- const ns = this.context[term.slice(0, colon)];
1660
- return ns ? `${ns}${term.slice(colon + 1)}` : term;
1661
- }
1662
- /** Compact a full IRI to a CURIE when a context namespace matches. */
1663
- compact(iri) {
1664
- let best = iri;
1665
- let bestNs = "";
1666
- for (const [prefix, ns] of Object.entries(this.context)) {
1667
- if (iri.startsWith(ns) && iri.length > ns.length && ns.length > bestNs.length) {
1668
- best = `${prefix}:${iri.slice(ns.length)}`;
1669
- bestNs = ns;
1670
- }
1671
- }
1672
- return best;
1497
+ // src/graph/commands/chunks.ts
1498
+ import { execFile } from "node:child_process";
1499
+ import { existsSync as existsSync5, mkdirSync, readFileSync as readFileSync5, writeFileSync } from "node:fs";
1500
+ import { basename, join as join3, resolve as resolve4 } from "node:path";
1501
+ import { promisify } from "node:util";
1502
+
1503
+ // src/graph/core/emit-jsonld.ts
1504
+ var XSD_STRING2 = `${NS.xsd}string`;
1505
+ function renderValue(term) {
1506
+ if (term.kind === "iri") {
1507
+ return {
1508
+ value: { "@id": term.value },
1509
+ kind: 0,
1510
+ primary: term.value,
1511
+ datatype: "",
1512
+ language: ""
1513
+ };
1673
1514
  }
1674
- addJsonLdNode(raw) {
1675
- const id = typeof raw["@id"] === "string" ? this.expand(raw["@id"]) : "";
1676
- if (!id) return;
1677
- this.ensureNode(id);
1678
- const rawTypes = raw["@type"];
1679
- for (const t of toArray(rawTypes)) {
1680
- if (typeof t === "string") {
1681
- this.addTriple(id, RDF_TYPE, { kind: "iri", value: this.expand(t) });
1682
- }
1683
- }
1684
- for (const [key, rawValue] of Object.entries(raw)) {
1685
- if (key === "@id" || key === "@type") continue;
1686
- const predicate = this.expand(key);
1687
- for (const v of toArray(rawValue)) {
1688
- const value = this.toValue(v);
1689
- if (value) this.addTriple(id, predicate, value);
1690
- }
1691
- }
1515
+ if (term.language) {
1516
+ return {
1517
+ value: { "@value": term.value, "@language": term.language },
1518
+ kind: 1,
1519
+ primary: term.value,
1520
+ datatype: "",
1521
+ language: term.language
1522
+ };
1692
1523
  }
1693
- toValue(v) {
1694
- if (typeof v === "string") return { kind: "literal", value: v };
1695
- if (typeof v === "number" || typeof v === "boolean") {
1696
- return { kind: "literal", value: String(v) };
1697
- }
1698
- if (v && typeof v === "object") {
1699
- const o = v;
1700
- if (typeof o["@id"] === "string") {
1701
- return { kind: "iri", value: this.expand(o["@id"]) };
1702
- }
1703
- if (o["@value"] !== void 0) {
1704
- const raw = o["@value"];
1705
- const lexical = typeof raw === "string" ? raw : JSON.stringify(raw);
1706
- if (typeof o["@language"] === "string") {
1707
- return { kind: "literal", value: lexical, language: o["@language"] };
1708
- }
1709
- const dt = typeof o["@type"] === "string" ? this.expand(o["@type"]) : void 0;
1710
- return dt && dt !== XSD_STRING2 ? { kind: "literal", value: lexical, datatype: dt } : { kind: "literal", value: lexical };
1711
- }
1712
- }
1713
- return void 0;
1524
+ if (term.datatype && term.datatype !== XSD_STRING2) {
1525
+ return {
1526
+ value: { "@value": term.value, "@type": compactIri(term.datatype) },
1527
+ kind: 1,
1528
+ primary: term.value,
1529
+ datatype: term.datatype,
1530
+ language: ""
1531
+ };
1714
1532
  }
1715
- ensureNode(id) {
1716
- let node = this.nodes.get(id);
1717
- if (!node) {
1718
- node = { id, types: [], props: /* @__PURE__ */ new Map() };
1719
- this.nodes.set(id, node);
1533
+ return { value: term.value, kind: 1, primary: term.value, datatype: "", language: "" };
1534
+ }
1535
+ function compareRendered(a, b) {
1536
+ if (a.kind !== b.kind) return a.kind - b.kind;
1537
+ const p = byCodeUnit(a.primary, b.primary);
1538
+ if (p !== 0) return p;
1539
+ return byCodeUnit(a.datatype, b.datatype) || byCodeUnit(a.language, b.language);
1540
+ }
1541
+ function collapse(values) {
1542
+ const rendered = [...values].sort(compareRendered).map((v) => v.value);
1543
+ return rendered.length === 1 ? rendered[0] : rendered;
1544
+ }
1545
+ function emitJsonLd(quads) {
1546
+ const context = {};
1547
+ for (const [prefix, ns] of PREFIXES) context[prefix] = ns;
1548
+ const subjects = /* @__PURE__ */ new Map();
1549
+ for (const quad of quads) {
1550
+ let preds = subjects.get(quad.s);
1551
+ if (!preds) {
1552
+ preds = /* @__PURE__ */ new Map();
1553
+ subjects.set(quad.s, preds);
1554
+ }
1555
+ let terms = preds.get(quad.p);
1556
+ if (!terms) {
1557
+ terms = [];
1558
+ preds.set(quad.p, terms);
1559
+ }
1560
+ terms.push(quad.o);
1561
+ }
1562
+ const graph = [...subjects.entries()].sort(([a], [b]) => byCodeUnit(a, b)).map(([subject, preds]) => {
1563
+ const node = { "@id": subject };
1564
+ const types = preds.get(RDF_TYPE);
1565
+ if (types) {
1566
+ const compacted = types.map((t) => compactIri(t.value)).sort(byCodeUnit);
1567
+ node["@type"] = compacted.length === 1 ? compacted[0] : compacted;
1568
+ }
1569
+ const predEntries = [...preds.entries()].filter(([p]) => p !== RDF_TYPE).sort(([a], [b]) => byCodeUnit(a, b));
1570
+ for (const [p, terms] of predEntries) {
1571
+ node[compactIri(p)] = collapse(terms.map(renderValue));
1720
1572
  }
1721
1573
  return node;
1574
+ });
1575
+ return `${JSON.stringify({ "@context": context, "@graph": graph }, null, 2)}
1576
+ `;
1577
+ }
1578
+
1579
+ // src/graph/commands/chunks.ts
1580
+ var run = promisify(execFile);
1581
+ var DOCUMENT2 = `${NS.graph}Document`;
1582
+ var PATH2 = `${NS.graph}path`;
1583
+ var LEVEL2 = `${NS.graph}level`;
1584
+ var TITLE2 = `${NS.dcterms}title`;
1585
+ var LANGUAGE2 = `${NS.dcterms}language`;
1586
+ var CHUNKS_MANIFEST = "chunks.json";
1587
+ function chunksFilename(language) {
1588
+ return `chunks.${language}.jsonl`;
1589
+ }
1590
+ async function exportChunks(opts) {
1591
+ const { cwd, config } = opts;
1592
+ const warnings = [];
1593
+ const notices = [];
1594
+ const quads = storeToQuads(loadGraph(opts.graphPath));
1595
+ const graph = GraphIndex.fromQuads(quads, Object.fromEntries(PREFIXES));
1596
+ const graphDigest = integrityOf(Buffer.from(emitJsonLd(quads), "utf8"));
1597
+ const sources = documentBase(config, {}, cwd);
1598
+ const pages = [];
1599
+ for (const doc of graph.instancesOf(DOCUMENT2)) {
1600
+ const path = graph.literal(doc, PATH2);
1601
+ if (path === void 0 || path === STDIN_PATH) continue;
1602
+ const abs = resolve4(sources, path);
1603
+ if (!existsSync5(abs)) continue;
1604
+ pages.push({ doc, path, content: readFileSync5(abs, "utf8") });
1605
+ }
1606
+ pages.sort((a, b) => byCodeUnit(a.path, b.path));
1607
+ const paths = pages.map((p) => p.path);
1608
+ const allPaths = new Set(paths);
1609
+ const routes = routesFrom(config, sources);
1610
+ const view = await openMetaView(opts.source, cwd, paths, sources);
1611
+ const models = await withExternalMetadata(
1612
+ pages.map((p) => analyzeDoc(p.content, p.path, allPaths, { routes })),
1613
+ view
1614
+ );
1615
+ const git = await gitState(sources, paths);
1616
+ if (git.reason !== void 0) {
1617
+ notices.push(`git cannot read this directory (${git.reason}), so records carry no commit and no derived dates.`);
1618
+ } else if (git.dirty.size > 0 && git.commit !== null) {
1619
+ const n = git.dirty.size;
1620
+ warnings.push(
1621
+ `${String(n)} ${n === 1 ? "page differs" : "pages differ"} from ${git.commit.slice(0, 8)}, so their records describe uncommitted text.`
1622
+ );
1623
+ }
1624
+ const worktree = git.commit === null ? null : git.dirty.size > 0 ? "modified" : "clean";
1625
+ const pins = await pinsByPage(opts, sources, paths, new Map(models.map((m) => [m.path, m.frontmatter])));
1626
+ const dates = await datesByPage(opts, sources, paths, git.commit !== null);
1627
+ const evals = readEvals(opts, sources, pages, warnings);
1628
+ if (opts.evals === void 0) warnings.push("no docevals report is configured, so records carry no eval verdicts.");
1629
+ const vectors = readVectors(opts.outDir);
1630
+ if (vectors === void 0) {
1631
+ warnings.push(
1632
+ "no vector sidecar, so chunks carry no vectors and retrieval is lexical only; configure graph.embed to add them."
1633
+ );
1722
1634
  }
1723
- addTriple(s, p, o) {
1724
- const node = this.ensureNode(s);
1725
- let values = node.props.get(p);
1726
- if (!values) {
1727
- values = [];
1728
- node.props.set(p, values);
1729
- }
1730
- values.push(o);
1731
- if (p === RDF_TYPE && o.kind === "iri") {
1732
- node.types.push(o.value);
1733
- const instances = this.byType.get(o.value);
1734
- if (instances) instances.push(s);
1735
- else this.byType.set(o.value, [s]);
1736
- }
1737
- if (o.kind === "iri") {
1738
- addEdge(this.outbound, s, p, o.value);
1739
- addEdge(this.inbound, o.value, p, s);
1740
- this.ensureNode(o.value);
1741
- }
1742
- }
1743
- /** Sort every collection so traversal order is deterministic. */
1744
- finalize() {
1745
- for (const node of this.nodes.values()) {
1746
- node.types.sort(byCodeUnit);
1747
- for (const values of node.props.values()) values.sort(compareValues);
1748
- }
1749
- for (const instances of this.byType.values()) instances.sort(byCodeUnit);
1750
- for (const map of [this.outbound, this.inbound]) {
1751
- for (const preds of map.values()) {
1752
- for (const targets of preds.values()) targets.sort(byCodeUnit);
1635
+ const rows = [];
1636
+ const pageMetadata = {};
1637
+ for (const [n, page] of pages.entries()) {
1638
+ const model = models[n];
1639
+ if (model === void 0) continue;
1640
+ const refs = view.refsFor(page.path, model.frontmatter);
1641
+ const { $schema: _schema, ...own } = model.frontmatter;
1642
+ void _schema;
1643
+ const metadata = plain(await deliveredFields(own, refs, view.validator));
1644
+ pageMetadata[page.path] = { metadata };
1645
+ const { bodyLine } = bodyOf(page.content, model.format);
1646
+ const blocks = [];
1647
+ const bySection = /* @__PURE__ */ new Map();
1648
+ for (const s of model.statements ?? []) {
1649
+ const data = plain(await deliveredFields(s.data, refs, view.validator));
1650
+ if (s.scope === "block") {
1651
+ blocks.push({ start: s.anchor.start - bodyLine + 1, end: s.anchor.end - bodyLine + 1, status: s.status, data });
1652
+ continue;
1753
1653
  }
1654
+ const section = model.sections.find(
1655
+ (x) => x.line !== null && x.line >= s.anchor.start && x.line <= s.anchor.end
1656
+ );
1657
+ if (section === void 0) continue;
1658
+ blocks.push({ start: s.anchor.start - bodyLine + 1, end: s.anchor.end - bodyLine + 1, status: s.status, data });
1659
+ const list = bySection.get(section.slug) ?? [];
1660
+ list.push(data);
1661
+ bySection.set(section.slug, list);
1662
+ }
1663
+ const language = languageOf(graph, page.doc);
1664
+ const record = (start, end) => ({
1665
+ page: page.path,
1666
+ lines: `${String(start)}-${String(end)}`,
1667
+ commit: git.commit,
1668
+ worktree,
1669
+ pins: summarize(pins.get(page.path) ?? [], start, end),
1670
+ dates: dates.get(page.path) ?? noDates(model.frontmatter),
1671
+ evals: evals?.get(page.path) ?? null,
1672
+ statements: blocks.filter((b) => b.start >= start && b.end <= end).map((b) => ({ lines: `${String(b.start)}-${String(b.end)}`, status: b.status, data: b.data }))
1673
+ });
1674
+ for (const passage of passagesOf(graph, page, model, bodyLine, language, metadata, bySection)) {
1675
+ const vector = vectors?.byId.get(passage.id);
1676
+ rows.push({
1677
+ id: passage.id,
1678
+ graph: graphDigest,
1679
+ page: passage.page,
1680
+ lines: `${String(passage.start)}-${String(passage.end)}`,
1681
+ language: passage.language,
1682
+ title: passage.title,
1683
+ text: passage.text,
1684
+ ...vector === void 0 ? {} : { vector },
1685
+ metadata: passage.metadata,
1686
+ provenance: { node: passage.id, ...record(passage.start, passage.end) }
1687
+ });
1754
1688
  }
1755
1689
  }
1756
- /** Every node IRI, sorted. */
1757
- ids() {
1758
- return [...this.nodes.keys()].sort(byCodeUnit);
1690
+ rows.sort((a, b) => byCodeUnit(a.id, b.id));
1691
+ const withhold = config.retrieve.withhold;
1692
+ const withheld = [];
1693
+ const kept = [];
1694
+ for (const row of rows) {
1695
+ const because = withhold.filter((reason) => withholds(row.provenance, reason));
1696
+ if (because.length === 0) kept.push(row);
1697
+ else withheld.push({ id: row.id, page: row.page, because });
1698
+ }
1699
+ if (withheld.length > 0) {
1700
+ const reasons = withhold.filter((r) => withheld.some((w) => w.because.includes(r)));
1701
+ const n = withheld.length;
1702
+ notices.push(
1703
+ `${String(n)} ${n === 1 ? "chunk" : "chunks"} withheld by graph.retrieve.withhold (${reasons.join(", ")}); ${CHUNKS_MANIFEST} lists them.`
1704
+ );
1705
+ }
1706
+ mkdirSync(opts.outDir, { recursive: true });
1707
+ const languages = {};
1708
+ const byLanguage = /* @__PURE__ */ new Map();
1709
+ for (const row of kept) {
1710
+ const list = byLanguage.get(row.language) ?? [];
1711
+ list.push(row);
1712
+ byLanguage.set(row.language, list);
1759
1713
  }
1760
- size() {
1761
- return this.nodes.size;
1714
+ for (const [language, list] of byLanguage) {
1715
+ if (!isLanguageTag(language)) {
1716
+ throw new GraphError(
1717
+ `Cannot write an index for language "${language}": not a BCP-47 tag. Fix the \`lang\`/\`language\` frontmatter, or the route's \`language\`, and rebuild \u2014 \`manni graph check\` reports which document carries it.`
1718
+ );
1719
+ }
1720
+ const file = chunksFilename(language);
1721
+ writeFileSync(join3(opts.outDir, file), list.map((row) => `${canonicalJson(row)}
1722
+ `).join(""), "utf8");
1723
+ languages[language] = { file, rows: list.length, model: vectors?.models.get(language) ?? null };
1724
+ }
1725
+ const manifest = {
1726
+ format: "manni-graph-chunks",
1727
+ version: 1,
1728
+ graph: graphDigest,
1729
+ graphFile: basename(opts.graphPath).replace(/\.[^.]*$/, "") + ".jsonld",
1730
+ searchIndex: LOCALIZATIONS_FILENAME,
1731
+ commit: git.commit,
1732
+ worktree,
1733
+ retrieve: { ...config.retrieve },
1734
+ evals: opts.evals === void 0 || evals === void 0 ? null : { report: opts.evals.label, digest: evals.digest },
1735
+ languages,
1736
+ pages: pageMetadata,
1737
+ withheld
1738
+ };
1739
+ const manifestPath = join3(opts.outDir, CHUNKS_MANIFEST);
1740
+ writeFileSync(manifestPath, `${canonicalJson(manifest, 2)}
1741
+ `, "utf8");
1742
+ const files = [manifestPath, ...Object.values(languages).map((l) => join3(opts.outDir, l.file))];
1743
+ return { manifestPath, rows: kept.length, withheld: withheld.length, warnings, notices, files };
1744
+ }
1745
+ function languageOf(graph, doc) {
1746
+ const tag = graph.literal(doc, LANGUAGE2);
1747
+ return tag === void 0 ? UNDETERMINED : canonicalLanguageTag(tag);
1748
+ }
1749
+ function passagesOf(graph, page, model, bodyLine, language, metadata, bySection) {
1750
+ const out = [];
1751
+ const fileLines = page.content.split(/\r?\n/);
1752
+ const body = fileLines.slice(bodyLine - 1).join("\n").trimEnd();
1753
+ if (body.trim() !== "") {
1754
+ out.push({
1755
+ id: page.doc,
1756
+ page: page.path,
1757
+ start: 1,
1758
+ end: body.split("\n").length,
1759
+ title: graph.literal(page.doc, TITLE2) ?? page.path,
1760
+ text: body,
1761
+ language,
1762
+ metadata
1763
+ });
1762
1764
  }
1763
- node(iri) {
1764
- return this.nodes.get(iri);
1765
+ const sections = documentSectionOrder(graph, page.doc);
1766
+ const spans = /* @__PURE__ */ new Map();
1767
+ const format = formatOf(page.path, model.format);
1768
+ if (isTreeFormat(format)) {
1769
+ const own = new Map(sectionSpans(graph, page.doc, page.path, page.content, sections).map((s) => [s.iri, s.span]));
1770
+ const levels = sections.map((iri) => Number.parseInt(graph.literal(iri, LEVEL2) ?? "", 10));
1771
+ for (const [i, iri] of sections.entries()) {
1772
+ const span = own.get(iri);
1773
+ if (span === void 0) continue;
1774
+ let end = span.end;
1775
+ for (let j = i + 1; j < sections.length; j++) {
1776
+ const level = levels[j] ?? Number.NaN;
1777
+ if (!(level > (levels[i] ?? Number.NaN))) break;
1778
+ end = Math.max(end, own.get(sections[j] ?? "")?.end ?? end);
1779
+ }
1780
+ spans.set(iri, { start: span.start, end });
1781
+ }
1782
+ } else {
1783
+ const occurrences = sectionOccurrences(graph, page.doc);
1784
+ for (const iri of sections) {
1785
+ const title = graph.literal(iri, TITLE2);
1786
+ if (title === void 0) continue;
1787
+ const level = Number.parseInt(graph.literal(iri, LEVEL2) ?? "", 10);
1788
+ const span = sectionLines(page.content, title, Number.isNaN(level) ? void 0 : level, occurrences.get(iri) ?? 0);
1789
+ if (span !== void 0) spans.set(iri, span);
1790
+ }
1765
1791
  }
1766
- has(iri) {
1767
- return this.nodes.has(iri);
1792
+ const slugs = new Map(model.sections.map((s) => [s.slug, s]));
1793
+ for (const iri of sections) {
1794
+ const span = spans.get(iri);
1795
+ if (span === void 0 || span.start < bodyLine) continue;
1796
+ const text = fileLines.slice(span.start - 1, span.end).join("\n").trimEnd();
1797
+ if (text === "") continue;
1798
+ const chain = [];
1799
+ let slug = iri.slice(iri.indexOf("#") + 1);
1800
+ const seen = /* @__PURE__ */ new Set();
1801
+ while (slug !== null && !seen.has(slug)) {
1802
+ seen.add(slug);
1803
+ chain.unshift(...bySection.get(slug) ?? []);
1804
+ slug = slugs.get(slug)?.parentSlug ?? null;
1805
+ }
1806
+ out.push({
1807
+ id: iri,
1808
+ page: page.path,
1809
+ start: span.start - bodyLine + 1,
1810
+ end: span.start - bodyLine + text.split("\n").length,
1811
+ title: graph.literal(iri, TITLE2) ?? iri,
1812
+ text,
1813
+ language,
1814
+ metadata: Object.assign({}, metadata, ...chain)
1815
+ });
1768
1816
  }
1769
- /** Class IRIs of a node, sorted. */
1770
- types(iri) {
1771
- return this.nodes.get(iri)?.types ?? [];
1817
+ return out;
1818
+ }
1819
+ async function gitState(dir, paths) {
1820
+ let commit;
1821
+ let prefix;
1822
+ try {
1823
+ commit = (await run("git", ["rev-parse", "HEAD"], { cwd: dir })).stdout.trim();
1824
+ prefix = (await run("git", ["rev-parse", "--show-prefix"], { cwd: dir })).stdout.trim();
1825
+ } catch (e) {
1826
+ const stderr = e.stderr;
1827
+ const said = typeof stderr === "string" && stderr.trim() !== "" ? stderr.trim().split(/\r?\n/)[0] ?? "" : errorMessage(e);
1828
+ return { commit: null, dirty: /* @__PURE__ */ new Set(), reason: said.replace(/^fatal:\s*/, "") };
1829
+ }
1830
+ const wanted = new Set(paths);
1831
+ const dirty = /* @__PURE__ */ new Set();
1832
+ const { stdout } = await run("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all", "--", "."], {
1833
+ cwd: dir,
1834
+ maxBuffer: 64 * 1024 * 1024
1835
+ });
1836
+ const entries = stdout.split("\0");
1837
+ for (let i = 0; i < entries.length; i++) {
1838
+ const entry2 = entries[i] ?? "";
1839
+ if (entry2.length < 4) continue;
1840
+ if (entry2[0] === "R" || entry2[0] === "C") i++;
1841
+ const fromRoot = entry2.slice(3);
1842
+ if (!fromRoot.startsWith(prefix)) continue;
1843
+ const path = fromRoot.slice(prefix.length);
1844
+ if (wanted.has(path)) dirty.add(path);
1845
+ }
1846
+ return { commit, dirty };
1847
+ }
1848
+ async function pinsByPage(opts, sources, paths, metadata) {
1849
+ const out = /* @__PURE__ */ new Map();
1850
+ if (paths.length === 0) return out;
1851
+ let reports;
1852
+ try {
1853
+ reports = (await runCheck({
1854
+ inputs: [...paths],
1855
+ cwd: sources,
1856
+ ...opts.source.configPath === void 0 ? {} : { configPath: resolve4(opts.cwd, opts.source.configPath) },
1857
+ ...opts.source.noConfig === void 0 ? {} : { noConfig: opts.source.noConfig }
1858
+ })).pages;
1859
+ } catch (e) {
1860
+ throw new GraphError(errorMessage(e));
1861
+ }
1862
+ for (const report of reports) {
1863
+ const content = readFileSync5(resolve4(sources, report.file), "utf8");
1864
+ const { bodyLine } = bodyOf(content, formatOf(report.file));
1865
+ const list = [];
1866
+ for (const result of report.citations) {
1867
+ const claim = claimLines(result, bodyLine);
1868
+ if (claim === void 0) continue;
1869
+ const entries = metadata.get(report.file)?.["citations"];
1870
+ const raw = Array.isArray(entries) ? entries[result.origin.index] : void 0;
1871
+ const entry2 = typeof raw === "object" && raw !== null ? raw : {};
1872
+ const findings = report.findings.filter((f) => f.index === result.origin.index).map((f) => ({ rule: f.rule, severity: f.severity }));
1873
+ list.push({
1874
+ ...claim,
1875
+ item: {
1876
+ id: result.citation.id ?? null,
1877
+ claim: claim.start === claim.end ? String(claim.start) : `${String(claim.start)}-${String(claim.end)}`,
1878
+ source: result.source.src,
1879
+ commit: result.citation.source["commit-sha"] ?? null,
1880
+ findings,
1881
+ lastVerified: asWritten(entry2["last-verified"]),
1882
+ verifiedBy: entriesOf(entry2["verified-by"])
1883
+ }
1884
+ });
1885
+ }
1886
+ out.set(report.file, list);
1772
1887
  }
1773
- /** Instances of a class, sorted. */
1774
- instancesOf(classIri) {
1775
- return this.byType.get(classIri) ?? [];
1888
+ return out;
1889
+ }
1890
+ function claimLines(result, bodyLine) {
1891
+ const claim = result.claim;
1892
+ if (claim === null) return void 0;
1893
+ const body = claim.status === "moved" && claim.newLines !== void 0 ? claim.newLines : claim.lines;
1894
+ if (body !== void 0) return range(body);
1895
+ if (claim.fileLines === void 0) return void 0;
1896
+ const file = range(claim.fileLines);
1897
+ return file && { start: file.start - bodyLine + 1, end: file.end - bodyLine + 1 };
1898
+ }
1899
+ var RANK = { notice: 1, warning: 2, error: 3 };
1900
+ function summarize(pins, start, end) {
1901
+ const summary = { total: 0, current: 0, notice: 0, warning: 0, error: 0, items: [] };
1902
+ for (const pin of pins) {
1903
+ if (pin.end < start || pin.start > end) continue;
1904
+ summary.total += 1;
1905
+ summary.items.push(pin.item);
1906
+ const worst = pin.item.findings.reduce(
1907
+ (w, f) => w === void 0 || RANK[f.severity] > RANK[w] ? f.severity : w,
1908
+ void 0
1909
+ );
1910
+ if (worst === void 0) summary.current += 1;
1911
+ else summary[worst] += 1;
1776
1912
  }
1777
- /** All values for a predicate, sorted. */
1778
- values(iri, predicate) {
1779
- return this.nodes.get(iri)?.props.get(predicate) ?? [];
1913
+ return summary;
1914
+ }
1915
+ async function datesByPage(opts, sources, paths, inGit) {
1916
+ const out = /* @__PURE__ */ new Map();
1917
+ if (paths.length === 0 || !inGit) return out;
1918
+ let derived;
1919
+ try {
1920
+ derived = await runDerive({
1921
+ inputs: [...paths],
1922
+ cwd: sources,
1923
+ fields: ["created", "last-updated"],
1924
+ sources: ["git"],
1925
+ // `check` judges and writes nothing, and offers no relocation.
1926
+ check: true,
1927
+ // Never read: an uncommitted change's day is dropped below.
1928
+ now: () => /* @__PURE__ */ new Date(0),
1929
+ ...opts.source.configPath === void 0 ? {} : { configPath: resolve4(opts.cwd, opts.source.configPath) },
1930
+ ...opts.source.noConfig === void 0 ? {} : { noConfig: opts.source.noConfig }
1931
+ });
1932
+ } catch (e) {
1933
+ throw new GraphError(errorMessage(e));
1934
+ }
1935
+ for (const result of derived.results) {
1936
+ const content = readFileSync5(resolve4(sources, result.file), "utf8");
1937
+ const page = analyzeDoc(content, result.file, /* @__PURE__ */ new Set([result.file])).frontmatter;
1938
+ const date = (field) => {
1939
+ const f = result.fields.find((x) => x.field === field);
1940
+ const asserted = f?.asserted ?? page[field];
1941
+ const day = f === void 0 || f.evidence === "uncommitted body change" ? null : asWritten(f.derived);
1942
+ if (day === null) return { day, stamp: null };
1943
+ const stamp = asserted === void 0 || asserted === null ? "absent" : f?.status === "current" ? "current" : "stale";
1944
+ return { day, stamp };
1945
+ };
1946
+ out.set(result.file, {
1947
+ created: date("created"),
1948
+ lastUpdated: date("last-updated"),
1949
+ lastVerified: asWritten(page["last-verified"]),
1950
+ verifiedBy: entriesOf(page["verified-by"])
1951
+ });
1780
1952
  }
1781
- /** Literal lexical forms for a predicate, sorted. */
1782
- literals(iri, predicate) {
1783
- return this.values(iri, predicate).filter((v) => v.kind === "literal").map((v) => v.value);
1953
+ return out;
1954
+ }
1955
+ function noDates(page) {
1956
+ return {
1957
+ created: { day: null, stamp: null },
1958
+ lastUpdated: { day: null, stamp: null },
1959
+ lastVerified: asWritten(page["last-verified"]),
1960
+ verifiedBy: entriesOf(page["verified-by"])
1961
+ };
1962
+ }
1963
+ function readEvals(opts, sources, pages, warnings) {
1964
+ if (opts.evals === void 0) return void 0;
1965
+ const { label, path } = opts.evals;
1966
+ if (!existsSync5(path)) throw new GraphError(`graph.export.chunks.evals names ${label}, which does not exist.`);
1967
+ const bytes = readFileSync5(path);
1968
+ const notReport = new GraphError(`${label} is not a docevals JSON report; write one with manni docevals run -f json.`);
1969
+ let parsed;
1970
+ try {
1971
+ parsed = JSON.parse(bytes.toString("utf8"));
1972
+ } catch {
1973
+ throw notReport;
1974
+ }
1975
+ const results = parsed?.evalResults;
1976
+ if (typeof parsed !== "object" || parsed === null || !Array.isArray(results) || typeof parsed.pages !== "number") {
1977
+ throw notReport;
1978
+ }
1979
+ const digest = integrityOf(bytes);
1980
+ const reportBase = opts.config.configSource === null ? opts.cwd : opts.config.configDir;
1981
+ const byPage = /* @__PURE__ */ new Map();
1982
+ const known = new Map(pages.map((p) => [resolve4(sources, p.path), p.path]));
1983
+ const strangers = /* @__PURE__ */ new Set();
1984
+ let anyIntegrity = false;
1985
+ for (const raw of results) {
1986
+ if (typeof raw !== "object" || raw === null) throw notReport;
1987
+ const r = raw;
1988
+ if (typeof r.file !== "string" || typeof r.evalName !== "string" || typeof r.outcome !== "string") throw notReport;
1989
+ if (r.integrity !== void 0) anyIntegrity = true;
1990
+ const page = known.get(resolve4(reportBase, r.file));
1991
+ if (page === void 0) {
1992
+ strangers.add(r.file);
1993
+ continue;
1994
+ }
1995
+ const list = byPage.get(page) ?? [];
1996
+ list.push(r);
1997
+ byPage.set(page, list);
1784
1998
  }
1785
- /** The first literal for a predicate, if any. */
1786
- literal(iri, predicate) {
1787
- return this.literals(iri, predicate)[0];
1999
+ if (results.length > 0 && !anyIntegrity) {
2000
+ warnings.push(`${label} records no page integrity, so every verdict reads stale; write it again with manni docevals run -f json.`);
1788
2001
  }
1789
- /** Outbound IRI targets: all predicates, or one. Sorted. */
1790
- out(iri, predicate) {
1791
- return edges(this.outbound, iri, predicate);
2002
+ const out = /* @__PURE__ */ new Map();
2003
+ out.digest = digest;
2004
+ let changed = 0;
2005
+ for (const page of pages) {
2006
+ const list = byPage.get(page.path);
2007
+ if (list === void 0) continue;
2008
+ const now = integrityOf(Buffer.from(page.content, "utf8"));
2009
+ const current = list.every((r) => r.integrity === now);
2010
+ if (!current && list.some((r) => r.integrity !== void 0)) changed += 1;
2011
+ const count = (outcome) => list.filter((r) => r.outcome === outcome).length;
2012
+ out.set(page.path, {
2013
+ report: digest,
2014
+ current,
2015
+ pass: count("pass"),
2016
+ fail: count("fail"),
2017
+ needsReview: count("needs-review"),
2018
+ skipped: count("skipped"),
2019
+ error: count("error"),
2020
+ items: list.map((r) => ({
2021
+ name: r.evalName,
2022
+ suite: r.suite ?? "",
2023
+ grader: r.grader,
2024
+ outcome: r.outcome,
2025
+ ...typeof r.consensus?.meanConfidence === "number" ? { confidence: r.consensus.meanConfidence } : {}
2026
+ })).sort((a, b) => byCodeUnit(a.suite, b.suite) || byCodeUnit(a.name, b.name))
2027
+ });
1792
2028
  }
1793
- /** Inbound IRI sources (who points at this node). Sorted. */
1794
- in(iri, predicate) {
1795
- return edges(this.inbound, iri, predicate);
2029
+ if (changed > 0) {
2030
+ warnings.push(
2031
+ `${String(changed)} ${changed === 1 ? "page" : "pages"} changed since ${label} was written, so their verdicts read stale.`
2032
+ );
1796
2033
  }
1797
- };
1798
- function addEdge(map, key, predicate, target) {
1799
- let preds = map.get(key);
1800
- if (!preds) {
1801
- preds = /* @__PURE__ */ new Map();
1802
- map.set(key, preds);
1803
- }
1804
- const targets = preds.get(predicate);
1805
- if (targets) targets.push(target);
1806
- else preds.set(predicate, [target]);
1807
- }
1808
- function edges(map, iri, predicate) {
1809
- const preds = map.get(iri);
1810
- if (!preds) return [];
1811
- const out = [];
1812
- const keys = predicate ? [predicate] : [...preds.keys()].sort(byCodeUnit);
1813
- for (const p of keys) {
1814
- for (const target of preds.get(p) ?? []) out.push({ predicate: p, target });
2034
+ if (strangers.size > 0) {
2035
+ const n = strangers.size;
2036
+ warnings.push(
2037
+ `${String(n)} ${n === 1 ? "page" : "pages"} in ${label} ${n === 1 ? "is" : "are"} not in the graph, so their verdicts are left out.`
2038
+ );
1815
2039
  }
1816
2040
  return out;
1817
2041
  }
1818
- function toArray(v) {
1819
- if (v === void 0 || v === null) return [];
1820
- return Array.isArray(v) ? v : [v];
2042
+ function readVectors(dir) {
2043
+ const manifestPath = join3(dir, LOCALIZATIONS_FILENAME);
2044
+ if (!existsSync5(manifestPath)) return void 0;
2045
+ const doc = parseLocalizations(readFileSync5(manifestPath, "utf8"));
2046
+ if (doc === void 0) return void 0;
2047
+ const byId = /* @__PURE__ */ new Map();
2048
+ const models = /* @__PURE__ */ new Map();
2049
+ for (const entry2 of doc.languages) {
2050
+ if (entry2.vectors === void 0) continue;
2051
+ const file = resolve4(dir, entry2.vectors.path);
2052
+ if (!existsSync5(file)) continue;
2053
+ const { header, vectors } = decodeVectorIndex(readFileSync5(file));
2054
+ models.set(canonicalLanguageTag(entry2.language), { id: header.model, dimensions: header.dims });
2055
+ for (const [i, id] of header.ids.entries()) {
2056
+ byId.set(id, Array.from(vectors.subarray(i * header.dims, (i + 1) * header.dims)));
2057
+ }
2058
+ }
2059
+ return models.size === 0 ? void 0 : { models, byId };
2060
+ }
2061
+ function asWritten(value) {
2062
+ if (value instanceof Date) return dateText(value);
2063
+ if (typeof value === "string") return value;
2064
+ return null;
2065
+ }
2066
+ function dateText(d) {
2067
+ const iso = d.toISOString();
2068
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
2069
+ }
2070
+ function entriesOf(value) {
2071
+ if (value === void 0 || value === null) return [];
2072
+ return (Array.isArray(value) ? value : [value]).map(plain);
2073
+ }
2074
+ function plain(value) {
2075
+ if (value instanceof Date) return dateText(value);
2076
+ if (Array.isArray(value)) return value.map(plain);
2077
+ if (typeof value === "object" && value !== null) {
2078
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, plain(v)]));
2079
+ }
2080
+ return value;
2081
+ }
2082
+ function canonicalJson(value, indent) {
2083
+ const sort = (v) => {
2084
+ if (Array.isArray(v)) return v.map(sort);
2085
+ if (typeof v === "object" && v !== null) {
2086
+ return Object.fromEntries(
2087
+ Object.keys(v).sort(byCodeUnit).map((k) => [k, sort(v[k])])
2088
+ );
2089
+ }
2090
+ return v;
2091
+ };
2092
+ return JSON.stringify(sort(value), null, indent);
1821
2093
  }
1822
2094
 
1823
- // src/graph/commands/questions.ts
1824
- var DOCUMENT = `${NS.graph}Document`;
1825
- var SECTION = `${NS.graph}Section`;
1826
- var PATH = `${NS.graph}path`;
1827
- var LEVEL = `${NS.graph}level`;
1828
- var TITLE = `${NS.dcterms}title`;
1829
- var LANGUAGE = `${NS.dcterms}language`;
1830
- var SAMPLE_QUESTION = `${NS.graph}sampleQuestion`;
1831
- var DOCUMENT_TYPE = compactIri(DOCUMENT);
1832
- var SECTION_TYPE = compactIri(SECTION);
1833
- function readManifest(indexDir) {
1834
- const path = join3(indexDir, LOCALIZATIONS_FILENAME);
1835
- if (!existsSync4(path)) return [];
1836
- const manifest = parseLocalizations(readFileSync5(path, "utf8"));
1837
- if (!manifest) {
2095
+ // src/graph/commands/traverse.ts
2096
+ import { resolve as resolve5 } from "node:path";
2097
+ function runTraverse(opts) {
2098
+ const cwd = opts.cwd ?? process.cwd();
2099
+ const config = loadRunConfig(
2100
+ {
2101
+ ...opts.config === void 0 ? {} : { configPath: opts.config },
2102
+ ...opts.noConfig === void 0 ? {} : { noConfig: opts.noConfig }
2103
+ },
2104
+ cwd
2105
+ );
2106
+ const store = loadGraph(resolve5(cwd, opts.graph ?? config.out));
2107
+ const quads = storeToQuads(store);
2108
+ const graph = GraphIndex.fromQuads(quads, Object.fromEntries(PREFIXES));
2109
+ const { node, predicates } = checkTraverseInputs(graph, quads, opts);
2110
+ const direction = opts.reverse ? "in" : "out";
2111
+ const result = opts.impact ? impact(graph, node, {
2112
+ depth: opts.depth,
2113
+ predicates,
2114
+ variant: opts.variant,
2115
+ subject: opts.subject,
2116
+ language: opts.lang,
2117
+ limit: opts.limit
2118
+ }) : traverse(graph, {
2119
+ seeds: [node],
2120
+ depth: opts.depth,
2121
+ predicates,
2122
+ direction,
2123
+ variant: opts.variant,
2124
+ subject: opts.subject,
2125
+ language: opts.lang,
2126
+ limit: opts.limit
2127
+ });
2128
+ return {
2129
+ node,
2130
+ nodes: result.nodes.map((n) => {
2131
+ const title = graph.literal(n.iri, `${NS.dcterms}title`);
2132
+ return title === void 0 ? { iri: n.iri, depth: n.depth } : { iri: n.iri, depth: n.depth, title };
2133
+ }),
2134
+ trace: result.trace
2135
+ };
2136
+ }
2137
+ function checkTraverseInputs(graph, quads, opts) {
2138
+ const node = expandTerm(opts.node);
2139
+ if (!graph.has(node)) {
1838
2140
  throw new GraphError(
1839
- `Not a manni graph localization manifest: ${path} \u2014 re-run \`manni graph export search\`.`
2141
+ `Node not found in the graph: ${opts.node} \u2014 check the IRI, or run \`manni graph build\` first.`,
2142
+ "unknown-node"
1840
2143
  );
1841
2144
  }
1842
- return manifest.languages;
1843
- }
1844
- async function openRetriever(doc, entry2, indexDir) {
1845
- const lexical = createLexicalIndex(doc);
1846
- if (!entry2?.vectors) return { lexical };
1847
- const path = resolve3(indexDir, entry2.vectors.path);
1848
- if (!existsSync4(path)) return { lexical };
1849
- let vectors;
1850
- try {
1851
- vectors = createVectorIndex(readFileSync5(path));
1852
- } catch (e) {
1853
- if (e instanceof VectorIndexError) {
1854
- throw new GraphError(`${e.message} (${path}) \u2014 re-run \`manni graph embed\`.`);
2145
+ checkScope(graph, opts);
2146
+ const predicates = opts.predicates?.map(expandTerm);
2147
+ if (predicates && predicates.length > 0) {
2148
+ const used = /* @__PURE__ */ new Set();
2149
+ for (const quad of quads) {
2150
+ if (quad.o.kind === "iri") used.add(quad.p);
1855
2151
  }
1856
- throw e;
1857
- }
1858
- const source = `sha256:${createHash2("sha256").update(emitSearchIndex(doc), "utf8").digest("hex")}`;
1859
- const stale = vectors.check({ source });
1860
- if (stale) {
1861
- warn(`${stale.detail} Falling back to lexical.`);
1862
- return { lexical };
2152
+ predicates.forEach((predicate, i) => {
2153
+ if (!used.has(predicate)) {
2154
+ throw new GraphError(
2155
+ `Unknown predicate: ${opts.predicates?.[i] ?? predicate}. No edge in the graph uses it.`,
2156
+ "unknown-scope"
2157
+ );
2158
+ }
2159
+ });
1863
2160
  }
1864
- const embedder = await resolveEmbedder(void 0, vectors, false);
1865
- return embedder ? { lexical, vectors, embedder } : { lexical };
1866
- }
1867
- async function rankNodes(question, r) {
1868
- const entry2 = await findEntry(question, {
1869
- lexical: r.lexical,
1870
- ...r.vectors && r.embedder ? { vectors: r.vectors, embedder: r.embedder } : {},
1871
- limit: r.lexical.size()
1872
- }).catch((e) => {
1873
- if (e instanceof VectorMismatchError) {
1874
- throw new GraphError(`${e.message} Re-run \`manni graph embed\`.`);
1875
- }
1876
- throw e;
1877
- });
1878
- return entry2.candidates.flatMap((c) => {
1879
- const type = r.lexical.entry(c.iri)?.type;
1880
- return type === DOCUMENT_TYPE || type === SECTION_TYPE ? [c.iri] : [];
1881
- });
1882
- }
1883
- function pageOf(iri) {
1884
- const hash = iri.indexOf("#");
1885
- return hash < 0 ? iri : iri.slice(0, hash);
2161
+ return { node, predicates };
1886
2162
  }
1887
- function lastLine(position) {
1888
- const { start, end } = position;
1889
- return end.column <= 1 && end.line > start.line ? end.line - 1 : end.line;
2163
+ function checkScope(graph, opts) {
2164
+ if (opts.variant && !resolveVariant(graph, opts.variant)) {
2165
+ throw new GraphError(
2166
+ `Unknown product variant: ${opts.variant} \u2014 no iirds:ProductVariant matches that IRI, title, or slug.`,
2167
+ "unknown-scope"
2168
+ );
2169
+ }
2170
+ if (opts.subject && !resolveSubject(graph, opts.subject)) {
2171
+ throw new GraphError(
2172
+ `Unknown software subject: ${opts.subject} \u2014 expected one of ${Object.keys(SOFTWARE_SUBJECT_IRIS).sort().join(", ")}, or a full IRI.`,
2173
+ "unknown-scope"
2174
+ );
2175
+ }
1890
2176
  }
1891
- function sectionSpans(graph, doc, path, content, sections) {
1892
- const format = formatOf(path);
1893
- const out = [];
1894
- if (isTreeFormat(format)) {
1895
- const known = new Set(sections);
1896
- const minted = mintTreeSections(parseTree(content, path, format).sections);
1897
- for (const [n, section] of minted.sections.entries()) {
1898
- const iri = `${doc}#${section.slug}`;
1899
- const node = minted.nodes[n];
1900
- if (!known.has(iri) || node === void 0) continue;
1901
- const head = node.titlePosition ?? node.position;
1902
- const end = Math.max(
1903
- lastLine(head),
1904
- ...(minted.owned[n] ?? []).map((c) => lastLine(c.position))
2177
+ function renderTraverse(report, format) {
2178
+ if (format === "json") return JSON.stringify(report, null, 2);
2179
+ const lines = [];
2180
+ for (const n of report.nodes) {
2181
+ const indent = " ".repeat(n.depth);
2182
+ const title = n.title ? ` \u2014 ${n.title}` : "";
2183
+ lines.push(`${indent}${compactIri(n.iri)}${title}`);
2184
+ }
2185
+ if (report.nodes.length === 0) lines.push("(no nodes)");
2186
+ if (report.trace.exclusions.length > 0) {
2187
+ lines.push("");
2188
+ lines.push("excluded by scope:");
2189
+ for (const e of report.trace.exclusions) {
2190
+ lines.push(
2191
+ ` ${compactIri(e.node)} \u2014 ${compactIri(e.rule)} ${compactIri(e.value)}`
1905
2192
  );
1906
- out.push({ iri, span: { start: head.start.line, end } });
1907
2193
  }
1908
- return out;
1909
- }
1910
- const occurrences = sectionOccurrences(graph, doc);
1911
- for (const iri of sections) {
1912
- const title = graph.literal(iri, TITLE);
1913
- if (title === void 0) continue;
1914
- const level = Number.parseInt(graph.literal(iri, LEVEL) ?? "", 10);
1915
- const span = sectionOwnLines(
1916
- content,
1917
- title,
1918
- Number.isNaN(level) ? void 0 : level,
1919
- occurrences.get(iri) ?? 0
1920
- );
1921
- if (span) out.push({ iri, span });
1922
2194
  }
1923
- return out;
2195
+ lines.push("");
2196
+ lines.push(
2197
+ `${report.nodes.length} node${report.nodes.length === 1 ? "" : "s"}, ${report.trace.hops.length} hop${report.trace.hops.length === 1 ? "" : "s"}, ${report.trace.exclusions.length} excluded`
2198
+ );
2199
+ return lines.join("\n");
1924
2200
  }
1925
- function bodyOf(content, format) {
1926
- const bodyLine = format === "html" || format === "xml" ? 1 : bodyLineOf(content, locateFrontmatter(content)?.closeEnd ?? 0);
1927
- return { bodyLine, body: splitLines(content).slice(bodyLine - 1) };
2201
+
2202
+ // src/graph/core/pkg.ts
2203
+ import { join as join4 } from "node:path";
2204
+ function bundledShapesPath(moduleUrl) {
2205
+ return join4(packageRoot(moduleUrl), "shapes", "graph", "shapes-1.2.0.ttl");
1928
2206
  }
1929
- function freshness(body, pin) {
1930
- const { lines, integrity } = pin;
1931
- if (integrity === void 0) {
1932
- return lines.end <= body.length ? { state: "current", ranges: [lines] } : { state: "changed" };
1933
- }
1934
- if (pinOfLines(body, lines) === integrity) return { state: "current", ranges: [lines] };
1935
- const length = lines.end - lines.start + 1;
1936
- const { starts } = findWindows(body, length, integrity, void 0, { around: lines.start });
1937
- const ranges = starts.map((start) => ({ start, end: start + length - 1 }));
1938
- if (ranges.length === 0) return { state: "changed" };
1939
- return { state: ranges.length === 1 ? "moved" : "ambiguous", ranges };
2207
+
2208
+ // src/graph/core/shacl.ts
2209
+ import { readFileSync as readFileSync6 } from "node:fs";
2210
+ import { DataFactory, Parser as Parser2, Store as Store2 } from "n3";
2211
+ import SHACLValidator from "rdf-validate-shacl";
2212
+ var SH = "http://www.w3.org/ns/shacl#";
2213
+ var OWL_ONTOLOGY = "http://www.w3.org/2002/07/owl#Ontology";
2214
+ var RDFS_SEE_ALSO = "http://www.w3.org/2000/01/rdf-schema#seeAlso";
2215
+ var FAMILY_SEVERITY = {
2216
+ violation: "error",
2217
+ warning: "warning",
2218
+ info: "notice"
2219
+ };
2220
+ function finding(shaclSeverity, rest) {
2221
+ return { severity: FAMILY_SEVERITY[shaclSeverity], shaclSeverity, ...rest };
1940
2222
  }
1941
- function matchList(ranges) {
1942
- const spelled = ranges.map(spellLines);
1943
- const head = spelled.slice(0, -1);
1944
- const last = spelled[spelled.length - 1] ?? "";
1945
- if (head.length === 0) return `lines ${last} match`;
1946
- const both = head.length === 1 ? "both" : "all";
1947
- return `lines ${head.join(", ")} and ${last} ${both} match`;
2223
+ var SEVERITY_RANK = {
2224
+ error: 0,
2225
+ warning: 1,
2226
+ notice: 2
2227
+ };
2228
+ function compareFindings(a, b) {
2229
+ return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || byCodeUnit(a.focusNode, b.focusNode) || byCodeUnit(a.path ?? "", b.path ?? "") || byCodeUnit(a.message, b.message);
1948
2230
  }
1949
- async function readPages(graph, sources, view, verb) {
1950
- const contents = /* @__PURE__ */ new Map();
1951
- const onDisk = [];
1952
- const byAbs = /* @__PURE__ */ new Map();
1953
- let missing = 0;
1954
- for (const doc of graph.instancesOf(DOCUMENT)) {
1955
- const path = graph.literal(doc, PATH);
1956
- if (path === void 0 || path === STDIN_PATH) continue;
1957
- const abs = resolve3(sources, path);
1958
- if (!existsSync4(abs)) {
1959
- missing += 1;
1960
- continue;
2231
+ function readShapesFile(source) {
2232
+ const { path, label } = typeof source === "string" ? { path: source, label: source } : source;
2233
+ let text;
2234
+ try {
2235
+ text = readFileSync6(path, "utf8");
2236
+ } catch (e) {
2237
+ if (e.code === "ENOENT") {
2238
+ throw new GraphError(
2239
+ `Shapes file not found: ${path}. Fix the path in --shapes or graph.check.shapes. Leave both unset to use the bundled shapes.`
2240
+ );
1961
2241
  }
1962
- contents.set(path, readFileSync5(abs, "utf8"));
1963
- onDisk.push({ doc, path });
1964
- byAbs.set(abs, { doc, path });
1965
- }
1966
- if (missing > 0) {
1967
- warn(
1968
- missing === 1 ? `1 page in the graph is not on disk, so its questions were not ${verb}; run manni graph build.` : `${String(missing)} pages in the graph are not on disk, so their questions were not ${verb}; run manni graph build.`
1969
- );
1970
- }
1971
- const sectionsOf = /* @__PURE__ */ new Map();
1972
- for (const section of graph.instancesOf(SECTION)) {
1973
- const doc = pageOf(section);
1974
- const siblings = sectionsOf.get(doc);
1975
- if (siblings) siblings.push(section);
1976
- else sectionsOf.set(doc, [section]);
2242
+ throw new GraphError(`Failed to read shapes ${path}: ${errorMessage(e)}`);
1977
2243
  }
1978
- const records = /* @__PURE__ */ new Map();
1979
- const record = (doc, path, questions) => {
1980
- const known = records.get(doc);
1981
- if (known) return known;
1982
- const content = contents.get(path) ?? "";
1983
- const { bodyLine, body } = bodyOf(content, formatOf(path));
1984
- const tag = graph.literal(doc, LANGUAGE);
1985
- const page = {
1986
- doc,
1987
- path,
1988
- language: tag === void 0 ? UNDETERMINED : canonicalLanguageTag(tag),
1989
- bodyLine,
1990
- body,
1991
- sections: sectionSpans(graph, doc, path, content, sectionsOf.get(doc) ?? []),
1992
- questions
1993
- };
1994
- records.set(doc, page);
1995
- return page;
1996
- };
1997
- const meta = await openMetaView(view.source, view.cwd, onDisk.map((p) => p.path), sources);
1998
- const pages = [];
1999
- for (const { doc, path } of onDisk) {
2000
- const content = contents.get(path) ?? "";
2001
- const format = formatOf(path);
2002
- const own = metadataOf(content, path, format);
2003
- const { data } = await mergePage(meta, path, own.data, own.present, format);
2004
- const questions = readSampleQuestions(data["sample-questions"]);
2005
- if (questions.length > 0) pages.push(record(doc, path, questions));
2244
+ let quads;
2245
+ try {
2246
+ quads = new Parser2({ format: "text/turtle" }).parse(text);
2247
+ } catch (e) {
2248
+ throw new GraphError(`Failed to parse shapes ${path}: ${errorMessage(e)}`);
2006
2249
  }
2007
- pages.sort((a, b) => byCodeUnit(a.path, b.path));
2250
+ const header = new Store2(quads);
2251
+ const ontology = header.getSubjects(DataFactory.namedNode(`${NS.rdf}type`), DataFactory.namedNode(OWL_ONTOLOGY), null).map((s) => s.value).sort(byCodeUnit)[0];
2252
+ const first = (predicate) => ontology === void 0 ? void 0 : header.getObjects(DataFactory.namedNode(ontology), DataFactory.namedNode(predicate), null).map((o) => o.value).sort(byCodeUnit)[0];
2253
+ const seeAlso = first(RDFS_SEE_ALSO);
2008
2254
  return {
2009
- pages,
2010
- contents,
2011
- pageAt: (abs) => {
2012
- const hit = byAbs.get(abs);
2013
- return hit && record(hit.doc, hit.path, []);
2014
- }
2255
+ label,
2256
+ id: first(`${NS.dcterms}identifier`) ?? label,
2257
+ guide: seeAlso !== void 0 && /^https?:\/\//.test(seeAlso) ? seeAlso : null,
2258
+ quads
2015
2259
  };
2016
2260
  }
2017
- function holdersOf(page, lines) {
2018
- const out = page.sections.filter(({ span }) => span.start <= lines.end && lines.start <= span.end).map(({ iri }) => iri);
2019
- for (let line = lines.start; line <= lines.end; line++) {
2020
- if (!page.sections.some(({ span }) => span.start <= line && line <= span.end)) {
2021
- return [page.doc, ...out];
2261
+ function loadShapes(sources) {
2262
+ const store = new Store2();
2263
+ const files = [];
2264
+ const fileOf = /* @__PURE__ */ new Map();
2265
+ for (const source of sources) {
2266
+ const file = readShapesFile(source);
2267
+ files.push(file);
2268
+ store.addQuads(file.quads);
2269
+ for (const q of file.quads) {
2270
+ if (!fileOf.has(q.subject.value)) fileOf.set(q.subject.value, file);
2022
2271
  }
2023
2272
  }
2024
- return out;
2273
+ return { store, files, fileOf };
2025
2274
  }
2026
- function percent(part, of) {
2027
- return of === 0 ? 0 : Math.floor(part / of * 100);
2275
+ function localName(iri) {
2276
+ const hash = iri.lastIndexOf("#");
2277
+ return iri.slice((hash === -1 ? iri.lastIndexOf("/") : hash) + 1);
2028
2278
  }
2029
- function plural(n, word) {
2030
- return `${String(n)} ${word}${n === 1 ? "" : "s"}`;
2279
+ function shapeText(store, shape, predicate) {
2280
+ const subject = shape.termType === "BlankNode" ? DataFactory.blankNode(shape.value) : DataFactory.namedNode(shape.value);
2281
+ return preferredLiteral(store.getObjects(subject, DataFactory.namedNode(predicate), null));
2031
2282
  }
2032
- function listOf(items) {
2033
- const head = items.slice(0, -1);
2034
- const last = items[items.length - 1] ?? "";
2035
- return head.length === 0 ? last : `${head.join(", ")} and ${last}`;
2283
+ function preferredLiteral(terms) {
2284
+ const literals = terms.flatMap(
2285
+ (t) => t.termType === "Literal" ? [{ value: t.value, language: t.language }] : []
2286
+ );
2287
+ const rank = (lang) => lang === "" ? 0 : lang.startsWith("en") ? 1 : 2;
2288
+ literals.sort(
2289
+ (a, b) => rank(a.language) - rank(b.language) || byCodeUnit(a.language, b.language) || byCodeUnit(a.value, b.value)
2290
+ );
2291
+ return literals[0]?.value ?? null;
2036
2292
  }
2037
- function renderQuestionSummary(s) {
2038
- const homes = [
2039
- ...s.pages > 0 ? [`on ${plural(s.pages, "page")}`] : [],
2040
- ...s.files.length > 0 ? [`in ${listOf(s.files)}`] : []
2041
- ];
2042
- const { reviewed, drafted } = s.found;
2043
- const a = s.answers;
2044
- return [
2045
- `questions ${String(s.total)}: ${String(s.reviewed)} reviewed, ${String(s.drafted)} drafted${homes.length > 0 ? `, ${homes.join(" and ")}` : ""}`,
2046
- ` found ${String(reviewed.inTop)} of ${String(reviewed.of)} reviewed in the top ${String(s.top)} (${String(percent(reviewed.inTop, reviewed.of))}%), ${String(reviewed.first)} first (${String(percent(reviewed.first, reviewed.of))}%)`,
2047
- ...drafted.of > 0 ? [` drafted ${String(drafted.inTop)} of ${String(drafted.of)} in the top ${String(s.top)}, not counted until reviewed`] : [],
2048
- ` answers ${String(a.pinned)} pinned, ${String(a.unreviewed)} not reviewed: ${String(a.current)} current, ${String(a.moved)} moved, ${String(a.changed)} changed; ${String(a.unpinned)} not pinned`,
2049
- ...s.gaps > 0 ? [` gaps ${plural(s.gaps, "question")} the docs don't answer`] : []
2050
- ];
2293
+ function labelOf(store, iri) {
2294
+ return preferredLiteral(
2295
+ store.getObjects(DataFactory.namedNode(iri), DataFactory.namedNode(`${NS.skos}prefLabel`), null)
2296
+ ) ?? compactIri(iri);
2051
2297
  }
2052
- async function askSampleQuestions(store, settings, sources, indexDir, view, questionFiles, configDir) {
2053
- const knob = settings.severity;
2054
- const top = settings.top;
2055
- const sets = questionFiles.map((label) => ({
2056
- label,
2057
- questions: readQuestionFile(resolve3(configDir, label), label)
2058
- }));
2059
- const graph = GraphIndex.fromQuads(storeToQuads(store), Object.fromEntries(PREFIXES));
2060
- const { pages, contents, pageAt } = await readPages(graph, sources, view, "checked");
2061
- const total = pages.reduce((n, p) => n + p.questions.length, 0) + sets.reduce((n, f) => n + f.questions.length, 0);
2062
- if (total === 0) return { findings: [] };
2063
- let byLanguage;
2064
- let manifest = [];
2065
- const retrievers = /* @__PURE__ */ new Map();
2066
- const ranked = /* @__PURE__ */ new Map();
2067
- const rank = async (language, question) => {
2068
- const key = JSON.stringify([language, question]);
2069
- const cached = ranked.get(key);
2070
- if (cached) return cached;
2071
- if (byLanguage === void 0) {
2072
- byLanguage = partitionByLanguage(
2073
- graph,
2074
- buildSearchIndex(graph, sources, { readDoc: (p) => contents.get(p) })
2075
- );
2076
- manifest = readManifest(indexDir);
2077
- }
2078
- let retriever = retrievers.get(language);
2079
- if (!retriever) {
2080
- retriever = await openRetriever(
2081
- byLanguage.get(language) ?? { version: 1, entries: [] },
2082
- manifest.find((l) => canonicalLanguageTag(l.language) === language),
2083
- indexDir
2084
- );
2085
- retrievers.set(language, retriever);
2086
- }
2087
- const nodes = await rankNodes(question, retriever);
2088
- ranked.set(key, nodes);
2089
- return nodes;
2090
- };
2091
- const describe = (iri) => {
2092
- const path = graph.literal(pageOf(iri), PATH) ?? pageOf(iri);
2093
- const title = iri.includes("#") ? graph.literal(iri, TITLE) : void 0;
2094
- return title === void 0 ? path : `${path} \xA7 ${title}`;
2095
- };
2096
- const where = (position, first) => [
2097
- position === 0 ? "it is not found" : `it ranks ${String(position)}`,
2098
- ...first === void 0 ? [] : [`first is ${describe(first)}`]
2099
- ].join("; ");
2100
- const findings = [];
2101
- const reporter = (target) => (kind, message, draft) => {
2102
- const level = kind === "knob" ? knob : kind;
2103
- if (level === "off") return;
2104
- const suffix = draft === "question" ? " (drafted, not reviewed)" : draft === "pin" ? " (answer not reviewed)" : "";
2105
- findings.push({
2106
- severity: draft ? "notice" : level,
2107
- message: `${message}${suffix}`,
2108
- focusNode: target.focusNode,
2109
- ...target.path === void 0 ? {} : { path: target.path },
2110
- docs: target.docs,
2111
- // A retrieval check judges a question, not a shape.
2112
- guidance: null
2113
- });
2114
- };
2115
- const empty = () => ({ inTop: 0, first: 0, of: 0 });
2116
- const summary = {
2117
- total,
2118
- reviewed: 0,
2119
- drafted: 0,
2120
- pages: pages.length,
2121
- files: [...questionFiles],
2122
- top,
2123
- found: { reviewed: empty(), drafted: empty() },
2124
- answers: { pinned: 0, unreviewed: 0, current: 0, moved: 0, changed: 0, unpinned: 0 },
2125
- gaps: 0
2126
- };
2127
- const tally = (reviewed, tests) => {
2128
- if (tests.length === 0) return;
2129
- const count = reviewed ? summary.found.reviewed : summary.found.drafted;
2130
- count.of += 1;
2131
- if (tests.every((p) => p >= 1 && p <= top)) count.inTop += 1;
2132
- if (tests.every((p) => p === 1)) count.first += 1;
2298
+ function quotedList(values) {
2299
+ const quoted = values.map((v) => `"${v}"`);
2300
+ const last = quoted.pop();
2301
+ if (last === void 0) return "";
2302
+ return quoted.length === 0 ? last : `${quoted.join(", ")} and ${last}`;
2303
+ }
2304
+ function shapeGuidance(loaded, shape) {
2305
+ if (shape === null) return null;
2306
+ const file = loaded.fileOf.get(shape.value);
2307
+ if (file === void 0) return null;
2308
+ const named = shape.termType === "NamedNode";
2309
+ return {
2310
+ id: file.id,
2311
+ rule: named ? localName(shape.value) : null,
2312
+ description: named ? shapeText(loaded.store, shape, `${SH}description`) : null,
2313
+ guide: file.guide
2133
2314
  };
2134
- const askPin = async (page, pin, question, language, report, draft, file) => {
2135
- const fresh = freshness(page.body, pin);
2136
- if (fresh.state === "changed") {
2137
- summary.answers.changed += 1;
2138
- const of2 = file === void 0 ? "" : ` of ${file}`;
2139
- const fix = file === void 0 ? "re-pair it with manni graph fill --fields sample-questions and review it" : "re-pin it and review it";
2140
- report(
2141
- "knob",
2142
- `lines ${spellLines(pin.lines)}${of2} no longer hold the answer to "${question}" as pinned, so ${fix}.`,
2143
- draft
2144
- );
2145
- return { position: 0 };
2315
+ }
2316
+ var bundled;
2317
+ function coreGuidance(rule) {
2318
+ bundled ??= loadShapes([bundledShapesPath(import.meta.url)]);
2319
+ const shape = bundled.store.getSubjects(DataFactory.namedNode(`${NS.rdf}type`), DataFactory.namedNode(`${SH}PropertyShape`), null).find((s) => localName(s.value) === rule);
2320
+ return shape === void 0 ? null : shapeGuidance(bundled, shape);
2321
+ }
2322
+ function blameDocs(store, focus) {
2323
+ const pathPred = DataFactory.namedNode(`${NS.graph}path`);
2324
+ const pathOf = (iri) => store.getQuads(DataFactory.namedNode(iri), pathPred, null, null)[0]?.object.value;
2325
+ const found = /* @__PURE__ */ new Set();
2326
+ const visited = /* @__PURE__ */ new Set();
2327
+ const walk = (iri, depth) => {
2328
+ if (visited.has(iri)) return;
2329
+ visited.add(iri);
2330
+ const own = pathOf(iri);
2331
+ if (own !== void 0) {
2332
+ found.add(own);
2333
+ return;
2146
2334
  }
2147
- const [range] = fresh.ranges;
2148
- const inFile = file === void 0 ? "" : ` in ${file}`;
2149
- if (fresh.state === "current") summary.answers.current += 1;
2150
- else summary.answers.moved += 1;
2151
- if (fresh.state === "moved" && range) {
2152
- report(
2153
- "notice",
2154
- `the answer to "${question}"${inFile} moved from lines ${spellLines(pin.lines)} to ${spellLines(range)}, so manni graph fill --fields sample-questions re-pins it.`,
2155
- draft
2156
- );
2157
- } else if (fresh.state === "ambiguous") {
2158
- report(
2159
- "warning",
2160
- `the answer to "${question}"${inFile} moved, and ${matchList(fresh.ranges)}, so pin one of them by hand.`,
2161
- draft
2162
- );
2335
+ const hash = iri.indexOf("#");
2336
+ if (hash !== -1) {
2337
+ const base = pathOf(iri.slice(0, hash));
2338
+ if (base !== void 0) {
2339
+ found.add(base);
2340
+ return;
2341
+ }
2163
2342
  }
2164
- const text = range ? page.body.slice(range.start - 1, range.end).join("\n") : void 0;
2165
- const nodes = await rank(language, question);
2166
- const answering = fresh.ranges.flatMap((r) => holdersOf(page, toFileLines(r, page.bodyLine)));
2167
- const positions = answering.map((iri) => nodes.indexOf(iri) + 1);
2168
- const best = positions.reduce(
2169
- (b, p, i) => p >= 1 && (b.p === 0 || p < b.p) ? { p, i } : b,
2170
- { p: 0, i: 0 }
2171
- );
2172
- if (best.p >= 1 && best.p <= top) return { position: best.p, ...text === void 0 ? {} : { text } };
2173
- const holder = answering[best.i];
2174
- if (holder !== void 0) {
2175
- const title = holder.includes("#") ? graph.literal(holder, TITLE) : void 0;
2176
- const target = file !== void 0 ? `does not find ${describe(holder)}` : title === void 0 ? "does not find this page, whose own text answers it," : `does not find the section that answers it, \xA7 ${title},`;
2177
- report("knob", `"${question}" ${target} in the top ${String(top)} (${where(best.p, nodes[0])})`, draft);
2343
+ if (depth === 0) return;
2344
+ for (const quad of store.getQuads(null, null, DataFactory.namedNode(iri), null)) {
2345
+ if (quad.subject.termType === "NamedNode") {
2346
+ walk(quad.subject.value, depth - 1);
2347
+ }
2178
2348
  }
2179
- return { position: best.p, ...text === void 0 ? {} : { text } };
2180
2349
  };
2181
- const copies = (question, said, report, draft) => {
2182
- const m = said.length === 0 ? void 0 : copiedPairs(question, ...said);
2183
- if (m && m.copied / m.of > COPIED_SHARE) {
2184
- report(
2185
- "notice",
2186
- `"${question}" repeats ${String(m.copied)} of its ${String(m.of)} word pairs from its answer, so it tests matching words more than finding.`,
2187
- draft
2350
+ walk(focus, 2);
2351
+ return [...found].sort();
2352
+ }
2353
+ function broaderEdges(store) {
2354
+ const edges = [];
2355
+ for (const q of store.getQuads(
2356
+ null,
2357
+ DataFactory.namedNode(`${NS.skos}broader`),
2358
+ null,
2359
+ null
2360
+ )) {
2361
+ if (q.object.termType === "NamedNode") {
2362
+ edges.push({ s: q.subject.value, o: q.object.value });
2363
+ }
2364
+ }
2365
+ for (const q of store.getQuads(
2366
+ null,
2367
+ DataFactory.namedNode(`${NS.skos}narrower`),
2368
+ null,
2369
+ null
2370
+ )) {
2371
+ if (q.object.termType === "NamedNode") {
2372
+ edges.push({ s: q.object.value, o: q.subject.value });
2373
+ }
2374
+ }
2375
+ return edges;
2376
+ }
2377
+ function broaderCycles(store) {
2378
+ const adjacency = /* @__PURE__ */ new Map();
2379
+ const selfLoops = /* @__PURE__ */ new Set();
2380
+ for (const { s, o } of broaderEdges(store)) {
2381
+ if (s === o) selfLoops.add(s);
2382
+ const list = adjacency.get(s);
2383
+ if (list) list.push(o);
2384
+ else adjacency.set(s, [o]);
2385
+ if (!adjacency.has(o)) adjacency.set(o, []);
2386
+ }
2387
+ for (const list of adjacency.values()) list.sort();
2388
+ const index = /* @__PURE__ */ new Map();
2389
+ const lowlink = /* @__PURE__ */ new Map();
2390
+ const onStack = /* @__PURE__ */ new Set();
2391
+ const stack = [];
2392
+ const components = [];
2393
+ let counter = 0;
2394
+ const numberOf = (map, node) => {
2395
+ const value = map.get(node);
2396
+ if (value === void 0) {
2397
+ throw new GraphError(
2398
+ `internal: ${node} was visited before it was numbered`
2188
2399
  );
2189
2400
  }
2401
+ return value;
2190
2402
  };
2191
- const asked = [];
2192
- for (const page of pages) {
2193
- const report = reporter({ focusNode: page.doc, path: SAMPLE_QUESTION, docs: [page.path] });
2194
- for (const [n, q] of page.questions.entries()) {
2195
- const drafted = q.reviewed ? void 0 : "question";
2196
- if (q.reviewed) summary.reviewed += 1;
2197
- else summary.drafted += 1;
2198
- asked.push({ key: questionKey(q.question), where: page.path, order: n, text: q.question, report, ...drafted ? { draft: drafted } : {} });
2199
- if (q.answers.length === 0) summary.answers.unpinned += 1;
2200
- const tests = [];
2201
- if (q.answers.length === 0 || q.reviewed && q.answers.every((a) => !a.reviewed)) {
2202
- const nodes = await rank(page.language, q.question);
2203
- const pagesFound = [...new Set(nodes.map(pageOf))];
2204
- const position = pagesFound.indexOf(page.doc) + 1;
2205
- tests.push(position);
2206
- if (position < 1 || position > top) {
2207
- report(
2208
- "knob",
2209
- `"${q.question}" does not find this page in the top ${String(top)} (${where(position, pagesFound[0])})`,
2210
- drafted
2403
+ const nodes = [...adjacency.keys()].sort();
2404
+ for (const root of nodes) {
2405
+ if (index.has(root)) continue;
2406
+ const frames = [[root, 0]];
2407
+ for (let frame = frames.at(-1); frame !== void 0; frame = frames.at(-1)) {
2408
+ const [node, childIdx] = frame;
2409
+ if (childIdx === 0) {
2410
+ index.set(node, counter);
2411
+ lowlink.set(node, counter);
2412
+ counter += 1;
2413
+ stack.push(node);
2414
+ onStack.add(node);
2415
+ }
2416
+ const children = adjacency.get(node) ?? [];
2417
+ const child = children[childIdx];
2418
+ if (child !== void 0) {
2419
+ frame[1] += 1;
2420
+ if (!index.has(child)) {
2421
+ frames.push([child, 0]);
2422
+ } else if (onStack.has(child)) {
2423
+ lowlink.set(
2424
+ node,
2425
+ Math.min(numberOf(lowlink, node), numberOf(index, child))
2211
2426
  );
2212
2427
  }
2213
- }
2214
- const said = [];
2215
- for (const pin of q.answers) {
2216
- const draft = drafted ?? (pin.reviewed ? void 0 : "pin");
2217
- summary.answers.pinned += 1;
2218
- if (draft) summary.answers.unreviewed += 1;
2219
- const { position, text } = await askPin(page, pin, q.question, page.language, report, draft);
2220
- if (text !== void 0) said.push(text);
2221
- if (draft !== "pin") tests.push(position);
2222
- }
2223
- copies(q.question, said, report, drafted);
2224
- tally(q.reviewed, tests);
2225
- }
2226
- }
2227
- for (const set of sets) {
2228
- for (const [n, q] of set.questions.entries()) {
2229
- const report = reporter({ focusNode: `${set.label}:${String(q.line)}`, docs: [set.label] });
2230
- const drafted = q.reviewed ? void 0 : "question";
2231
- if (q.reviewed) summary.reviewed += 1;
2232
- else summary.drafted += 1;
2233
- asked.push({ key: questionKey(q.question), where: set.label, order: n, text: q.question, report, ...drafted ? { draft: drafted } : {} });
2234
- if (q.answers.length === 0) {
2235
- summary.gaps += 1;
2236
- continue;
2237
- }
2238
- const [firstAnswer] = q.answers;
2239
- const firstPage = firstAnswer && pageAt(resolve3(configDir, firstAnswer.file));
2240
- const language = q.language !== void 0 ? canonicalLanguageTag(q.language) : firstPage?.language ?? UNDETERMINED;
2241
- const tests = [];
2242
- const said = [];
2243
- for (const pin of q.answers) {
2244
- const draft = drafted ?? (pin.reviewed ? void 0 : "pin");
2245
- summary.answers.pinned += 1;
2246
- if (draft) summary.answers.unreviewed += 1;
2247
- const abs = resolve3(configDir, pin.file);
2248
- const page = pageAt(abs);
2249
- if (page === void 0) {
2250
- if (existsSync4(abs)) {
2251
- const nodes = await rank(language, q.question);
2252
- report("knob", `"${q.question}" does not find ${pin.file} in the top ${String(top)} (${where(0, nodes[0])})`, draft);
2253
- } else {
2254
- summary.answers.changed += 1;
2255
- report(
2256
- "knob",
2257
- `${pin.file}, which holds the answer to "${q.question}", does not exist, so re-pin or remove the question.`,
2258
- draft
2259
- );
2428
+ } else {
2429
+ if (lowlink.get(node) === index.get(node)) {
2430
+ const component = [];
2431
+ let member;
2432
+ do {
2433
+ member = stack.pop();
2434
+ if (member === void 0) break;
2435
+ onStack.delete(member);
2436
+ component.push(member);
2437
+ } while (member !== node);
2438
+ if (component.length > 1 || selfLoops.has(node)) {
2439
+ components.push(component.sort());
2260
2440
  }
2261
- if (draft !== "pin") tests.push(0);
2262
- continue;
2263
2441
  }
2264
- const { position, text } = await askPin(page, pin, q.question, language, report, draft, pin.file);
2265
- if (text !== void 0) said.push(text);
2266
- if (draft !== "pin") tests.push(position);
2442
+ frames.pop();
2443
+ const parent = frames.at(-1);
2444
+ if (parent) {
2445
+ lowlink.set(
2446
+ parent[0],
2447
+ Math.min(numberOf(lowlink, parent[0]), numberOf(lowlink, node))
2448
+ );
2449
+ }
2267
2450
  }
2268
- copies(q.question, said, report, drafted);
2269
- tally(q.reviewed, tests);
2270
2451
  }
2271
2452
  }
2272
- asked.sort((a, b) => byCodeUnit(a.where, b.where) || a.order - b.order);
2273
- const firstAt = /* @__PURE__ */ new Map();
2274
- for (const copy of asked) {
2275
- if (copy.key === "") continue;
2276
- const first = firstAt.get(copy.key);
2277
- if (first === void 0) firstAt.set(copy.key, copy.where);
2278
- else copy.report("knob", `"${copy.text}" is also asked on ${first}, so keep it where it is answered.`, copy.draft);
2279
- }
2280
- const threshold = settings.foundThreshold;
2281
- const { inTop, of } = summary.found.reviewed;
2282
- if (threshold !== null && of > 0 && inTop / of * 100 < threshold) {
2283
- findings.push({
2284
- severity: "error",
2285
- message: `${String(inTop)} of ${String(of)} reviewed questions are found in the top ${String(top)} (${String(percent(inTop, of))}%), under the ${String(threshold)}% that graph.check.questions.foundThreshold asks for.`,
2286
- focusNode: "questions",
2287
- docs: [],
2288
- guidance: null
2453
+ return components.sort((a, b) => (a[0] ?? "") < (b[0] ?? "") ? -1 : 1);
2454
+ }
2455
+ function broaderClosure(edges, start) {
2456
+ const adjacency = /* @__PURE__ */ new Map();
2457
+ for (const { s, o } of edges) {
2458
+ const list = adjacency.get(s);
2459
+ if (list) list.push(o);
2460
+ else adjacency.set(s, [o]);
2461
+ }
2462
+ const seen = /* @__PURE__ */ new Set();
2463
+ const queue = [...adjacency.get(start) ?? []];
2464
+ for (let node = queue.shift(); node !== void 0; node = queue.shift()) {
2465
+ if (seen.has(node)) continue;
2466
+ seen.add(node);
2467
+ queue.push(...adjacency.get(node) ?? []);
2468
+ }
2469
+ return seen;
2470
+ }
2471
+ function relatedConflicts(store) {
2472
+ const edges = broaderEdges(store);
2473
+ const related = `${NS.skos}related`;
2474
+ const has = (index2, a, b) => index2.get(a)?.has(b) ?? false;
2475
+ const put = (index2, a, b) => {
2476
+ const targets = index2.get(a);
2477
+ if (targets) targets.add(b);
2478
+ else index2.set(a, /* @__PURE__ */ new Set([b]));
2479
+ };
2480
+ const index = (predicate) => {
2481
+ const out = /* @__PURE__ */ new Map();
2482
+ for (const q of store.getQuads(null, DataFactory.namedNode(predicate), null, null)) {
2483
+ if (q.object.termType === "NamedNode") put(out, q.subject.value, q.object.value);
2484
+ }
2485
+ return out;
2486
+ };
2487
+ const relatedIndex = index(related);
2488
+ const broaderIndex = index(`${NS.skos}broader`);
2489
+ const disjointFires = (a, b) => has(relatedIndex, a, b) && has(broaderIndex, a, b) || has(relatedIndex, b, a) && has(broaderIndex, b, a);
2490
+ const closures = /* @__PURE__ */ new Map();
2491
+ const ancestors = (node) => {
2492
+ let found = closures.get(node);
2493
+ if (found === void 0) {
2494
+ found = broaderClosure(edges, node);
2495
+ closures.set(node, found);
2496
+ }
2497
+ return found;
2498
+ };
2499
+ const seen = /* @__PURE__ */ new Map();
2500
+ const findings = [];
2501
+ for (const [s, targets] of [...relatedIndex].sort(([a], [b]) => byCodeUnit(a, b))) {
2502
+ for (const o of [...targets].sort(byCodeUnit)) {
2503
+ const [a, b] = byCodeUnit(s, o) <= 0 ? [s, o] : [o, s];
2504
+ if (has(seen, a, b)) continue;
2505
+ put(seen, a, b);
2506
+ if (disjointFires(a, b)) continue;
2507
+ const bAboveA = ancestors(a).has(b);
2508
+ if (!bAboveA && !ancestors(b).has(a)) continue;
2509
+ const [descendant, ancestor] = bAboveA ? [a, b] : [b, a];
2510
+ findings.push(
2511
+ finding("violation", {
2512
+ message: `"${labelOf(store, ancestor)}" is both related to "${labelOf(store, descendant)}" and one of its ancestors. Remove one link: from \`related-concepts\` or \`related-terms\`, or from the \`broader\` chain between them.`,
2513
+ focusNode: descendant,
2514
+ path: related,
2515
+ docs: [
2516
+ .../* @__PURE__ */ new Set([...blameDocs(store, descendant), ...blameDocs(store, ancestor)])
2517
+ ].sort(byCodeUnit),
2518
+ guidance: coreGuidance("Concept-related")
2519
+ })
2520
+ );
2521
+ }
2522
+ }
2523
+ return findings;
2524
+ }
2525
+ function cycleFindings(store) {
2526
+ return broaderCycles(store).map((members) => {
2527
+ const labels = members.map((m) => labelOf(store, m));
2528
+ return finding("violation", {
2529
+ message: labels.length === 1 ? `${quotedList(labels)} forms a broader cycle with itself, so it is its own ancestor. Remove the \`broader\` or \`narrower\` value that names it.` : `${quotedList(labels)} form a broader cycle, so each is its own ancestor. Remove one \`broader\` or \`narrower\` value on the cycle.`,
2530
+ // `broaderCycles` returns only components of at least one member, so
2531
+ // the first is there; `?? ""` says that without asserting it.
2532
+ focusNode: members[0] ?? "",
2533
+ path: `${NS.skos}broader`,
2534
+ docs: [...new Set(members.flatMap((m) => blameDocs(store, m)))].sort(),
2535
+ guidance: coreGuidance("Concept-broader")
2289
2536
  });
2537
+ });
2538
+ }
2539
+ var SHAPES_1_0_0_COLLISION = "concept carries multiple prefLabels (same slug, different spellings) \u2014 settle on one spelling";
2540
+ function untaggedPrefLabelFindings(store) {
2541
+ const prefLabel = `${NS.skos}prefLabel`;
2542
+ const untagged = /* @__PURE__ */ new Map();
2543
+ for (const q of store.getQuads(null, DataFactory.namedNode(prefLabel), null, null)) {
2544
+ if (q.object.termType !== "Literal" || q.object.language !== "") continue;
2545
+ const spellings = untagged.get(q.subject.value);
2546
+ if (spellings) spellings.add(q.object.value);
2547
+ else untagged.set(q.subject.value, /* @__PURE__ */ new Set([q.object.value]));
2290
2548
  }
2291
- return { findings, summary };
2549
+ return [...untagged].filter(([, spellings]) => spellings.size > 1).map(
2550
+ ([focusNode, spellings]) => finding("warning", {
2551
+ message: `Pages spell this concept ${spellings.size === 2 ? "two" : String(spellings.size)} ways: ${quotedList([...spellings].sort(byCodeUnit))}. Use one spelling on every page that names it.`,
2552
+ focusNode,
2553
+ path: prefLabel,
2554
+ docs: blameDocs(store, focusNode),
2555
+ guidance: coreGuidance("Concept-prefLabel-collision")
2556
+ })
2557
+ );
2292
2558
  }
2293
- async function exportSampleQuestions(store, sources, view, questionFiles, configDir) {
2294
- const sets = questionFiles.map((label) => ({
2295
- label,
2296
- questions: readQuestionFile(resolve3(configDir, label), label)
2297
- }));
2298
- const graph = GraphIndex.fromQuads(storeToQuads(store), Object.fromEntries(PREFIXES));
2299
- const { pages, pageAt } = await readPages(graph, sources, view, "exported");
2300
- let stale = 0;
2301
- const pinned = (page, file, pin, reviewed) => {
2302
- const fresh = freshness(page.body, pin);
2303
- const range = fresh.state === "changed" ? pin.lines : fresh.ranges[0] ?? pin.lines;
2304
- if (fresh.state === "changed") stale += 1;
2305
- const first = toFileLines({ start: range.start, end: range.start }, page.bodyLine);
2306
- const text = page.body.slice(range.start - 1, range.end).join("\n");
2307
- return {
2308
- id: holdersOf(page, first)[0] ?? page.doc,
2309
- file,
2310
- lines: spellLines(range),
2311
- reviewed,
2312
- ...fresh.state === "changed" ? { stale: true } : {},
2313
- ...text === "" ? {} : { text }
2314
- };
2315
- };
2316
- const lines = [];
2317
- const write = (id, question, language, reviewed, expected) => {
2318
- lines.push(
2319
- JSON.stringify({ id, question, language, reviewed, answerable: expected.length > 0, expected })
2320
- );
2321
- };
2322
- for (const page of pages) {
2323
- const slugger = new GithubSlugger();
2324
- for (const q of page.questions) {
2325
- const expected = q.answers.length === 0 ? [{ id: page.doc, file: page.path, reviewed: q.reviewed }] : q.answers.map((pin) => pinned(page, page.path, pin, q.reviewed && pin.reviewed));
2326
- write(`${page.path}#${slugger.slug(q.question)}`, q.question, page.language, q.reviewed, expected);
2559
+ var MAPPINGS = [
2560
+ ["exactMatch", "exact-matches"],
2561
+ ["closeMatch", "close-matches"],
2562
+ ["broadMatch", "broad-matches"],
2563
+ ["narrowMatch", "narrow-matches"],
2564
+ ["relatedMatch", "related-matches"]
2565
+ ];
2566
+ function inSchemeMappingFindings(store) {
2567
+ const inScheme = DataFactory.namedNode(`${NS.skos}inScheme`);
2568
+ const findings = [];
2569
+ for (const [mapping, key] of MAPPINGS) {
2570
+ const path = `${NS.skos}${mapping}`;
2571
+ for (const q of store.getQuads(null, DataFactory.namedNode(path), null, null)) {
2572
+ if (q.object.termType !== "NamedNode") continue;
2573
+ const schemes = new Set(store.getObjects(q.subject, inScheme, null).map((o) => o.value));
2574
+ const shared = store.getObjects(q.object, inScheme, null).some((o) => schemes.has(o.value));
2575
+ if (!shared) continue;
2576
+ findings.push(
2577
+ finding("violation", {
2578
+ message: `\`${key}\` names "${labelOf(store, q.object.value)}", a concept in this glossary. Use \`broader\`, \`narrower\` or \`related-terms\` for it instead.`,
2579
+ focusNode: q.subject.value,
2580
+ path,
2581
+ docs: blameDocs(store, q.subject.value),
2582
+ guidance: coreGuidance(`Concept-${mapping}`)
2583
+ })
2584
+ );
2327
2585
  }
2328
2586
  }
2329
- for (const set of sets) {
2330
- const slugger = new GithubSlugger();
2331
- for (const q of set.questions) {
2332
- const expected = q.answers.map((pin) => {
2333
- const reviewed = q.reviewed && pin.reviewed;
2334
- const abs = resolve3(configDir, pin.file);
2335
- const page = pageAt(abs);
2336
- if (page) return pinned(page, pin.file, pin, reviewed);
2337
- const gone = !existsSync4(abs);
2338
- if (gone) stale += 1;
2339
- return { file: pin.file, lines: spellLines(pin.lines), reviewed, ...gone ? { stale: true } : {} };
2340
- });
2341
- const [firstAnswer] = q.answers;
2342
- const firstPage = firstAnswer && pageAt(resolve3(configDir, firstAnswer.file));
2343
- const language = q.language !== void 0 ? canonicalLanguageTag(q.language) : firstPage?.language ?? UNDETERMINED;
2344
- write(`${set.label}#${slugger.slug(q.question)}`, q.question, language, q.reviewed, expected);
2587
+ return findings;
2588
+ }
2589
+ var CURATED_FIELDS = /* @__PURE__ */ new Set(["sections", "revision-of", "derived-from"]);
2590
+ var GRAPH_FILL_FRAGMENT = "#prov.graph-fill.";
2591
+ function curatedFieldFindings(store) {
2592
+ const filledField = `${NS.graph}filledField`;
2593
+ const pathPred = DataFactory.namedNode(`${NS.graph}path`);
2594
+ const findings = [];
2595
+ for (const q of store.getQuads(null, DataFactory.namedNode(filledField), null, null)) {
2596
+ if (q.object.termType !== "Literal") continue;
2597
+ const field = q.object.value;
2598
+ if (!CURATED_FIELDS.has(field)) continue;
2599
+ const node = q.subject.value;
2600
+ const at = node.indexOf(GRAPH_FILL_FRAGMENT);
2601
+ const fieldAt = node.lastIndexOf(".field.");
2602
+ if (at === -1 || fieldAt <= at) continue;
2603
+ const activity = node.slice(0, fieldAt);
2604
+ const model = node.slice(at + GRAPH_FILL_FRAGMENT.length, fieldAt);
2605
+ const docIri = activity.slice(0, activity.indexOf("#"));
2606
+ const path = store.getQuads(DataFactory.namedNode(docIri), pathPred, null, null)[0]?.object.value;
2607
+ findings.push(
2608
+ finding("violation", {
2609
+ message: `\`meta-provenance\` credits ${model} with /graph/${field}, a field only a person writes. Check the value, then delete that entry.`,
2610
+ focusNode: activity,
2611
+ path: filledField,
2612
+ docs: path === void 0 ? blameDocs(store, activity) : [path],
2613
+ guidance: coreGuidance("FilledFieldEntry-name")
2614
+ })
2615
+ );
2616
+ }
2617
+ return findings;
2618
+ }
2619
+ function severityOf(iri) {
2620
+ if (iri === "http://www.w3.org/ns/shacl#Warning") return "warning";
2621
+ if (iri === "http://www.w3.org/ns/shacl#Info") return "info";
2622
+ return "violation";
2623
+ }
2624
+ async function validateGraph(store, shapesPaths) {
2625
+ const shapes = loadShapes(shapesPaths);
2626
+ const validator = new SHACLValidator(shapes.store);
2627
+ let report;
2628
+ try {
2629
+ report = await validator.validate(store);
2630
+ } catch (e) {
2631
+ throw new GraphError(
2632
+ `SHACL validation failed: ${errorMessage(e)}`
2633
+ );
2634
+ }
2635
+ const merged = /* @__PURE__ */ new Map();
2636
+ const groups = [];
2637
+ for (const result of report.results) {
2638
+ const focus = result.focusNode?.value ?? "";
2639
+ const path = result.path?.value;
2640
+ const messages = result.message.map((m) => m.value).filter((m) => m.length > 0);
2641
+ const declared = result.sourceShape === null ? null : shapeText(shapes.store, result.sourceShape, `${SH}message`);
2642
+ const message = declared !== null && !/\{[$?]/.test(declared) ? declared : messages.length > 0 ? messages.join("; ") : `constraint violated${path ? ` on ${compactIri(path)}` : ""}`;
2643
+ const byFocus = merged.get(result.sourceShape?.value ?? "") ?? /* @__PURE__ */ new Map();
2644
+ merged.set(result.sourceShape?.value ?? "", byFocus);
2645
+ const byPath = byFocus.get(focus) ?? /* @__PURE__ */ new Map();
2646
+ byFocus.set(focus, byPath);
2647
+ const earlier = byPath.get(path ?? "");
2648
+ if (earlier !== void 0) {
2649
+ if (!earlier.messages.includes(message)) earlier.messages.push(message);
2650
+ continue;
2345
2651
  }
2652
+ const found = finding(severityOf(result.severity?.value), {
2653
+ message,
2654
+ focusNode: focus,
2655
+ ...path !== void 0 ? { path } : {},
2656
+ docs: blameDocs(store, focus),
2657
+ guidance: shapeGuidance(shapes, result.sourceShape)
2658
+ });
2659
+ const group = { found, messages: [message] };
2660
+ byPath.set(path ?? "", group);
2661
+ groups.push(group);
2346
2662
  }
2347
- return { lines, stale };
2663
+ const findings = groups.map(({ found, messages }) => ({ ...found, message: messages.join("; ") }));
2664
+ const said = new Set(
2665
+ findings.filter((f) => f.message === SHAPES_1_0_0_COLLISION).map((f) => f.focusNode)
2666
+ );
2667
+ findings.push(
2668
+ ...cycleFindings(store),
2669
+ ...relatedConflicts(store),
2670
+ ...curatedFieldFindings(store),
2671
+ ...inSchemeMappingFindings(store),
2672
+ ...untaggedPrefLabelFindings(store).filter((f) => !said.has(f.focusNode))
2673
+ );
2674
+ findings.sort(compareFindings);
2675
+ return findings;
2348
2676
  }
2349
2677
 
2350
2678
  export {
@@ -2353,12 +2681,7 @@ export {
2353
2681
  storeToQuads,
2354
2682
  expandTerm,
2355
2683
  compactIri,
2356
- bundledShapesPath,
2357
- compareFindings,
2358
- loadShapes,
2359
- localName,
2360
- shapeText,
2361
- validateGraph,
2684
+ emitJsonLd,
2362
2685
  splitFragment,
2363
2686
  documentSectionOrder,
2364
2687
  sectionOccurrences,
@@ -2371,23 +2694,12 @@ export {
2371
2694
  emitSearchIndex,
2372
2695
  partitionByLanguage,
2373
2696
  documentsByLanguage,
2374
- VectorIndexError,
2375
- normalize,
2376
- encodeVectorIndex,
2377
- decodeVectorIndex,
2378
- VectorMismatchError,
2379
- searchIndexDigest,
2380
- createVectorIndex,
2381
- createTrace,
2382
- reachedNodes,
2383
- rrfMerge,
2384
- findEntry,
2385
- GraphIndex,
2386
- createLexicalIndex,
2387
2697
  EmbedderUnavailableError,
2388
2698
  createLocalEmbedder,
2389
2699
  createMockEmbedder,
2390
2700
  SEARCH_MODES,
2701
+ noIndexFor,
2702
+ langRequired,
2391
2703
  runSearch,
2392
2704
  renderSearch,
2393
2705
  bodyOf,
@@ -2395,6 +2707,18 @@ export {
2395
2707
  matchList,
2396
2708
  renderQuestionSummary,
2397
2709
  askSampleQuestions,
2398
- exportSampleQuestions
2710
+ exportSampleQuestions,
2711
+ CHUNKS_MANIFEST,
2712
+ exportChunks,
2713
+ runTraverse,
2714
+ checkTraverseInputs,
2715
+ checkScope,
2716
+ renderTraverse,
2717
+ bundledShapesPath,
2718
+ compareFindings,
2719
+ loadShapes,
2720
+ localName,
2721
+ shapeText,
2722
+ validateGraph
2399
2723
  };
2400
- //# sourceMappingURL=chunk-B3XXCDYW.js.map
2724
+ //# sourceMappingURL=chunk-VV4YM6VM.js.map