@unbrained/pm-cli 2026.6.7 → 2026.6.8

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 (460) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +42 -0
  4. package/CONTRIBUTING.md +1 -1
  5. package/README.md +1 -1
  6. package/dist/cli/bootstrap-args.js +30 -13
  7. package/dist/cli/bootstrap-args.js.map +1 -1
  8. package/dist/cli/commands/close-many.js +9 -3
  9. package/dist/cli/commands/close-many.js.map +1 -1
  10. package/dist/cli/commands/close.js +15 -3
  11. package/dist/cli/commands/close.js.map +1 -1
  12. package/dist/cli/commands/comments-audit.js +4 -3
  13. package/dist/cli/commands/comments-audit.js.map +1 -1
  14. package/dist/cli/commands/completion.js +40 -33
  15. package/dist/cli/commands/completion.js.map +1 -1
  16. package/dist/cli/commands/extension/scaffold.js +6 -14
  17. package/dist/cli/commands/extension/scaffold.js.map +1 -1
  18. package/dist/cli/commands/gc.js +10 -2
  19. package/dist/cli/commands/gc.js.map +1 -1
  20. package/dist/cli/commands/health.js +10 -2
  21. package/dist/cli/commands/health.js.map +1 -1
  22. package/dist/cli/commands/index.d.ts +1 -1
  23. package/dist/cli/commands/index.js +3 -3
  24. package/dist/cli/commands/index.js.map +1 -1
  25. package/dist/cli/commands/init.d.ts +1 -0
  26. package/dist/cli/commands/init.js +48 -2
  27. package/dist/cli/commands/init.js.map +1 -1
  28. package/dist/cli/commands/list.d.ts +11 -2
  29. package/dist/cli/commands/list.js +104 -2
  30. package/dist/cli/commands/list.js.map +1 -1
  31. package/dist/cli/commands/normalize.js +6 -4
  32. package/dist/cli/commands/normalize.js.map +1 -1
  33. package/dist/cli/commands/schema.d.ts +13 -2
  34. package/dist/cli/commands/schema.js +66 -12
  35. package/dist/cli/commands/schema.js.map +1 -1
  36. package/dist/cli/commands/search.d.ts +10 -2
  37. package/dist/cli/commands/search.js +94 -5
  38. package/dist/cli/commands/search.js.map +1 -1
  39. package/dist/cli/commands/upgrade.js +4 -12
  40. package/dist/cli/commands/upgrade.js.map +1 -1
  41. package/dist/cli/main.js +7 -18
  42. package/dist/cli/main.js.map +1 -1
  43. package/dist/cli/register-list-query.js +5 -3
  44. package/dist/cli/register-list-query.js.map +1 -1
  45. package/dist/cli/register-mutation.js +33 -24
  46. package/dist/cli/register-mutation.js.map +1 -1
  47. package/dist/cli/register-setup.js +4 -2
  48. package/dist/cli/register-setup.js.map +1 -1
  49. package/dist/cli/registration-helpers.js +7 -3
  50. package/dist/cli/registration-helpers.js.map +1 -1
  51. package/dist/cli-bundle/chunks/activity-A3QKFSSF.js +16 -0
  52. package/dist/cli-bundle/chunks/{activity-YVB3QRTE.js → activity-Q7XMIZIH.js} +11 -11
  53. package/dist/cli-bundle/chunks/{aggregate-LH66F75F.js → aggregate-GBSHSXOB.js} +10 -10
  54. package/dist/cli-bundle/chunks/{aggregate-OHSWFQJM.js → aggregate-HKQJZUBG.js} +10 -10
  55. package/dist/cli-bundle/chunks/{append-2PPYFAG5.js → append-3RFOU7P5.js} +8 -8
  56. package/dist/cli-bundle/chunks/{append-AUGT5W6J.js → append-OM74OJVT.js} +8 -8
  57. package/dist/cli-bundle/chunks/{chunk-HRMHZ4RV.js → chunk-2BYKYPWY.js} +2 -2
  58. package/dist/cli-bundle/chunks/{chunk-TP4DDY27.js → chunk-2HMD3JM2.js} +6 -6
  59. package/dist/cli-bundle/chunks/{chunk-4CHEG6UK.js → chunk-2YPVCD7T.js} +8 -8
  60. package/dist/cli-bundle/chunks/{chunk-WAA7UI6M.js → chunk-3E3MDBTB.js} +10 -14
  61. package/dist/cli-bundle/chunks/chunk-3E3MDBTB.js.map +7 -0
  62. package/dist/cli-bundle/chunks/{chunk-UJUT6AHZ.js → chunk-3TXWDGPU.js} +48 -12
  63. package/dist/cli-bundle/chunks/chunk-3TXWDGPU.js.map +7 -0
  64. package/dist/cli-bundle/chunks/{chunk-UT6WFXW2.js → chunk-4TI3532H.js} +2 -2
  65. package/dist/cli-bundle/chunks/{chunk-KNGVP5WJ.js → chunk-4WYBLB6J.js} +3 -3
  66. package/dist/cli-bundle/chunks/{chunk-V6EYFTRL.js → chunk-5NVJA7IW.js} +7 -7
  67. package/dist/cli-bundle/chunks/{chunk-42LOFGJS.js → chunk-5WO2VKFA.js} +108 -9
  68. package/dist/cli-bundle/chunks/chunk-5WO2VKFA.js.map +7 -0
  69. package/dist/cli-bundle/chunks/{chunk-QQL5QSTZ.js → chunk-7NQIY7Z6.js} +6 -5
  70. package/dist/cli-bundle/chunks/chunk-7NQIY7Z6.js.map +1 -0
  71. package/dist/cli-bundle/chunks/{chunk-KR6R465K.js → chunk-7WXGR44E.js} +5 -5
  72. package/dist/cli-bundle/chunks/{chunk-KR6R465K.js.map → chunk-7WXGR44E.js.map} +2 -2
  73. package/dist/cli-bundle/chunks/{chunk-WYEXLDDY.js → chunk-AEMKH5WQ.js} +3 -3
  74. package/dist/cli-bundle/chunks/{chunk-XS3O2TFJ.js → chunk-ALSRBNYB.js} +8 -8
  75. package/dist/cli-bundle/chunks/chunk-ALSRBNYB.js.map +1 -0
  76. package/dist/cli-bundle/chunks/{chunk-OKSKJKHX.js → chunk-AXBUHLW7.js} +9 -9
  77. package/dist/cli-bundle/chunks/{chunk-UEWA73ZZ.js → chunk-BFJPMUF5.js} +5 -5
  78. package/dist/cli-bundle/chunks/{chunk-B5RF3IP7.js → chunk-BKQMJXWY.js} +3 -3
  79. package/dist/cli-bundle/chunks/{chunk-HV5SSZXF.js → chunk-CBJXWXI5.js} +2 -2
  80. package/dist/cli-bundle/chunks/{chunk-NHR2QXXZ.js → chunk-D7WK2PKB.js} +20 -8
  81. package/dist/cli-bundle/chunks/chunk-D7WK2PKB.js.map +1 -0
  82. package/dist/cli-bundle/chunks/{chunk-MWRS7Z4P.js → chunk-DV27WDA7.js} +15 -13
  83. package/dist/cli-bundle/chunks/chunk-DV27WDA7.js.map +7 -0
  84. package/dist/cli-bundle/chunks/{chunk-LI65XLJR.js → chunk-EPWT7BEA.js} +8 -8
  85. package/dist/cli-bundle/chunks/{chunk-LMTOY5HE.js → chunk-ETZZU5QF.js} +2 -2
  86. package/dist/cli-bundle/chunks/{chunk-XYNT7UFP.js → chunk-F33AQIB4.js} +6 -6
  87. package/dist/cli-bundle/chunks/{chunk-XYNT7UFP.js.map → chunk-F33AQIB4.js.map} +1 -1
  88. package/dist/cli-bundle/chunks/{chunk-LIN2BPJ7.js → chunk-F33VC5EX.js} +2 -2
  89. package/dist/cli-bundle/chunks/{chunk-SFFVGNHC.js → chunk-FGRJZVXD.js} +3 -3
  90. package/dist/cli-bundle/chunks/{chunk-HLC3KTLP.js → chunk-FO2TYSQZ.js} +2 -2
  91. package/dist/cli-bundle/chunks/{chunk-3A2CMEM7.js → chunk-HOA3GMB6.js} +4 -4
  92. package/dist/cli-bundle/chunks/{chunk-HMMMWBK2.js → chunk-HP35AVFS.js} +2 -2
  93. package/dist/cli-bundle/chunks/{chunk-AVJD6VTA.js → chunk-J4DKAGTM.js} +3 -3
  94. package/dist/cli-bundle/chunks/{chunk-YO3THIJF.js → chunk-JS47EKLP.js} +7 -7
  95. package/dist/cli-bundle/chunks/{chunk-2IXCHCLM.js → chunk-K62SNVVE.js} +2 -2
  96. package/dist/cli-bundle/chunks/{chunk-IMCJBN2Q.js → chunk-KBKJVXUS.js} +19 -7
  97. package/dist/cli-bundle/chunks/chunk-KBKJVXUS.js.map +7 -0
  98. package/dist/cli-bundle/chunks/{chunk-CLD3XNCH.js → chunk-KCGMABHM.js} +14 -12
  99. package/dist/cli-bundle/chunks/chunk-KCGMABHM.js.map +1 -0
  100. package/dist/cli-bundle/chunks/{chunk-H7EO3QA3.js → chunk-KN4WSESY.js} +5 -5
  101. package/dist/cli-bundle/chunks/{chunk-C5W2UH56.js → chunk-KP4KIUQT.js} +3 -3
  102. package/dist/cli-bundle/chunks/{chunk-YPH4ESA2.js → chunk-KS2U7BZ3.js} +11 -6
  103. package/dist/cli-bundle/chunks/chunk-KS2U7BZ3.js.map +1 -0
  104. package/dist/cli-bundle/chunks/{chunk-GPXQBR3H.js → chunk-KVXIQDJG.js} +12 -12
  105. package/dist/cli-bundle/chunks/{chunk-NQL32HQ5.js → chunk-L3LYL3ID.js} +12 -12
  106. package/dist/cli-bundle/chunks/{chunk-WCQZBDDH.js → chunk-M7UBTVFT.js} +3 -3
  107. package/dist/cli-bundle/chunks/{chunk-3EOBJOF4.js → chunk-MSH23UWO.js} +4 -4
  108. package/dist/cli-bundle/chunks/{chunk-UAQOQ7IE.js → chunk-N4SQZ7L3.js} +2 -2
  109. package/dist/cli-bundle/chunks/{chunk-FY6Z3FYY.js → chunk-NDSMKB2I.js} +3 -3
  110. package/dist/cli-bundle/chunks/{chunk-2IF7WLB7.js → chunk-NGEEXR2R.js} +2 -2
  111. package/dist/cli-bundle/chunks/{chunk-UIIQC5YO.js → chunk-NLVCMVC7.js} +2 -2
  112. package/dist/cli-bundle/chunks/{chunk-LQHBENVW.js → chunk-NUKHZZNM.js} +3 -3
  113. package/dist/cli-bundle/chunks/{chunk-YBZW2QQ7.js → chunk-ODN53S6H.js} +6 -6
  114. package/dist/cli-bundle/chunks/{chunk-LXO6V66E.js → chunk-OTY2YEH5.js} +12 -12
  115. package/dist/cli-bundle/chunks/{chunk-6RZXO5M2.js → chunk-OVSSE2JP.js} +8 -8
  116. package/dist/cli-bundle/chunks/{chunk-4GHZR3BA.js → chunk-PQDH3S54.js} +10 -14
  117. package/dist/cli-bundle/chunks/chunk-PQDH3S54.js.map +1 -0
  118. package/dist/cli-bundle/chunks/{chunk-R3V3YCMH.js → chunk-QF4OPBAG.js} +9 -9
  119. package/dist/cli-bundle/chunks/{chunk-FHHBD7PN.js → chunk-QFVASU44.js} +2 -2
  120. package/dist/cli-bundle/chunks/{chunk-SQPKRA54.js → chunk-QQPZYP73.js} +12 -12
  121. package/dist/cli-bundle/chunks/{chunk-5AXMRKN5.js → chunk-QWNUDGFQ.js} +8 -8
  122. package/dist/cli-bundle/chunks/{chunk-TYJJOTUA.js → chunk-R4XIE7NQ.js} +54 -8
  123. package/dist/cli-bundle/chunks/chunk-R4XIE7NQ.js.map +1 -0
  124. package/dist/cli-bundle/chunks/{chunk-O7HSSFCC.js → chunk-RISLL7XH.js} +10 -5
  125. package/dist/cli-bundle/chunks/{chunk-O7HSSFCC.js.map → chunk-RISLL7XH.js.map} +2 -2
  126. package/dist/cli-bundle/chunks/{chunk-6J4K6JLA.js → chunk-SDLEYY6A.js} +3 -3
  127. package/dist/cli-bundle/chunks/{chunk-TINUJMWN.js → chunk-SM3RMWGO.js} +109 -10
  128. package/dist/cli-bundle/chunks/chunk-SM3RMWGO.js.map +1 -0
  129. package/dist/cli-bundle/chunks/{chunk-MOYM2C3J.js → chunk-TBLBEOEX.js} +9 -9
  130. package/dist/cli-bundle/chunks/{chunk-WR5567FH.js → chunk-TXKENAQP.js} +5 -4
  131. package/dist/cli-bundle/chunks/chunk-TXKENAQP.js.map +7 -0
  132. package/dist/cli-bundle/chunks/{chunk-TNPBPNII.js → chunk-UEXNNF3K.js} +7 -7
  133. package/dist/cli-bundle/chunks/{chunk-RVPTZKBC.js → chunk-UMMJAJB2.js} +9 -9
  134. package/dist/cli-bundle/chunks/{chunk-THDEID2Z.js → chunk-URJEZOLB.js} +2 -2
  135. package/dist/cli-bundle/chunks/{chunk-M2PW7EZU.js → chunk-VXBUXLVD.js} +7 -7
  136. package/dist/cli-bundle/chunks/chunk-VXBUXLVD.js.map +7 -0
  137. package/dist/cli-bundle/chunks/{chunk-UYQ7HXH4.js → chunk-XEKZCBCS.js} +3 -3
  138. package/dist/cli-bundle/chunks/{chunk-2OJHLWBZ.js → chunk-XLSQ3QLT.js} +2 -2
  139. package/dist/cli-bundle/chunks/{chunk-X7UHMKPE.js → chunk-XNGMIVQY.js} +3 -3
  140. package/dist/cli-bundle/chunks/{chunk-B2KZGPM2.js → chunk-XZS4MV37.js} +2 -2
  141. package/dist/cli-bundle/chunks/{chunk-GNIUOLZ2.js → chunk-YEFOCDIK.js} +7 -7
  142. package/dist/cli-bundle/chunks/{chunk-X4IZKYHP.js → chunk-YJAKN2N2.js} +46 -10
  143. package/dist/cli-bundle/chunks/chunk-YJAKN2N2.js.map +1 -0
  144. package/dist/cli-bundle/chunks/{chunk-GUZBNB3G.js → chunk-Z2HXAFFH.js} +2 -2
  145. package/dist/cli-bundle/chunks/{chunk-CKLBZHS7.js → chunk-Z55JACL2.js} +53 -7
  146. package/dist/cli-bundle/chunks/chunk-Z55JACL2.js.map +7 -0
  147. package/dist/cli-bundle/chunks/{claim-KW743OSW.js → claim-NHBIIBOW.js} +10 -10
  148. package/dist/cli-bundle/chunks/{claim-BJ4QMPJC.js → claim-RNEBQCOO.js} +10 -10
  149. package/dist/cli-bundle/chunks/close-UNTFXVM3.js +13 -0
  150. package/dist/cli-bundle/chunks/{close-SYHSRZDC.js → close-ZMXL2WDS.js} +8 -8
  151. package/dist/cli-bundle/chunks/{close-many-LAC5VR4G.js → close-many-CDPQGQUB.js} +24 -18
  152. package/dist/cli-bundle/chunks/close-many-CDPQGQUB.js.map +1 -0
  153. package/dist/cli-bundle/chunks/{close-many-DBLEYFOY.js → close-many-IQV5C2SI.js} +23 -17
  154. package/dist/cli-bundle/chunks/close-many-IQV5C2SI.js.map +7 -0
  155. package/dist/cli-bundle/chunks/{comments-JEO6HHVM.js → comments-EFVBHWPT.js} +10 -10
  156. package/dist/cli-bundle/chunks/{comments-YT2PQ5DD.js → comments-J5Q4IJPH.js} +10 -10
  157. package/dist/cli-bundle/chunks/{config-RZRVS3ZV.js → config-72253M2O.js} +10 -11
  158. package/dist/cli-bundle/chunks/config-72253M2O.js.map +1 -0
  159. package/dist/cli-bundle/chunks/{config-YJSAAADD.js → config-VFYA6BMI.js} +9 -10
  160. package/dist/cli-bundle/chunks/config-VFYA6BMI.js.map +7 -0
  161. package/dist/cli-bundle/chunks/{context-LGYEEKAW.js → context-AVLO4IFH.js} +13 -13
  162. package/dist/cli-bundle/chunks/{context-ZUH5IOOI.js → context-WMSI2D65.js} +13 -13
  163. package/dist/cli-bundle/chunks/{contracts-YXJ6NXKH.js → contracts-D4BN3VSQ.js} +4 -4
  164. package/dist/cli-bundle/chunks/{contracts-ZIBXROPE.js → contracts-RGPOBLPL.js} +4 -4
  165. package/dist/cli-bundle/chunks/{copy-YPWEIAPD.js → copy-H6TXHK7S.js} +7 -7
  166. package/dist/cli-bundle/chunks/{copy-BZALX5MQ.js → copy-WXE3OOLZ.js} +7 -7
  167. package/dist/cli-bundle/chunks/create-EZWAMUKR.js +27 -0
  168. package/dist/cli-bundle/chunks/{create-CF7EVRX7.js → create-PUAIJEZ7.js} +13 -13
  169. package/dist/cli-bundle/chunks/{delete-KR4VBWVE.js → delete-PKR2JHLH.js} +7 -7
  170. package/dist/cli-bundle/chunks/{delete-XLZRTRKR.js → delete-WBME6WG5.js} +7 -7
  171. package/dist/cli-bundle/chunks/{deps-2YTXD3VM.js → deps-4BQEDV4L.js} +7 -7
  172. package/dist/cli-bundle/chunks/{deps-GZMFMTGS.js → deps-KWHQRO75.js} +7 -7
  173. package/dist/cli-bundle/chunks/{docs-SLROFEQ4.js → docs-364GT3ZR.js} +9 -9
  174. package/dist/cli-bundle/chunks/{docs-ZHISRR2D.js → docs-SCNBUGSV.js} +9 -9
  175. package/dist/cli-bundle/chunks/{extension-XYCUXICD.js → extension-CRE7JM47.js} +5 -5
  176. package/dist/cli-bundle/chunks/{extension-3C7OOI4F.js → extension-KK2UPXJD.js} +5 -5
  177. package/dist/cli-bundle/chunks/{files-FUWF2FYJ.js → files-3GESQAWL.js} +9 -9
  178. package/dist/cli-bundle/chunks/{files-J4I5IU4O.js → files-66EHM5ZR.js} +9 -9
  179. package/dist/cli-bundle/chunks/{gc-34NXSNSN.js → gc-D5IWOKQH.js} +13 -5
  180. package/dist/cli-bundle/chunks/gc-D5IWOKQH.js.map +1 -0
  181. package/dist/cli-bundle/chunks/{gc-SPIIZX3A.js → gc-MOQDND5J.js} +12 -4
  182. package/dist/cli-bundle/chunks/gc-MOQDND5J.js.map +7 -0
  183. package/dist/cli-bundle/chunks/{get-SZKNRHMA.js → get-7J2ZCBV5.js} +11 -11
  184. package/dist/cli-bundle/chunks/{get-VITKYP6S.js → get-WXSLXV3K.js} +11 -11
  185. package/dist/cli-bundle/chunks/{health-7G3EPM57.js → health-B6AEM7BV.js} +21 -14
  186. package/dist/cli-bundle/chunks/health-B6AEM7BV.js.map +1 -0
  187. package/dist/cli-bundle/chunks/{health-4SNTA2TF.js → health-YMZGOMVX.js} +20 -13
  188. package/dist/cli-bundle/chunks/health-YMZGOMVX.js.map +7 -0
  189. package/dist/cli-bundle/chunks/{history-SDAWYZR3.js → history-TJTO5GCR.js} +10 -10
  190. package/dist/cli-bundle/chunks/history-ZERISU2L.js +20 -0
  191. package/dist/cli-bundle/chunks/{history-compact-POTZGG7K.js → history-compact-CKNN6UKW.js} +11 -11
  192. package/dist/cli-bundle/chunks/{history-compact-DMW536VH.js → history-compact-N2Q7IR3T.js} +11 -11
  193. package/dist/cli-bundle/chunks/history-redact-GODBYT5A.js +19 -0
  194. package/dist/cli-bundle/chunks/{history-redact-EPJ7GENL.js → history-redact-JUXUOH54.js} +11 -11
  195. package/dist/cli-bundle/chunks/{history-repair-YNESJRT6.js → history-repair-CCCPBNTF.js} +11 -11
  196. package/dist/cli-bundle/chunks/{history-repair-IJ7LLBET.js → history-repair-TDBBSRVK.js} +11 -11
  197. package/dist/cli-bundle/chunks/{init-YHVBTEET.js → init-6ZPKD3YN.js} +9 -9
  198. package/dist/cli-bundle/chunks/init-CBZHXBR3.js +17 -0
  199. package/dist/cli-bundle/chunks/{learnings-T4PF24YN.js → learnings-U7U2FNIO.js} +10 -10
  200. package/dist/cli-bundle/chunks/{learnings-4YBMIVCZ.js → learnings-WYNTYQ5T.js} +10 -10
  201. package/dist/cli-bundle/chunks/list-7MTPPZHC.js +20 -0
  202. package/dist/cli-bundle/chunks/{list-3KEVBOYW.js → list-JGP7ODML.js} +10 -10
  203. package/dist/cli-bundle/chunks/{notes-GJKALVZM.js → notes-P25YVTEG.js} +10 -10
  204. package/dist/cli-bundle/chunks/{notes-FLUCNJSH.js → notes-QIF6A7XS.js} +10 -10
  205. package/dist/cli-bundle/chunks/{plan-YYMIL3HV.js → plan-RACB5PI6.js} +13 -13
  206. package/dist/cli-bundle/chunks/{plan-T5MMZLI3.js → plan-SSBJFWXA.js} +13 -13
  207. package/dist/cli-bundle/chunks/{register-list-query-I65EZ3HB.js → register-list-query-5IXDPUZ6.js} +23 -21
  208. package/dist/cli-bundle/chunks/register-list-query-5IXDPUZ6.js.map +1 -0
  209. package/dist/cli-bundle/chunks/{register-list-query-OECMHO4G.js → register-list-query-GQAEIG4K.js} +22 -20
  210. package/dist/cli-bundle/chunks/register-list-query-GQAEIG4K.js.map +7 -0
  211. package/dist/cli-bundle/chunks/{register-mutation-2FLXORLR.js → register-mutation-FAS4YG63.js} +41 -37
  212. package/dist/cli-bundle/chunks/{register-mutation-2FLXORLR.js.map → register-mutation-FAS4YG63.js.map} +1 -1
  213. package/dist/cli-bundle/chunks/{register-mutation-5GPDEKHR.js → register-mutation-YZCUILGO.js} +40 -36
  214. package/dist/cli-bundle/chunks/{register-mutation-5GPDEKHR.js.map → register-mutation-YZCUILGO.js.map} +2 -2
  215. package/dist/cli-bundle/chunks/{register-operations-GQKT35H5.js → register-operations-IBYWNJN5.js} +30 -30
  216. package/dist/cli-bundle/chunks/{register-operations-BNGAUMGK.js → register-operations-S2BOLUPF.js} +30 -30
  217. package/dist/cli-bundle/chunks/{register-setup-EJY44FPH.js → register-setup-ABA2JPWO.js} +19 -18
  218. package/dist/cli-bundle/chunks/{register-setup-EJY44FPH.js.map → register-setup-ABA2JPWO.js.map} +2 -2
  219. package/dist/cli-bundle/chunks/{register-setup-DNDCGZ4O.js → register-setup-JRZ4UMWZ.js} +20 -19
  220. package/dist/cli-bundle/chunks/register-setup-JRZ4UMWZ.js.map +1 -0
  221. package/dist/cli-bundle/chunks/restore-3JRX27QW.js +17 -0
  222. package/dist/cli-bundle/chunks/{restore-DDJGVZIN.js → restore-K72ZNPEP.js} +11 -11
  223. package/dist/cli-bundle/chunks/{schema-B7NQ6XVP.js → schema-3VKRDBLC.js} +76 -20
  224. package/dist/cli-bundle/chunks/schema-3VKRDBLC.js.map +7 -0
  225. package/dist/cli-bundle/chunks/{schema-HEGYH6CE.js → schema-UL4B2JX5.js} +77 -21
  226. package/dist/cli-bundle/chunks/schema-UL4B2JX5.js.map +1 -0
  227. package/dist/cli-bundle/chunks/{search-JNEZJV7H.js → search-632WJ7GO.js} +103 -14
  228. package/dist/cli-bundle/chunks/search-632WJ7GO.js.map +7 -0
  229. package/dist/cli-bundle/chunks/{search-DVVQ4UO2.js → search-EQDHSE4G.js} +104 -15
  230. package/dist/cli-bundle/chunks/search-EQDHSE4G.js.map +1 -0
  231. package/dist/cli-bundle/chunks/{stats-SYTJRR4Z.js → stats-O4UTMJMC.js} +7 -7
  232. package/dist/cli-bundle/chunks/{stats-7JDIJRDH.js → stats-WLJ3XBF5.js} +7 -7
  233. package/dist/cli-bundle/chunks/{telemetry-4HHWD5Y7.js → telemetry-EUVHFSQU.js} +4 -4
  234. package/dist/cli-bundle/chunks/{telemetry-EGWP7ZUX.js → telemetry-NRVWX25E.js} +4 -4
  235. package/dist/cli-bundle/chunks/{test-IIELLSZX.js → test-GXUBQNUC.js} +14 -14
  236. package/dist/cli-bundle/chunks/test-XN7RJL5Z.js +32 -0
  237. package/dist/cli-bundle/chunks/{test-all-IHTUJRRC.js → test-all-UTFXC7S2.js} +14 -14
  238. package/dist/cli-bundle/chunks/{test-all-7DNCMML7.js → test-all-XM6OKI3L.js} +14 -14
  239. package/dist/cli-bundle/chunks/{test-runs-5FEMBV3A.js → test-runs-7FHCPEA3.js} +5 -5
  240. package/dist/cli-bundle/chunks/{test-runs-RNKZ37PS.js → test-runs-IK6E2HNX.js} +5 -5
  241. package/dist/cli-bundle/chunks/update-LFBSEW3N.js +21 -0
  242. package/dist/cli-bundle/chunks/update-U4B4OMHZ.js +25 -0
  243. package/dist/cli-bundle/chunks/{update-many-BSZZZYXY.js → update-many-5KD33MKY.js} +22 -22
  244. package/dist/cli-bundle/chunks/{update-many-BWKJJEBF.js → update-many-N3YTM7K4.js} +22 -22
  245. package/dist/cli-bundle/chunks/{upgrade-YWI5DJFA.js → upgrade-5SRFLUNW.js} +8 -15
  246. package/dist/cli-bundle/chunks/upgrade-5SRFLUNW.js.map +7 -0
  247. package/dist/cli-bundle/chunks/{upgrade-RSE5PC44.js → upgrade-FFXGO43H.js} +9 -16
  248. package/dist/cli-bundle/chunks/upgrade-FFXGO43H.js.map +1 -0
  249. package/dist/cli-bundle/chunks/{validate-UCEOB7S6.js → validate-CRWXZILW.js} +16 -16
  250. package/dist/cli-bundle/chunks/{validate-NK3WKB7C.js → validate-T3LPWSZG.js} +16 -16
  251. package/dist/cli-bundle/main.js +51 -62
  252. package/dist/cli-bundle/main.js.map +3 -3
  253. package/dist/core/config/nested-settings.d.ts +0 -2
  254. package/dist/core/config/nested-settings.js +2 -4
  255. package/dist/core/config/nested-settings.js.map +1 -1
  256. package/dist/core/diagnostics/remediation.js +7 -2
  257. package/dist/core/diagnostics/remediation.js.map +1 -1
  258. package/dist/core/fs/fs-utils.js +29 -4
  259. package/dist/core/fs/fs-utils.js.map +1 -1
  260. package/dist/core/packages/root.d.ts +10 -0
  261. package/dist/core/packages/root.js +24 -2
  262. package/dist/core/packages/root.js.map +1 -1
  263. package/dist/core/schema/runtime-schema.js +3 -6
  264. package/dist/core/schema/runtime-schema.js.map +1 -1
  265. package/dist/core/search/background-refresh.d.ts +0 -8
  266. package/dist/core/search/background-refresh.js +2 -9
  267. package/dist/core/search/background-refresh.js.map +1 -1
  268. package/dist/core/search/vector-stores.js +6 -8
  269. package/dist/core/search/vector-stores.js.map +1 -1
  270. package/dist/core/sentry/instrument.js +4 -17
  271. package/dist/core/sentry/instrument.js.map +1 -1
  272. package/dist/core/store/paths.js +17 -3
  273. package/dist/core/store/paths.js.map +1 -1
  274. package/dist/core/telemetry/runtime.d.ts +1 -0
  275. package/dist/core/telemetry/runtime.js +3 -3
  276. package/dist/core/telemetry/runtime.js.map +1 -1
  277. package/dist/mcp/server.js +76 -13
  278. package/dist/mcp/server.js.map +1 -1
  279. package/dist/sdk/cli-contracts/commander-types.js +4 -4
  280. package/dist/sdk/cli-contracts/commander-types.js.map +1 -1
  281. package/dist/sdk/cli-contracts/tool-parameter-tables.js +3 -3
  282. package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
  283. package/dist/sdk/cli-contracts.js +10 -8
  284. package/dist/sdk/cli-contracts.js.map +1 -1
  285. package/docs/AGENT_GUIDE.md +3 -1
  286. package/docs/CLAUDE_CODE_PLUGIN.md +2 -2
  287. package/docs/COMMANDS.md +6 -4
  288. package/docs/CONFIGURATION.md +6 -0
  289. package/docs/EXTENSIONS.md +0 -5
  290. package/docs/RELEASING.md +17 -0
  291. package/marketplace.json +1 -1
  292. package/package.json +1 -1
  293. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  294. package/plugins/pm-claude/README.md +3 -3
  295. package/plugins/pm-claude/commands/pm-init.md +1 -1
  296. package/dist/cli-bundle/chunks/activity-5UROHJ3D.js +0 -16
  297. package/dist/cli-bundle/chunks/chunk-42LOFGJS.js.map +0 -7
  298. package/dist/cli-bundle/chunks/chunk-4GHZR3BA.js.map +0 -1
  299. package/dist/cli-bundle/chunks/chunk-CKLBZHS7.js.map +0 -7
  300. package/dist/cli-bundle/chunks/chunk-CLD3XNCH.js.map +0 -1
  301. package/dist/cli-bundle/chunks/chunk-IMCJBN2Q.js.map +0 -7
  302. package/dist/cli-bundle/chunks/chunk-M2PW7EZU.js.map +0 -7
  303. package/dist/cli-bundle/chunks/chunk-MWRS7Z4P.js.map +0 -7
  304. package/dist/cli-bundle/chunks/chunk-NHR2QXXZ.js.map +0 -1
  305. package/dist/cli-bundle/chunks/chunk-QQL5QSTZ.js.map +0 -1
  306. package/dist/cli-bundle/chunks/chunk-TINUJMWN.js.map +0 -1
  307. package/dist/cli-bundle/chunks/chunk-TYJJOTUA.js.map +0 -1
  308. package/dist/cli-bundle/chunks/chunk-UJUT6AHZ.js.map +0 -7
  309. package/dist/cli-bundle/chunks/chunk-WAA7UI6M.js.map +0 -7
  310. package/dist/cli-bundle/chunks/chunk-WR5567FH.js.map +0 -7
  311. package/dist/cli-bundle/chunks/chunk-X4IZKYHP.js.map +0 -1
  312. package/dist/cli-bundle/chunks/chunk-XS3O2TFJ.js.map +0 -1
  313. package/dist/cli-bundle/chunks/chunk-YPH4ESA2.js.map +0 -1
  314. package/dist/cli-bundle/chunks/close-P4ZBKODL.js +0 -13
  315. package/dist/cli-bundle/chunks/close-many-DBLEYFOY.js.map +0 -7
  316. package/dist/cli-bundle/chunks/close-many-LAC5VR4G.js.map +0 -1
  317. package/dist/cli-bundle/chunks/config-RZRVS3ZV.js.map +0 -1
  318. package/dist/cli-bundle/chunks/config-YJSAAADD.js.map +0 -7
  319. package/dist/cli-bundle/chunks/create-4DS2QWQC.js +0 -27
  320. package/dist/cli-bundle/chunks/gc-34NXSNSN.js.map +0 -1
  321. package/dist/cli-bundle/chunks/gc-SPIIZX3A.js.map +0 -7
  322. package/dist/cli-bundle/chunks/health-4SNTA2TF.js.map +0 -7
  323. package/dist/cli-bundle/chunks/health-7G3EPM57.js.map +0 -1
  324. package/dist/cli-bundle/chunks/history-YDUEILKP.js +0 -20
  325. package/dist/cli-bundle/chunks/history-redact-KASLLPE7.js +0 -19
  326. package/dist/cli-bundle/chunks/init-IGSS4GNH.js +0 -17
  327. package/dist/cli-bundle/chunks/list-E44O2K64.js +0 -20
  328. package/dist/cli-bundle/chunks/register-list-query-I65EZ3HB.js.map +0 -1
  329. package/dist/cli-bundle/chunks/register-list-query-OECMHO4G.js.map +0 -7
  330. package/dist/cli-bundle/chunks/register-setup-DNDCGZ4O.js.map +0 -1
  331. package/dist/cli-bundle/chunks/restore-SJSASGZP.js +0 -17
  332. package/dist/cli-bundle/chunks/schema-B7NQ6XVP.js.map +0 -7
  333. package/dist/cli-bundle/chunks/schema-HEGYH6CE.js.map +0 -1
  334. package/dist/cli-bundle/chunks/search-DVVQ4UO2.js.map +0 -1
  335. package/dist/cli-bundle/chunks/search-JNEZJV7H.js.map +0 -7
  336. package/dist/cli-bundle/chunks/test-ML5RLWXE.js +0 -32
  337. package/dist/cli-bundle/chunks/update-6C67X4KS.js +0 -21
  338. package/dist/cli-bundle/chunks/update-VF26YPT3.js +0 -25
  339. package/dist/cli-bundle/chunks/upgrade-RSE5PC44.js.map +0 -1
  340. package/dist/cli-bundle/chunks/upgrade-YWI5DJFA.js.map +0 -7
  341. /package/dist/cli-bundle/chunks/{activity-5UROHJ3D.js.map → activity-A3QKFSSF.js.map} +0 -0
  342. /package/dist/cli-bundle/chunks/{activity-YVB3QRTE.js.map → activity-Q7XMIZIH.js.map} +0 -0
  343. /package/dist/cli-bundle/chunks/{aggregate-LH66F75F.js.map → aggregate-GBSHSXOB.js.map} +0 -0
  344. /package/dist/cli-bundle/chunks/{aggregate-OHSWFQJM.js.map → aggregate-HKQJZUBG.js.map} +0 -0
  345. /package/dist/cli-bundle/chunks/{append-2PPYFAG5.js.map → append-3RFOU7P5.js.map} +0 -0
  346. /package/dist/cli-bundle/chunks/{append-AUGT5W6J.js.map → append-OM74OJVT.js.map} +0 -0
  347. /package/dist/cli-bundle/chunks/{chunk-HRMHZ4RV.js.map → chunk-2BYKYPWY.js.map} +0 -0
  348. /package/dist/cli-bundle/chunks/{chunk-TP4DDY27.js.map → chunk-2HMD3JM2.js.map} +0 -0
  349. /package/dist/cli-bundle/chunks/{chunk-4CHEG6UK.js.map → chunk-2YPVCD7T.js.map} +0 -0
  350. /package/dist/cli-bundle/chunks/{chunk-UT6WFXW2.js.map → chunk-4TI3532H.js.map} +0 -0
  351. /package/dist/cli-bundle/chunks/{chunk-KNGVP5WJ.js.map → chunk-4WYBLB6J.js.map} +0 -0
  352. /package/dist/cli-bundle/chunks/{chunk-V6EYFTRL.js.map → chunk-5NVJA7IW.js.map} +0 -0
  353. /package/dist/cli-bundle/chunks/{chunk-WYEXLDDY.js.map → chunk-AEMKH5WQ.js.map} +0 -0
  354. /package/dist/cli-bundle/chunks/{chunk-OKSKJKHX.js.map → chunk-AXBUHLW7.js.map} +0 -0
  355. /package/dist/cli-bundle/chunks/{chunk-UEWA73ZZ.js.map → chunk-BFJPMUF5.js.map} +0 -0
  356. /package/dist/cli-bundle/chunks/{chunk-B5RF3IP7.js.map → chunk-BKQMJXWY.js.map} +0 -0
  357. /package/dist/cli-bundle/chunks/{chunk-HV5SSZXF.js.map → chunk-CBJXWXI5.js.map} +0 -0
  358. /package/dist/cli-bundle/chunks/{chunk-LI65XLJR.js.map → chunk-EPWT7BEA.js.map} +0 -0
  359. /package/dist/cli-bundle/chunks/{chunk-LMTOY5HE.js.map → chunk-ETZZU5QF.js.map} +0 -0
  360. /package/dist/cli-bundle/chunks/{chunk-LIN2BPJ7.js.map → chunk-F33VC5EX.js.map} +0 -0
  361. /package/dist/cli-bundle/chunks/{chunk-SFFVGNHC.js.map → chunk-FGRJZVXD.js.map} +0 -0
  362. /package/dist/cli-bundle/chunks/{chunk-HLC3KTLP.js.map → chunk-FO2TYSQZ.js.map} +0 -0
  363. /package/dist/cli-bundle/chunks/{chunk-3A2CMEM7.js.map → chunk-HOA3GMB6.js.map} +0 -0
  364. /package/dist/cli-bundle/chunks/{chunk-HMMMWBK2.js.map → chunk-HP35AVFS.js.map} +0 -0
  365. /package/dist/cli-bundle/chunks/{chunk-AVJD6VTA.js.map → chunk-J4DKAGTM.js.map} +0 -0
  366. /package/dist/cli-bundle/chunks/{chunk-YO3THIJF.js.map → chunk-JS47EKLP.js.map} +0 -0
  367. /package/dist/cli-bundle/chunks/{chunk-2IXCHCLM.js.map → chunk-K62SNVVE.js.map} +0 -0
  368. /package/dist/cli-bundle/chunks/{chunk-H7EO3QA3.js.map → chunk-KN4WSESY.js.map} +0 -0
  369. /package/dist/cli-bundle/chunks/{chunk-C5W2UH56.js.map → chunk-KP4KIUQT.js.map} +0 -0
  370. /package/dist/cli-bundle/chunks/{chunk-GPXQBR3H.js.map → chunk-KVXIQDJG.js.map} +0 -0
  371. /package/dist/cli-bundle/chunks/{chunk-NQL32HQ5.js.map → chunk-L3LYL3ID.js.map} +0 -0
  372. /package/dist/cli-bundle/chunks/{chunk-WCQZBDDH.js.map → chunk-M7UBTVFT.js.map} +0 -0
  373. /package/dist/cli-bundle/chunks/{chunk-3EOBJOF4.js.map → chunk-MSH23UWO.js.map} +0 -0
  374. /package/dist/cli-bundle/chunks/{chunk-UAQOQ7IE.js.map → chunk-N4SQZ7L3.js.map} +0 -0
  375. /package/dist/cli-bundle/chunks/{chunk-FY6Z3FYY.js.map → chunk-NDSMKB2I.js.map} +0 -0
  376. /package/dist/cli-bundle/chunks/{chunk-2IF7WLB7.js.map → chunk-NGEEXR2R.js.map} +0 -0
  377. /package/dist/cli-bundle/chunks/{chunk-UIIQC5YO.js.map → chunk-NLVCMVC7.js.map} +0 -0
  378. /package/dist/cli-bundle/chunks/{chunk-LQHBENVW.js.map → chunk-NUKHZZNM.js.map} +0 -0
  379. /package/dist/cli-bundle/chunks/{chunk-YBZW2QQ7.js.map → chunk-ODN53S6H.js.map} +0 -0
  380. /package/dist/cli-bundle/chunks/{chunk-LXO6V66E.js.map → chunk-OTY2YEH5.js.map} +0 -0
  381. /package/dist/cli-bundle/chunks/{chunk-6RZXO5M2.js.map → chunk-OVSSE2JP.js.map} +0 -0
  382. /package/dist/cli-bundle/chunks/{chunk-R3V3YCMH.js.map → chunk-QF4OPBAG.js.map} +0 -0
  383. /package/dist/cli-bundle/chunks/{chunk-FHHBD7PN.js.map → chunk-QFVASU44.js.map} +0 -0
  384. /package/dist/cli-bundle/chunks/{chunk-SQPKRA54.js.map → chunk-QQPZYP73.js.map} +0 -0
  385. /package/dist/cli-bundle/chunks/{chunk-5AXMRKN5.js.map → chunk-QWNUDGFQ.js.map} +0 -0
  386. /package/dist/cli-bundle/chunks/{chunk-6J4K6JLA.js.map → chunk-SDLEYY6A.js.map} +0 -0
  387. /package/dist/cli-bundle/chunks/{chunk-MOYM2C3J.js.map → chunk-TBLBEOEX.js.map} +0 -0
  388. /package/dist/cli-bundle/chunks/{chunk-TNPBPNII.js.map → chunk-UEXNNF3K.js.map} +0 -0
  389. /package/dist/cli-bundle/chunks/{chunk-RVPTZKBC.js.map → chunk-UMMJAJB2.js.map} +0 -0
  390. /package/dist/cli-bundle/chunks/{chunk-THDEID2Z.js.map → chunk-URJEZOLB.js.map} +0 -0
  391. /package/dist/cli-bundle/chunks/{chunk-UYQ7HXH4.js.map → chunk-XEKZCBCS.js.map} +0 -0
  392. /package/dist/cli-bundle/chunks/{chunk-2OJHLWBZ.js.map → chunk-XLSQ3QLT.js.map} +0 -0
  393. /package/dist/cli-bundle/chunks/{chunk-X7UHMKPE.js.map → chunk-XNGMIVQY.js.map} +0 -0
  394. /package/dist/cli-bundle/chunks/{chunk-B2KZGPM2.js.map → chunk-XZS4MV37.js.map} +0 -0
  395. /package/dist/cli-bundle/chunks/{chunk-GNIUOLZ2.js.map → chunk-YEFOCDIK.js.map} +0 -0
  396. /package/dist/cli-bundle/chunks/{chunk-GUZBNB3G.js.map → chunk-Z2HXAFFH.js.map} +0 -0
  397. /package/dist/cli-bundle/chunks/{claim-KW743OSW.js.map → claim-NHBIIBOW.js.map} +0 -0
  398. /package/dist/cli-bundle/chunks/{claim-BJ4QMPJC.js.map → claim-RNEBQCOO.js.map} +0 -0
  399. /package/dist/cli-bundle/chunks/{close-P4ZBKODL.js.map → close-UNTFXVM3.js.map} +0 -0
  400. /package/dist/cli-bundle/chunks/{close-SYHSRZDC.js.map → close-ZMXL2WDS.js.map} +0 -0
  401. /package/dist/cli-bundle/chunks/{comments-JEO6HHVM.js.map → comments-EFVBHWPT.js.map} +0 -0
  402. /package/dist/cli-bundle/chunks/{comments-YT2PQ5DD.js.map → comments-J5Q4IJPH.js.map} +0 -0
  403. /package/dist/cli-bundle/chunks/{context-LGYEEKAW.js.map → context-AVLO4IFH.js.map} +0 -0
  404. /package/dist/cli-bundle/chunks/{context-ZUH5IOOI.js.map → context-WMSI2D65.js.map} +0 -0
  405. /package/dist/cli-bundle/chunks/{contracts-YXJ6NXKH.js.map → contracts-D4BN3VSQ.js.map} +0 -0
  406. /package/dist/cli-bundle/chunks/{contracts-ZIBXROPE.js.map → contracts-RGPOBLPL.js.map} +0 -0
  407. /package/dist/cli-bundle/chunks/{copy-YPWEIAPD.js.map → copy-H6TXHK7S.js.map} +0 -0
  408. /package/dist/cli-bundle/chunks/{copy-BZALX5MQ.js.map → copy-WXE3OOLZ.js.map} +0 -0
  409. /package/dist/cli-bundle/chunks/{create-4DS2QWQC.js.map → create-EZWAMUKR.js.map} +0 -0
  410. /package/dist/cli-bundle/chunks/{create-CF7EVRX7.js.map → create-PUAIJEZ7.js.map} +0 -0
  411. /package/dist/cli-bundle/chunks/{delete-KR4VBWVE.js.map → delete-PKR2JHLH.js.map} +0 -0
  412. /package/dist/cli-bundle/chunks/{delete-XLZRTRKR.js.map → delete-WBME6WG5.js.map} +0 -0
  413. /package/dist/cli-bundle/chunks/{deps-2YTXD3VM.js.map → deps-4BQEDV4L.js.map} +0 -0
  414. /package/dist/cli-bundle/chunks/{deps-GZMFMTGS.js.map → deps-KWHQRO75.js.map} +0 -0
  415. /package/dist/cli-bundle/chunks/{docs-SLROFEQ4.js.map → docs-364GT3ZR.js.map} +0 -0
  416. /package/dist/cli-bundle/chunks/{docs-ZHISRR2D.js.map → docs-SCNBUGSV.js.map} +0 -0
  417. /package/dist/cli-bundle/chunks/{extension-XYCUXICD.js.map → extension-CRE7JM47.js.map} +0 -0
  418. /package/dist/cli-bundle/chunks/{extension-3C7OOI4F.js.map → extension-KK2UPXJD.js.map} +0 -0
  419. /package/dist/cli-bundle/chunks/{files-FUWF2FYJ.js.map → files-3GESQAWL.js.map} +0 -0
  420. /package/dist/cli-bundle/chunks/{files-J4I5IU4O.js.map → files-66EHM5ZR.js.map} +0 -0
  421. /package/dist/cli-bundle/chunks/{get-SZKNRHMA.js.map → get-7J2ZCBV5.js.map} +0 -0
  422. /package/dist/cli-bundle/chunks/{get-VITKYP6S.js.map → get-WXSLXV3K.js.map} +0 -0
  423. /package/dist/cli-bundle/chunks/{history-SDAWYZR3.js.map → history-TJTO5GCR.js.map} +0 -0
  424. /package/dist/cli-bundle/chunks/{history-YDUEILKP.js.map → history-ZERISU2L.js.map} +0 -0
  425. /package/dist/cli-bundle/chunks/{history-compact-POTZGG7K.js.map → history-compact-CKNN6UKW.js.map} +0 -0
  426. /package/dist/cli-bundle/chunks/{history-compact-DMW536VH.js.map → history-compact-N2Q7IR3T.js.map} +0 -0
  427. /package/dist/cli-bundle/chunks/{history-redact-KASLLPE7.js.map → history-redact-GODBYT5A.js.map} +0 -0
  428. /package/dist/cli-bundle/chunks/{history-redact-EPJ7GENL.js.map → history-redact-JUXUOH54.js.map} +0 -0
  429. /package/dist/cli-bundle/chunks/{history-repair-YNESJRT6.js.map → history-repair-CCCPBNTF.js.map} +0 -0
  430. /package/dist/cli-bundle/chunks/{history-repair-IJ7LLBET.js.map → history-repair-TDBBSRVK.js.map} +0 -0
  431. /package/dist/cli-bundle/chunks/{init-YHVBTEET.js.map → init-6ZPKD3YN.js.map} +0 -0
  432. /package/dist/cli-bundle/chunks/{init-IGSS4GNH.js.map → init-CBZHXBR3.js.map} +0 -0
  433. /package/dist/cli-bundle/chunks/{learnings-T4PF24YN.js.map → learnings-U7U2FNIO.js.map} +0 -0
  434. /package/dist/cli-bundle/chunks/{learnings-4YBMIVCZ.js.map → learnings-WYNTYQ5T.js.map} +0 -0
  435. /package/dist/cli-bundle/chunks/{list-E44O2K64.js.map → list-7MTPPZHC.js.map} +0 -0
  436. /package/dist/cli-bundle/chunks/{list-3KEVBOYW.js.map → list-JGP7ODML.js.map} +0 -0
  437. /package/dist/cli-bundle/chunks/{notes-GJKALVZM.js.map → notes-P25YVTEG.js.map} +0 -0
  438. /package/dist/cli-bundle/chunks/{notes-FLUCNJSH.js.map → notes-QIF6A7XS.js.map} +0 -0
  439. /package/dist/cli-bundle/chunks/{plan-YYMIL3HV.js.map → plan-RACB5PI6.js.map} +0 -0
  440. /package/dist/cli-bundle/chunks/{plan-T5MMZLI3.js.map → plan-SSBJFWXA.js.map} +0 -0
  441. /package/dist/cli-bundle/chunks/{register-operations-GQKT35H5.js.map → register-operations-IBYWNJN5.js.map} +0 -0
  442. /package/dist/cli-bundle/chunks/{register-operations-BNGAUMGK.js.map → register-operations-S2BOLUPF.js.map} +0 -0
  443. /package/dist/cli-bundle/chunks/{restore-SJSASGZP.js.map → restore-3JRX27QW.js.map} +0 -0
  444. /package/dist/cli-bundle/chunks/{restore-DDJGVZIN.js.map → restore-K72ZNPEP.js.map} +0 -0
  445. /package/dist/cli-bundle/chunks/{stats-SYTJRR4Z.js.map → stats-O4UTMJMC.js.map} +0 -0
  446. /package/dist/cli-bundle/chunks/{stats-7JDIJRDH.js.map → stats-WLJ3XBF5.js.map} +0 -0
  447. /package/dist/cli-bundle/chunks/{telemetry-4HHWD5Y7.js.map → telemetry-EUVHFSQU.js.map} +0 -0
  448. /package/dist/cli-bundle/chunks/{telemetry-EGWP7ZUX.js.map → telemetry-NRVWX25E.js.map} +0 -0
  449. /package/dist/cli-bundle/chunks/{test-IIELLSZX.js.map → test-GXUBQNUC.js.map} +0 -0
  450. /package/dist/cli-bundle/chunks/{test-ML5RLWXE.js.map → test-XN7RJL5Z.js.map} +0 -0
  451. /package/dist/cli-bundle/chunks/{test-all-IHTUJRRC.js.map → test-all-UTFXC7S2.js.map} +0 -0
  452. /package/dist/cli-bundle/chunks/{test-all-7DNCMML7.js.map → test-all-XM6OKI3L.js.map} +0 -0
  453. /package/dist/cli-bundle/chunks/{test-runs-5FEMBV3A.js.map → test-runs-7FHCPEA3.js.map} +0 -0
  454. /package/dist/cli-bundle/chunks/{test-runs-RNKZ37PS.js.map → test-runs-IK6E2HNX.js.map} +0 -0
  455. /package/dist/cli-bundle/chunks/{update-6C67X4KS.js.map → update-LFBSEW3N.js.map} +0 -0
  456. /package/dist/cli-bundle/chunks/{update-VF26YPT3.js.map → update-U4B4OMHZ.js.map} +0 -0
  457. /package/dist/cli-bundle/chunks/{update-many-BSZZZYXY.js.map → update-many-5KD33MKY.js.map} +0 -0
  458. /package/dist/cli-bundle/chunks/{update-many-BWKJJEBF.js.map → update-many-N3YTM7K4.js.map} +0 -0
  459. /package/dist/cli-bundle/chunks/{validate-UCEOB7S6.js.map → validate-CRWXZILW.js.map} +0 -0
  460. /package/dist/cli-bundle/chunks/{validate-NK3WKB7C.js.map → validate-T3LPWSZG.js.map} +0 -0
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../../core/search/http-client.ts", "../../../../../../../../core/search/providers.ts", "../../../../../../../../core/search/corpus.ts", "../../../../../../../../core/search/semantic-defaults.ts", "../../../../../../../../core/search/vector-stores.ts", "../../../../../../../../core/search/cache.ts", "../../../../../../../../core/search/embedding-batches.ts", "../../../../../../../../core/search/background-refresh.ts", "../../../../../../../../core/search/vectorization-metadata.ts"],
4
+ "sourcesContent": ["import { toErrorMessage } from \"../shared/primitives.js\";\n\nexport const DEFAULT_SEARCH_HTTP_TIMEOUT_MS = 30_000;\n\nexport interface SearchHttpResponse {\n ok: boolean;\n status: number;\n statusText: string;\n json(): Promise<unknown>;\n text(): Promise<string>;\n}\n\nexport interface SearchHttpRequestInit {\n method: \"DELETE\" | \"POST\" | \"PUT\";\n headers: Record<string, string>;\n body: string;\n signal: AbortSignal;\n}\n\nexport type SearchHttpFetcher<ResponseType extends SearchHttpResponse = SearchHttpResponse> = (\n url: string,\n init: SearchHttpRequestInit,\n) => Promise<ResponseType>;\n\nexport interface ExecuteSearchJsonRequestOptions<ResponseType extends SearchHttpResponse = SearchHttpResponse> {\n endpoint: string;\n method: \"DELETE\" | \"POST\" | \"PUT\";\n headers: Record<string, string>;\n body: Record<string, unknown>;\n timeoutMs: number;\n fetcher: SearchHttpFetcher<ResponseType>;\n requestLabel: string;\n responseLabel: string;\n}\n\nexport function normalizeSearchHttpTimeoutMs(\n timeoutMs: number | undefined,\n requestLabel: string,\n defaultTimeoutMs = DEFAULT_SEARCH_HTTP_TIMEOUT_MS,\n): number {\n const resolved = timeoutMs ?? defaultTimeoutMs;\n if (!Number.isFinite(resolved) || resolved <= 0) {\n throw new Error(`${requestLabel} timeout must be a positive finite number`);\n }\n return Math.floor(resolved);\n}\n\nexport function resolveSearchHttpFetcher<ResponseType extends SearchHttpResponse>(\n fetcher: SearchHttpFetcher<ResponseType> | undefined,\n requestLabel: string,\n): SearchHttpFetcher<ResponseType> {\n if (fetcher) {\n return fetcher;\n }\n if (typeof globalThis.fetch === \"function\") {\n return globalThis.fetch.bind(globalThis) as unknown as SearchHttpFetcher<ResponseType>;\n }\n throw new Error(`${requestLabel} execution requires a fetch implementation`);\n}\n\nexport async function readFailedSearchHttpResponseBody(response: SearchHttpResponse): Promise<string> {\n try {\n return (await response.text()).replaceAll(/\\s+/g, \" \").trim();\n } catch (error) {\n return `(failed to read response body: ${toErrorMessage(error)})`;\n }\n}\n\nexport async function executeSearchJsonRequest<ResponseType extends SearchHttpResponse>(\n options: ExecuteSearchJsonRequestOptions<ResponseType>,\n): Promise<unknown> {\n const controller = new AbortController();\n const timeoutHandle = setTimeout(() => {\n controller.abort();\n }, options.timeoutMs);\n\n try {\n let response: ResponseType;\n try {\n response = await options.fetcher(options.endpoint, {\n method: options.method,\n headers: options.headers,\n body: JSON.stringify(options.body),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw new Error(`${options.requestLabel} timed out after ${options.timeoutMs}ms`);\n }\n throw new Error(`${options.requestLabel} execution failed: ${toErrorMessage(error)}`);\n }\n\n if (!response.ok) {\n const responseBody = await readFailedSearchHttpResponseBody(response);\n const detail = responseBody.length > 0 ? `: ${responseBody}` : \"\";\n throw new Error(`${options.requestLabel} failed with status ${response.status} ${response.statusText}${detail}`);\n }\n\n try {\n return await response.json();\n } catch (error) {\n throw new Error(`${options.responseLabel} JSON parse failed: ${toErrorMessage(error)}`);\n }\n } finally {\n clearTimeout(timeoutHandle);\n }\n}\n", "import type { PmSettings } from \"../../types/index.js\";\nimport {\n executeSearchJsonRequest,\n normalizeSearchHttpTimeoutMs,\n resolveSearchHttpFetcher,\n} from \"./http-client.js\";\nimport type { SearchHttpFetcher, SearchHttpResponse } from \"./http-client.js\";\nimport {\n isFiniteNumberArray,\n toNonEmptyString,\n trimTrailingSlashes,\n} from \"../shared/primitives.js\";\n\nexport type EmbeddingProviderName = \"openai\" | \"ollama\";\n\nexport interface EmbeddingProviderConfig {\n name: EmbeddingProviderName;\n base_url: string;\n model: string;\n api_key?: string;\n}\n\nexport interface EmbeddingProviderResolution {\n active: EmbeddingProviderConfig | null;\n available: EmbeddingProviderConfig[];\n}\n\nexport interface EmbeddingRequestTarget {\n provider: EmbeddingProviderName;\n endpoint: string;\n model: string;\n}\n\nexport interface EmbeddingRequestPlan {\n target: EmbeddingRequestTarget;\n method: \"POST\";\n headers: Record<string, string>;\n body: Record<string, unknown>;\n}\n\nexport type EmbeddingHttpResponse = SearchHttpResponse;\n\nexport type EmbeddingRequestFetcher = SearchHttpFetcher<EmbeddingHttpResponse>;\n\nexport interface ExecuteEmbeddingRequestOptions {\n timeout_ms?: number;\n fetcher?: EmbeddingRequestFetcher;\n}\n\ntype ProviderSettingsInput = {\n providers?: {\n openai?: {\n base_url?: string;\n api_key?: string;\n model?: string;\n };\n ollama?: {\n base_url?: string;\n model?: string;\n };\n };\n};\n\nfunction normalizeOpenAiEmbeddingsEndpoint(baseUrl: string): string {\n const normalizedBaseUrl = trimTrailingSlashes(baseUrl);\n const normalizedLower = normalizedBaseUrl.toLowerCase();\n if (normalizedLower.endsWith(\"/embeddings\")) {\n return normalizedBaseUrl;\n }\n if (normalizedLower.endsWith(\"/v1\")) {\n return `${normalizedBaseUrl}/embeddings`;\n }\n return `${normalizedBaseUrl}/v1/embeddings`;\n}\n\nfunction resolveSearchEmbeddingModelOverride(settings: ProviderSettingsInput): string | null {\n // `settings.search.embedding_model` is documented as overriding the\n // provider-specific model when set (see CONFIG_KEY_ALIASES for\n // `search_embedding_model` in src/core/config/nested-settings.ts). Each\n // provider resolver picks this up after its own model is read so the\n // override applies to whichever built-in is selected.\n const candidate = (settings as { search?: { embedding_model?: unknown } }).search?.embedding_model;\n return toNonEmptyString(candidate) || null;\n}\n\nfunction resolveOpenAiProvider(settings: ProviderSettingsInput): EmbeddingProviderConfig | null {\n const baseUrl = toNonEmptyString(settings.providers?.openai?.base_url);\n const model = toNonEmptyString(settings.providers?.openai?.model);\n if (!baseUrl || !model) {\n return null;\n }\n const override = resolveSearchEmbeddingModelOverride(settings);\n const apiKey = toNonEmptyString(settings.providers?.openai?.api_key);\n return {\n name: \"openai\",\n base_url: baseUrl,\n model: override ?? model,\n ...(apiKey ? { api_key: apiKey } : {}),\n };\n}\n\nfunction resolveOllamaProvider(settings: ProviderSettingsInput): EmbeddingProviderConfig | null {\n const baseUrl = toNonEmptyString(settings.providers?.ollama?.base_url);\n const model = toNonEmptyString(settings.providers?.ollama?.model);\n if (!baseUrl || !model) {\n return null;\n }\n const override = resolveSearchEmbeddingModelOverride(settings);\n return {\n name: \"ollama\",\n base_url: baseUrl,\n model: override ?? model,\n };\n}\n\nfunction normalizeEmbeddingInputs(input: string | string[]): string[] {\n const inputs = (Array.isArray(input) ? input : [input])\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n if (inputs.length === 0) {\n throw new Error(\"Embedding input must include at least one non-empty string\");\n }\n return inputs;\n}\n\ninterface DedupedEmbeddingInputs {\n uniqueInputs: string[];\n originalToUniqueIndex: number[];\n}\n\nfunction dedupeEmbeddingInputs(inputs: string[]): DedupedEmbeddingInputs {\n const uniqueInputs: string[] = [];\n const originalToUniqueIndex: number[] = [];\n const uniqueIndexByInput = new Map<string, number>();\n for (const entry of inputs) {\n const existingUniqueIndex = uniqueIndexByInput.get(entry);\n if (existingUniqueIndex === undefined) {\n const nextUniqueIndex = uniqueInputs.length;\n uniqueInputs.push(entry);\n uniqueIndexByInput.set(entry, nextUniqueIndex);\n originalToUniqueIndex.push(nextUniqueIndex);\n continue;\n }\n originalToUniqueIndex.push(existingUniqueIndex);\n }\n return {\n uniqueInputs,\n originalToUniqueIndex,\n };\n}\n\ninterface OpenAiEmbeddingResponseEntry {\n embedding: unknown;\n index: unknown;\n position: number;\n}\n\nfunction buildOrderedOpenAiEntries(data: unknown[]): OpenAiEmbeddingResponseEntry[] {\n const openAiEntries = data.map((entry, position) => ({\n embedding: (entry as { embedding?: unknown }).embedding,\n index: (entry as { index?: unknown }).index,\n position,\n }));\n const hasExplicitIndex = openAiEntries.some((entry) => entry.index !== undefined);\n if (hasExplicitIndex) {\n for (const entry of openAiEntries) {\n if (!Number.isInteger(entry.index)) {\n throw new TypeError(`OpenAI embedding response entry at position ${entry.position} is missing a valid integer index`);\n }\n }\n return [...openAiEntries].sort((a, b) => {\n const byIndex = (a.index as number) - (b.index as number);\n if (byIndex !== 0) {\n return byIndex;\n }\n return a.position - b.position;\n });\n }\n return openAiEntries;\n}\n\nexport function resolveEmbeddingProviders(settings: PmSettings | ProviderSettingsInput): EmbeddingProviderResolution {\n const openAi = resolveOpenAiProvider(settings);\n const ollama = resolveOllamaProvider(settings);\n const available = [openAi, ollama].filter((entry): entry is EmbeddingProviderConfig => entry !== null);\n // Honor `settings.search.provider` when set: if both built-in providers are\n // configured, the preferred name wins; otherwise fall back to the first\n // available entry (preserves the previous tie-break: openai > ollama).\n // Match case-insensitively so \"OpenAI\" / \"Ollama\" / \"OLLAMA\" all work.\n const preferredName = toNonEmptyString(\n (settings as { search?: { provider?: unknown } }).search?.provider,\n );\n const preferredKey = preferredName ? preferredName.toLowerCase() : null;\n const preferred = preferredKey\n ? available.find((entry) => entry.name === preferredKey)\n : undefined;\n return {\n active: preferred ?? available[0] ?? null,\n available,\n };\n}\n\nexport function resolveEmbeddingRequestTarget(provider: EmbeddingProviderConfig): EmbeddingRequestTarget {\n const baseUrl = trimTrailingSlashes(provider.base_url);\n if (provider.name === \"openai\") {\n return {\n provider: \"openai\",\n endpoint: normalizeOpenAiEmbeddingsEndpoint(baseUrl),\n model: provider.model,\n };\n }\n return {\n provider: \"ollama\",\n endpoint: `${baseUrl}/api/embed`,\n model: provider.model,\n };\n}\n\nexport function buildEmbeddingRequestPlan(provider: EmbeddingProviderConfig, input: string | string[]): EmbeddingRequestPlan {\n const normalizedInputs = normalizeEmbeddingInputs(input);\n if (provider.name === \"openai\") {\n return {\n target: resolveEmbeddingRequestTarget(provider),\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n ...(provider.api_key ? { authorization: `Bearer ${provider.api_key}` } : {}),\n },\n body: {\n model: provider.model,\n input: normalizedInputs.length === 1 ? normalizedInputs[0] : normalizedInputs,\n },\n };\n }\n return {\n target: resolveEmbeddingRequestTarget(provider),\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n },\n body: {\n model: provider.model,\n input: normalizedInputs,\n },\n };\n}\n\nexport function normalizeEmbeddingResponse(provider: EmbeddingProviderConfig, response: unknown): number[][] {\n if (provider.name === \"openai\") {\n const data = (response as { data?: unknown }).data;\n if (!Array.isArray(data) || data.length === 0) {\n throw new Error(\"OpenAI embedding response must include a non-empty data array\");\n }\n const orderedEntries = buildOrderedOpenAiEntries(data);\n\n return orderedEntries.map((entry, index) => {\n const embedding = entry.embedding;\n if (!isFiniteNumberArray(embedding)) {\n throw new Error(`OpenAI embedding response entry at index ${index} is missing a numeric embedding vector`);\n }\n return [...embedding];\n });\n }\n\n const singleEmbedding = (response as { embedding?: unknown }).embedding;\n if (isFiniteNumberArray(singleEmbedding)) {\n return [[...singleEmbedding]];\n }\n\n const multipleEmbeddings = (response as { embeddings?: unknown }).embeddings;\n if (Array.isArray(multipleEmbeddings) && multipleEmbeddings.length > 0) {\n return multipleEmbeddings.map((entry, index) => {\n if (!isFiniteNumberArray(entry)) {\n throw new Error(`Ollama embedding response entry at index ${index} is missing a numeric embedding vector`);\n }\n return [...entry];\n });\n }\n\n throw new Error(\"Ollama embedding response must include embedding or embeddings vectors\");\n}\n\nexport async function executeEmbeddingRequest(\n provider: EmbeddingProviderConfig,\n input: string | string[],\n options: ExecuteEmbeddingRequestOptions = {},\n): Promise<number[][]> {\n const timeoutMs = normalizeSearchHttpTimeoutMs(options.timeout_ms, \"Embedding request\");\n const fetcher = resolveSearchHttpFetcher(options.fetcher, \"Embedding request\");\n const normalizedInputs = normalizeEmbeddingInputs(input);\n const dedupedInputs = dedupeEmbeddingInputs(normalizedInputs);\n const requestPlan = buildEmbeddingRequestPlan(provider, dedupedInputs.uniqueInputs);\n const payload = await executeSearchJsonRequest({\n endpoint: requestPlan.target.endpoint,\n method: requestPlan.method,\n headers: requestPlan.headers,\n body: requestPlan.body,\n timeoutMs,\n fetcher,\n requestLabel: \"Embedding request\",\n responseLabel: \"Embedding response\",\n });\n const vectors = normalizeEmbeddingResponse(provider, payload);\n if (vectors.length !== dedupedInputs.uniqueInputs.length) {\n throw new Error(\n `Embedding response cardinality mismatch: expected ${dedupedInputs.uniqueInputs.length} vector(s), received ${vectors.length}`,\n );\n }\n return dedupedInputs.originalToUniqueIndex.map((uniqueIndex) => [...vectors[uniqueIndex]]);\n}\n", "import type { ItemDocument, ItemMetadata } from \"../../types/index.js\";\nimport { coercePositiveInteger } from \"../shared/primitives.js\";\n\nexport const DEFAULT_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS = 8_000;\nexport const OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS = 3_200;\nexport const SEMANTIC_CORPUS_TRUNCATION_SUFFIX = \"...[semantic corpus truncated]\";\nexport const SEARCH_EMBEDDING_CORPUS_MAX_CHARACTERS_INVALID_WARNING =\n \"search_embedding_corpus_max_characters_invalid:using_provider_default\";\n\nfunction compactParts(parts: Array<string | boolean | number | null | undefined>): string {\n return parts\n .map((part) => (part === undefined || part === null ? \"\" : String(part).trim()))\n .filter((part) => part.length > 0)\n .join(\" \");\n}\n\nexport function buildReminderCorpus(item: ItemMetadata): string[] {\n return (item.reminders ?? []).map((reminder) => compactParts([reminder.at, reminder.text]));\n}\n\nexport function buildEventCorpus(item: ItemMetadata): string[] {\n return (item.events ?? []).map((event) =>\n compactParts([\n event.start_at,\n event.end_at,\n event.title,\n event.description,\n event.location,\n event.all_day === true ? \"all day\" : undefined,\n event.timezone,\n event.recurrence?.freq,\n event.recurrence?.interval,\n event.recurrence?.count,\n event.recurrence?.until,\n event.recurrence?.by_weekday?.join(\" \"),\n event.recurrence?.by_month_day?.join(\" \"),\n event.recurrence?.exdates?.join(\" \"),\n ]),\n );\n}\n\nexport function buildPlanFlatCorpus(item: ItemMetadata): string {\n const segments: Array<string | undefined> = [];\n segments.push(item.plan_mode, item.plan_scope, item.plan_harness, item.plan_resume_context);\n for (const step of item.plan_steps ?? []) {\n segments.push(step.title, step.body, step.status, step.owner, step.evidence, step.blocked_reason, step.superseded_by);\n for (const link of step.linked_items ?? []) {\n segments.push(`${link.kind} ${link.id}`, link.note);\n }\n for (const file of step.files ?? []) segments.push(file.path, file.note);\n for (const test of step.tests ?? []) segments.push(test.command, test.path, test.note);\n for (const doc of step.docs ?? []) segments.push(doc.path, doc.note);\n }\n for (const decision of item.plan_decisions ?? []) {\n segments.push(decision.decision, decision.rationale, decision.evidence);\n }\n for (const discovery of item.plan_discoveries ?? []) {\n segments.push(discovery.text);\n }\n for (const check of item.plan_validation ?? []) {\n segments.push(check.text, check.command, check.expected);\n }\n return segments.filter((segment): segment is string => typeof segment === \"string\" && segment.length > 0).join(\" \");\n}\n\nexport function buildPlanCorpus(item: ItemMetadata): Record<string, unknown> | undefined {\n const steps = (item.plan_steps ?? []).map((step) =>\n compactParts([\n step.order,\n step.id,\n step.title,\n step.body,\n step.status,\n step.owner,\n step.evidence,\n step.blocked_reason,\n step.superseded_by,\n (step.linked_items ?? []).map((link) => compactParts([link.kind, link.id, link.note])).join(\" \"),\n (step.files ?? []).map((file) => compactParts([file.path, file.note])).join(\" \"),\n (step.tests ?? []).map((test) => compactParts([test.command, test.path, test.note])).join(\" \"),\n (step.docs ?? []).map((doc) => compactParts([doc.path, doc.note])).join(\" \"),\n ]),\n );\n const decisions = (item.plan_decisions ?? []).map((entry) =>\n compactParts([entry.decision, entry.rationale, entry.evidence, entry.step_id]),\n );\n const discoveries = (item.plan_discoveries ?? []).map((entry) => compactParts([entry.text, entry.step_id]));\n const validation = (item.plan_validation ?? []).map((entry) =>\n compactParts([entry.text, entry.command, entry.expected]),\n );\n const hasPlanContent =\n item.plan_mode !== undefined ||\n item.plan_scope !== undefined ||\n item.plan_harness !== undefined ||\n item.plan_resume_context !== undefined ||\n steps.length > 0 ||\n decisions.length > 0 ||\n discoveries.length > 0 ||\n validation.length > 0;\n if (!hasPlanContent) {\n return undefined;\n }\n return {\n mode: item.plan_mode,\n scope: item.plan_scope,\n harness: item.plan_harness,\n resume_context: item.plan_resume_context,\n steps,\n decisions,\n discoveries,\n validation,\n };\n}\n\nexport function buildSearchCorpus(document: ItemDocument): Record<string, unknown> {\n const item = document.metadata;\n const plan = buildPlanCorpus(item);\n const corpus: Record<string, unknown> = {\n title: item.title,\n description: item.description,\n tags: item.tags,\n status: item.status,\n body: document.body,\n comments: (item.comments ?? []).map((entry) => entry.text),\n notes: (item.notes ?? []).map((entry) => entry.text),\n learnings: (item.learnings ?? []).map((entry) => entry.text),\n reminders: buildReminderCorpus(item),\n events: buildEventCorpus(item),\n dependencies: (item.dependencies ?? []).map((entry) => ({\n id: entry.id,\n kind: entry.kind,\n })),\n };\n if (plan) {\n corpus.plan = plan;\n }\n return corpus;\n}\n\nexport function resolveSemanticCorpusInputCharacterLimit(providerName: string | undefined): number {\n if (providerName?.trim().toLowerCase() === \"ollama\") {\n return OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS;\n }\n return DEFAULT_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS;\n}\n\nexport interface SemanticCorpusCharacterLimitResolution {\n maxCharacters: number;\n warning: string | null;\n}\n\nexport function resolveSemanticCorpusCharacterLimit(\n providerName: string | undefined,\n configuredMaxCharacters: unknown,\n): SemanticCorpusCharacterLimitResolution {\n const providerDefaultLimit = resolveSemanticCorpusInputCharacterLimit(providerName);\n const parsed = coercePositiveInteger(configuredMaxCharacters);\n if (parsed !== null) {\n return {\n maxCharacters: parsed,\n warning: null,\n };\n }\n return {\n maxCharacters: providerDefaultLimit,\n warning:\n configuredMaxCharacters === undefined || configuredMaxCharacters === null\n ? null\n : SEARCH_EMBEDDING_CORPUS_MAX_CHARACTERS_INVALID_WARNING,\n };\n}\n\nexport interface SemanticCorpusInputOptions {\n providerName?: string;\n maxCharacters?: number;\n}\n\nexport function buildSemanticCorpusInput(document: ItemDocument, options: SemanticCorpusInputOptions = {}): string {\n const serialized = JSON.stringify(buildSearchCorpus(document));\n const maxCharacters = resolveSemanticCorpusCharacterLimit(options.providerName, options.maxCharacters)\n .maxCharacters;\n if (serialized.length <= maxCharacters) {\n return serialized;\n }\n if (maxCharacters <= SEMANTIC_CORPUS_TRUNCATION_SUFFIX.length) {\n return SEMANTIC_CORPUS_TRUNCATION_SUFFIX.slice(0, maxCharacters);\n }\n const keepLength = Math.max(0, maxCharacters - SEMANTIC_CORPUS_TRUNCATION_SUFFIX.length);\n return `${serialized.slice(0, keepLength)}${SEMANTIC_CORPUS_TRUNCATION_SUFFIX}`;\n}\n", "import { spawnSync } from \"node:child_process\";\nimport type { PmSettings } from \"../../types/index.js\";\nimport { toNonEmptyString } from \"../shared/primitives.js\";\n\nconst DISABLE_AUTO_DEFAULTS_ENV = \"PM_DISABLE_OLLAMA_AUTO_DEFAULTS\";\nconst OLLAMA_MODEL_ENV = \"PM_OLLAMA_MODEL\";\nconst DEFAULT_OLLAMA_BASE_URL = \"http://localhost:11434\";\nconst DEFAULT_OLLAMA_MODEL = \"qwen3-embedding:0.6b\";\nconst DEFAULT_LANCEDB_PATH = \".agents/pm/search/lancedb/\";\nconst OLLAMA_VERSION_TIMEOUT_MS = 1_500;\nconst OLLAMA_LIST_TIMEOUT_MS = 2_500;\nconst QWEN_EMBEDDING_MODEL_PATTERN = /qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i;\nconst EMBEDDING_MODEL_PATTERN = /embed|embedding/i;\n\nexport interface SemanticRuntimeDefaultsResolution {\n settings: PmSettings;\n auto_ollama_defaults_applied: boolean;\n}\n\nconst toOptionalNonEmptyString = toNonEmptyString;\n\nfunction isAutoDefaultsDisabled(): boolean {\n const raw = toOptionalNonEmptyString(process.env[DISABLE_AUTO_DEFAULTS_ENV]);\n if (!raw) {\n return false;\n }\n const normalized = raw.toLowerCase();\n return normalized === \"1\" || normalized === \"true\" || normalized === \"yes\";\n}\n\n/**\n * True only when the user has opted into a provider/store that COMPETES with the\n * Ollama + LanceDB auto-default stack: an explicit non-Ollama search provider, a\n * non-LanceDB vector adapter, or any OpenAI/Qdrant credentials. A partial Ollama\n * setup (e.g. only `ollama.base_url`) is NOT competing — its missing leaves are\n * filled per-field below so a single config write can never silently disable\n * semantic search and then hard-error `pm reindex`.\n */\nfunction hasCompetingSemanticConfiguration(settings: PmSettings): boolean {\n const provider = toOptionalNonEmptyString(settings.search?.provider);\n if (provider && provider.toLowerCase() !== \"ollama\") {\n return true;\n }\n const adapter = toOptionalNonEmptyString(settings.vector_store?.adapter);\n if (adapter && adapter.toLowerCase() !== \"lancedb\") {\n return true;\n }\n const openaiConfigured = [\n settings.providers?.openai?.base_url,\n settings.providers?.openai?.model,\n settings.providers?.openai?.api_key,\n ].some((entry) => toOptionalNonEmptyString(entry) !== null);\n if (openaiConfigured) {\n return true;\n }\n const qdrantConfigured = [\n settings.vector_store?.qdrant?.url,\n settings.vector_store?.qdrant?.api_key,\n ].some((entry) => toOptionalNonEmptyString(entry) !== null);\n return qdrantConfigured;\n}\n\nfunction isOllamaInstalled(): boolean {\n const result = spawnSync(\"ollama\", [\"--version\"], {\n encoding: \"utf8\",\n timeout: OLLAMA_VERSION_TIMEOUT_MS,\n });\n if (result.error) {\n return false;\n }\n return result.status === 0;\n}\n\nfunction parseOllamaModelList(output: string): string | null {\n const lines = output\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n if (lines.length === 0) {\n return null;\n }\n const models = lines\n .map((line) => line.split(/\\s+/)[0]?.trim())\n .filter((entry): entry is string => Boolean(entry && entry.length > 0))\n .filter((entry) => entry.toUpperCase() !== \"NAME\");\n if (models.length === 0) {\n return null;\n }\n const preferredQwenEmbeddingModel = models.find((entry) => QWEN_EMBEDDING_MODEL_PATTERN.test(entry));\n if (preferredQwenEmbeddingModel) {\n return preferredQwenEmbeddingModel;\n }\n const embeddingModel = models.find((entry) => EMBEDDING_MODEL_PATTERN.test(entry));\n return embeddingModel ?? null;\n}\n\nfunction resolveAutoOllamaModel(settings: PmSettings): string {\n const settingsModel = toOptionalNonEmptyString(settings.providers?.ollama?.model);\n if (settingsModel) {\n return settingsModel;\n }\n const envModel = toOptionalNonEmptyString(process.env[OLLAMA_MODEL_ENV]);\n if (envModel) {\n return envModel;\n }\n const listed = spawnSync(\"ollama\", [\"list\"], {\n encoding: \"utf8\",\n timeout: OLLAMA_LIST_TIMEOUT_MS,\n });\n if (!listed.error && listed.status === 0) {\n const listedModel = parseOllamaModelList(typeof listed.stdout === \"string\" ? listed.stdout : \"\");\n if (listedModel) {\n return listedModel;\n }\n }\n return DEFAULT_OLLAMA_MODEL;\n}\n\nexport function resolveSettingsWithSemanticRuntimeDefaults(settings: PmSettings): SemanticRuntimeDefaultsResolution {\n const unchanged: SemanticRuntimeDefaultsResolution = {\n settings,\n auto_ollama_defaults_applied: false,\n };\n if (isAutoDefaultsDisabled()) {\n return unchanged;\n }\n if (hasCompetingSemanticConfiguration(settings)) {\n return unchanged;\n }\n\n const needsBaseUrl = toOptionalNonEmptyString(settings.providers?.ollama?.base_url) === null;\n const needsModel = toOptionalNonEmptyString(settings.providers?.ollama?.model) === null;\n const needsLancedbPath = toOptionalNonEmptyString(settings.vector_store?.lancedb?.path) === null;\n const needsEmbeddingModel = toOptionalNonEmptyString(settings.search?.embedding_model) === null;\n if (!needsBaseUrl && !needsModel && !needsLancedbPath && !needsEmbeddingModel) {\n // A fully-configured Ollama/LanceDB stack — nothing to fill, and no need to\n // probe for Ollama at all.\n return unchanged;\n }\n\n // Auto-discovering the embedding model (via `ollama list`) is the only step that\n // requires Ollama to be installed. When a model is already configured we mirror it\n // into the remaining leaves without forcing an Ollama probe; when it is missing we\n // require Ollama to actually be present rather than writing an unusable default.\n if (needsModel && !isOllamaInstalled()) {\n return unchanged;\n }\n\n const nextSettings = structuredClone(settings);\n const resolvedModel = resolveAutoOllamaModel(nextSettings);\n // `readSettings` always normalizes these nested objects, but this function is\n // exported and runs on the search hot path with caller-supplied settings, so a\n // partial object (e.g. providers/vector_store set but no `search` block) must\n // fill the missing leaf rather than throwing on an undefined parent.\n if (needsBaseUrl || needsModel) {\n const providers = (nextSettings.providers ??= {} as PmSettings[\"providers\"]);\n const ollama = (providers.ollama ??= {} as PmSettings[\"providers\"][\"ollama\"]);\n if (needsBaseUrl) {\n ollama.base_url = DEFAULT_OLLAMA_BASE_URL;\n }\n if (needsModel) {\n ollama.model = resolvedModel;\n }\n }\n if (needsLancedbPath) {\n const vectorStore = (nextSettings.vector_store ??= {} as PmSettings[\"vector_store\"]);\n const lancedb = (vectorStore.lancedb ??= {} as PmSettings[\"vector_store\"][\"lancedb\"]);\n lancedb.path = DEFAULT_LANCEDB_PATH;\n }\n if (needsEmbeddingModel) {\n const search = (nextSettings.search ??= {} as PmSettings[\"search\"]);\n search.embedding_model = resolvedModel;\n }\n return {\n settings: nextSettings,\n auto_ollama_defaults_applied: true,\n };\n}\n", "import type { PmSettings } from \"../../types/index.js\";\nimport { mkdir, readFile, stat, unlink } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport {\n executeSearchJsonRequest,\n normalizeSearchHttpTimeoutMs,\n resolveSearchHttpFetcher,\n} from \"./http-client.js\";\nimport type { SearchHttpFetcher, SearchHttpResponse } from \"./http-client.js\";\nimport {\n isFiniteNumberArray,\n toErrorMessage,\n toNonEmptyString,\n trimTrailingSlashes,\n} from \"../shared/primitives.js\";\nimport { writeFileAtomic } from \"../fs/fs-utils.js\";\n\nexport type VectorStoreName = \"qdrant\" | \"lancedb\";\n\nexport interface QdrantVectorStoreConfig {\n name: \"qdrant\";\n url: string;\n collection_name?: string;\n api_key?: string;\n}\n\nexport interface LanceDbVectorStoreConfig {\n name: \"lancedb\";\n path: string;\n collection_name?: string;\n}\n\nexport type VectorStoreConfig = QdrantVectorStoreConfig | LanceDbVectorStoreConfig;\n\nexport interface VectorStoreResolution {\n active: VectorStoreConfig | null;\n available: VectorStoreConfig[];\n}\n\nexport interface VectorStoreRequestTarget {\n store: VectorStoreName;\n query_target: string;\n upsert_target: string;\n}\n\nexport interface VectorQueryPlan {\n target: VectorStoreRequestTarget;\n method: \"POST\" | \"LOCAL\";\n headers: Record<string, string>;\n body: Record<string, unknown>;\n}\n\nexport interface VectorRecord {\n id: string;\n vector: number[];\n payload?: Record<string, unknown>;\n}\n\nexport interface VectorUpsertPlan {\n target: VectorStoreRequestTarget;\n method: \"POST\" | \"LOCAL\";\n headers: Record<string, string>;\n body: Record<string, unknown>;\n}\n\nexport interface VectorDeletePlan {\n target: VectorStoreRequestTarget;\n method: \"POST\" | \"LOCAL\";\n headers: Record<string, string>;\n body: Record<string, unknown>;\n}\n\nexport interface VectorQueryHit {\n id: string;\n score: number;\n payload?: Record<string, unknown>;\n}\n\nexport interface VectorUpsertResult {\n status: string;\n}\n\nexport type VectorHttpResponse = SearchHttpResponse;\n\nexport type VectorRequestFetcher = SearchHttpFetcher<VectorHttpResponse>;\n\nexport interface ExecuteVectorRequestOptions {\n timeout_ms?: number;\n fetcher?: VectorRequestFetcher;\n warnings?: string[];\n}\n\ntype VectorSettingsInput = {\n vector_store?: {\n collection_name?: string;\n qdrant?: {\n url?: string;\n api_key?: string;\n };\n lancedb?: {\n path?: string;\n };\n };\n};\n\ntype RemoteVectorMethod = \"DELETE\" | \"POST\" | \"PUT\";\n\nconst DEFAULT_COLLECTION = \"pm_items\";\nconst COLLECTION_SANITIZE_PATTERN = /[^a-zA-Z0-9_-]/g;\nconst MAX_COLLECTION_NAME_LENGTH = 128;\nconst LANCE_DB_LOCAL_SNAPSHOT_DIR = \".pm-cli-local-vectors\";\nconst LANCE_DB_LOCAL_SNAPSHOT_VERSION = 1;\ninterface LanceDbLocalTableCacheEntry {\n records: Map<string, VectorRecord>;\n mtimeMs: number | null;\n size: number | null;\n}\n\nconst lanceDbLocalTables = new Map<string, LanceDbLocalTableCacheEntry>();\n\nfunction resolveStoreCollectionName(store: VectorStoreConfig): string {\n const candidate = toNonEmptyString(store.collection_name) ?? DEFAULT_COLLECTION;\n return candidate.replaceAll(COLLECTION_SANITIZE_PATTERN, \"_\").slice(0, MAX_COLLECTION_NAME_LENGTH);\n}\n\nfunction normalizeVector(value: unknown): number[] {\n if (!isFiniteNumberArray(value) || value.length === 0) {\n throw new Error(\"Vector values must be a non-empty numeric array\");\n }\n return [...value];\n}\n\nfunction normalizeLimit(value: number): number {\n if (!Number.isFinite(value) || value <= 0) {\n throw new Error(\"Vector query limit must be a positive number\");\n }\n return Math.floor(value);\n}\n\nfunction normalizeQdrantQueryResponse(payload: unknown): VectorQueryHit[] {\n const result = (payload as { result?: unknown }).result;\n if (!Array.isArray(result)) {\n throw new TypeError(\"Qdrant query response must include a result array\");\n }\n const hits = result.map((entry, index) => {\n const idValue = (entry as { id?: unknown }).id;\n const idCandidate = typeof idValue === \"number\" ? String(idValue) : idValue;\n const id = toNonEmptyString(idCandidate);\n if (!id) {\n throw new Error(`Qdrant query response entry at index ${index} is missing a non-empty id`);\n }\n\n const score = (entry as { score?: unknown }).score;\n if (typeof score !== \"number\" || !Number.isFinite(score)) {\n throw new TypeError(`Qdrant query response entry at index ${index} is missing a finite numeric score`);\n }\n\n const payloadValue = (entry as { payload?: unknown }).payload;\n if (\n payloadValue !== undefined &&\n (typeof payloadValue !== \"object\" || payloadValue === null || Array.isArray(payloadValue))\n ) {\n throw new Error(`Qdrant query response entry at index ${index} must provide payload as an object when set`);\n }\n\n return {\n id,\n score,\n ...(payloadValue ? { payload: payloadValue as Record<string, unknown> } : {}),\n };\n });\n hits.sort((left, right) => {\n if (left.score !== right.score) {\n return right.score - left.score;\n }\n return left.id.localeCompare(right.id);\n });\n return hits;\n}\n\nfunction normalizeQdrantUpsertResponse(payload: unknown): VectorUpsertResult {\n const nestedStatus = toNonEmptyString((payload as { result?: { status?: unknown } }).result?.status);\n if (nestedStatus) {\n return { status: nestedStatus };\n }\n const topLevelStatus = toNonEmptyString((payload as { status?: unknown }).status);\n if (topLevelStatus) {\n return { status: topLevelStatus };\n }\n throw new Error(\"Qdrant upsert response must include status metadata\");\n}\n\nasync function executeRemoteVectorPlan(\n endpoint: string,\n plan: {\n method: RemoteVectorMethod;\n headers: Record<string, string>;\n body: Record<string, unknown>;\n },\n timeoutMs: number,\n fetcher: VectorRequestFetcher,\n requestKind: \"query\" | \"upsert\" | \"delete\",\n): Promise<unknown> {\n return await executeSearchJsonRequest({\n endpoint,\n method: plan.method,\n headers: plan.headers,\n body: plan.body,\n timeoutMs,\n fetcher,\n requestLabel: `Vector ${requestKind} request`,\n responseLabel: `Vector ${requestKind} response`,\n });\n}\n\nfunction resolveQdrantStore(settings: VectorSettingsInput): QdrantVectorStoreConfig | null {\n const url = toNonEmptyString(settings.vector_store?.qdrant?.url);\n if (!url) {\n return null;\n }\n const collectionName = toNonEmptyString(settings.vector_store?.collection_name);\n const apiKey = toNonEmptyString(settings.vector_store?.qdrant?.api_key);\n return {\n name: \"qdrant\",\n url,\n ...(collectionName && collectionName !== DEFAULT_COLLECTION ? { collection_name: collectionName } : {}),\n ...(apiKey ? { api_key: apiKey } : {}),\n };\n}\n\nfunction resolveLanceDbStore(settings: VectorSettingsInput): LanceDbVectorStoreConfig | null {\n const lancedbPath = toNonEmptyString(settings.vector_store?.lancedb?.path);\n if (!lancedbPath) {\n return null;\n }\n const collectionName = toNonEmptyString(settings.vector_store?.collection_name);\n return {\n name: \"lancedb\",\n path: lancedbPath,\n ...(collectionName && collectionName !== DEFAULT_COLLECTION ? { collection_name: collectionName } : {}),\n };\n}\n\nfunction normalizeVectorRecords(records: VectorRecord[]): VectorRecord[] {\n if (!Array.isArray(records) || records.length === 0) {\n throw new Error(\"Vector upsert records must include at least one entry\");\n }\n return records.map((record, index) => {\n const id = toNonEmptyString(record.id);\n if (!id) {\n throw new Error(`Vector upsert record at index ${index} is missing a non-empty id`);\n }\n const vector = normalizeVector(record.vector);\n const payload = record.payload;\n if (payload !== undefined && (typeof payload !== \"object\" || payload === null || Array.isArray(payload))) {\n throw new Error(`Vector upsert record at index ${index} must provide payload as an object when set`);\n }\n return {\n id,\n vector,\n ...(payload ? { payload } : {}),\n };\n });\n}\n\nfunction normalizeVectorDeleteIds(ids: string[]): string[] {\n if (!Array.isArray(ids) || ids.length === 0) {\n throw new Error(\"Vector delete ids must include at least one entry\");\n }\n const normalizedIds = ids\n .map((id, index) => {\n const normalized = toNonEmptyString(id);\n if (!normalized) {\n throw new Error(`Vector delete id at index ${index} is missing a non-empty value`);\n }\n return normalized;\n })\n .sort((left, right) => left.localeCompare(right));\n const uniqueIds: string[] = [];\n for (const id of normalizedIds) {\n if (uniqueIds.at(-1) !== id) {\n uniqueIds.push(id);\n }\n }\n return uniqueIds;\n}\n\nfunction resolveQdrantDeleteTarget(upsertTarget: string): string {\n return upsertTarget.replace(/\\/points\\?wait=true$/, \"/points/delete?wait=true\");\n}\n\nfunction resolveQdrantCollectionTarget(upsertTarget: string): string {\n return upsertTarget.replace(/\\/points\\?wait=true$/, \"\");\n}\n\nfunction buildQdrantJsonHeaders(store: QdrantVectorStoreConfig): Record<string, string> {\n return {\n \"content-type\": \"application/json\",\n ...(store.api_key ? { \"api-key\": store.api_key } : {}),\n };\n}\n\nfunction getLanceDbLocalTableKey(storePath: string, table: string): string {\n return getLanceDbSnapshotPath(storePath, table);\n}\n\nfunction getLanceDbSnapshotPath(storePath: string, table: string): string {\n return join(resolve(storePath), LANCE_DB_LOCAL_SNAPSHOT_DIR, `${table}.json`);\n}\n\nfunction isNodeErrorWithCode(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === code;\n}\n\nfunction normalizeSnapshotRecord(entry: unknown, index: number, snapshotPath: string): VectorRecord {\n const id = toNonEmptyString((entry as { id?: unknown }).id);\n if (!id) {\n throw new Error(`LanceDB local snapshot '${snapshotPath}' record at index ${index} is missing a non-empty id`);\n }\n const vector = normalizeVector((entry as { vector?: unknown }).vector);\n const payload = (entry as { payload?: unknown }).payload;\n if (payload !== undefined && (typeof payload !== \"object\" || payload === null || Array.isArray(payload))) {\n throw new Error(\n `LanceDB local snapshot '${snapshotPath}' record '${id}' must provide payload as an object when set`,\n );\n }\n return {\n id,\n vector,\n ...(payload ? { payload: payload as Record<string, unknown> } : {}),\n };\n}\n\nfunction parseLanceDbSnapshot(snapshotPath: string, expectedTable: string, raw: string): Map<string, VectorRecord> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch (error) {\n throw new Error(`LanceDB local snapshot at '${snapshotPath}' is not valid JSON: ${toErrorMessage(error)}`);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new Error(`LanceDB local snapshot at '${snapshotPath}' must be a JSON object`);\n }\n\n const version = (parsed as { version?: unknown }).version;\n if (version !== LANCE_DB_LOCAL_SNAPSHOT_VERSION) {\n throw new Error(\n `LanceDB local snapshot at '${snapshotPath}' must include version=${LANCE_DB_LOCAL_SNAPSHOT_VERSION}`,\n );\n }\n\n const table = toNonEmptyString((parsed as { table?: unknown }).table);\n if (!table) {\n throw new Error(`LanceDB local snapshot at '${snapshotPath}' must include a non-empty table value`);\n }\n if (table !== expectedTable) {\n throw new Error(\n `LanceDB local snapshot at '${snapshotPath}' table mismatch: expected '${expectedTable}', received '${table}'`,\n );\n }\n\n const recordsValue = (parsed as { records?: unknown }).records;\n if (!Array.isArray(recordsValue)) {\n throw new TypeError(`LanceDB local snapshot at '${snapshotPath}' must include a records array`);\n }\n\n const tableRecords = new Map<string, VectorRecord>();\n for (let index = 0; index < recordsValue.length; index += 1) {\n const record = normalizeSnapshotRecord(recordsValue[index], index, snapshotPath);\n tableRecords.set(record.id, record);\n }\n return tableRecords;\n}\n\nasync function loadLanceDbLocalTable(storePath: string, table: string): Promise<Map<string, VectorRecord>> {\n const key = getLanceDbLocalTableKey(storePath, table);\n const snapshotPath = getLanceDbSnapshotPath(storePath, table);\n let snapshotStats: { mtimeMs: number; size: number } | null = null;\n try {\n const stats = await stat(snapshotPath);\n snapshotStats = { mtimeMs: stats.mtimeMs, size: stats.size };\n } catch (error) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw error;\n }\n }\n\n const cached = lanceDbLocalTables.get(key);\n if (cached && !snapshotStats) {\n if (cached.mtimeMs === null && cached.size === null && cached.records.size === 0) {\n return cached.records;\n }\n const loaded = new Map<string, VectorRecord>();\n lanceDbLocalTables.set(key, { records: loaded, mtimeMs: null, size: null });\n return loaded;\n }\n if (\n cached &&\n snapshotStats &&\n cached.mtimeMs === snapshotStats.mtimeMs &&\n cached.size === snapshotStats.size\n ) {\n return cached.records;\n }\n\n let loaded = new Map<string, VectorRecord>();\n try {\n const raw = await readFile(snapshotPath, \"utf8\");\n loaded = parseLanceDbSnapshot(snapshotPath, table, raw);\n } catch (error) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw error;\n }\n }\n lanceDbLocalTables.set(key, {\n records: loaded,\n mtimeMs: snapshotStats?.mtimeMs ?? null,\n size: snapshotStats?.size ?? null,\n });\n return loaded;\n}\n\nfunction buildSnapshotRecords(table: Map<string, VectorRecord>): VectorRecord[] {\n const records = [...table.values()];\n records.sort((left, right) => left.id.localeCompare(right.id));\n return records.map((record) => ({\n id: record.id,\n vector: [...record.vector],\n ...(record.payload ? { payload: record.payload } : {}),\n }));\n}\n\nasync function removeSnapshotFile(snapshotPath: string): Promise<void> {\n try {\n await unlink(snapshotPath);\n } catch (error) {\n if (!isNodeErrorWithCode(error, \"ENOENT\")) {\n throw new Error(`LanceDB local snapshot delete failed at '${snapshotPath}': ${toErrorMessage(error)}`);\n }\n }\n}\n\nasync function persistLanceDbLocalTable(storePath: string, tableName: string, table: Map<string, VectorRecord>): Promise<void> {\n const snapshotPath = getLanceDbSnapshotPath(storePath, tableName);\n if (table.size === 0) {\n await removeSnapshotFile(snapshotPath);\n return;\n }\n\n const snapshotDir = dirname(snapshotPath);\n try {\n await mkdir(snapshotDir, { recursive: true });\n } catch (error) {\n throw new Error(\n `LanceDB local snapshot directory create failed at '${snapshotDir}': ${toErrorMessage(error)}`,\n );\n }\n\n // Serialize compactly: the snapshot is an internal, gitignored cache re-read via\n // JSON.parse (whitespace-agnostic). Pretty-printing put every embedding float on its\n // own indented line, roughly doubling file size and parse/serialize cost — a real\n // per-mutation latency tax on large indexes. Compact JSON keeps it instant.\n const serialized = `${JSON.stringify({\n version: LANCE_DB_LOCAL_SNAPSHOT_VERSION,\n table: tableName,\n records: buildSnapshotRecords(table),\n })}\\n`;\n try {\n await writeFileAtomic(snapshotPath, serialized);\n } catch (error) {\n throw new Error(`LanceDB local snapshot write failed at '${snapshotPath}': ${toErrorMessage(error)}`);\n }\n}\n\nasync function resetLanceDbLocalTable(storePath: string, tableName: string): Promise<void> {\n const key = getLanceDbLocalTableKey(storePath, tableName);\n const snapshotPath = getLanceDbSnapshotPath(storePath, tableName);\n await removeSnapshotFile(snapshotPath);\n lanceDbLocalTables.delete(key);\n}\n\nfunction l2Norm(vector: number[]): number {\n let sumSq = 0;\n for (let index = 0; index < vector.length; index += 1) {\n sumSq += vector[index] * vector[index];\n }\n return Math.sqrt(sumSq);\n}\n\nfunction cosineSimilarity(left: number[], right: number[]): number {\n let dotProd = 0;\n for (let index = 0; index < left.length; index += 1) {\n dotProd += left[index] * right[index];\n }\n const leftNorm = l2Norm(left);\n const rightNorm = l2Norm(right);\n if (leftNorm === 0 || rightNorm === 0) {\n return 0;\n }\n return dotProd / (leftNorm * rightNorm);\n}\n\nexport function resolveVectorStores(settings: PmSettings | VectorSettingsInput): VectorStoreResolution {\n const qdrant = resolveQdrantStore(settings);\n const lancedb = resolveLanceDbStore(settings);\n const available = [qdrant, lancedb].filter((entry): entry is VectorStoreConfig => entry !== null);\n // Honor `settings.vector_store.adapter` when set: if both built-in stores\n // are configured, the preferred adapter wins; otherwise fall back to the\n // first available entry (preserves the previous tie-break: qdrant > lancedb).\n // Match case-insensitively so \"Qdrant\" / \"LanceDB\" / \"lancedb\" all work.\n const preferredName = toNonEmptyString(\n (settings as { vector_store?: { adapter?: unknown } }).vector_store?.adapter,\n );\n const preferredKey = preferredName ? preferredName.toLowerCase() : null;\n const preferred = preferredKey\n ? available.find((entry) => entry.name === preferredKey)\n : undefined;\n return {\n active: preferred ?? available[0] ?? null,\n available,\n };\n}\n\nexport function resolveVectorStoreRequestTarget(store: VectorStoreConfig): VectorStoreRequestTarget {\n const collectionName = resolveStoreCollectionName(store);\n if (store.name === \"qdrant\") {\n const baseUrl = trimTrailingSlashes(store.url);\n const encodedCollection = encodeURIComponent(collectionName);\n return {\n store: \"qdrant\",\n query_target: `${baseUrl}/collections/${encodedCollection}/points/search`,\n upsert_target: `${baseUrl}/collections/${encodedCollection}/points?wait=true`,\n };\n }\n const encodedPath = encodeURIComponent(store.path);\n const encodedCollection = encodeURIComponent(collectionName);\n return {\n store: \"lancedb\",\n query_target: `lancedb://${encodedPath}#${encodedCollection}`,\n upsert_target: `lancedb://${encodedPath}#${encodedCollection}`,\n };\n}\n\nexport function buildVectorQueryPlan(store: VectorStoreConfig, vector: number[], limit: number): VectorQueryPlan {\n const target = resolveVectorStoreRequestTarget(store);\n const normalizedVector = normalizeVector(vector);\n const normalizedLimit = normalizeLimit(limit);\n if (store.name === \"qdrant\") {\n return {\n target,\n method: \"POST\",\n headers: buildQdrantJsonHeaders(store),\n body: {\n vector: normalizedVector,\n limit: normalizedLimit,\n with_payload: true,\n },\n };\n }\n return {\n target,\n method: \"LOCAL\",\n headers: {},\n body: {\n table: resolveStoreCollectionName(store),\n vector: normalizedVector,\n limit: normalizedLimit,\n },\n };\n}\n\nexport function buildVectorUpsertPlan(store: VectorStoreConfig, records: VectorRecord[]): VectorUpsertPlan {\n const target = resolveVectorStoreRequestTarget(store);\n const normalizedRecords = normalizeVectorRecords(records);\n if (store.name === \"qdrant\") {\n return {\n target,\n method: \"POST\",\n headers: buildQdrantJsonHeaders(store),\n body: {\n points: normalizedRecords,\n },\n };\n }\n return {\n target,\n method: \"LOCAL\",\n headers: {},\n body: {\n table: resolveStoreCollectionName(store),\n records: normalizedRecords,\n },\n };\n}\n\nexport function buildVectorDeletePlan(store: VectorStoreConfig, ids: string[]): VectorDeletePlan {\n const target = resolveVectorStoreRequestTarget(store);\n const normalizedIds = normalizeVectorDeleteIds(ids);\n if (store.name === \"qdrant\") {\n return {\n target,\n method: \"POST\",\n headers: buildQdrantJsonHeaders(store),\n body: {\n points: normalizedIds,\n },\n };\n }\n return {\n target,\n method: \"LOCAL\",\n headers: {},\n body: {\n table: resolveStoreCollectionName(store),\n ids: normalizedIds,\n },\n };\n}\n\nexport async function executeVectorQuery(\n store: VectorStoreConfig,\n vector: number[],\n limit: number,\n options: ExecuteVectorRequestOptions = {},\n): Promise<VectorQueryHit[]> {\n const plan = buildVectorQueryPlan(store, vector, limit);\n if (plan.method === \"LOCAL\") {\n const lanceDbStore = store as LanceDbVectorStoreConfig;\n const queryBody = plan.body as {\n table: string;\n vector: number[];\n limit: number;\n };\n const table = await loadLanceDbLocalTable(lanceDbStore.path, queryBody.table);\n if (table.size === 0) {\n return [];\n }\n const queryVector = normalizeVector(queryBody.vector);\n const queryLimit = normalizeLimit(queryBody.limit);\n const hits: VectorQueryHit[] = [];\n let dimensionMismatchCount = 0;\n for (const record of table.values()) {\n if (record.vector.length !== queryVector.length) {\n dimensionMismatchCount++;\n continue;\n }\n hits.push({\n id: record.id,\n score: cosineSimilarity(queryVector, record.vector),\n ...(record.payload ? { payload: record.payload } : {}),\n });\n }\n if (dimensionMismatchCount > 0 && options.warnings) {\n options.warnings.push(\n `vector_dimension_mismatch:${dimensionMismatchCount} records skipped (expected ${queryVector.length} dimensions)`,\n );\n }\n hits.sort((left, right) => {\n if (left.score !== right.score) {\n return right.score - left.score;\n }\n return left.id.localeCompare(right.id);\n });\n return hits.slice(0, queryLimit);\n }\n const timeoutMs = normalizeSearchHttpTimeoutMs(options.timeout_ms, \"Vector request\");\n const fetcher = resolveSearchHttpFetcher(options.fetcher, \"Vector request\");\n const payload = await executeRemoteVectorPlan(\n plan.target.query_target,\n {\n method: \"POST\",\n headers: plan.headers,\n body: plan.body,\n },\n timeoutMs,\n fetcher,\n \"query\",\n );\n return normalizeQdrantQueryResponse(payload);\n}\n\nexport async function executeVectorUpsert(\n store: VectorStoreConfig,\n records: VectorRecord[],\n options: ExecuteVectorRequestOptions = {},\n): Promise<VectorUpsertResult> {\n const plan = buildVectorUpsertPlan(store, records);\n if (plan.method === \"LOCAL\") {\n const lanceDbStore = store as LanceDbVectorStoreConfig;\n const upsertBody = plan.body as {\n table: string;\n records: VectorRecord[];\n };\n const key = getLanceDbLocalTableKey(lanceDbStore.path, upsertBody.table);\n const table = await loadLanceDbLocalTable(lanceDbStore.path, upsertBody.table);\n for (const record of upsertBody.records) {\n table.set(record.id, record);\n }\n await persistLanceDbLocalTable(lanceDbStore.path, upsertBody.table, table);\n const snapshotPath = getLanceDbSnapshotPath(lanceDbStore.path, upsertBody.table);\n const snapshotStats = await stat(snapshotPath);\n lanceDbLocalTables.set(key, {\n records: table,\n mtimeMs: snapshotStats.mtimeMs,\n size: snapshotStats.size,\n });\n return { status: \"ok\" };\n }\n const timeoutMs = normalizeSearchHttpTimeoutMs(options.timeout_ms, \"Vector request\");\n const fetcher = resolveSearchHttpFetcher(options.fetcher, \"Vector request\");\n const payload = await executeRemoteVectorPlan(\n plan.target.upsert_target,\n {\n method: \"POST\",\n headers: plan.headers,\n body: plan.body,\n },\n timeoutMs,\n fetcher,\n \"upsert\",\n );\n return normalizeQdrantUpsertResponse(payload);\n}\n\nexport async function executeVectorDelete(\n store: VectorStoreConfig,\n ids: string[],\n options: ExecuteVectorRequestOptions = {},\n): Promise<VectorUpsertResult> {\n const plan = buildVectorDeletePlan(store, ids);\n if (plan.method === \"LOCAL\") {\n const lanceDbStore = store as LanceDbVectorStoreConfig;\n const deleteBody = plan.body as {\n table: string;\n ids: string[];\n };\n const key = getLanceDbLocalTableKey(lanceDbStore.path, deleteBody.table);\n const table = await loadLanceDbLocalTable(lanceDbStore.path, deleteBody.table);\n if (table.size === 0) {\n return { status: \"ok\" };\n }\n for (const id of deleteBody.ids) {\n table.delete(id);\n }\n await persistLanceDbLocalTable(lanceDbStore.path, deleteBody.table, table);\n if (table.size === 0) {\n lanceDbLocalTables.delete(key);\n } else {\n const snapshotPath = getLanceDbSnapshotPath(lanceDbStore.path, deleteBody.table);\n const snapshotStats = await stat(snapshotPath);\n lanceDbLocalTables.set(key, {\n records: table,\n mtimeMs: snapshotStats.mtimeMs,\n size: snapshotStats.size,\n });\n }\n return { status: \"ok\" };\n }\n const timeoutMs = normalizeSearchHttpTimeoutMs(options.timeout_ms, \"Vector request\");\n const fetcher = resolveSearchHttpFetcher(options.fetcher, \"Vector request\");\n const payload = await executeRemoteVectorPlan(\n resolveQdrantDeleteTarget(plan.target.upsert_target),\n {\n method: \"POST\",\n headers: plan.headers,\n body: plan.body,\n },\n timeoutMs,\n fetcher,\n \"delete\",\n );\n return normalizeQdrantUpsertResponse(payload);\n}\n\nexport async function executeVectorReset(\n store: VectorStoreConfig,\n knownIds: string[] = [],\n options: ExecuteVectorRequestOptions = {},\n vectorDimension?: number,\n): Promise<VectorUpsertResult> {\n if (store.name === \"lancedb\") {\n await resetLanceDbLocalTable(store.path, resolveStoreCollectionName(store));\n return { status: \"ok\" };\n }\n if (vectorDimension !== undefined) {\n if (!Number.isInteger(vectorDimension) || vectorDimension <= 0) {\n throw new Error(\"Vector reset dimension must be a positive integer when provided\");\n }\n const target = resolveVectorStoreRequestTarget(store);\n const collectionTarget = resolveQdrantCollectionTarget(target.upsert_target);\n const timeoutMs = normalizeSearchHttpTimeoutMs(options.timeout_ms, \"Vector request\");\n const fetcher = resolveSearchHttpFetcher(options.fetcher, \"Vector request\");\n const headers = buildQdrantJsonHeaders(store);\n try {\n await executeRemoteVectorPlan(\n collectionTarget,\n {\n method: \"DELETE\",\n headers,\n body: {},\n },\n timeoutMs,\n fetcher,\n \"delete\",\n );\n } catch (error: unknown) {\n if (!toErrorMessage(error).includes(\"failed with status 404\")) {\n throw error;\n }\n }\n const payload = await executeRemoteVectorPlan(\n collectionTarget,\n {\n method: \"PUT\",\n headers,\n body: {\n vectors: {\n size: vectorDimension,\n distance: \"Cosine\",\n },\n },\n },\n timeoutMs,\n fetcher,\n \"upsert\",\n );\n return normalizeQdrantUpsertResponse(payload);\n }\n const idsToDelete = knownIds.map((id) => id.trim()).filter((id) => id.length > 0);\n if (idsToDelete.length === 0) {\n return { status: \"ok\" };\n }\n return await executeVectorDelete(store, idsToDelete, options);\n}\n", "import path from \"node:path\";\nimport { getActiveExtensionRegistrations } from \"../extensions/index.js\";\nimport { pathExists, readFileIfExists, removeFileIfExists, writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { resolveItemTypeRegistry } from \"../item/type-registry.js\";\nimport { toErrorMessage } from \"../shared/primitives.js\";\nimport { locateItem, readLocatedItem } from \"../store/item-store.js\";\nimport { getSettingsPath } from \"../store/paths.js\";\nimport { readSettings } from \"../store/settings.js\";\nimport { executeEmbeddingBatchesWithRetry } from \"./embedding-batches.js\";\nimport {\n buildSemanticCorpusInput,\n resolveSemanticCorpusCharacterLimit,\n} from \"./corpus.js\";\nimport { resolveEmbeddingProviders } from \"./providers.js\";\nimport type { EmbeddingProviderConfig } from \"./providers.js\";\nimport { resolveSettingsWithSemanticRuntimeDefaults } from \"./semantic-defaults.js\";\nimport { scheduleBackgroundSemanticRefresh } from \"./background-refresh.js\";\nimport { executeVectorDelete, executeVectorReset, executeVectorUpsert, resolveVectorStores } from \"./vector-stores.js\";\nimport type { VectorStoreConfig } from \"./vector-stores.js\";\nimport {\n buildVectorizationEmbeddingIdentity,\n buildVectorizationEmbeddingMetadata,\n hasVectorizationEmbeddingIdentityChanged,\n hasVectorizationVectorDimensionChanged,\n inferConsistentVectorDimension,\n normalizeVectorizationEmbeddingMetadata,\n} from \"./vectorization-metadata.js\";\nimport type {\n VectorizationEmbeddingIdentity,\n VectorizationEmbeddingMetadata,\n} from \"./vectorization-metadata.js\";\nimport { nowIso } from \"../shared/time.js\";\nimport type { ItemDocument, ItemFrontMatter } from \"../../types/index.js\";\n\nexport const SEARCH_CACHE_ARTIFACT_PATHS = [\"index/manifest.json\", \"search/embeddings.jsonl\"] as const;\nexport const VECTORIZATION_STATUS_LEDGER_PATH = \"search/vectorization-status.json\";\n\nexport interface SearchCacheInvalidationResult {\n invalidated: string[];\n warnings: string[];\n}\n\nexport interface SemanticMutationRefreshResult {\n refreshed: string[];\n skipped: string[];\n warnings: string[];\n}\n\nexport interface SearchMutationArtifactRefreshResult extends SearchCacheInvalidationResult {\n refreshed: string[];\n skipped: string[];\n /** True when the semantic refresh was dispatched to a detached background worker. */\n scheduled?: boolean;\n}\n\nexport interface RefreshSearchArtifactsForMutationOptions {\n /**\n * When true and semantic search is active, the (slow) embedding refresh is\n * dispatched to a detached background worker instead of awaited inline so the\n * mutation returns immediately. The synchronous keyword-cache invalidation\n * still runs first. Callers pass this only outside test runners.\n */\n background?: boolean;\n}\n\nexport interface SemanticRefreshOptions {\n settings?: Awaited<ReturnType<typeof readSettings>>;\n apply_runtime_defaults?: boolean;\n}\n\nexport interface VectorizationStatusLedgerReadResult {\n entries: Record<string, string>;\n embedding: VectorizationEmbeddingMetadata | null;\n warnings: string[];\n}\n\nfunction formatInvalidationWarning(relativePath: string, error: unknown): string {\n return `search_cache_invalidation_failed:${relativePath}:${String(error)}`;\n}\n\n\nfunction toUniqueSorted(values: Iterable<string>): string[] {\n return [...new Set([...values].map((value) => value.trim()).filter((value) => value.length > 0))]\n .sort((left, right) => left.localeCompare(right));\n}\n\nfunction isValidUpdatedAt(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0 && Number.isFinite(Date.parse(value));\n}\n\nfunction normalizeVectorizationLedgerEntries(entries: Record<string, string>): Record<string, string> {\n const normalized = new Map<string, string>();\n for (const [rawId, rawUpdatedAt] of Object.entries(entries)) {\n const id = rawId.trim();\n if (id.length === 0 || !isValidUpdatedAt(rawUpdatedAt)) {\n continue;\n }\n normalized.set(id, rawUpdatedAt);\n }\n return Object.fromEntries([...normalized.entries()].sort((left, right) => left[0].localeCompare(right[0])));\n}\n\nexport async function readVectorizationStatusLedger(pmRoot: string): Promise<VectorizationStatusLedgerReadResult> {\n const ledgerPath = path.join(pmRoot, VECTORIZATION_STATUS_LEDGER_PATH);\n const raw = await readFileIfExists(ledgerPath);\n if (raw === null || raw.trim().length === 0) {\n return {\n entries: {},\n embedding: null,\n warnings: [],\n };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n return {\n entries: {},\n embedding: null,\n warnings: [\"search_vectorization_status_ledger_invalid\"],\n };\n }\n\n if (\n typeof parsed !== \"object\" ||\n parsed === null ||\n (parsed as { version?: unknown }).version !== 1 ||\n !Array.isArray((parsed as { items?: unknown }).items)\n ) {\n return {\n entries: {},\n embedding: null,\n warnings: [\"search_vectorization_status_ledger_invalid\"],\n };\n }\n\n const mapped = new Map<string, string>();\n for (const entry of (parsed as { items: unknown[] }).items) {\n if (typeof entry !== \"object\" || entry === null) {\n return {\n entries: {},\n embedding: null,\n warnings: [\"search_vectorization_status_ledger_invalid\"],\n };\n }\n const id = (entry as { id?: unknown }).id;\n const updatedAt = (entry as { updated_at?: unknown }).updated_at;\n if (typeof id !== \"string\" || id.trim().length === 0 || !isValidUpdatedAt(updatedAt)) {\n return {\n entries: {},\n embedding: null,\n warnings: [\"search_vectorization_status_ledger_invalid\"],\n };\n }\n mapped.set(id.trim(), updatedAt);\n }\n\n let embedding: VectorizationEmbeddingMetadata | null = null;\n try {\n embedding = normalizeVectorizationEmbeddingMetadata((parsed as { embedding?: unknown }).embedding);\n } catch {\n return {\n entries: {},\n embedding: null,\n warnings: [\"search_vectorization_status_ledger_invalid\"],\n };\n }\n\n return {\n entries: Object.fromEntries([...mapped.entries()].sort((left, right) => left[0].localeCompare(right[0]))),\n embedding,\n warnings: [],\n };\n}\n\nexport async function writeVectorizationStatusLedger(\n pmRoot: string,\n entries: Record<string, string>,\n embedding?: VectorizationEmbeddingMetadata | null,\n): Promise<void> {\n const normalizedEntries = normalizeVectorizationLedgerEntries(entries);\n const ledgerPath = path.join(pmRoot, VECTORIZATION_STATUS_LEDGER_PATH);\n const serialized = `${JSON.stringify(\n {\n version: 1,\n generated_at: nowIso(),\n ...(embedding ? { embedding } : {}),\n items: Object.entries(normalizedEntries).map(([id, updated_at]) => ({\n id,\n updated_at,\n })),\n },\n null,\n 2,\n )}\\n`;\n await writeFileAtomic(ledgerPath, serialized);\n}\n\nfunction buildVectorPayload(item: ItemFrontMatter): Record<string, unknown> {\n return {\n id: item.id,\n type: item.type,\n status: item.status,\n priority: item.priority,\n updated_at: item.updated_at,\n };\n}\n\ninterface SemanticRefreshRuntimeContext {\n settings: Awaited<ReturnType<typeof readSettings>>;\n provider: EmbeddingProviderConfig;\n vectorStore: VectorStoreConfig;\n}\n\ninterface SemanticRefreshWorkload {\n documents: Array<{ id: string; document: ItemDocument }>;\n missingIds: string[];\n skippedIds: string[];\n warnings: string[];\n}\n\ninterface SemanticRefreshOperationResult {\n refreshed: string[];\n skipped: string[];\n warnings: string[];\n}\n\ninterface SemanticEmbeddingOperationResult {\n vectors: number[][];\n vector_dimension: number;\n warnings: string[];\n}\n\nfunction buildVectorizationIdentityForProvider(provider: EmbeddingProviderConfig): VectorizationEmbeddingIdentity {\n const identity = buildVectorizationEmbeddingIdentity(provider.name, provider.model);\n if (!identity) {\n throw new Error(\"Embedding provider must include a provider name and model\");\n }\n return identity;\n}\n\nfunction buildSkippedSemanticRefreshResult(itemIds: string[], warning: string): SemanticMutationRefreshResult {\n return {\n refreshed: [],\n skipped: itemIds,\n warnings: [warning],\n };\n}\n\nasync function resolveSemanticRefreshRuntimeContext(\n pmRoot: string,\n normalizedItemIds: string[],\n options: SemanticRefreshOptions,\n): Promise<SemanticRefreshRuntimeContext | SemanticMutationRefreshResult> {\n if (!options.settings && !(await pathExists(getSettingsPath(pmRoot)))) {\n return buildSkippedSemanticRefreshResult(normalizedItemIds, \"search_semantic_refresh_skipped:settings_not_initialized\");\n }\n\n let settings: Awaited<ReturnType<typeof readSettings>>;\n try {\n settings = options.settings ?? (await readSettings(pmRoot));\n } catch (error: unknown) {\n return buildSkippedSemanticRefreshResult(\n normalizedItemIds,\n `search_semantic_refresh_skipped:settings_read_failed:${toErrorMessage(error)}`,\n );\n }\n const effectiveSettings = options.apply_runtime_defaults\n ? resolveSettingsWithSemanticRuntimeDefaults(settings).settings\n : settings;\n\n const provider = resolveEmbeddingProviders(effectiveSettings).active;\n if (!provider) {\n return buildSkippedSemanticRefreshResult(normalizedItemIds, \"search_semantic_refresh_skipped:provider_unconfigured\");\n }\n const vectorStore = resolveVectorStores(effectiveSettings).active;\n if (!vectorStore) {\n return buildSkippedSemanticRefreshResult(normalizedItemIds, \"search_semantic_refresh_skipped:vector_store_unconfigured\");\n }\n\n return {\n settings: effectiveSettings,\n provider,\n vectorStore,\n };\n}\n\nasync function collectSemanticRefreshWorkload(\n pmRoot: string,\n idPrefix: string,\n preferredFormat: \"toon\" | \"json_markdown\",\n normalizedItemIds: string[],\n typeToFolder: Record<string, string>,\n schema: Awaited<ReturnType<typeof readSettings>>[\"schema\"],\n): Promise<SemanticRefreshWorkload> {\n const warnings: string[] = [];\n const skipped = new Set<string>();\n const missing = new Set<string>();\n const documents: Array<{ id: string; document: ItemDocument }> = [];\n\n for (const itemId of normalizedItemIds) {\n const located = await locateItem(pmRoot, itemId, idPrefix, preferredFormat, typeToFolder);\n if (!located) {\n missing.add(itemId);\n continue;\n }\n\n try {\n const loaded = await readLocatedItem(located, { schema });\n documents.push({\n id: loaded.document.metadata.id,\n document: loaded.document,\n });\n } catch (error: unknown) {\n skipped.add(located.id);\n warnings.push(`search_semantic_refresh_item_read_failed:${located.id}:${toErrorMessage(error)}`);\n }\n }\n\n documents.sort((left, right) => left.id.localeCompare(right.id));\n return {\n documents,\n missingIds: toUniqueSorted(missing),\n skippedIds: toUniqueSorted(skipped),\n warnings,\n };\n}\n\nasync function embedLocatedSemanticVectors(\n settings: Awaited<ReturnType<typeof readSettings>>,\n provider: EmbeddingProviderConfig,\n documents: Array<{ id: string; document: ItemDocument }>,\n): Promise<SemanticEmbeddingOperationResult> {\n const corpusCharacterLimit = resolveSemanticCorpusCharacterLimit(\n provider.name,\n settings.search.embedding_corpus_max_characters,\n ).maxCharacters;\n const corpusInputs = documents.map((entry) =>\n buildSemanticCorpusInput(entry.document, {\n providerName: provider.name,\n maxCharacters: corpusCharacterLimit,\n }),\n );\n const embeddingResult = await executeEmbeddingBatchesWithRetry(provider, settings, corpusInputs);\n return {\n vectors: embeddingResult.vectors,\n vector_dimension: inferConsistentVectorDimension(embeddingResult.vectors, \"Semantic refresh embedding\"),\n warnings: embeddingResult.warnings,\n };\n}\n\nasync function upsertLocatedSemanticVectors(\n vectorStore: VectorStoreConfig,\n documents: Array<{ id: string; document: ItemDocument }>,\n vectors: number[][],\n): Promise<SemanticRefreshOperationResult> {\n await executeVectorUpsert(\n vectorStore,\n documents.map((entry, index) => ({\n id: entry.id,\n vector: vectors[index],\n payload: buildVectorPayload(entry.document.metadata),\n })),\n );\n return {\n refreshed: documents.map((entry) => entry.id),\n skipped: [],\n warnings: [],\n };\n}\n\nasync function resetSemanticVectorStore(\n vectorStore: VectorStoreConfig,\n ledgerEntries: Record<string, string>,\n): Promise<SemanticRefreshOperationResult> {\n try {\n await executeVectorReset(vectorStore, Object.keys(ledgerEntries));\n return { refreshed: [], skipped: [], warnings: [] };\n } catch (error: unknown) {\n return {\n refreshed: [],\n skipped: [],\n warnings: [`search_semantic_refresh_reset_failed:${toErrorMessage(error)}`],\n };\n }\n}\n\nasync function pruneMissingSemanticVectors(\n vectorStore: VectorStoreConfig,\n missingIds: string[],\n): Promise<SemanticRefreshOperationResult> {\n if (missingIds.length === 0) {\n return { refreshed: [], skipped: [], warnings: [] };\n }\n try {\n await executeVectorDelete(vectorStore, missingIds);\n return {\n refreshed: [],\n skipped: [],\n warnings: [],\n };\n } catch (error: unknown) {\n return {\n refreshed: [],\n skipped: missingIds,\n warnings: [`search_semantic_refresh_delete_failed:${toErrorMessage(error)}`],\n };\n }\n}\n\nexport async function invalidateSearchCacheArtifacts(pmRoot: string): Promise<SearchCacheInvalidationResult> {\n const invalidated: string[] = [];\n const warnings: string[] = [];\n\n for (const relativePath of SEARCH_CACHE_ARTIFACT_PATHS) {\n const artifactPath = path.join(pmRoot, relativePath);\n try {\n if (!(await pathExists(artifactPath))) {\n continue;\n }\n await removeFileIfExists(artifactPath);\n invalidated.push(relativePath);\n } catch (error: unknown) {\n warnings.push(formatInvalidationWarning(relativePath, error));\n }\n }\n\n return {\n invalidated,\n warnings,\n };\n}\n\nexport async function refreshSemanticEmbeddingsForMutatedItems(\n pmRoot: string,\n itemIds: string[],\n options: SemanticRefreshOptions = {},\n): Promise<SemanticMutationRefreshResult> {\n const normalizedItemIds = toUniqueSorted(itemIds);\n if (normalizedItemIds.length === 0) {\n return {\n refreshed: [],\n skipped: [],\n warnings: [],\n };\n }\n\n const runtimeContext = await resolveSemanticRefreshRuntimeContext(pmRoot, normalizedItemIds, options);\n if (!(\"settings\" in runtimeContext)) {\n return runtimeContext;\n }\n const typeRegistry = resolveItemTypeRegistry(runtimeContext.settings, getActiveExtensionRegistrations());\n const workload = await collectSemanticRefreshWorkload(\n pmRoot,\n runtimeContext.settings.id_prefix,\n runtimeContext.settings.item_format,\n normalizedItemIds,\n typeRegistry.type_to_folder,\n runtimeContext.settings.schema,\n );\n const ledgerRead =\n workload.documents.length > 0 || workload.missingIds.length > 0\n ? await readVectorizationStatusLedger(pmRoot)\n : { entries: {}, embedding: null, warnings: [] };\n const embeddingIdentity = buildVectorizationIdentityForProvider(runtimeContext.provider);\n const nextLedgerBaseEntries = ledgerRead.entries;\n let refreshedResult: SemanticRefreshOperationResult = { refreshed: [], skipped: [], warnings: [] };\n let nextEmbeddingMetadata = ledgerRead.embedding;\n if (workload.documents.length > 0) {\n if (ledgerRead.embedding && hasVectorizationEmbeddingIdentityChanged(ledgerRead.embedding, embeddingIdentity)) {\n refreshedResult = {\n refreshed: [],\n skipped: workload.documents.map((entry) => entry.id),\n warnings: [\"search_semantic_refresh_requires_reindex:embedding_identity_changed\"],\n };\n } else {\n try {\n const embedded = await embedLocatedSemanticVectors(\n runtimeContext.settings,\n runtimeContext.provider,\n workload.documents,\n );\n if (hasVectorizationVectorDimensionChanged(ledgerRead.embedding, embedded.vector_dimension)) {\n refreshedResult = {\n refreshed: [],\n skipped: workload.documents.map((entry) => entry.id),\n warnings: [...embedded.warnings, \"search_semantic_refresh_requires_reindex:vector_dimension_changed\"],\n };\n } else {\n nextEmbeddingMetadata = buildVectorizationEmbeddingMetadata(embeddingIdentity, embedded.vector_dimension);\n const upserted = await upsertLocatedSemanticVectors(runtimeContext.vectorStore, workload.documents, embedded.vectors);\n refreshedResult = {\n refreshed: upserted.refreshed,\n skipped: upserted.skipped,\n warnings: [...embedded.warnings, ...upserted.warnings],\n };\n }\n } catch (error: unknown) {\n refreshedResult = {\n refreshed: [],\n skipped: workload.documents.map((entry) => entry.id),\n warnings: [`search_semantic_refresh_failed:${toErrorMessage(error)}`],\n };\n }\n }\n }\n const pruneResult = await pruneMissingSemanticVectors(runtimeContext.vectorStore, workload.missingIds);\n const refreshedIdSet = new Set(refreshedResult.refreshed);\n const refreshedEntries = Object.fromEntries(\n workload.documents\n .filter((entry) => refreshedIdSet.has(entry.id))\n .map((entry) => [entry.id, entry.document.metadata.updated_at]),\n );\n const ledgerWarnings: string[] = [];\n if (Object.keys(refreshedEntries).length > 0 || workload.missingIds.length > 0) {\n const nextEntries = {\n ...nextLedgerBaseEntries,\n ...normalizeVectorizationLedgerEntries(refreshedEntries),\n };\n for (const missingId of workload.missingIds) {\n delete nextEntries[missingId];\n }\n try {\n await writeVectorizationStatusLedger(pmRoot, nextEntries, nextEmbeddingMetadata);\n } catch (error: unknown) {\n ledgerWarnings.push(`search_vectorization_status_ledger_write_failed:${toErrorMessage(error)}`);\n }\n ledgerWarnings.push(...ledgerRead.warnings);\n }\n\n return {\n refreshed: toUniqueSorted([...refreshedResult.refreshed, ...pruneResult.refreshed]),\n skipped: toUniqueSorted([...workload.skippedIds, ...refreshedResult.skipped, ...pruneResult.skipped]),\n warnings: [...workload.warnings, ...refreshedResult.warnings, ...pruneResult.warnings, ...ledgerWarnings],\n };\n}\n\n/**\n * Returns true when a semantic embedding refresh would do real work for these\n * settings (an embedding provider AND a vector store both resolve). Used to\n * decide whether a mutation's refresh is worth dispatching to a background\n * worker — when semantic search is not configured the inline path is already a\n * fast no-op and no child is spawned.\n */\nexport function isSemanticRefreshActive(\n settings: Awaited<ReturnType<typeof readSettings>>,\n applyRuntimeDefaults: boolean,\n): boolean {\n const effectiveSettings = applyRuntimeDefaults\n ? resolveSettingsWithSemanticRuntimeDefaults(settings).settings\n : settings;\n return Boolean(resolveEmbeddingProviders(effectiveSettings).active && resolveVectorStores(effectiveSettings).active);\n}\n\nexport async function refreshSearchArtifactsForMutation(\n pmRoot: string,\n itemIds: string[],\n options: RefreshSearchArtifactsForMutationOptions = {},\n): Promise<SearchMutationArtifactRefreshResult> {\n const invalidation = await invalidateSearchCacheArtifacts(pmRoot);\n const normalizedItemIds = toUniqueSorted(itemIds);\n if (normalizedItemIds.length === 0) {\n return {\n invalidated: invalidation.invalidated,\n refreshed: [],\n skipped: [],\n warnings: invalidation.warnings,\n };\n }\n\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n const semanticRefresh = await refreshSemanticEmbeddingsForMutatedItems(pmRoot, normalizedItemIds);\n return {\n invalidated: invalidation.invalidated,\n refreshed: semanticRefresh.refreshed,\n skipped: semanticRefresh.skipped,\n warnings: [...invalidation.warnings, ...semanticRefresh.warnings],\n };\n }\n\n let settings: Awaited<ReturnType<typeof readSettings>>;\n try {\n settings = await readSettings(pmRoot);\n } catch (error: unknown) {\n return {\n invalidated: invalidation.invalidated,\n refreshed: [],\n skipped: normalizedItemIds,\n warnings: [\n ...invalidation.warnings,\n `search_semantic_refresh_skipped:settings_read_failed:${toErrorMessage(error)}`,\n ],\n };\n }\n\n if (settings.search.mutation_refresh_policy === \"cache_only\") {\n return {\n invalidated: invalidation.invalidated,\n refreshed: [],\n skipped: normalizedItemIds,\n warnings: invalidation.warnings,\n };\n }\n\n const applyRuntimeDefaults = settings.search.mutation_refresh_policy === \"semantic_auto\";\n\n // Keyword cache is already invalidated synchronously above (so keyword search\n // stays immediately correct). When requested, dispatch the slow embedding\n // refresh to a detached worker so the mutation returns instantly; the\n // vector_index_stale health/search warning covers the catch-up window.\n if (options.background && isSemanticRefreshActive(settings, applyRuntimeDefaults)) {\n await scheduleBackgroundSemanticRefresh(pmRoot, normalizedItemIds);\n return {\n invalidated: invalidation.invalidated,\n refreshed: [],\n skipped: [],\n warnings: [...invalidation.warnings, \"search_semantic_refresh_scheduled_background\"],\n scheduled: true,\n };\n }\n\n const semanticRefresh = await refreshSemanticEmbeddingsForMutatedItems(pmRoot, normalizedItemIds, {\n settings,\n apply_runtime_defaults: applyRuntimeDefaults,\n });\n return {\n invalidated: invalidation.invalidated,\n refreshed: semanticRefresh.refreshed,\n skipped: semanticRefresh.skipped,\n warnings: [...invalidation.warnings, ...semanticRefresh.warnings],\n };\n}\n", "import type { PmSettings } from \"../../types/index.js\";\nimport { executeEmbeddingRequest } from \"./providers.js\";\nimport type { EmbeddingProviderConfig } from \"./providers.js\";\nimport { toErrorMessage } from \"../shared/primitives.js\";\nimport {\n OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS,\n SEMANTIC_CORPUS_TRUNCATION_SUFFIX,\n resolveSemanticCorpusCharacterLimit,\n} from \"./corpus.js\";\n\nexport interface EmbeddingBatchExecutionResult {\n vectors: number[][];\n warnings: string[];\n}\n\nexport interface EmbeddingBatchProgressEvent {\n batch_index: number;\n batch_total: number;\n batch_size: number;\n completed_inputs: number;\n total_inputs: number;\n attempt?: number;\n phase: \"start\" | \"complete\";\n}\n\nexport interface EmbeddingBatchExecutionOptions {\n onProgress?: (event: EmbeddingBatchProgressEvent) => void;\n}\n\ninterface EmbeddingBatchRuntime {\n batchSize: number;\n timeoutMs: number;\n maxRetries: number;\n maxBatchInputCharacters: number;\n maxInputCharacters: number;\n}\n\nfunction resolveBatchRuntime(\n settings: PmSettings,\n maxInputCharacters: number,\n): EmbeddingBatchRuntime {\n const batchSizeCandidate = settings.search.embedding_batch_size;\n const timeoutMsCandidate = settings.search.embedding_timeout_ms;\n const maxRetriesCandidate = settings.search.scanner_max_batch_retries;\n const batchSize = Number.isFinite(batchSizeCandidate) && batchSizeCandidate > 0 ? Math.floor(batchSizeCandidate) : 1;\n const timeoutMs =\n Number.isFinite(timeoutMsCandidate) && timeoutMsCandidate > 0 ? Math.floor(timeoutMsCandidate) : 30_000;\n const maxRetries = Number.isFinite(maxRetriesCandidate) && maxRetriesCandidate >= 0 ? Math.floor(maxRetriesCandidate) : 0;\n return {\n batchSize,\n timeoutMs,\n maxRetries,\n maxBatchInputCharacters: Number.POSITIVE_INFINITY,\n maxInputCharacters,\n };\n}\n\nfunction createBatches(inputs: string[], batchSize: number, maxBatchInputCharacters: number): string[][] {\n const batches: string[][] = [];\n let currentBatch: string[] = [];\n let currentCharacters = 0;\n for (const input of inputs) {\n const wouldExceedCount = currentBatch.length >= batchSize;\n const wouldExceedCharacters =\n currentBatch.length > 0 &&\n Number.isFinite(maxBatchInputCharacters) &&\n currentCharacters + input.length > maxBatchInputCharacters;\n if (wouldExceedCount || wouldExceedCharacters) {\n batches.push(currentBatch);\n currentBatch = [];\n currentCharacters = 0;\n }\n currentBatch.push(input);\n currentCharacters += input.length;\n }\n batches.push(currentBatch);\n return batches;\n}\n\nfunction resolveProviderBatchRuntime(provider: EmbeddingProviderConfig, runtime: EmbeddingBatchRuntime): EmbeddingBatchRuntime {\n if (provider.name !== \"ollama\") {\n return runtime;\n }\n return {\n ...runtime,\n maxBatchInputCharacters: OLLAMA_SEMANTIC_CORPUS_INPUT_MAX_CHARACTERS,\n };\n}\n\nfunction truncateInputForRuntime(input: string, maxInputCharacters: number): string {\n if (!Number.isFinite(maxInputCharacters) || maxInputCharacters <= 0 || input.length <= maxInputCharacters) {\n return input;\n }\n const keepLength = Math.max(0, maxInputCharacters - SEMANTIC_CORPUS_TRUNCATION_SUFFIX.length);\n return `${input.slice(0, keepLength)}${SEMANTIC_CORPUS_TRUNCATION_SUFFIX}`.slice(0, maxInputCharacters);\n}\n\nfunction isEmbeddingTimeoutError(error: unknown): boolean {\n const message = toErrorMessage(error).toLowerCase();\n return message.includes(\"timed out\") || message.includes(\"timeout\");\n}\n\nfunction buildEmbeddingFailureMessage(\n provider: EmbeddingProviderConfig,\n batchLabel: string,\n batchSize: number,\n timeoutMs: number,\n attempts: number,\n error: unknown,\n): string {\n const base = `Embedding batch ${batchLabel} failed after ${attempts} attempt(s): ${toErrorMessage(error)}`;\n const details = `provider=${provider.name} model=${provider.model} batch_size=${batchSize} timeout_ms=${timeoutMs}`;\n if (!isEmbeddingTimeoutError(error)) {\n return `${base} (${details})`;\n }\n return `${base} (${details}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`;\n}\n\nasync function executeBatchWithAdaptiveSplit(\n provider: EmbeddingProviderConfig,\n batch: string[],\n batchLabel: string,\n timeoutMs: number,\n maxRetries: number,\n warnings: string[],\n): Promise<number[][]> {\n let lastError: unknown = null;\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n try {\n const batchVectors = await executeEmbeddingRequest(provider, batch, { timeout_ms: timeoutMs });\n if (attempt > 0) {\n warnings.push(\n `search_embedding_batch_retry_succeeded:batch=${batchLabel}:attempt=${attempt + 1}:size=${batch.length}`,\n );\n }\n return batchVectors;\n } catch (error: unknown) {\n lastError = error;\n if (isEmbeddingTimeoutError(error) && batch.length > 1) {\n const midpoint = Math.ceil(batch.length / 2);\n const left = batch.slice(0, midpoint);\n const right = batch.slice(midpoint);\n warnings.push(\n `search_embedding_batch_split_after_timeout:batch=${batchLabel}:size=${batch.length}:parts=${left.length}|${right.length}`,\n );\n return [\n ...(await executeBatchWithAdaptiveSplit(provider, left, `${batchLabel}.1`, timeoutMs, maxRetries, warnings)),\n ...(await executeBatchWithAdaptiveSplit(provider, right, `${batchLabel}.2`, timeoutMs, maxRetries, warnings)),\n ];\n }\n if (attempt < maxRetries) {\n const delayMs = Math.min(1000 * 2 ** attempt, 8000);\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n }\n }\n throw new Error(buildEmbeddingFailureMessage(provider, batchLabel, batch.length, timeoutMs, maxRetries + 1, lastError));\n}\n\nexport async function executeEmbeddingBatchesWithRetry(\n provider: EmbeddingProviderConfig,\n settings: PmSettings,\n inputs: string[],\n options: EmbeddingBatchExecutionOptions = {},\n): Promise<EmbeddingBatchExecutionResult> {\n if (inputs.length === 0) {\n return {\n vectors: [],\n warnings: [],\n };\n }\n const warnings: string[] = [];\n const corpusLimitResolution = resolveSemanticCorpusCharacterLimit(\n provider.name,\n settings.search.embedding_corpus_max_characters,\n );\n if (corpusLimitResolution.warning) {\n warnings.push(corpusLimitResolution.warning);\n }\n const runtime = resolveProviderBatchRuntime(\n provider,\n resolveBatchRuntime(settings, corpusLimitResolution.maxCharacters),\n );\n let truncatedInputCount = 0;\n const normalizedInputs = inputs.map((input) => {\n const normalized = truncateInputForRuntime(input, runtime.maxInputCharacters);\n if (normalized.length < input.length) {\n truncatedInputCount += 1;\n }\n return normalized;\n });\n if (truncatedInputCount > 0) {\n warnings.push(`search_embedding_input_truncated:count=${truncatedInputCount}:max_characters=${runtime.maxInputCharacters}`);\n }\n const batches = createBatches(normalizedInputs, runtime.batchSize, runtime.maxBatchInputCharacters);\n const vectors: number[][] = [];\n let completedInputs = 0;\n for (let batchIndex = 0; batchIndex < batches.length; batchIndex += 1) {\n const batch = batches[batchIndex];\n options.onProgress?.({\n batch_index: batchIndex + 1,\n batch_total: batches.length,\n batch_size: batch.length,\n completed_inputs: completedInputs,\n total_inputs: normalizedInputs.length,\n phase: \"start\",\n });\n vectors.push(\n ...(await executeBatchWithAdaptiveSplit(\n provider,\n batch,\n String(batchIndex + 1),\n runtime.timeoutMs,\n runtime.maxRetries,\n warnings,\n )),\n );\n completedInputs += batch.length;\n options.onProgress?.({\n batch_index: batchIndex + 1,\n batch_total: batches.length,\n batch_size: batch.length,\n completed_inputs: completedInputs,\n total_inputs: normalizedInputs.length,\n phase: \"complete\",\n });\n }\n return {\n vectors,\n warnings,\n };\n}\n", "import { spawn } from \"node:child_process\";\nimport { mkdirSync, rmSync, statSync } from \"node:fs\";\nimport path from \"node:path\";\n\nimport { pathExists, readFileIfExists, writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { acquireLock } from \"../lock/lock.js\";\nimport { resolvePmPackageRootFromModule } from \"../packages/root.js\";\nimport { readSettings } from \"../store/settings.js\";\nimport { toErrorMessage } from \"../shared/primitives.js\";\nimport { resolveSettingsWithSemanticRuntimeDefaults } from \"./semantic-defaults.js\";\n\n/**\n * Shared lock id for any process that rewrites the local vector store. Reindex\n * and the background mutation-refresh worker both acquire this so they never\n * write concurrently and corrupt the store. Exported so `pm reindex` reuses the\n * same id rather than duplicating the literal.\n */\nexport const REINDEX_LOCK_ID = \"reindex\";\n\nconst PENDING_QUEUE_REL_PATH = \"search/pending-refresh.json\";\nconst PENDING_QUEUE_GATE_REL_PATH = \"search/pending-refresh.gate.lock\";\nconst PENDING_QUEUE_GATE_STALE_MS = 30_000;\n\n// Bounded reindex-lock retry for the background worker (~3.2s worst case).\nconst LOCK_ACQUIRE_ATTEMPTS = 8;\nconst LOCK_ACQUIRE_BACKOFF_MS = 400;\n\nconst SEARCH_REFRESH_INLINE_ENV = \"PM_SEARCH_REFRESH_INLINE\";\nconst SEARCH_REFRESH_CHILD_ENV = \"PM_SEARCH_REFRESH_CHILD\";\n\nfunction parseBooleanTrueLike(value: string | undefined): boolean {\n if (typeof value !== \"string\") {\n return false;\n }\n const normalized = value.trim().toLowerCase();\n return normalized === \"1\" || normalized === \"true\" || normalized === \"yes\" || normalized === \"on\";\n}\n\n/**\n * Mutation search refresh runs inline (blocking) under test runners, inside the\n * background worker child itself, or when explicitly requested. Otherwise the\n * semantic refresh is dispatched to a detached child so mutations return without\n * waiting on embeddings. Mirrors the telemetry-flush inline gate so the full test\n * suite stays deterministic.\n */\nexport function shouldRunSearchRefreshInForeground(): boolean {\n if (parseBooleanTrueLike(process.env[SEARCH_REFRESH_INLINE_ENV])) {\n return true;\n }\n if (parseBooleanTrueLike(process.env[SEARCH_REFRESH_CHILD_ENV])) {\n return true;\n }\n const nodeEnv = (process.env.NODE_ENV ?? \"\").trim().toLowerCase();\n return (\n typeof process.env.VITEST === \"string\" ||\n typeof process.env.VITEST_WORKER_ID === \"string\" ||\n nodeEnv === \"test\"\n );\n}\n\nfunction pendingQueuePath(pmRoot: string): string {\n return path.join(pmRoot, PENDING_QUEUE_REL_PATH);\n}\n\nfunction pendingQueueGatePath(pmRoot: string): string {\n return path.join(pmRoot, PENDING_QUEUE_GATE_REL_PATH);\n}\n\nfunction acquireQueueGate(pmRoot: string): boolean {\n const gatePath = pendingQueueGatePath(pmRoot);\n try {\n if (Date.now() - statSync(gatePath).mtimeMs < PENDING_QUEUE_GATE_STALE_MS) {\n return false;\n }\n rmSync(gatePath, { recursive: true, force: true });\n } catch {\n // Missing gate is the common case; fall through to create it.\n }\n try {\n mkdirSync(path.dirname(gatePath), { recursive: true });\n mkdirSync(gatePath);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction releaseQueueGate(pmRoot: string): void {\n try {\n rmSync(pendingQueueGatePath(pmRoot), { recursive: true, force: true });\n } catch {\n // Best effort; a stale gate self-heals after PENDING_QUEUE_GATE_STALE_MS.\n }\n}\n\nasync function withQueueGate<T>(pmRoot: string, fn: () => Promise<T>, fallback: T): Promise<T> {\n // Briefly serialize read-modify-write access to the pending queue across the\n // mutation process and the worker child. Acquisition is best effort; if a\n // healthy gate is held we skip rather than risk a torn queue.\n for (let attempt = 0; attempt < 50; attempt += 1) {\n if (acquireQueueGate(pmRoot)) {\n try {\n return await fn();\n } finally {\n releaseQueueGate(pmRoot);\n }\n }\n await delay(20);\n }\n return fallback;\n}\n\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms).unref?.();\n });\n}\n\nasync function readPendingQueueIds(pmRoot: string): Promise<string[]> {\n const raw = await readFileIfExists(pendingQueuePath(pmRoot));\n if (!raw || raw.trim().length === 0) {\n return [];\n }\n try {\n const parsed = JSON.parse(raw) as { ids?: unknown };\n if (!Array.isArray(parsed.ids)) {\n return [];\n }\n return parsed.ids.filter((id): id is string => typeof id === \"string\" && id.length > 0);\n } catch {\n return [];\n }\n}\n\nasync function writePendingQueueIds(pmRoot: string, ids: string[]): Promise<void> {\n await writeFileAtomic(pendingQueuePath(pmRoot), `${JSON.stringify({ ids })}\\n`);\n}\n\n/** Merge mutated item ids into the persistent pending-refresh queue. */\nexport async function enqueuePendingRefreshIds(pmRoot: string, itemIds: string[]): Promise<void> {\n const incoming = itemIds.filter((id) => typeof id === \"string\" && id.trim().length > 0);\n if (incoming.length === 0) {\n return;\n }\n const mergeIncoming = async (): Promise<void> => {\n const existing = await readPendingQueueIds(pmRoot);\n const merged = [...new Set([...existing, ...incoming])].sort((left, right) => left.localeCompare(right));\n await writePendingQueueIds(pmRoot, merged);\n };\n const gated = await withQueueGate(\n pmRoot,\n async () => {\n await mergeIncoming();\n return true;\n },\n false,\n );\n if (!gated) {\n // The gate stayed contended past the retry budget. Never silently drop a\n // mutation's refresh work: fall back to a best-effort unguarded merge.\n // writeFileAtomic keeps the file valid; the only risk is losing a concurrent\n // writer's delta, which its own next dispatch and the vector_index_stale\n // warning both recover.\n await mergeIncoming();\n }\n}\n\n/** Atomically read and clear the pending-refresh queue, returning drained ids. */\nexport async function drainPendingRefreshIds(pmRoot: string): Promise<string[]> {\n return withQueueGate(\n pmRoot,\n async () => {\n const ids = await readPendingQueueIds(pmRoot);\n if (ids.length > 0) {\n await writePendingQueueIds(pmRoot, []);\n }\n return ids;\n },\n [],\n );\n}\n\nfunction searchRefreshRunnerPath(): string {\n return path.join(\n resolvePmPackageRootFromModule(import.meta.url, [\"../../..\"]),\n \"dist\",\n \"cli\",\n \"search-refresh.js\",\n );\n}\n\n/**\n * Spawn the detached refresh worker child for this pm root. Best effort: a\n * failed dispatch must never keep the CLI alive or fail a mutation; the next\n * mutation re-dispatches and `vector_index_stale` warns about the catch-up\n * window in the meantime.\n */\nfunction dispatchRefreshChild(pmRoot: string): void {\n try {\n const child = spawn(process.execPath, [searchRefreshRunnerPath()], {\n detached: true,\n stdio: \"ignore\",\n env: {\n ...process.env,\n PM_PATH: pmRoot,\n [SEARCH_REFRESH_CHILD_ENV]: \"1\",\n },\n });\n // A detached child can emit an async 'error' event (e.g. spawn EAGAIN/ENOENT,\n // resource limits). Swallow it so it never becomes an unhandled error that\n // crashes the parent CLI; dispatch is best effort.\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // Best effort — see doc comment above.\n }\n}\n\n/**\n * Enqueue mutated ids and dispatch a detached worker child to refresh semantic\n * embeddings without blocking the mutation. The reindex lock the worker acquires\n * serializes concurrent refreshes, so the spawn itself stays unconditional and\n * cheap; a worker that loses the lock exits and its ids are drained by the holder.\n */\nexport async function scheduleBackgroundSemanticRefresh(pmRoot: string, itemIds: string[]): Promise<void> {\n await enqueuePendingRefreshIds(pmRoot, itemIds);\n dispatchRefreshChild(pmRoot);\n}\n\nexport interface SemanticRefreshWorkerResult {\n processed: string[];\n rounds: number;\n warnings: string[];\n}\n\ntype SemanticRefreshFn = (\n pmRoot: string,\n itemIds: string[],\n) => Promise<{ refreshed: string[]; skipped: string[]; warnings: string[] }>;\n\n/**\n * Drain the pending queue and refresh semantic vectors under the reindex lock so\n * the local vector store is never rewritten concurrently. If the lock is held by\n * another worker we exit immediately — that holder drains our enqueued ids. After\n * releasing we re-check the queue once and re-dispatch if a sibling enqueued ids\n * during our final window, guaranteeing eventual processing.\n */\nexport async function runSemanticRefreshWorker(\n pmRoot: string,\n refresh: SemanticRefreshFn,\n): Promise<SemanticRefreshWorkerResult> {\n const warnings: string[] = [];\n const processed: string[] = [];\n if (!(await pathExists(pmRoot))) {\n return { processed, rounds: 0, warnings };\n }\n\n let settings: Awaited<ReturnType<typeof readSettings>>;\n try {\n settings = resolveSettingsWithSemanticRuntimeDefaults(await readSettings(pmRoot)).settings;\n } catch (error: unknown) {\n return { processed, rounds: 0, warnings: [`search_background_refresh_settings_read_failed:${toErrorMessage(error)}`] };\n }\n\n // Retry the reindex lock with backoff rather than exiting on the first\n // conflict: a sibling refresh worker holds it only briefly (~one embed), so a\n // few retries pick up the queued ids in this run instead of stranding them\n // until the next mutation. If a long `pm reindex` keeps it, we give up — that\n // full pass re-embeds everything anyway and the next dispatch retries.\n let release: (() => Promise<void>) | null = null;\n for (let attempt = 0; attempt < LOCK_ACQUIRE_ATTEMPTS && !release; attempt += 1) {\n try {\n release = await acquireLock(\n pmRoot,\n REINDEX_LOCK_ID,\n settings.locks.ttl_seconds,\n process.env.PM_AUTHOR ?? \"pm-search-refresh\",\n false,\n settings.governance.force_required_for_stale_lock,\n );\n } catch {\n if (attempt < LOCK_ACQUIRE_ATTEMPTS - 1) {\n await delay(LOCK_ACQUIRE_BACKOFF_MS);\n }\n }\n }\n if (!release) {\n return { processed, rounds: 0, warnings };\n }\n\n let rounds = 0;\n let failed = false;\n try {\n for (;;) {\n const ids = await drainPendingRefreshIds(pmRoot);\n if (ids.length === 0) {\n break;\n }\n rounds += 1;\n try {\n const result = await refresh(pmRoot, ids);\n processed.push(...result.refreshed);\n warnings.push(...result.warnings);\n } catch (error: unknown) {\n warnings.push(`search_background_refresh_failed:${toErrorMessage(error)}`);\n // Re-enqueue so the work is retried by a later dispatch rather than lost.\n await enqueuePendingRefreshIds(pmRoot, ids);\n failed = true;\n break;\n }\n }\n } finally {\n await release?.();\n }\n\n // Close the race where a sibling enqueued ids between our last empty drain and\n // releasing the lock: re-dispatch so those ids are eventually processed. Skip\n // this after a refresh failure — the failed ids were re-enqueued and an\n // immediate respawn would just fail again, spinning indefinitely. They wait\n // for the next mutation's dispatch instead.\n const remaining = failed ? [] : await readPendingQueueIds(pmRoot);\n if (remaining.length > 0) {\n dispatchRefreshChild(pmRoot);\n }\n\n return { processed: [...new Set(processed)].sort((a, b) => a.localeCompare(b)), rounds, warnings };\n}\n", "import { toNonEmptyString } from \"../shared/primitives.js\";\n\nexport interface VectorizationEmbeddingIdentity {\n provider: string;\n model: string;\n}\n\nexport interface VectorizationEmbeddingMetadata extends VectorizationEmbeddingIdentity {\n vector_dimension: number;\n}\n\nexport function buildVectorizationEmbeddingIdentity(\n provider: unknown,\n model: unknown,\n): VectorizationEmbeddingIdentity | null {\n const normalizedProvider = toNonEmptyString(provider);\n const normalizedModel = toNonEmptyString(model);\n if (!normalizedProvider || !normalizedModel) {\n return null;\n }\n return {\n provider: normalizedProvider,\n model: normalizedModel,\n };\n}\n\nexport function normalizeVectorizationEmbeddingMetadata(value: unknown): VectorizationEmbeddingMetadata | null {\n if (value === undefined || value === null) {\n return null;\n }\n if (typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\"Vectorization embedding metadata must be an object when set\");\n }\n const identity = buildVectorizationEmbeddingIdentity(\n (value as { provider?: unknown }).provider,\n (value as { model?: unknown }).model,\n );\n const vectorDimension = (value as { vector_dimension?: unknown }).vector_dimension;\n if (!identity || typeof vectorDimension !== \"number\" || !Number.isInteger(vectorDimension) || vectorDimension <= 0) {\n throw new Error(\"Vectorization embedding metadata must include provider, model, and positive vector_dimension\");\n }\n return {\n ...identity,\n vector_dimension: vectorDimension,\n };\n}\n\nexport function buildVectorizationEmbeddingMetadata(\n identity: VectorizationEmbeddingIdentity,\n vectorDimension: number,\n): VectorizationEmbeddingMetadata {\n if (!Number.isInteger(vectorDimension) || vectorDimension <= 0) {\n throw new Error(\"Vectorization embedding metadata requires a positive vector dimension\");\n }\n return {\n provider: identity.provider,\n model: identity.model,\n vector_dimension: vectorDimension,\n };\n}\n\nexport function hasVectorizationEmbeddingIdentityChanged(\n metadata: VectorizationEmbeddingMetadata | null | undefined,\n identity: VectorizationEmbeddingIdentity,\n): boolean {\n return !metadata || metadata.provider !== identity.provider || metadata.model !== identity.model;\n}\n\nexport function hasVectorizationVectorDimensionChanged(\n metadata: VectorizationEmbeddingMetadata | null | undefined,\n vectorDimension: number,\n): boolean {\n return Boolean(metadata && metadata.vector_dimension !== vectorDimension);\n}\n\nexport function inferConsistentVectorDimension(vectors: readonly number[][], context: string): number {\n if (vectors.length === 0) {\n throw new Error(`${context} returned no vectors`);\n }\n const firstVector = vectors[0] as number[];\n const dimension = firstVector.length;\n if (!Number.isInteger(dimension) || dimension <= 0) {\n throw new Error(`${context} returned an empty vector`);\n }\n for (let index = 1; index < vectors.length; index += 1) {\n if (vectors[index]?.length !== dimension) {\n throw new Error(`${context} returned mixed vector dimensions`);\n }\n }\n return dimension;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEO,IAAM,iCAAiC;AAiCxC,SAAU,6BACd,WACA,cACA,mBAAmB,gCAA8B;AAEjD,QAAM,WAAW,aAAa;AAC9B,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a;QAChB,wDAAwD,eAAe,KAAK,CAAC;;;EAGnF;AAEA,MAAI,SAAS,OAAO,4BAA4B,cAAc;AAC5D,WAAO;MACL,aAAa,aAAa;MAC1B,WAAW,CAAA;MACX,SAAS;MACT,UAAU,aAAa;;EAE3B;AAEA,QAAM,uBAAuB,SAAS,OAAO,4BAA4B;AAMzE,MAAI,QAAQ,cAAc,wBAAwB,UAAU,oBAAoB,GAAG;AACjF,UAAM,kCAAkC,QAAQ,iBAAiB;AACjE,WAAO;MACL,aAAa,aAAa;MAC1B,WAAW,CAAA;MACX,SAAS,CAAA;MACT,UAAU,CAAC,GAAG,aAAa,UAAU,8CAA8C;MACnF,WAAW;;EAEf;AAEA,QAAM,kBAAkB,MAAM,yCAAyC,QAAQ,mBAAmB;IAChG;IACA,wBAAwB;GACzB;AACD,SAAO;IACL,aAAa,aAAa;IAC1B,WAAW,gBAAgB;IAC3B,SAAS,gBAAgB;IACzB,UAAU,CAAC,GAAG,aAAa,UAAU,GAAG,gBAAgB,QAAQ;;AAEpE;",
6
+ "names": ["loaded", "encodedCollection", "path", "resolve", "resolve", "path", "path", "semanticRefresh"]
7
+ }
@@ -1,11 +1,11 @@
1
1
  // dist/core/fs/fs-utils.js
2
- import fs from "node:fs/promises";
2
+ import * as fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import crypto from "node:crypto";
5
5
  !(function() {
6
6
  try {
7
7
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
8
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "24293159-379b-5416-a184-9ed7ef02ca92");
8
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "8b4dd1a6-7645-5c6e-afd3-f4c23fe19182");
9
9
  } catch (e2) {
10
10
  }
11
11
  })();
@@ -35,7 +35,26 @@ async function writeFileAtomic(targetPath, contents) {
35
35
  await ensureDir(dirPath);
36
36
  const tempPath = path.join(dirPath, `.${path.basename(targetPath)}.${process.pid}.${Date.now()}.${crypto.randomBytes(4).toString("hex")}.tmp`);
37
37
  await fs.writeFile(tempPath, contents, "utf8");
38
- await fs.rename(tempPath, targetPath);
38
+ try {
39
+ await fs.rename(tempPath, targetPath);
40
+ } catch (error) {
41
+ if (isErrno(error, "EXDEV")) {
42
+ try {
43
+ await fs.copyFile(tempPath, targetPath);
44
+ } finally {
45
+ try {
46
+ await fs.unlink(tempPath);
47
+ } catch {
48
+ }
49
+ }
50
+ return;
51
+ }
52
+ try {
53
+ await fs.unlink(tempPath);
54
+ } catch {
55
+ }
56
+ throw error;
57
+ }
39
58
  }
40
59
  async function appendLineAtomic(targetPath, line) {
41
60
  const dirPath = path.dirname(targetPath);
@@ -85,7 +104,7 @@ import { fileURLToPath } from "node:url";
85
104
  !(function() {
86
105
  try {
87
106
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
88
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "20b7827b-6f96-518c-8df3-b699d41dec88");
107
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "71eb0333-ba65-5a8a-aafe-a5ec10f24a8a");
89
108
  } catch (e2) {
90
109
  }
91
110
  })();
@@ -120,6 +139,18 @@ function resolvePmPackageRootFromModule(metaUrl, fallbackRelativeSegments = [])
120
139
  }
121
140
  return path3.resolve(path3.dirname(modulePath), ...fallbackRelativeSegments);
122
141
  }
142
+ function resolvePmCliVersion(metaUrl, fallbackRelativeSegments = []) {
143
+ try {
144
+ const packageJsonPath = path3.join(resolvePmPackageRootFromModule(metaUrl, fallbackRelativeSegments), "package.json");
145
+ if (!fs2.existsSync(packageJsonPath)) {
146
+ return void 0;
147
+ }
148
+ const parsed = JSON.parse(fs2.readFileSync(packageJsonPath, "utf8"));
149
+ return typeof parsed.version === "string" && parsed.version.trim().length > 0 ? parsed.version : void 0;
150
+ } catch {
151
+ return void 0;
152
+ }
153
+ }
123
154
 
124
155
  // dist/core/extensions/extension-types.js
125
156
  !(function() {
@@ -601,7 +632,7 @@ import path4 from "node:path";
601
632
  !(function() {
602
633
  try {
603
634
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
604
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "69c3e476-e726-5f10-8c7d-89914dcc7a59");
635
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "0827d0fd-560e-5f98-961d-350989b068a6");
605
636
  } catch (e2) {
606
637
  }
607
638
  })();
@@ -641,7 +672,14 @@ function resolvePmRoot(cwd, cliPath) {
641
672
  const envPath = process.env.PM_PATH;
642
673
  const explicitPath = cliPath?.trim() || envPath?.trim();
643
674
  if (explicitPath) {
644
- return path4.resolve(cwd, explicitPath);
675
+ const resolved = path4.resolve(cwd, explicitPath);
676
+ if (!pathExists2(getSettingsPath(resolved))) {
677
+ const nestedRoot = path4.join(resolved, PM_DIRNAME);
678
+ if (pathExists2(getSettingsPath(nestedRoot))) {
679
+ return nestedRoot;
680
+ }
681
+ }
682
+ return resolved;
645
683
  }
646
684
  const discoveredRoot = discoverPmRootFromAncestors(cwd);
647
685
  if (discoveredRoot) {
@@ -3972,7 +4010,7 @@ import path6 from "node:path";
3972
4010
  !(function() {
3973
4011
  try {
3974
4012
  var e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
3975
- n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "11167959-e632-5d72-a6d1-103f6a7d50ef");
4013
+ n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "221fcd13-8553-5c32-a2d8-2845d0f71047");
3976
4014
  } catch (e2) {
3977
4015
  }
3978
4016
  })();
@@ -4346,10 +4384,7 @@ async function loadRuntimeSchemaFromOptionalFiles(pmRoot, schema) {
4346
4384
  const statusFilePath = filePathForSchemaSection(pmRoot, normalizedSchema.files.statuses, DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.statuses);
4347
4385
  const fieldsFilePath = filePathForSchemaSection(pmRoot, normalizedSchema.files.fields, DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields);
4348
4386
  const workflowsFilePath = filePathForSchemaSection(pmRoot, normalizedSchema.files.workflows, DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows);
4349
- const typeDefinitionsFromFile = /* @__PURE__ */ (() => {
4350
- return void 0;
4351
- })();
4352
- let loadedTypeDefinitions = typeDefinitionsFromFile;
4387
+ let loadedTypeDefinitions;
4353
4388
  let loadedStatuses;
4354
4389
  let loadedFields;
4355
4390
  let loadedWorkflow;
@@ -5855,6 +5890,7 @@ export {
5855
5890
  removeFileIfExists,
5856
5891
  isPathWithinDirectory,
5857
5892
  resolvePmPackageRootFromModule,
5893
+ resolvePmCliVersion,
5858
5894
  KNOWN_EXTENSION_CAPABILITIES,
5859
5895
  EXTENSION_CAPABILITY_CONTRACT,
5860
5896
  KNOWN_EXTENSION_POLICY_MODES,
@@ -5977,4 +6013,4 @@ export {
5977
6013
  readSettings,
5978
6014
  writeSettings
5979
6015
  };
5980
- //# sourceMappingURL=chunk-UJUT6AHZ.js.map
6016
+ //# sourceMappingURL=chunk-3TXWDGPU.js.map