prjct-cli 3.93.0 → 3.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (265) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +27 -21
  3. package/dist/bin/hook-chunks/{agent-switch-A6AYZRJ5.mjs → agent-switch-4ZJJWKMD.mjs} +1 -1
  4. package/dist/bin/hook-chunks/{analysis-WPRPBYHY.mjs → analysis-UGHAG2SK.mjs} +3 -3
  5. package/dist/bin/hook-chunks/{auth-config-WNUARXTJ.mjs → auth-config-JIITQ6GY.mjs} +1 -1
  6. package/dist/bin/hook-chunks/auto-flush-CXWTU3RF.mjs +8 -0
  7. package/dist/bin/hook-chunks/{auto-updater-EHRRMCYY.mjs → auto-updater-4TIXYSEX.mjs} +1 -1
  8. package/dist/bin/hook-chunks/capture-gate-PS6QUXLX.mjs +8 -0
  9. package/dist/bin/hook-chunks/chunk-22AXWLI6.mjs +26 -0
  10. package/dist/bin/hook-chunks/chunk-32RX4YGI.mjs +9 -0
  11. package/dist/bin/hook-chunks/{chunk-6EWGHM32.mjs → chunk-3WQBTXUC.mjs} +1 -1
  12. package/dist/bin/hook-chunks/{chunk-ZZ65CN5F.mjs → chunk-4HAKTI36.mjs} +1 -1
  13. package/dist/bin/hook-chunks/{chunk-V37VTXDW.mjs → chunk-4KVPAHFV.mjs} +1 -1
  14. package/dist/bin/hook-chunks/chunk-4KXXDQYI.mjs +11 -0
  15. package/dist/bin/hook-chunks/{chunk-4WHS7CO7.mjs → chunk-4NTVXJD7.mjs} +1 -1
  16. package/dist/bin/hook-chunks/{chunk-HIFIDMH5.mjs → chunk-5H3KJWQS.mjs} +2 -2
  17. package/dist/bin/hook-chunks/chunk-5XA5RL5I.mjs +8 -0
  18. package/dist/bin/hook-chunks/chunk-6GAFRIUQ.mjs +18 -0
  19. package/dist/bin/hook-chunks/{chunk-4OYUJTPR.mjs → chunk-76GDLA3Z.mjs} +3 -3
  20. package/dist/bin/hook-chunks/chunk-7YT2FGO7.mjs +8 -0
  21. package/dist/bin/hook-chunks/chunk-A6K4H3YT.mjs +9 -0
  22. package/dist/bin/hook-chunks/{chunk-MEQS4VPO.mjs → chunk-ABJNOG2I.mjs} +1 -1
  23. package/dist/bin/hook-chunks/{chunk-7SI6X3Z7.mjs → chunk-B36LC2JR.mjs} +1 -1
  24. package/dist/bin/hook-chunks/chunk-BCAHWZH7.mjs +8 -0
  25. package/dist/bin/hook-chunks/{chunk-EM6ZDJAK.mjs → chunk-BDOAQVIF.mjs} +1 -1
  26. package/dist/bin/hook-chunks/chunk-BOBFTVAY.mjs +11 -0
  27. package/dist/bin/hook-chunks/{chunk-7OZDWT6C.mjs → chunk-BU22R6JX.mjs} +1 -1
  28. package/dist/bin/hook-chunks/chunk-BX7VKYA7.mjs +8 -0
  29. package/dist/bin/hook-chunks/chunk-C4O243NG.mjs +9 -0
  30. package/dist/bin/hook-chunks/chunk-CYZ7ST2P.mjs +36 -0
  31. package/dist/bin/hook-chunks/chunk-DCSKTMDX.mjs +8 -0
  32. package/dist/bin/hook-chunks/{chunk-WDGDFXSB.mjs → chunk-DVDZA63F.mjs} +1 -1
  33. package/dist/bin/hook-chunks/{chunk-ZX2KFQV5.mjs → chunk-EWOK4VE7.mjs} +1 -1
  34. package/dist/bin/hook-chunks/{chunk-ODWWIFSN.mjs → chunk-FEFP6JOL.mjs} +1 -1
  35. package/dist/bin/hook-chunks/{chunk-7AN7VQHN.mjs → chunk-FW4MEPTB.mjs} +1 -1
  36. package/dist/bin/hook-chunks/chunk-FXFG6PV6.mjs +69 -0
  37. package/dist/bin/hook-chunks/chunk-G7QQZMAO.mjs +9 -0
  38. package/dist/bin/hook-chunks/{chunk-P5ZYAXSE.mjs → chunk-GCDLPKOH.mjs} +1 -1
  39. package/dist/bin/hook-chunks/{chunk-ACKEPXP4.mjs → chunk-GDECEHO5.mjs} +1 -1
  40. package/dist/bin/hook-chunks/chunk-GDESYWTD.mjs +14 -0
  41. package/dist/bin/hook-chunks/chunk-GLPKMG5A.mjs +18 -0
  42. package/dist/bin/hook-chunks/chunk-GPZP7NXL.mjs +11 -0
  43. package/dist/bin/hook-chunks/{chunk-PSSR7LSW.mjs → chunk-H4CA3XZ6.mjs} +1 -1
  44. package/dist/bin/hook-chunks/chunk-HEDZA6KC.mjs +8 -0
  45. package/dist/bin/hook-chunks/{chunk-3LG3ACQV.mjs → chunk-I26F7TLM.mjs} +1 -1
  46. package/dist/bin/hook-chunks/chunk-IGHY4FGS.mjs +8 -0
  47. package/dist/bin/hook-chunks/{chunk-DMXFGLZE.mjs → chunk-IWJG7CZX.mjs} +1 -1
  48. package/dist/bin/hook-chunks/{chunk-LLQUB6YR.mjs → chunk-J5UQVJUW.mjs} +2 -2
  49. package/dist/bin/hook-chunks/chunk-J5UVRZ44.mjs +15 -0
  50. package/dist/bin/hook-chunks/{chunk-QDQ7DTDV.mjs → chunk-JR542RI2.mjs} +1 -1
  51. package/dist/bin/hook-chunks/{chunk-P4J6TY2L.mjs → chunk-KHLYWNHT.mjs} +1 -1
  52. package/dist/bin/hook-chunks/{chunk-75UJIVMO.mjs → chunk-KOGZCFBC.mjs} +1 -1
  53. package/dist/bin/hook-chunks/{chunk-Q5I2UPD6.mjs → chunk-KSSRINDX.mjs} +1 -1
  54. package/dist/bin/hook-chunks/{chunk-ZTZTVBAZ.mjs → chunk-LNB2GLYI.mjs} +1 -1
  55. package/dist/bin/hook-chunks/chunk-M5E2YOZ4.mjs +8 -0
  56. package/dist/bin/hook-chunks/{chunk-PWMMLXZS.mjs → chunk-MHNWIB7B.mjs} +2 -2
  57. package/dist/bin/hook-chunks/{chunk-LFY5O66D.mjs → chunk-N3L77UNM.mjs} +1 -1
  58. package/dist/bin/hook-chunks/{chunk-TSCXXNUF.mjs → chunk-NLKPAJND.mjs} +1 -1
  59. package/dist/bin/hook-chunks/{chunk-3JUE6MNF.mjs → chunk-OC4CYF7V.mjs} +1 -1
  60. package/dist/bin/hook-chunks/chunk-OGIFB3OE.mjs +19 -0
  61. package/dist/bin/hook-chunks/chunk-OUAS3LZ3.mjs +8 -0
  62. package/dist/bin/hook-chunks/{chunk-6WXGOGAN.mjs → chunk-OUAVSD47.mjs} +1 -1
  63. package/dist/bin/hook-chunks/{chunk-X5RDLFPM.mjs → chunk-OWOPA2O7.mjs} +1 -1
  64. package/dist/bin/hook-chunks/chunk-PGWFGRX4.mjs +47 -0
  65. package/dist/bin/hook-chunks/chunk-PO3QDKTE.mjs +8 -0
  66. package/dist/bin/hook-chunks/{chunk-RXD7MHJ6.mjs → chunk-PP6DANGV.mjs} +1 -1
  67. package/dist/bin/hook-chunks/{chunk-HT3ZCLLJ.mjs → chunk-PTA7DMLM.mjs} +1 -1
  68. package/dist/bin/hook-chunks/{chunk-45I2C2UB.mjs → chunk-QBYHZX33.mjs} +1 -1
  69. package/dist/bin/hook-chunks/chunk-QL3NYJTW.mjs +16 -0
  70. package/dist/bin/hook-chunks/{chunk-AOPJ4Z6O.mjs → chunk-QP5USCDX.mjs} +1 -1
  71. package/dist/bin/hook-chunks/chunk-QWQFF2UG.mjs +10 -0
  72. package/dist/bin/hook-chunks/chunk-R4ILCXKE.mjs +8 -0
  73. package/dist/bin/hook-chunks/{chunk-D7TRY3CO.mjs → chunk-RHKF7EJW.mjs} +1 -1
  74. package/dist/bin/hook-chunks/{chunk-HZIORCPO.mjs → chunk-ROA2AJXY.mjs} +1 -1
  75. package/dist/bin/hook-chunks/{chunk-AUUWQH3S.mjs → chunk-RTEEXGEA.mjs} +1 -1
  76. package/dist/bin/hook-chunks/{chunk-QK2IMCDC.mjs → chunk-S5ISOGDB.mjs} +1 -1
  77. package/dist/bin/hook-chunks/{chunk-GIMUTVLP.mjs → chunk-S5N2ZZDL.mjs} +1 -1
  78. package/dist/bin/hook-chunks/{chunk-742LOGHA.mjs → chunk-S6L3FECF.mjs} +1 -1
  79. package/dist/bin/hook-chunks/{chunk-CREPUNOS.mjs → chunk-T6ELTQZM.mjs} +1 -1
  80. package/dist/bin/hook-chunks/{chunk-UK7D7EFV.mjs → chunk-TXSLON7M.mjs} +2 -2
  81. package/dist/bin/hook-chunks/chunk-U4OON3S7.mjs +31 -0
  82. package/dist/bin/hook-chunks/chunk-UH4MD3F3.mjs +9 -0
  83. package/dist/bin/hook-chunks/{chunk-HDHVBB6Q.mjs → chunk-UHVYBU7F.mjs} +1 -1
  84. package/dist/bin/hook-chunks/chunk-UYQC63MC.mjs +11 -0
  85. package/dist/bin/hook-chunks/{chunk-3WY2AYPE.mjs → chunk-V2FR2NPL.mjs} +4 -4
  86. package/dist/bin/hook-chunks/{chunk-L4376X2P.mjs → chunk-WGWE3CSC.mjs} +1 -1
  87. package/dist/bin/hook-chunks/{chunk-KXWBIQGJ.mjs → chunk-X5W2UYQK.mjs} +2 -2
  88. package/dist/bin/hook-chunks/{chunk-YUOTOCKK.mjs → chunk-XDBJSJOT.mjs} +1 -1
  89. package/dist/bin/hook-chunks/{chunk-2NMSEZTQ.mjs → chunk-XFQ7NNLN.mjs} +1 -1
  90. package/dist/bin/hook-chunks/{chunk-SOPRYWUY.mjs → chunk-XS45K7ZQ.mjs} +1 -1
  91. package/dist/bin/hook-chunks/{chunk-BISPGBNN.mjs → chunk-XXRAQZNC.mjs} +1 -1
  92. package/dist/bin/hook-chunks/{chunk-NLG2EW6M.mjs → chunk-YDBZO6I3.mjs} +1 -1
  93. package/dist/bin/hook-chunks/{chunk-6IKHMK2U.mjs → chunk-YQ55MHKL.mjs} +1 -1
  94. package/dist/bin/hook-chunks/chunk-Z4X7JIAP.mjs +11 -0
  95. package/dist/bin/hook-chunks/{chunk-2OU2MKNS.mjs → chunk-Z6KVLCMK.mjs} +1 -1
  96. package/dist/bin/hook-chunks/{chunk-OGOCHZ3S.mjs → chunk-ZFLIVOFX.mjs} +1 -1
  97. package/dist/bin/hook-chunks/{chunk-54LH63LM.mjs → chunk-ZMLA5SKR.mjs} +1 -0
  98. package/dist/bin/hook-chunks/chunk-ZOX6OV6X.mjs +12 -0
  99. package/dist/bin/hook-chunks/client-CRXA774S.mjs +10 -0
  100. package/dist/bin/hook-chunks/code-graph-cloud-GTSLO7CD.mjs +8 -0
  101. package/dist/bin/hook-chunks/{codex-skill-ZCAUF2RM.mjs → codex-skill-NUBNPSMF.mjs} +1 -1
  102. package/dist/bin/hook-chunks/{command-installer-LNK7WC5I.mjs → command-installer-UHSXC3UG.mjs} +1 -1
  103. package/dist/bin/hook-chunks/{config-manager-4VWDBPMG.mjs → config-manager-DX5OOPW5.mjs} +1 -1
  104. package/dist/bin/hook-chunks/{content-bound-stamp-72EQVZLP.mjs → content-bound-stamp-OG2KKN3L.mjs} +1 -1
  105. package/dist/bin/hook-chunks/{context7-service-4C6VNJUS.mjs → context7-service-GDJ3QICX.mjs} +1 -1
  106. package/dist/bin/hook-chunks/custom-workflow-storage-FD47DPA3.mjs +8 -0
  107. package/dist/bin/hook-chunks/cwd-changed-EP3UIRK6.mjs +8 -0
  108. package/dist/bin/hook-chunks/{database-SLDTQXWG.mjs → database-ZUC7OEZG.mjs} +1 -1
  109. package/dist/bin/hook-chunks/{delivery-geometry-VHCURJ7E.mjs → delivery-geometry-WYOEMKMO.mjs} +1 -1
  110. package/dist/bin/hook-chunks/{detect-changes-M2OYIOE5.mjs → detect-changes-OJUBWWTU.mjs} +1 -1
  111. package/dist/bin/hook-chunks/{detection-MEYHME4X.mjs → detection-QRVSNMKL.mjs} +1 -1
  112. package/dist/bin/hook-chunks/developer-evolution-WNSTHDAA.mjs +12 -0
  113. package/dist/bin/hook-chunks/distill-GOGPFQFK.mjs +8 -0
  114. package/dist/bin/hook-chunks/{editors-config-3N6VREZR.mjs → editors-config-2CACBNS4.mjs} +1 -1
  115. package/dist/bin/hook-chunks/enriched-recall-QF22RIK7.mjs +8 -0
  116. package/dist/bin/hook-chunks/exec-2P5VOBHM.mjs +8 -0
  117. package/dist/bin/hook-chunks/format-J3X3R225.mjs +8 -0
  118. package/dist/bin/hook-chunks/{git-helpers-6JLP2OJZ.mjs → git-helpers-HELM6DXJ.mjs} +1 -1
  119. package/dist/bin/hook-chunks/{judgment-ledger-storage-UKROWRVA.mjs → judgment-ledger-storage-FE4HXTHM.mjs} +1 -1
  120. package/dist/bin/hook-chunks/{judgment-orchestrator-UFGNBTEK.mjs → judgment-orchestrator-YDJTKNV2.mjs} +1 -1
  121. package/dist/bin/hook-chunks/judgment-receipt-7A2DXVJA.mjs +8 -0
  122. package/dist/bin/hook-chunks/land-cue-SZWJH6XP.mjs +9 -0
  123. package/dist/bin/hook-chunks/land-synthesis-JLYUBKHR.mjs +8 -0
  124. package/dist/bin/hook-chunks/legacy-crew-sweep-JXYO62UE.mjs +24 -0
  125. package/dist/bin/hook-chunks/memory-index-CIYDXN2G.mjs +8 -0
  126. package/dist/bin/hook-chunks/notification-UA7RTVHG.mjs +8 -0
  127. package/dist/bin/hook-chunks/{pack-integrity-62XJ5A75.mjs → pack-integrity-GZC5NGFN.mjs} +1 -1
  128. package/dist/bin/hook-chunks/{pack-manager-K3PQ7MCS.mjs → pack-manager-AF5F7PRT.mjs} +1 -1
  129. package/dist/bin/hook-chunks/{package-legitimacy-HXC4L73B.mjs → package-legitimacy-MIR3VZSF.mjs} +1 -1
  130. package/dist/bin/hook-chunks/{path-manager-F2HE2GGK.mjs → path-manager-375HH6TB.mjs} +1 -1
  131. package/dist/bin/hook-chunks/{planning-WMLFXZMA.mjs → planning-M3RAOZVB.mjs} +2 -2
  132. package/dist/bin/hook-chunks/post-edit-QRDYPZLZ.mjs +8 -0
  133. package/dist/bin/hook-chunks/{pr-convention-7UGI7TFA.mjs → pr-convention-5NPXQJ2R.mjs} +1 -1
  134. package/dist/bin/hook-chunks/pre-bash-TWWFVNQ7.mjs +11 -0
  135. package/dist/bin/hook-chunks/pre-commit-PTFF7JIN.mjs +8 -0
  136. package/dist/bin/hook-chunks/pre-edit-PMMWDR2B.mjs +11 -0
  137. package/dist/bin/hook-chunks/pre-package-325ALZKD.mjs +8 -0
  138. package/dist/bin/hook-chunks/pre-search-GOHVFAFH.mjs +9 -0
  139. package/dist/bin/hook-chunks/pre-secrets-MYNM5KI4.mjs +8 -0
  140. package/dist/bin/hook-chunks/{precision-judgment-WPTCNTGV.mjs → precision-judgment-TT3DRNAX.mjs} +1 -1
  141. package/dist/bin/hook-chunks/{prjct-md-Q6C5YNI3.mjs → prjct-md-RCB6FWD6.mjs} +1 -1
  142. package/dist/bin/hook-chunks/{project-agent-surfaces-3BBZIQNI.mjs → project-agent-surfaces-V4P5RTUR.mjs} +1 -1
  143. package/dist/bin/hook-chunks/{project-file-inventory-ZAPKPKY6.mjs → project-file-inventory-OKIP4LBO.mjs} +1 -1
  144. package/dist/bin/hook-chunks/project-memory-JK2MXRJB.mjs +8 -0
  145. package/dist/bin/hook-chunks/project-style-evolution-RPGATIYJ.mjs +8 -0
  146. package/dist/bin/hook-chunks/prompt-DOENKHLQ.mjs +24 -0
  147. package/dist/bin/hook-chunks/{velocity-storage-UPW6TLK6.mjs → publish-helper-SX7HEV2L.mjs} +1 -1
  148. package/dist/bin/hook-chunks/purge-XKHUAB4H.mjs +8 -0
  149. package/dist/bin/hook-chunks/retention-C3NQT65W.mjs +8 -0
  150. package/dist/bin/hook-chunks/sdd-6PF7MBAY.mjs +10 -0
  151. package/dist/bin/hook-chunks/session-continuity-UEXQDGZE.mjs +11 -0
  152. package/dist/bin/hook-chunks/session-start-B4P7L33E.mjs +8 -0
  153. package/dist/bin/hook-chunks/setup-ZOHG6MGF.mjs +141 -0
  154. package/dist/bin/hook-chunks/{shipping-HV5IAM2J.mjs → shipping-QVGTOO6U.mjs} +5 -5
  155. package/dist/bin/hook-chunks/{skill-index-OOVAXHYJ.mjs → skill-index-FGDQVYHM.mjs} +1 -1
  156. package/dist/bin/hook-chunks/{spec-context-inference-UBHJLOIJ.mjs → spec-context-inference-6Z52BT37.mjs} +1 -1
  157. package/dist/bin/hook-chunks/{spec-service-TA4Q5S3X.mjs → spec-service-UAQ5AEXQ.mjs} +2 -2
  158. package/dist/bin/hook-chunks/spec-task-breakdown-LAXGVLMY.mjs +8 -0
  159. package/dist/bin/hook-chunks/state-storage-XU35ZYNA.mjs +8 -0
  160. package/dist/bin/hook-chunks/stop-CFB2H3XC.mjs +16 -0
  161. package/dist/bin/hook-chunks/subagent-start-KFAZZUHS.mjs +8 -0
  162. package/dist/bin/hook-chunks/subagent-stop-OUG4PR7S.mjs +8 -0
  163. package/dist/bin/hook-chunks/{surface-attribution-HYCBHBTC.mjs → surface-attribution-A6GCGRFM.mjs} +1 -1
  164. package/dist/bin/hook-chunks/symbol-graph-DMPBNBX7.mjs +8 -0
  165. package/dist/bin/hook-chunks/{sync-analyzer-FKC57RTV.mjs → sync-analyzer-6U5GHYV3.mjs} +1 -1
  166. package/dist/bin/hook-chunks/{sync-client-DJWOG2ZQ.mjs → sync-client-PIRHMHXL.mjs} +1 -1
  167. package/dist/bin/hook-chunks/{sync-cursor-storage-2VKG757H.mjs → sync-cursor-storage-VVLA3L2U.mjs} +1 -1
  168. package/dist/bin/hook-chunks/{task-orchestration-MLOCR7GA.mjs → task-orchestration-HFZYWYLR.mjs} +1 -1
  169. package/dist/bin/hook-chunks/{task-overview-6ZQKJGSH.mjs → task-overview-PCUZWL5Q.mjs} +1 -1
  170. package/dist/bin/hook-chunks/task-service-PXCDU55T.mjs +8 -0
  171. package/dist/bin/hook-chunks/tdd-QZL4OSM7.mjs +10 -0
  172. package/dist/bin/hook-chunks/{template-loader-SO6OHPJI.mjs → template-loader-SKXILJLJ.mjs} +1 -1
  173. package/dist/bin/hook-chunks/{transcript-jsonl-6X4DDD6R.mjs → transcript-jsonl-7W2NOJPZ.mjs} +1 -1
  174. package/dist/bin/hook-chunks/{trust-boundary-ERMDF2C5.mjs → trust-boundary-EX65SUYR.mjs} +1 -1
  175. package/dist/bin/hook-chunks/{usefulness-253CZLNY.mjs → usefulness-SZLG6LVC.mjs} +1 -1
  176. package/dist/bin/hook-chunks/{vault-retire-notice-GRT3QRLZ.mjs → vault-retire-notice-HOXPURNQ.mjs} +1 -1
  177. package/dist/bin/hook-chunks/velocity-storage-5J6BAMCW.mjs +8 -0
  178. package/dist/bin/hook-chunks/weak-model-mode-ZRNKFTFF.mjs +8 -0
  179. package/dist/bin/hook-chunks/work-graph-PGYHFLEL.mjs +49 -0
  180. package/dist/bin/hook-chunks/work-scope-FIB6LBKE.mjs +8 -0
  181. package/dist/bin/hook-chunks/{workspace-occupancy-UVIRHY5Z.mjs → workspace-occupancy-3D4OKQRB.mjs} +1 -1
  182. package/dist/bin/hook-chunks/{worktree-service-XGRN5TTE.mjs → worktree-service-AS7JVBK5.mjs} +1 -1
  183. package/dist/bin/hook-fast-darwin-arm64 +0 -0
  184. package/dist/bin/hook-fast-darwin-x64 +0 -0
  185. package/dist/bin/hook-fast-linux-x64 +0 -0
  186. package/dist/bin/prjct-core.mjs +737 -736
  187. package/dist/bin/prjct-hooks.mjs +2 -2
  188. package/dist/bin/prjct.mjs +1 -1
  189. package/dist/daemon/entry.mjs +651 -647
  190. package/dist/mcp/server.mjs +310 -312
  191. package/package.json +1 -1
  192. package/dist/bin/hook-chunks/auto-flush-5D4PKOMM.mjs +0 -8
  193. package/dist/bin/hook-chunks/capture-gate-EOOSAGAP.mjs +0 -8
  194. package/dist/bin/hook-chunks/chunk-4DDCWMI6.mjs +0 -8
  195. package/dist/bin/hook-chunks/chunk-4KY2EHXS.mjs +0 -9
  196. package/dist/bin/hook-chunks/chunk-A5RNWWTH.mjs +0 -9
  197. package/dist/bin/hook-chunks/chunk-A7SGMNOK.mjs +0 -11
  198. package/dist/bin/hook-chunks/chunk-AKIN5WSQ.mjs +0 -9
  199. package/dist/bin/hook-chunks/chunk-BNWB77U5.mjs +0 -9
  200. package/dist/bin/hook-chunks/chunk-CQHPIYNM.mjs +0 -8
  201. package/dist/bin/hook-chunks/chunk-CTWZQ7YI.mjs +0 -8
  202. package/dist/bin/hook-chunks/chunk-DLHSCKBJ.mjs +0 -15
  203. package/dist/bin/hook-chunks/chunk-DV7KV2O4.mjs +0 -38
  204. package/dist/bin/hook-chunks/chunk-EHP4DYVQ.mjs +0 -71
  205. package/dist/bin/hook-chunks/chunk-FGQZ62ZP.mjs +0 -47
  206. package/dist/bin/hook-chunks/chunk-HJ4HEI45.mjs +0 -8
  207. package/dist/bin/hook-chunks/chunk-J6JZ4PQA.mjs +0 -18
  208. package/dist/bin/hook-chunks/chunk-JRKGG2E3.mjs +0 -8
  209. package/dist/bin/hook-chunks/chunk-L4COZ7ZH.mjs +0 -13
  210. package/dist/bin/hook-chunks/chunk-LT5WSSQO.mjs +0 -8
  211. package/dist/bin/hook-chunks/chunk-MHRMV4WI.mjs +0 -31
  212. package/dist/bin/hook-chunks/chunk-N5WOHG36.mjs +0 -8
  213. package/dist/bin/hook-chunks/chunk-NJAMZSHM.mjs +0 -26
  214. package/dist/bin/hook-chunks/chunk-NWY5M34K.mjs +0 -12
  215. package/dist/bin/hook-chunks/chunk-OB5GRS7T.mjs +0 -18
  216. package/dist/bin/hook-chunks/chunk-PW3KYKVS.mjs +0 -9
  217. package/dist/bin/hook-chunks/chunk-SVZHJZ5T.mjs +0 -9
  218. package/dist/bin/hook-chunks/chunk-UB53HQMG.mjs +0 -14
  219. package/dist/bin/hook-chunks/chunk-UBMIPWJR.mjs +0 -19
  220. package/dist/bin/hook-chunks/chunk-VPPHD762.mjs +0 -11
  221. package/dist/bin/hook-chunks/chunk-VV7VNUTF.mjs +0 -16
  222. package/dist/bin/hook-chunks/chunk-YJMWY4Y6.mjs +0 -8
  223. package/dist/bin/hook-chunks/client-SKFMAUI5.mjs +0 -10
  224. package/dist/bin/hook-chunks/code-graph-cloud-65GCWNII.mjs +0 -8
  225. package/dist/bin/hook-chunks/custom-workflow-storage-M77INP6Z.mjs +0 -8
  226. package/dist/bin/hook-chunks/cwd-changed-FYNPPO73.mjs +0 -8
  227. package/dist/bin/hook-chunks/developer-evolution-R5BXQH6G.mjs +0 -12
  228. package/dist/bin/hook-chunks/distill-W7QGQUDX.mjs +0 -8
  229. package/dist/bin/hook-chunks/enriched-recall-W7KYRYVR.mjs +0 -8
  230. package/dist/bin/hook-chunks/exec-I7XE7NMD.mjs +0 -8
  231. package/dist/bin/hook-chunks/format-BOWFDUBP.mjs +0 -8
  232. package/dist/bin/hook-chunks/judgment-receipt-WGTFKID7.mjs +0 -8
  233. package/dist/bin/hook-chunks/land-cue-WLGSULSO.mjs +0 -9
  234. package/dist/bin/hook-chunks/land-synthesis-V7UH5QV6.mjs +0 -8
  235. package/dist/bin/hook-chunks/legacy-crew-sweep-MFE4BDNR.mjs +0 -24
  236. package/dist/bin/hook-chunks/memory-index-B53F5HAX.mjs +0 -10
  237. package/dist/bin/hook-chunks/notification-HJLS4L7Y.mjs +0 -8
  238. package/dist/bin/hook-chunks/post-edit-TT3XOG55.mjs +0 -8
  239. package/dist/bin/hook-chunks/pre-bash-2KKF4V6G.mjs +0 -11
  240. package/dist/bin/hook-chunks/pre-commit-UU4SKKWV.mjs +0 -8
  241. package/dist/bin/hook-chunks/pre-edit-RTBLZPWH.mjs +0 -11
  242. package/dist/bin/hook-chunks/pre-package-LQTINBT4.mjs +0 -8
  243. package/dist/bin/hook-chunks/pre-search-UJU3XZ2K.mjs +0 -9
  244. package/dist/bin/hook-chunks/pre-secrets-IE5NX5X5.mjs +0 -8
  245. package/dist/bin/hook-chunks/project-memory-YHQBRX3D.mjs +0 -8
  246. package/dist/bin/hook-chunks/project-style-evolution-HS6HYI7W.mjs +0 -8
  247. package/dist/bin/hook-chunks/prompt-AYY7BZFG.mjs +0 -22
  248. package/dist/bin/hook-chunks/publish-helper-I37V4L7U.mjs +0 -8
  249. package/dist/bin/hook-chunks/purge-AXMYTZVM.mjs +0 -8
  250. package/dist/bin/hook-chunks/retention-22OSCAGV.mjs +0 -8
  251. package/dist/bin/hook-chunks/sdd-W3OUQPHD.mjs +0 -10
  252. package/dist/bin/hook-chunks/session-continuity-LO2KNHXU.mjs +0 -11
  253. package/dist/bin/hook-chunks/session-start-5UZSL6OY.mjs +0 -8
  254. package/dist/bin/hook-chunks/setup-BSWLQJPE.mjs +0 -142
  255. package/dist/bin/hook-chunks/spec-task-breakdown-QJWGCON2.mjs +0 -8
  256. package/dist/bin/hook-chunks/state-storage-KNGP2CQV.mjs +0 -8
  257. package/dist/bin/hook-chunks/stop-QVDK6LUV.mjs +0 -17
  258. package/dist/bin/hook-chunks/subagent-start-UYBSD7VK.mjs +0 -8
  259. package/dist/bin/hook-chunks/subagent-stop-FHLL7X66.mjs +0 -8
  260. package/dist/bin/hook-chunks/symbol-graph-LZM4RZXZ.mjs +0 -8
  261. package/dist/bin/hook-chunks/task-service-RMCQEHV6.mjs +0 -8
  262. package/dist/bin/hook-chunks/tdd-LV63NXZ3.mjs +0 -10
  263. package/dist/bin/hook-chunks/weak-model-mode-VDYJ25PX.mjs +0 -8
  264. package/dist/bin/hook-chunks/work-graph-QJGNBVIP.mjs +0 -49
  265. package/dist/bin/hook-chunks/work-scope-OKFSTW6D.mjs +0 -8
package/CHANGELOG.md CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [3.95.0] - 2026-08-16
6
+
7
+ ### Added
8
+ - kimi code full integration
9
+
10
+ ## [3.94.0] - 2026-08-16
11
+
12
+ ### Added
13
+ - eliminate duplicate code
14
+
5
15
  ## [3.93.0] - 2026-08-16
6
16
 
7
17
  ### Added
package/README.md CHANGED
@@ -173,10 +173,16 @@ It reports concrete support levels:
173
173
  | `hosted` | Repo instructions are the portable layer; platform config may be manual. |
174
174
 
175
175
  Run `prjct agents doctor --md` to see the current machine/project matrix for
176
- Claude Code, Codex, Gemini CLI, OpenCode, Qwen Code, Kimi CLI, Grok Build,
176
+ Claude Code, Codex, Gemini CLI, OpenCode, Qwen Code, Kimi Code CLI, Grok Build,
177
177
  Cursor, Pi, Cline/Roo-family agents, hosted agents, and future
178
178
  AGENTS.md/MCP clients.
179
179
 
180
+ Kimi Code CLI is `full`: native `[[hooks]]` entries in
181
+ `~/.kimi-code/config.toml`, MCP servers in `~/.kimi-code/mcp.json`, and the
182
+ compact skill at `~/.agents/skills/prjct/SKILL.md` — all installed by
183
+ `prjct install` when Kimi is detected (the legacy `~/.kimi/` directory remains
184
+ a detection fallback only).
185
+
180
186
  Use `prjct agents doctor --fix` inside a prjct project to refresh the portable
181
187
  `AGENTS.md` surface and any repo-local IDE rule adapters prjct manages. The
182
188
  command is idempotent and reports what changed.
@@ -333,27 +339,27 @@ Seven built-in packs (TypeScript manifests in `core/packs/manifests.ts`, not bas
333
339
 
334
340
  Slots ship **empty** — the human or the agent fills them on demand.
335
341
 
336
- ## Claude Hooks Adapter (opt-in)
342
+ ## Hooks Adapter (opt-in) — Claude Code + Kimi Code CLI
337
343
 
338
- `prjct install` refreshes the universal project surface (`AGENTS.md`) when run inside a prjct project, writes the Claude Code hooks adapter to `~/.claude/settings.json`, and repairs detected Codex config in `~/.codex/config.toml` (prjct MCP + TUI `status_line`). Most of the 13 hook subcommands inject `additionalContext`; two guard: the credential guard denies tool calls that would leak secrets, and the package guard denies unknown installs under strict packs. Other agents use the support level shown by `prjct agents doctor`.
344
+ `prjct install` refreshes the universal project surface (`AGENTS.md`) when run inside a prjct project, writes the Claude Code hooks adapter to `~/.claude/settings.json`, writes the native Kimi Code CLI hooks adapter as `[[hooks]]` entries in `~/.kimi-code/config.toml` (marked with a `# prjct-managed` comment each — TOML forbids extra entry fields, and user entries or other tools' blocks stay byte-identical), and repairs detected Codex config in `~/.codex/config.toml` (prjct MCP + TUI `status_line`). Most of the 13 hook subcommands inject `additionalContext` (plain stdout text under Kimi, which appends it to context); two guard: the credential guard denies tool calls that would leak secrets, and the package guard denies unknown installs under strict packs. Kimi applies hook config on the next session (or after `/reload`). Other agents use the support level shown by `prjct agents doctor`.
339
345
 
340
- | Event | Does |
341
- |---|---|
342
- | `SessionStart` | Persona; on cold start (startup/clear/compact) also the knowledge digest — top traps + decisions in force, so a freshly-updated model starts grounded |
343
- | `UserPromptSubmit` | Active project state (task, branch, inbox) |
344
- | `PreToolUse` (any tool) | Credential guard — **denies** the call when tool arguments contain secret material, so credentials never leave the machine |
345
- | `PreToolUse` (Bash package installs) | Package legitimacy — flags packages not already in `package.json` before the install runs (strict packs deny) |
346
- | `PreToolUse` (Bash git commit) | Anti-patterns tagged with touched files |
347
- | `PreToolUse` (Edit/Write) | The file's preventive memory (gotchas/anti-patterns) right before you edit it — pushes what `prjct guard` makes pull |
348
- | `PreToolUse` (Grep/Glob) | Injects indexed symbol-graph hits alongside search results (never gates) |
349
- | `PostToolUse` (Edit/Write) | Silently annotates `files_touched` on active task |
350
- | `Stop` | Async prompt: "learn anything reusable?"; scans the transcript for durable captures |
351
- | `SubagentStart` | Persona for fresh-brain subagents (cache-stable, digest-free) |
352
- | `SubagentStop` | Desktop notification when a subagent finishes (`config.notify`, default on) |
353
- | `Notification` | Desktop notification when the agent is waiting for input or permission |
354
- | `CwdChanged` | Re-contextualizes on project switch |
355
-
356
- Remove with `prjct claude uninstall` (hooks only) or `prjct uninstall` (everything).
346
+ | Event | Does | Kimi |
347
+ |---|---|---|
348
+ | `SessionStart` | Persona; on cold start (startup/clear/compact) also the knowledge digest — top traps + decisions in force, so a freshly-updated model starts grounded | ✓ |
349
+ | `UserPromptSubmit` | Active project state (task, branch, inbox) | ✓ |
350
+ | `PreToolUse` (any tool) | Credential guard — **denies** the call when tool arguments contain secret material, so credentials never leave the machine | ✓ |
351
+ | `PreToolUse` (Bash package installs) | Package legitimacy — flags packages not already in `package.json` before the install runs (strict packs deny) | ✓ |
352
+ | `PreToolUse` (Bash git commit) | Anti-patterns tagged with touched files | ✓ |
353
+ | `PreToolUse` (Edit/Write) | The file's preventive memory (gotchas/anti-patterns) right before you edit it — pushes what `prjct guard` makes pull | ✓ |
354
+ | `PreToolUse` (Grep/Glob) | Injects indexed symbol-graph hits alongside search results (never gates) | ✓ |
355
+ | `PostToolUse` (Edit/Write) | Silently annotates `files_touched` on active task | ✓ |
356
+ | `Stop` | Async prompt: "learn anything reusable?"; scans the transcript for durable captures | ✓ |
357
+ | `SubagentStart` | Persona for fresh-brain subagents (cache-stable, digest-free) | ✓ |
358
+ | `SubagentStop` | Desktop notification when a subagent finishes (`config.notify`, default on) | ✓ |
359
+ | `Notification` | Desktop notification when the agent is waiting for input or permission | ✓ |
360
+ | `CwdChanged` | Re-contextualizes on project switch | — (no Kimi equivalent; every Kimi payload already carries `cwd`) |
361
+
362
+ Remove with `prjct claude uninstall` (Claude hooks only) or `prjct uninstall` (everything — including the prjct-managed `[[hooks]]` entries in `~/.kimi-code/config.toml` and the prjct/context7 servers in Kimi's `mcp.json`).
357
363
 
358
364
  ## MCP Server
359
365
 
@@ -526,7 +532,7 @@ prjct-cli/
526
532
  ## Requirements
527
533
 
528
534
  - Node.js 22.5+ (ships `node:sqlite`) or Bun 1.0+
529
- - One of: Claude Code, OpenAI Codex, Gemini CLI, Cursor, OpenCode, Cline, Grok Build, Pi, Kimi CLI, or Antigravity
535
+ - One of: Claude Code, OpenAI Codex, Gemini CLI, Cursor, OpenCode, Cline, Grok Build, Pi, Kimi Code CLI, or Antigravity
530
536
 
531
537
  ## Common questions
532
538
 
@@ -5,7 +5,7 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{a as E,b as I}from"./chunk-X5RDLFPM.mjs";import{a as P}from"./chunk-VV7VNUTF.mjs";import{a as O}from"./chunk-5WAONIPX.mjs";import{a as C}from"./chunk-5TBQNW2G.mjs";import{b as N,c as H,d as L}from"./chunk-TRMBRDKH.mjs";import{h as _}from"./chunk-EHP4DYVQ.mjs";import"./chunk-L4376X2P.mjs";import"./chunk-Q5I2UPD6.mjs";import"./chunk-PSSR7LSW.mjs";import"./chunk-PWMMLXZS.mjs";import{c as D,d as A}from"./chunk-CREPUNOS.mjs";import"./chunk-D7TRY3CO.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-ODWWIFSN.mjs";import"./chunk-UB53HQMG.mjs";import"./chunk-LLQUB6YR.mjs";import"./chunk-NLG2EW6M.mjs";import"./chunk-6IKHMK2U.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-75UJIVMO.mjs";import"./chunk-QDQ7DTDV.mjs";import"./chunk-2OU2MKNS.mjs";import"./chunk-YJMWY4Y6.mjs";import"./chunk-NJAMZSHM.mjs";import"./chunk-6EWGHM32.mjs";import"./chunk-SJ75V4WG.mjs";import"./chunk-4DDCWMI6.mjs";import"./chunk-BNWB77U5.mjs";import"./chunk-KXWBIQGJ.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-3WY2AYPE.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-QK2IMCDC.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-3FBCOCPD.mjs";import{b as y}from"./chunk-BISPGBNN.mjs";import"./chunk-LT5WSSQO.mjs";import"./chunk-HJ4HEI45.mjs";import{a as x}from"./chunk-3LG3ACQV.mjs";import"./chunk-AOPJ4Z6O.mjs";import"./chunk-AUUWQH3S.mjs";import"./chunk-GVNMXVVA.mjs";import{b as h}from"./chunk-JRKGG2E3.mjs";import"./chunk-MEQS4VPO.mjs";import{d as f,g as v}from"./chunk-HDHVBB6Q.mjs";import"./chunk-CE4RCNC7.mjs";import{b as m,e as V,i as S,k as Y,l as R,r as q}from"./chunk-AKIN5WSQ.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-SVZHJZ5T.mjs";import"./chunk-CTWZQ7YI.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-P5ZYAXSE.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a}from"./chunk-E66B27AL.mjs";q();import{spawn as X}from"node:child_process";v();V();v();function G(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}a(G,"parseEvidence");function $(t){return{id:t.id,projectId:t.project_id,taskId:t.task_id,taskDescription:t.task_description,fromAgent:t.from_agent,fromIdentity:t.from_identity,toAgent:t.to_agent,reason:t.reason,evidence:G(t.evidence),status:t.status,workspaceId:t.workspace_id,worktreePath:t.worktree_path,branch:t.branch,createdAt:t.created_at,acceptedAt:t.accepted_at,acceptedBy:t.accepted_by,expiresAt:t.expires_at}}a($,"toHandoff");function M(t){let e=new Date;return e.setTime(e.getTime()+Math.max(1,t)*36e5),e.toISOString()}a(M,"expiresAtIso");function W(t){let e=`hand_${x()}`,o=m(),n=t.ttlHours??24,r=t.evidence?JSON.stringify(t.evidence):null;return f.run(t.projectId,`INSERT INTO task_handoffs (
8
+ import{a as E,b as I}from"./chunk-OWOPA2O7.mjs";import{a as P}from"./chunk-QL3NYJTW.mjs";import{a as O}from"./chunk-5WAONIPX.mjs";import{a as C}from"./chunk-5TBQNW2G.mjs";import"./chunk-HEDZA6KC.mjs";import{b as N,c as H,d as L}from"./chunk-TRMBRDKH.mjs";import{h as _}from"./chunk-FXFG6PV6.mjs";import"./chunk-WGWE3CSC.mjs";import"./chunk-KSSRINDX.mjs";import"./chunk-H4CA3XZ6.mjs";import"./chunk-MHNWIB7B.mjs";import{c as D,d as A}from"./chunk-T6ELTQZM.mjs";import"./chunk-RHKF7EJW.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-FEFP6JOL.mjs";import"./chunk-GDESYWTD.mjs";import"./chunk-J5UQVJUW.mjs";import"./chunk-YDBZO6I3.mjs";import"./chunk-YQ55MHKL.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-KOGZCFBC.mjs";import"./chunk-Z6KVLCMK.mjs";import"./chunk-IGHY4FGS.mjs";import"./chunk-22AXWLI6.mjs";import"./chunk-3WQBTXUC.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-SJ75V4WG.mjs";import"./chunk-DCSKTMDX.mjs";import"./chunk-R4ILCXKE.mjs";import"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-3FBCOCPD.mjs";import{b as y}from"./chunk-XXRAQZNC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-5XA5RL5I.mjs";import{a as x}from"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-GAOQHD5S.mjs";import{b as h}from"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import{d as f,g as v}from"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import{b as m,h as V,l as S,n as Y,o as R,u as q}from"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a}from"./chunk-E66B27AL.mjs";q();import{spawn as X}from"node:child_process";v();V();v();function G(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}a(G,"parseEvidence");function $(t){return{id:t.id,projectId:t.project_id,taskId:t.task_id,taskDescription:t.task_description,fromAgent:t.from_agent,fromIdentity:t.from_identity,toAgent:t.to_agent,reason:t.reason,evidence:G(t.evidence),status:t.status,workspaceId:t.workspace_id,worktreePath:t.worktree_path,branch:t.branch,createdAt:t.created_at,acceptedAt:t.accepted_at,acceptedBy:t.accepted_by,expiresAt:t.expires_at}}a($,"toHandoff");function M(t){let e=new Date;return e.setTime(e.getTime()+Math.max(1,t)*36e5),e.toISOString()}a(M,"expiresAtIso");function W(t){let e=`hand_${x()}`,o=m(),n=t.ttlHours??24,r=t.evidence?JSON.stringify(t.evidence):null;return f.run(t.projectId,`INSERT INTO task_handoffs (
9
9
  id, project_id, task_id, task_description, from_agent, from_identity,
10
10
  to_agent, reason, evidence, status, workspace_id, worktree_path, branch,
11
11
  created_at, accepted_at, accepted_by, expires_at
@@ -5,10 +5,10 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{a as G,b as Se,c as b,d as U,e as q,f as H,g as ve,h as $e,i as v}from"./chunk-DV7KV2O4.mjs";import"./chunk-FGQZ62ZP.mjs";import"./chunk-TXJT3G53.mjs";import"./chunk-A5RNWWTH.mjs";import"./chunk-HZIORCPO.mjs";import"./chunk-WDGDFXSB.mjs";import"./chunk-NWY5M34K.mjs";import"./chunk-EHP4DYVQ.mjs";import"./chunk-L4376X2P.mjs";import"./chunk-Q5I2UPD6.mjs";import{a as y,b as R,c as M,d as we,e as E,f as L,g as z}from"./chunk-ACKEPXP4.mjs";import{b as ge,c as A,d as ke}from"./chunk-742LOGHA.mjs";import"./chunk-PSSR7LSW.mjs";import{a as d}from"./chunk-PWMMLXZS.mjs";import"./chunk-CREPUNOS.mjs";import"./chunk-D7TRY3CO.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-ODWWIFSN.mjs";import"./chunk-UB53HQMG.mjs";import"./chunk-LLQUB6YR.mjs";import"./chunk-NLG2EW6M.mjs";import"./chunk-6IKHMK2U.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-75UJIVMO.mjs";import"./chunk-A7SGMNOK.mjs";import"./chunk-QDQ7DTDV.mjs";import"./chunk-ZTZTVBAZ.mjs";import{a as ue}from"./chunk-DYHYDHCW.mjs";import"./chunk-2OU2MKNS.mjs";import{a as D,b as ye,c as K}from"./chunk-7OZDWT6C.mjs";import"./chunk-YJMWY4Y6.mjs";import"./chunk-NJAMZSHM.mjs";import"./chunk-DLHSCKBJ.mjs";import"./chunk-TSCXXNUF.mjs";import"./chunk-KEJ5RMAI.mjs";import"./chunk-6EWGHM32.mjs";import"./chunk-J6JZ4PQA.mjs";import"./chunk-P4J6TY2L.mjs";import"./chunk-54LH63LM.mjs";import"./chunk-SJ75V4WG.mjs";import{e as pe}from"./chunk-4DDCWMI6.mjs";import{d as fe}from"./chunk-BNWB77U5.mjs";import"./chunk-KXWBIQGJ.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as he}from"./chunk-3WY2AYPE.mjs";import"./chunk-GAOQHD5S.mjs";import{a as de}from"./chunk-QK2IMCDC.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-3FBCOCPD.mjs";import{b as me}from"./chunk-BISPGBNN.mjs";import"./chunk-LT5WSSQO.mjs";import"./chunk-HJ4HEI45.mjs";import"./chunk-3LG3ACQV.mjs";import"./chunk-AOPJ4Z6O.mjs";import"./chunk-AUUWQH3S.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-JRKGG2E3.mjs";import"./chunk-MEQS4VPO.mjs";import{d as _,g as ce}from"./chunk-HDHVBB6Q.mjs";import"./chunk-CE4RCNC7.mjs";import{d as le}from"./chunk-VPPHD762.mjs";import{b as I,d as oe,e as X,s as ie,t as We}from"./chunk-AKIN5WSQ.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import{j as ae,n as Qe}from"./chunk-SVZHJZ5T.mjs";import{a as N,b as ne,o as re}from"./chunk-CTWZQ7YI.mjs";import"./chunk-7AN7VQHN.mjs";import"./chunk-SYHDEUVU.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-P5ZYAXSE.mjs";import"./chunk-PKDYFXMI.mjs";import{a as $,e as k,f as J}from"./chunk-BUDZL4DW.mjs";import{a as m}from"./chunk-E66B27AL.mjs";J();re();Qe();import j from"node:fs/promises";import C from"node:path";var Y=class{static{m(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=C.join(this.projectPath,"package.json"),t=await j.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if($(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=C.join(this.projectPath,"Cargo.toml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readRequirements(){try{let e=C.join(this.projectPath,"requirements.txt");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readGoMod(){try{let e=C.join(this.projectPath,"go.mod");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readGemfile(){try{let e=C.join(this.projectPath,"Gemfile");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readMixExs(){try{let e=C.join(this.projectPath,"mix.exs");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readPomXml(){try{let e=C.join(this.projectPath,"pom.xml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readComposerJson(){try{let e=C.join(this.projectPath,"composer.json"),t=await j.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if($(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=C.join(this.projectPath,"pyproject.toml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await N('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" ! -path "*/.next/*" | sed "s/.*\\./\\./" | sort | uniq -c | sort -rn',{cwd:this.projectPath}),t={};return e.trim().split(`
8
+ import{a as G,b as Se,c as b,d as U,e as q,f as H,g as ve,h as $e,i as v}from"./chunk-CYZ7ST2P.mjs";import"./chunk-PGWFGRX4.mjs";import"./chunk-TXJT3G53.mjs";import"./chunk-G7QQZMAO.mjs";import"./chunk-ROA2AJXY.mjs";import"./chunk-DVDZA63F.mjs";import"./chunk-ZOX6OV6X.mjs";import"./chunk-FXFG6PV6.mjs";import"./chunk-WGWE3CSC.mjs";import"./chunk-KSSRINDX.mjs";import{a as y,b as R,c as M,d as we,e as E,f as L,g as z}from"./chunk-GDECEHO5.mjs";import{b as ge,c as A,d as ke}from"./chunk-S6L3FECF.mjs";import"./chunk-H4CA3XZ6.mjs";import{a as d}from"./chunk-MHNWIB7B.mjs";import"./chunk-T6ELTQZM.mjs";import"./chunk-RHKF7EJW.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-FEFP6JOL.mjs";import"./chunk-GDESYWTD.mjs";import"./chunk-J5UQVJUW.mjs";import"./chunk-YDBZO6I3.mjs";import"./chunk-YQ55MHKL.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-KOGZCFBC.mjs";import"./chunk-UYQC63MC.mjs";import"./chunk-LNB2GLYI.mjs";import{a as ue}from"./chunk-DYHYDHCW.mjs";import"./chunk-Z6KVLCMK.mjs";import{a as D,b as ye,c as K}from"./chunk-BU22R6JX.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-IGHY4FGS.mjs";import"./chunk-22AXWLI6.mjs";import"./chunk-J5UVRZ44.mjs";import"./chunk-NLKPAJND.mjs";import"./chunk-KEJ5RMAI.mjs";import"./chunk-3WQBTXUC.mjs";import"./chunk-6GAFRIUQ.mjs";import"./chunk-KHLYWNHT.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-SJ75V4WG.mjs";import{e as pe}from"./chunk-DCSKTMDX.mjs";import"./chunk-R4ILCXKE.mjs";import{d as fe}from"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as he}from"./chunk-V2FR2NPL.mjs";import{a as de}from"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-3FBCOCPD.mjs";import{b as me}from"./chunk-XXRAQZNC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-5XA5RL5I.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-XS45K7ZQ.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-4KVPAHFV.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import{d as _,g as ce}from"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import{d as le}from"./chunk-4KXXDQYI.mjs";import{b as I,g as oe,h as X,v as ie,w as We}from"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import{k as ae,o as Qe}from"./chunk-UH4MD3F3.mjs";import{a as N,b as ne,p as re}from"./chunk-QWQFF2UG.mjs";import"./chunk-FW4MEPTB.mjs";import"./chunk-SYHDEUVU.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import{a as $,e as k,f as J}from"./chunk-BUDZL4DW.mjs";import{a as m}from"./chunk-E66B27AL.mjs";J();re();Qe();import j from"node:fs/promises";import C from"node:path";var Y=class{static{m(this,"CodebaseAnalyzer")}projectPath=null;init(e=process.cwd()){this.projectPath=e}async readPackageJson(){try{let e=C.join(this.projectPath,"package.json"),t=await j.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if($(e)||e instanceof SyntaxError)return null;throw e}}async readCargoToml(){try{let e=C.join(this.projectPath,"Cargo.toml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readRequirements(){try{let e=C.join(this.projectPath,"requirements.txt");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readGoMod(){try{let e=C.join(this.projectPath,"go.mod");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readGemfile(){try{let e=C.join(this.projectPath,"Gemfile");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readMixExs(){try{let e=C.join(this.projectPath,"mix.exs");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readPomXml(){try{let e=C.join(this.projectPath,"pom.xml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async readComposerJson(){try{let e=C.join(this.projectPath,"composer.json"),t=await j.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if($(e)||e instanceof SyntaxError)return null;throw e}}async readPyprojectToml(){try{let e=C.join(this.projectPath,"pyproject.toml");return await j.readFile(e,"utf-8")}catch(e){if($(e))return null;throw e}}async getFileExtensions(){try{let{stdout:e}=await N('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" ! -path "*/.next/*" | sed "s/.*\\./\\./" | sort | uniq -c | sort -rn',{cwd:this.projectPath}),t={};return e.trim().split(`
9
9
  `).filter(Boolean).forEach(o=>{let s=o.trim().match(/^\s*(\d+)\s+(\.\w+)$/);s&&(t[s[2]]=parseInt(s[1],10))}),t}catch{return{}}}async listConfigFiles(){try{let e=await j.readdir(this.projectPath),t=[/^package\.json$/,/^Cargo\.toml$/,/^go\.mod$/,/^requirements\.txt$/,/^Gemfile$/,/^mix\.exs$/,/^pom\.xml$/,/^composer\.json$/,/^pyproject\.toml$/,/^tsconfig.*\.json$/,/^\..*rc(\.json|\.js|\.cjs)?$/,/^Dockerfile$/,/^docker-compose.*\.ya?ml$/,/^\.env.*$/];return e.filter(o=>t.some(s=>s.test(o)))}catch(e){if($(e))return[];throw e}}async listDirectories(){try{return(await j.readdir(this.projectPath,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).filter(t=>!t.startsWith(".")&&t!=="node_modules")}catch(e){if($(e))return[];throw e}}async getGitLog(e=50){try{let{stdout:t}=await N(`git log -n ${e} --pretty=format:"%h|%an|%ar|%s"`,{cwd:this.projectPath});return t}catch{return""}}async getGitStats(){try{let{stdout:e}=await N("git rev-list --count HEAD",{cwd:this.projectPath}),{stdout:t}=await N('git log --format="%an" | sort -u | wc -l',{cwd:this.projectPath}),{stdout:o}=await N('git log --reverse --pretty=format:"%ar" | head -1',{cwd:this.projectPath});return{totalCommits:parseInt(e.trim(),10)||0,contributors:parseInt(t.trim(),10)||0,age:o.trim()||"unknown"}}catch{return{totalCommits:0,contributors:0,age:"unknown"}}}async countFiles(){try{let{stdout:e}=await N('find . -type f ! -path "*/node_modules/*" ! -path "*/.git/*" ! -path "*/dist/*" | wc -l',{cwd:this.projectPath});return parseInt(e.trim(),10)||0}catch{return 0}}async fileExists(e){return ae(C.join(this.projectPath,e))}async readFile(e){try{let t=C.join(this.projectPath,e);return await j.readFile(t,"utf-8")}catch(t){if($(t))return null;throw t}}async findFiles(e){try{let{stdout:t}=await N(`find . -type f -name "${e}" ! -path "*/node_modules/*" ! -path "*/.git/*"`,{cwd:this.projectPath});return t.trim().split(`
10
10
  `).filter(Boolean)}catch{return[]}}},Xe=new Y,S=Xe;We();import je from"node:fs/promises";import Pe from"node:path";var V=800,Z=6,Ke=8,Ye=5;async function ee(r,e,t,o){let[s,i,n,a]=await Promise.all([Ze(r,e,o),et(r),tt(r),st(r)]);return{project:{name:o.name,ecosystem:o.ecosystem,languages:o.languages,frameworks:o.frameworks,fileCount:o.fileCount,projectType:o.projectType},git:{branch:t.branch,recentCommits:t.recentCommits.slice(0,Ke).map(u=>({message:u.message,date:u.date})),hasChanges:t.hasChanges,weeklyCommits:t.weeklyCommits},codeSamples:s,existingPatterns:i,taskHistory:n,previousAnalysis:a??void 0}}m(ee,"buildAnalysisPayload");async function Ze(r,e,t){let o=[],s=[...t.frameworks.map(a=>a.toLowerCase()),"config","router","middleware","service","model","schema","database","api","auth"].join(" "),i=pe(r,s,Z*2);for(let a of i){if(o.length>=Z)break;try{let u=Pe.join(e,a.path),c=await je.readFile(u,"utf-8");c.length>V*3?o.push({path:a.path,content:`${c.slice(0,V)}
11
- // ... truncated`,reason:`BM25 score: ${a.score.toFixed(2)} (truncated, ${c.length} chars)`}):o.push({path:a.path,content:c.slice(0,V),reason:`BM25 score: ${a.score.toFixed(2)}`})}catch{}}let n=["package.json","tsconfig.json","src/index.ts","src/main.ts","app.ts"];for(let a of n){if(o.length>=Z)break;if(!o.some(u=>u.path===a))try{let u=Pe.join(e,a),c=await je.readFile(u,"utf-8");o.push({path:a,content:c.slice(0,V),reason:"entry point"})}catch{}}return o}m(Ze,"selectCodeSamples");async function et(r){try{let e=await b.getActive(r);return e?{patterns:(e.patterns??[]).map(t=>({name:t.name,description:t.description})),antiPatterns:(e.antiPatterns??[]).map(t=>({issue:t.issue,file:t.file,suggestion:t.suggestion}))}:{patterns:[],antiPatterns:[]}}catch{return{patterns:[],antiPatterns:[]}}}m(et,"getExistingPatterns");async function tt(r){try{return(await me.getTaskHistory(r)).slice(0,Ye).map(t=>({description:t.title,status:t.classification,branch:t.branchName}))}catch{return[]}}m(tt,"getTaskHistory");function st(r){try{let e=D.getActiveSummary(r);return Promise.resolve(e)}catch(e){return ue.debug("Failed to get previous LLM analysis summary",{error:e}),Promise.resolve(null)}}m(st,"getPreviousAnalysisSummary");J();X();ce();J();async function be(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json&&console.log(JSON.stringify({success:!1,error:"No project ID found"})),t.result;let o=t.value,s=await b.seal(o);return e.json?(console.log(JSON.stringify({success:s.success,signature:s.signature,error:s.error})),{success:s.success,error:s.error}):s.success?(d.done("Analysis sealed"),console.log(` Signature: ${s.signature?.substring(0,16)}...`),console.log(""),{success:!0,data:{signature:s.signature}}):(d.fail(s.error||"Seal failed"),{success:!1,error:s.error})}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):d.fail(o),{success:!1,error:o}}}m(be,"seal");async function Ce(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json&&console.log(JSON.stringify({success:!1,error:"No project ID found"})),t.result;let o=t.value,s=await b.rollback(o);return e.json?(console.log(JSON.stringify({success:s.success,restoredSignature:s.restoredSignature,error:s.error})),{success:s.success,error:s.error}):e.md?s.success?(console.log(y(L("Analysis Rolled Back"),E({"Restored signature":`${s.restoredSignature?.substring(0,16)}...`,Note:"Previous sealed version is now active. Current version moved to draft."}))),{success:!0,data:{restoredSignature:s.restoredSignature}}):(console.log(y("## Rollback Failed",`> ${s.error}`)),{success:!1,error:s.error}):s.success?(d.done("Analysis rolled back to previous sealed version"),console.log(` Restored signature: ${s.restoredSignature?.substring(0,16)}...`),console.log(" Previous sealed version demoted to draft"),console.log(""),{success:!0,data:{restoredSignature:s.restoredSignature}}):(d.fail(s.error||"Rollback failed"),{success:!1,error:s.error})}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):e.md?console.log(y("## Rollback Failed",`> ${o}`)):d.fail(o),{success:!1,error:o}}}m(Ce,"rollback");async function xe(r=process.cwd(),e={}){if(e.semantic)return te(r,e);try{let t=await v(r);if(!t.ok)return t.result;let o=t.value,s=await b.verify(o);return e.json?(console.log(JSON.stringify(s)),{success:s.valid}):(s.valid?d.done(s.message):d.fail(s.message),console.log(""),{success:s.valid,data:s})}catch(t){let o=k(t);return ge(o)}}m(xe,"verify");async function te(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json?console.log(JSON.stringify({success:!1,error:"No project ID found"})):d.fail("No project ID found"),t.result;let o=t.value,s=(()=>{try{return _.getDoc(o,"project")?.repoPath||r}catch{return r}})(),i=await b.semanticVerify(o,s);if(e.json)return console.log(JSON.stringify(i)),{success:i.passed,data:i};console.log(""),i.passed?(d.done("Semantic verification passed"),console.log(` ${i.passedCount}/${i.checks.length} checks passed (${i.totalMs}ms)`)):(d.fail("Semantic verification failed"),console.log(` ${i.failedCount}/${i.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let n of i.checks){let a=n.passed?"\u2713":"\u2717",u=n.passed?`${n.output} (${n.durationMs}ms)`:n.error||"Failed";console.log(` ${a} ${n.name}: ${u}`)}return console.log(""),{success:i.passed,data:i}}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):d.fail(o),{success:!1,error:o}}}m(te,"semanticVerifyCommand");import De from"node:fs/promises";import Re from"node:path";import{z as l}from"zod";var nt=l.object({style:l.string(),insights:l.array(l.string()),domains:l.array(l.string())}),rt=l.object({name:l.string(),description:l.string(),locations:l.array(l.string()),confidence:l.number().min(0).max(1),category:l.string()}),ot=l.object({issue:l.string(),reasoning:l.string(),files:l.array(l.string()),suggestion:l.string(),severity:l.enum(["low","medium","high"]),confidence:l.number().min(0).max(1)}),at=l.object({description:l.string(),area:l.string(),effort:l.enum(["small","medium","large"]),impact:l.string(),priority:l.enum(["low","medium","high"])}),it=l.object({path:l.string(),reason:l.string(),risk:l.string(),severity:l.enum(["low","medium","high"])}),ct=l.object({description:l.string(),files:l.array(l.string()),benefit:l.string(),effort:l.enum(["small","medium","large"])}),lt=l.object({category:l.string(),rule:l.string(),example:l.string().optional()}),ut=l.object({build:l.string().optional(),test:l.string().optional(),lint:l.string().optional(),dev:l.string().optional(),format:l.string().optional(),install:l.string().optional()}),mt=l.object({languages:l.array(l.string()),frameworks:l.array(l.string()),packageManager:l.string().optional()}),gt=l.object({version:l.literal(1),commitHash:l.string().nullable(),analyzedAt:l.string(),architecture:nt,patterns:l.array(rt),antiPatterns:l.array(ot),techDebt:l.array(at),riskAreas:l.array(it),refactorSuggestions:l.array(ct),projectInsights:l.array(l.string()),conventions:l.array(lt),commands:ut.optional(),stack:mt.optional()});function Ae(r){let e=gt.safeParse(r);return e.success?{ok:!0,value:e.data}:{ok:!1,error:e.error.issues.map(o=>`${o.path.length>0?o.path.join("."):"<root>"}: ${o.message}`).join("; ")}}m(Ae,"parseLlmAnalysis");X();re();async function Le(r,e=process.cwd(),t={}){try{let o=await v(e);if(!o.ok)return o.result;let s=o.value,i=await pt(r,e),n=await ft(i.content,e),a=D.getActive(s),u=!!(a&&ye(a)&&K(n)),c=u?dt(a,n):n;D.save(s,c);try{let{recomputeProjectStyle:f}=await import("./project-style-evolution-HS6HYI7W.mjs"),{gatherStats:h,detectStack:x,detectCommands:B}=await import("./sync-analyzer-FKC57RTV.mjs"),[T,P,Q]=await Promise.all([h(e),x(e),B(e)]);await f({projectId:s,projectPath:e,stats:T,stack:P,commands:Q,commitHash:c.commitHash,source:"analysis-save"})}catch{}let p=K(c)&&!u;if(t.md){let h=[L(u?"LLM Analysis Notes Merged (house style preserved)":p?"LLM Analysis Notes Saved (thin \u2014 not house style)":"LLM Analysis Saved"),E({Input:i.source,Architecture:c.architecture.style,Patterns:c.patterns.length,"Anti-patterns":c.antiPatterns?.length||0,"Tech debt items":c.techDebt?.length||0,"Risk areas":c.riskAreas?.length||0,Conventions:c.conventions?.length||0,...u?{Merge:"thin notes \u2192 existing rich analysis"}:{},...p?{Kind:"thin markdown/notes"}:{}})];p&&h.push(z("Prefer schema v1 JSON (architecture/patterns/conventions) via `prjct analysis-save-llm <file> --md`. Markdown alone leaves patterns empty and burns a retry loop.")),console.log(y(...h))}else console.log(JSON.stringify({success:!0,message:u?"LLM analysis notes merged into existing rich analysis":p?"LLM analysis thin notes saved (prefer schema v1 JSON for house style)":"LLM analysis saved",input:i.source,mergedNotes:u,thin:p,stats:{patterns:c.patterns.length,antiPatterns:c.antiPatterns?.length||0,techDebt:c.techDebt?.length||0},...p?{tip:"Prefer schema v1 JSON (architecture/patterns/conventions). Markdown alone is thin notes."}:{}}));return{success:!0}}catch(o){return A(o)}}m(Le,"saveLlmAnalysis");function dt(r,e){let t=m((o,s,i)=>{let n=[],a=new Set;for(let u of[...o,...s]){let c=u.toLowerCase();if(!(a.has(c)||!u.trim())&&(a.add(c),n.push(u),n.length>=i))break}return n},"mergeUnique");return{...r,analyzedAt:e.analyzedAt,commitHash:e.commitHash??r.commitHash,projectInsights:t(r.projectInsights??[],e.projectInsights??[],60),architecture:{...r.architecture,insights:t(r.architecture.insights??[],e.architecture.insights??[],24)}}}m(dt,"mergeThinNotesIntoRich");async function pt(r,e){let t=r.trim();if(!t)throw new Error("analysis-save-llm requires analysis text, JSON, or a file path");let o=Re.isAbsolute(t)?t:Re.resolve(e,t);try{if((await De.stat(o)).isFile())return{content:await De.readFile(o,"utf-8"),source:"file"}}catch{}return{content:r,source:"inline"}}m(pt,"resolveAnalysisInput");async function ft(r,e){let t=r.trim();if(!t)throw new Error("analysis-save-llm received an empty analysis");let o=ht(t);if(o.ok){let s=Ae(o.value);return s.ok?s.value:Me(`Structured analysis did not match the legacy schema; preserved as LLM notes.
11
+ // ... truncated`,reason:`BM25 score: ${a.score.toFixed(2)} (truncated, ${c.length} chars)`}):o.push({path:a.path,content:c.slice(0,V),reason:`BM25 score: ${a.score.toFixed(2)}`})}catch{}}let n=["package.json","tsconfig.json","src/index.ts","src/main.ts","app.ts"];for(let a of n){if(o.length>=Z)break;if(!o.some(u=>u.path===a))try{let u=Pe.join(e,a),c=await je.readFile(u,"utf-8");o.push({path:a,content:c.slice(0,V),reason:"entry point"})}catch{}}return o}m(Ze,"selectCodeSamples");async function et(r){try{let e=await b.getActive(r);return e?{patterns:(e.patterns??[]).map(t=>({name:t.name,description:t.description})),antiPatterns:(e.antiPatterns??[]).map(t=>({issue:t.issue,file:t.file,suggestion:t.suggestion}))}:{patterns:[],antiPatterns:[]}}catch{return{patterns:[],antiPatterns:[]}}}m(et,"getExistingPatterns");async function tt(r){try{return(await me.getTaskHistory(r)).slice(0,Ye).map(t=>({description:t.title,status:t.classification,branch:t.branchName}))}catch{return[]}}m(tt,"getTaskHistory");function st(r){try{let e=D.getActiveSummary(r);return Promise.resolve(e)}catch(e){return ue.debug("Failed to get previous LLM analysis summary",{error:e}),Promise.resolve(null)}}m(st,"getPreviousAnalysisSummary");J();X();ce();J();async function be(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json&&console.log(JSON.stringify({success:!1,error:"No project ID found"})),t.result;let o=t.value,s=await b.seal(o);return e.json?(console.log(JSON.stringify({success:s.success,signature:s.signature,error:s.error})),{success:s.success,error:s.error}):s.success?(d.done("Analysis sealed"),console.log(` Signature: ${s.signature?.substring(0,16)}...`),console.log(""),{success:!0,data:{signature:s.signature}}):(d.fail(s.error||"Seal failed"),{success:!1,error:s.error})}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):d.fail(o),{success:!1,error:o}}}m(be,"seal");async function Ce(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json&&console.log(JSON.stringify({success:!1,error:"No project ID found"})),t.result;let o=t.value,s=await b.rollback(o);return e.json?(console.log(JSON.stringify({success:s.success,restoredSignature:s.restoredSignature,error:s.error})),{success:s.success,error:s.error}):e.md?s.success?(console.log(y(L("Analysis Rolled Back"),E({"Restored signature":`${s.restoredSignature?.substring(0,16)}...`,Note:"Previous sealed version is now active. Current version moved to draft."}))),{success:!0,data:{restoredSignature:s.restoredSignature}}):(console.log(y("## Rollback Failed",`> ${s.error}`)),{success:!1,error:s.error}):s.success?(d.done("Analysis rolled back to previous sealed version"),console.log(` Restored signature: ${s.restoredSignature?.substring(0,16)}...`),console.log(" Previous sealed version demoted to draft"),console.log(""),{success:!0,data:{restoredSignature:s.restoredSignature}}):(d.fail(s.error||"Rollback failed"),{success:!1,error:s.error})}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):e.md?console.log(y("## Rollback Failed",`> ${o}`)):d.fail(o),{success:!1,error:o}}}m(Ce,"rollback");async function xe(r=process.cwd(),e={}){if(e.semantic)return te(r,e);try{let t=await v(r);if(!t.ok)return t.result;let o=t.value,s=await b.verify(o);return e.json?(console.log(JSON.stringify(s)),{success:s.valid}):(s.valid?d.done(s.message):d.fail(s.message),console.log(""),{success:s.valid,data:s})}catch(t){let o=k(t);return ge(o)}}m(xe,"verify");async function te(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return e.json?console.log(JSON.stringify({success:!1,error:"No project ID found"})):d.fail("No project ID found"),t.result;let o=t.value,s=(()=>{try{return _.getDoc(o,"project")?.repoPath||r}catch{return r}})(),i=await b.semanticVerify(o,s);if(e.json)return console.log(JSON.stringify(i)),{success:i.passed,data:i};console.log(""),i.passed?(d.done("Semantic verification passed"),console.log(` ${i.passedCount}/${i.checks.length} checks passed (${i.totalMs}ms)`)):(d.fail("Semantic verification failed"),console.log(` ${i.failedCount}/${i.checks.length} checks failed`)),console.log(""),console.log("Check Results:");for(let n of i.checks){let a=n.passed?"\u2713":"\u2717",u=n.passed?`${n.output} (${n.durationMs}ms)`:n.error||"Failed";console.log(` ${a} ${n.name}: ${u}`)}return console.log(""),{success:i.passed,data:i}}catch(t){let o=k(t);return e.json?console.log(JSON.stringify({success:!1,error:o})):d.fail(o),{success:!1,error:o}}}m(te,"semanticVerifyCommand");import De from"node:fs/promises";import Re from"node:path";import{z as l}from"zod";var nt=l.object({style:l.string(),insights:l.array(l.string()),domains:l.array(l.string())}),rt=l.object({name:l.string(),description:l.string(),locations:l.array(l.string()),confidence:l.number().min(0).max(1),category:l.string()}),ot=l.object({issue:l.string(),reasoning:l.string(),files:l.array(l.string()),suggestion:l.string(),severity:l.enum(["low","medium","high"]),confidence:l.number().min(0).max(1)}),at=l.object({description:l.string(),area:l.string(),effort:l.enum(["small","medium","large"]),impact:l.string(),priority:l.enum(["low","medium","high"])}),it=l.object({path:l.string(),reason:l.string(),risk:l.string(),severity:l.enum(["low","medium","high"])}),ct=l.object({description:l.string(),files:l.array(l.string()),benefit:l.string(),effort:l.enum(["small","medium","large"])}),lt=l.object({category:l.string(),rule:l.string(),example:l.string().optional()}),ut=l.object({build:l.string().optional(),test:l.string().optional(),lint:l.string().optional(),dev:l.string().optional(),format:l.string().optional(),install:l.string().optional()}),mt=l.object({languages:l.array(l.string()),frameworks:l.array(l.string()),packageManager:l.string().optional()}),gt=l.object({version:l.literal(1),commitHash:l.string().nullable(),analyzedAt:l.string(),architecture:nt,patterns:l.array(rt),antiPatterns:l.array(ot),techDebt:l.array(at),riskAreas:l.array(it),refactorSuggestions:l.array(ct),projectInsights:l.array(l.string()),conventions:l.array(lt),commands:ut.optional(),stack:mt.optional()});function Ae(r){let e=gt.safeParse(r);return e.success?{ok:!0,value:e.data}:{ok:!1,error:e.error.issues.map(o=>`${o.path.length>0?o.path.join("."):"<root>"}: ${o.message}`).join("; ")}}m(Ae,"parseLlmAnalysis");X();re();async function Le(r,e=process.cwd(),t={}){try{let o=await v(e);if(!o.ok)return o.result;let s=o.value,i=await pt(r,e),n=await ft(i.content,e),a=D.getActive(s),u=!!(a&&ye(a)&&K(n)),c=u?dt(a,n):n;D.save(s,c);try{let{recomputeProjectStyle:f}=await import("./project-style-evolution-RPGATIYJ.mjs"),{gatherStats:h,detectStack:x,detectCommands:B}=await import("./sync-analyzer-6U5GHYV3.mjs"),[T,P,Q]=await Promise.all([h(e),x(e),B(e)]);await f({projectId:s,projectPath:e,stats:T,stack:P,commands:Q,commitHash:c.commitHash,source:"analysis-save"})}catch{}let p=K(c)&&!u;if(t.md){let h=[L(u?"LLM Analysis Notes Merged (house style preserved)":p?"LLM Analysis Notes Saved (thin \u2014 not house style)":"LLM Analysis Saved"),E({Input:i.source,Architecture:c.architecture.style,Patterns:c.patterns.length,"Anti-patterns":c.antiPatterns?.length||0,"Tech debt items":c.techDebt?.length||0,"Risk areas":c.riskAreas?.length||0,Conventions:c.conventions?.length||0,...u?{Merge:"thin notes \u2192 existing rich analysis"}:{},...p?{Kind:"thin markdown/notes"}:{}})];p&&h.push(z("Prefer schema v1 JSON (architecture/patterns/conventions) via `prjct analysis-save-llm <file> --md`. Markdown alone leaves patterns empty and burns a retry loop.")),console.log(y(...h))}else console.log(JSON.stringify({success:!0,message:u?"LLM analysis notes merged into existing rich analysis":p?"LLM analysis thin notes saved (prefer schema v1 JSON for house style)":"LLM analysis saved",input:i.source,mergedNotes:u,thin:p,stats:{patterns:c.patterns.length,antiPatterns:c.antiPatterns?.length||0,techDebt:c.techDebt?.length||0},...p?{tip:"Prefer schema v1 JSON (architecture/patterns/conventions). Markdown alone is thin notes."}:{}}));return{success:!0}}catch(o){return A(o)}}m(Le,"saveLlmAnalysis");function dt(r,e){let t=m((o,s,i)=>{let n=[],a=new Set;for(let u of[...o,...s]){let c=u.toLowerCase();if(!(a.has(c)||!u.trim())&&(a.add(c),n.push(u),n.length>=i))break}return n},"mergeUnique");return{...r,analyzedAt:e.analyzedAt,commitHash:e.commitHash??r.commitHash,projectInsights:t(r.projectInsights??[],e.projectInsights??[],60),architecture:{...r.architecture,insights:t(r.architecture.insights??[],e.architecture.insights??[],24)}}}m(dt,"mergeThinNotesIntoRich");async function pt(r,e){let t=r.trim();if(!t)throw new Error("analysis-save-llm requires analysis text, JSON, or a file path");let o=Re.isAbsolute(t)?t:Re.resolve(e,t);try{if((await De.stat(o)).isFile())return{content:await De.readFile(o,"utf-8"),source:"file"}}catch{}return{content:r,source:"inline"}}m(pt,"resolveAnalysisInput");async function ft(r,e){let t=r.trim();if(!t)throw new Error("analysis-save-llm received an empty analysis");let o=ht(t);if(o.ok){let s=Ae(o.value);return s.ok?s.value:Me(`Structured analysis did not match the legacy schema; preserved as LLM notes.
12
12
 
13
13
  ${JSON.stringify(o.value,null,2)}`,e)}return Me(t,e)}m(ft,"normalizeAnalysis");function ht(r){try{return{ok:!0,value:JSON.parse(r)}}catch{return{ok:!1}}}m(ht,"tryParseJson");async function Me(r,e){let t=yt(r);return{version:1,commitHash:await wt(e),analyzedAt:I(),architecture:{style:"unknown",insights:t.slice(0,8),domains:[]},patterns:[],antiPatterns:[],techDebt:[],riskAreas:[],refactorSuggestions:[],projectInsights:t,conventions:[]}}m(Me,"analysisFromText");function yt(r){let e=r.split(/\r?\n/).map(s=>s.replace(/^\s{0,3}#{1,6}\s+/,"").replace(/^\s*[-*]\s+\[[ xX]\]\s+/,"").replace(/^\s*[-*]\s+/,"").replace(/^\s*\d+[.)]\s+/,"").trim()).filter(St),t=[],o=new Set;for(let s of e){let i=s.toLowerCase();if(!o.has(i)&&(o.add(i),t.push(s),t.length>=40))break}return t.length>0?t:[r.slice(0,2e3)]}m(yt,"textToInsights");function St(r){if(!r||!/[\p{L}\p{N}]/u.test(r))return!1;let e=r.toLowerCase().replace(/\s+/g," ").trim();return!(["current work","wip","misc","todo","n/a","none","latest","unreleased","changelog"].includes(e)||/^[-=_]{3,}$/.test(e)||/^(added|changed|fixed|removed)$/i.test(e)||/^v?\d+\.\d+\.\d+(?:-[\w.-]+)?$/i.test(e))}m(St,"isUsefulInsight");async function wt(r){try{let{stdout:e}=await ne("git",["rev-parse","HEAD"],{cwd:r});return e.trim()||null}catch{return null}}m(wt,"resolveCurrentCommit");async function Ne(r=process.cwd(),e={}){try{let t=await v(r);if(!t.ok)return t.result;let o=t.value,s=D.getActive(o);if(!s)return e.md?console.log(y("## No LLM Analysis","> Run `prjct sync` to generate.")):console.log(JSON.stringify({success:!1,message:"No LLM analysis found"})),{success:!1,message:"No LLM analysis found"};if(e.md){let i=[L(`LLM Analysis (${s.architecture.style})`),""];if(s.architecture.insights.length>0&&i.push(R("Architecture Insights",M(s.architecture.insights.slice(0,5)))),s.patterns.length>0){let n=s.patterns.slice(0,8);i.push(R(`Patterns (${s.patterns.length})`,M(n.map(a=>`**${a.name}** \u2014 ${a.description} (${a.category})`))))}if(s.antiPatterns.length>0){let n=s.antiPatterns.slice(0,5);i.push(R(`Anti-Patterns (${s.antiPatterns.length})`,M(n.map(a=>`[${a.severity}] ${a.issue} \u2014 ${a.suggestion}`))))}if(s.techDebt.length>0){let n=s.techDebt.slice(0,5);i.push(R(`Tech Debt (${s.techDebt.length})`,M(n.map(a=>`[${a.priority}/${a.effort}] ${a.description}`))))}s.conventions.length>0&&i.push(R("Conventions",M(s.conventions.slice(0,5).map(n=>`**${n.category}**: ${n.rule}`)))),console.log(y(...i))}else{let i={...s,patterns:s.patterns.slice(0,10),antiPatterns:s.antiPatterns.slice(0,6),techDebt:s.techDebt.slice(0,6),conventions:s.conventions.slice(0,6)};console.log(JSON.stringify({success:!0,analysis:i}))}return{success:!0,data:s}}catch(t){return A(t)}}m(Ne,"getLlmAnalysis");ce();J();import $t from"node:path";X();async function Te(r,e){let t=Date.now()-e;await le.installGlobalConfig(),d.done(`Synced ${r.stats.name||"project"} (${(t/1e3).toFixed(1)}s)`),console.log("");let o=r.stats.frameworks.length>0?` (${r.stats.frameworks[0]})`:"",s=r.syncMetrics?.indexes,i=[`${r.stats.fileCount} files indexed`,`Stack: ${r.stats.ecosystem}${o} | Branch: ${r.git.branch}`];if(s?.bm25Files){let a=s.bm25Files*(s.bm25AvgTokens||0);i.push(`Index: ${O(a)} tokens | ${s.bm25VocabSize||0} terms | ${s.importEdges||0} imports`)}d.box("Sync Summary",i.join(`
14
14
  `));let n=[];if(r.generatedSkills?.generated&&r.generatedSkills.generated.length>0){let a=r.generatedSkills.generated.length,u=a===1?"skill":"skills";n.push(`${a} ${u} generated`)}if(r.context7&&n.push(`Context7: ${r.context7.verified?"verified":`not ready${r.context7.message?` (${r.context7.message})`:""}`}`),r.analysisSummary&&n.push(`Analysis: ${r.analysisSummary.patterns} patterns | ${r.analysisSummary.antiPatterns} anti-patterns (${r.analysisSummary.criticalAntiPatterns} critical)`),r.contextQuality){let a=r.contextQuality,u=a.irrelevantRemoved>0||a.repairEntriesCreated>0?`, repaired ${a.repairEntriesCreated}, removed ${a.irrelevantRemoved}`:"";n.push(`Context quality: ${a.score}/${a.threshold}${a.passed?"":" (needs review)"}${u}`)}if(d.section("Generated"),d.list(n,{bullet:"\u2713"}),console.log(""),r.phaseTimings&&r.phaseTimings.length>0){let a=[...r.phaseTimings].sort((u,c)=>c.ms-u.ms).slice(0,3).map(u=>`${u.phase} ${(u.ms/1e3).toFixed(1)}s`).join(", ");console.log(`Slowest phases: ${a}`),console.log("")}if(r.git.hasChanges&&(d.warn("Uncommitted changes detected"),console.log("")),r.verification){let a=r.verification;if(a.passed){let u=a.checks.map(c=>`${c.name} (${c.durationMs}ms)`);d.section("Verified"),d.list(u,{bullet:"\u2713"})}else{d.section("Verification");let u=a.checks.map(c=>c.passed?`\u2713 ${c.name}`:`\u2717 ${c.name}${c.error?` \u2014 ${c.error}`:""}`);d.list(u),a.skippedCount>0&&d.warn(`${a.skippedCount} check(s) skipped (fail-fast)`)}console.log("")}return ve("sync"),{success:!0,data:r,metrics:{elapsed:t,fileCount:r.stats.fileCount}}}m(Te,"showSyncResult");async function Fe(r){try{let e=await de.getRecentEvents(r,100),t=new Date().toISOString().split("T")[0],o=e.filter(c=>(c.timestamp||c.ts)?.startsWith(t)),s=(()=>{if(o.length<2)return null;let c=o.map(f=>new Date(f.timestamp||f.ts).getTime()).filter(f=>!Number.isNaN(f)).sort((f,h)=>f-h);if(c.length<2)return null;let p=c[c.length-1]-c[0];return oe(p)})(),i=o.filter(c=>c.action==="task_completed").length,n=o.filter(c=>c.action==="feature_shipped").length,a=new Map;for(let c of o)if(c.action==="sync"&&Array.isArray(c.subagents))for(let p of c.subagents)a.set(p,(a.get(p)||0)+1);let u=Array.from(a.entries()).map(([c,p])=>({name:c,count:p})).sort((c,p)=>p.count-c.count);return{sessionDuration:s,tasksCompleted:i,featuresShipped:n,agentsUsed:u}}catch{return{sessionDuration:null,tasksCompleted:0,featuresShipped:0,agentsUsed:[]}}}m(Fe,"getSessionActivity");function O(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}m(O,"formatTokens");function se(r){return r<1e3?`${Math.round(r)}ms`:`${(r/1e3).toFixed(1)}s`}m(se,"formatDuration");function Ee(r){if(r.length===0)return"";let e="\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588",t=r.map(s=>s.tokensSaved),o=Math.max(...t,1);return t.map(s=>{let i=Math.min(Math.floor(s/o*(e.length-1)),e.length-1);return e[i]}).join("")}m(Ee,"generateSparkline");function Oe(r,e,t,o,s,i){let n=[];if(n.push(`# ${t} - Stats Dashboard`),n.push(""),n.push(`_Generated: ${new Date().toLocaleString()} | Tracking since: ${o}_`),n.push(""),s){if(n.push("## Today's Activity"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),s.sessionDuration&&n.push(`| Duration | ${s.sessionDuration} |`),n.push(`| Tasks completed | ${s.tasksCompleted} |`),n.push(`| Features shipped | ${s.featuresShipped} |`),s.agentsUsed.length>0){let a=s.agentsUsed.slice(0,3).map(u=>`${u.name} (${u.count}\xD7)`).join(", ");n.push(`| Agents used | ${a} |`)}n.push("")}if(i&&(i.decisions>0||i.preferences>0)&&(n.push("## Patterns Learned"),n.push(""),n.push("| Type | Count |"),n.push("|------|-------|"),n.push(`| Decisions | ${i.learnedDecisions} confirmed (${i.decisions} total) |`),n.push(`| Preferences | ${i.preferences} |`),n.push(`| Workflows | ${i.workflows} |`),n.push("")),n.push("## Context Efficiency"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),n.push(`| Tokens reduced | ${O(r.totalTokensSaved)} |`),n.push(`| Compression | ${(r.compressionRate*100).toFixed(0)}% |`),n.push(`| Est. cost saved | ${U(r.estimatedCostSaved)} |`),n.push(""),n.push("## Performance"),n.push(""),n.push("| Metric | Value |"),n.push("|--------|-------|"),n.push(`| Syncs | ${r.syncCount} |`),n.push(`| Avg time | ${se(r.avgSyncDuration)} |`),n.push(""),r.topAgents.length>0){n.push("## Agent Usage"),n.push(""),n.push("| Agent | Usage |"),n.push("|-------|-------|");let a=r.topAgents.reduce((u,c)=>u+c.usageCount,0);for(let u of r.topAgents){let c=a>0?(u.usageCount/a*100).toFixed(0):0;n.push(`| ${u.agentName} | ${c}% (${u.usageCount}) |`)}n.push("")}if(n.push("## 30-Day Trend"),n.push(""),n.push(`- Tokens saved: ${O(r.last30DaysTokens)}`),r.trend!==0){let a=r.trend>0?"+":"";n.push(`- Trend: ${a}${r.trend.toFixed(0)}% vs previous period`)}return n.push(""),n.push("---"),n.push(""),n.push("_Generated with [prjct-cli](https://prjct.app)_"),n.join(`
@@ -37,6 +37,6 @@ ${JSON.stringify(o.value,null,2)}`,e)}return Me(t,e)}m(ft,"normalizeAnalysis");f
37
37
  Next steps:`),console.log("\u2022 p. sync \u2192 Generate agents based on stack"),console.log('\u2022 p. work "<intent>" \u2192 Start a work cycle'),{success:!0,summary:s,data:o}}catch(o){return console.error("\u274C Error:",k(o)),A(o)}}async sync(e=process.cwd(),t={}){try{let o=await v(e);if(!o.ok)return o.result;let s=o.value,i=Date.now();if(t.package){let a=await ie.detectMonorepo(e);if(!a.isMonorepo)return{success:!1,error:"Not a monorepo. --package flag only works in monorepos."};let u=a.packages.find(p=>p.name===t.package||p.relativePath===t.package);if(!u){let p=a.packages.map(f=>f.name).join(", ");return{success:!1,error:`Package "${t.package}" not found. Available: ${p}`}}let c=await H.sync(e,{packagePath:u.path,packageName:u.name});return t.json?console.log(JSON.stringify({success:c.success,package:u.name,path:u.relativePath})):t.md?console.log(y(L(`Synced package: ${u.name}`))):d.done(`Synced package: ${u.name}`),{success:c.success}}t.md||d.spin("Syncing project...");let n=await H.sync(e,{full:t.full});if(!n.success)return t.md?console.log(y("## Sync Failed",`> ${n.error||"Unknown error"}`)):d.fail(n.error||"Sync failed"),{success:!1,error:n.error};if(t.md||d.stop(),t.md){let a=Date.now()-i,u=n.generatedSkills?.generated?.length??0,c=await b.diff(s).then(g=>g?.hasChanges?G(g):null).catch(()=>null),p=n.git.recentCommits[0]?.hash??null,h=p&&D.isCurrent(s,p)?null:await ee(s,e,n.git,n.stats).then(g=>["## Analysis Payload",Ge,"### Data","```json",JSON.stringify(g),"```"].join(`
38
38
  `)).catch(()=>"### Next: Run `prjct analysis-payload --md` to update project analysis"),x=$e("sync",!0),B=(()=>{try{let g=he.recall(s,{types:["context"],limit:5}).map(F=>`- ${fe(F)} \`${F.id}\``);return g.length>0?["### Evaluate recent context","Task contexts captured recently \u2014 fold their decisions, patterns and","anti-patterns into the project analysis (and supersede anything now wrong):","",...g].join(`
39
39
  `):null}catch{return null}})(),T=n.syncMetrics?.indexes,P={Duration:`${(a/1e3).toFixed(1)}s`,Skills:`${u} generated`,"Files indexed":n.stats.fileCount};if(T?.bm25Files){let g=T.bm25Files*(T.bm25AvgTokens||0);P["Tokens indexed"]=`${Math.round(g/1e3)}K`,P["Import edges"]=T.importEdges||0,P["Co-change commits"]=T.cochangeCommits||0}n.contextQuality&&(P["Context quality"]=`${n.contextQuality.score}/${n.contextQuality.threshold}`+(n.contextQuality.passed?"":" needs review"),P["Context removed"]=n.contextQuality.irrelevantRemoved,P["Context repairs"]=n.contextQuality.repairEntriesCreated);let Q=n.phaseTimings&&n.phaseTimings.length>0?R("Phase timings (slowest first)",M([...n.phaseTimings].sort((g,F)=>F.ms-g.ms).map(g=>`${g.phase}: ${(g.ms/1e3).toFixed(2)}s`))):null,qe=(()=>{if(!n.retentionDryRun)return null;let g=n.retentionDryRun,F=g.dryRun===!1?"applied":"dry-run",Be=g.dryRun===!1?` \xB7 acted: ${g.archived??0} archived, ${g.deleted??0} deleted`+(g.inboxMerged||g.inboxArchived?`, inbox ${g.inboxMerged??0} merged/${g.inboxArchived??0} archived`:""):"";if(P[`Retention (${F})`]=`${g.active} active \xB7 ${g.archive} archive \xB7 ${g.delete} delete${Be}`,g.vault){let w=g.vault,W=g.dryRun===!1?` \xB7 purged: hard\u0394${w.softDeletedPurged??0} distill\u0394${w.distilledDiscarded??0} digests+${w.digestsWritten??0} arch\u0394${w.archivesPruned??0}`:"";P.Vault=`${w.live} live \xB7 soft-del ${w.softDeleted} \xB7 archives ${w.archives} \xB7 auto ${w.autoSourceLive}${W}`}return g.samples.length>0?R(g.dryRun===!1?"Retention (Rho) \u2014 worst excess/score (actions applied)":"Retention (Rho) dry-run \u2014 worst excess/score (nothing removed)",M(g.samples.map(w=>{let W="excess"in w&&typeof w.excess=="number"?` excess=${w.excess.toFixed(2)}`:"";return`\`${w.id}\` [${w.type}] ${w.verdict} (${w.score}${W}) \u2014 ${w.reasons.join(", ")}`}))):null})(),He=n.projectStyle?.evolutionMd?n.projectStyle.evolutionMd:n.projectStyle?.summary?["## Project style","",n.projectStyle.summary,"",`Coverage: ${n.projectStyle.styleCoverage}/100 \xB7 ${n.projectStyle.patternCount} patterns \xB7 ${n.projectStyle.conventionCount} conventions \xB7 ${n.projectStyle.antiPatternCount} anti-patterns`].join(`
40
- `):null,ze=n.developerSnapshotCaptured?await import("./developer-evolution-R5BXQH6G.mjs").then(({renderDeveloperEvolution:g})=>g(s,4)).catch(()=>`## Developer evolution
40
+ `):null,ze=n.developerSnapshotCaptured?await import("./developer-evolution-WNSTHDAA.mjs").then(({renderDeveloperEvolution:g})=>g(s,4)).catch(()=>`## Developer evolution
41
41
 
42
42
  Weekly developer snapshot captured.`):null,Ve=y(L("Sync Complete"),E(P),Q,qe,c,He,ze,n.git.hasChanges?z("Uncommitted changes detected"):null,B,h,we(x.map(g=>({label:g.desc,command:g.cmd}))));return console.log(Ve),{success:!0,data:n,metrics:{elapsed:a,skillCount:u,fileCount:n.stats.fileCount}}}return Te(n,i)}catch(o){return t.md?console.log(y("## Sync Failed",`> ${k(o)}`)):d.fail(k(o)),A(o)}}async analysisPayload(e=process.cwd(),t={}){try{let o=await v(e);if(!o.ok)return o.result;let s=o.value,i=await H.sync(e);if(!i.success)return{success:!1,error:i.error||"Failed to gather project data"};let n=i.git.recentCommits[0]?.hash??null;if(n&&D.isCurrent(s,n))return t.md?console.log(y(L("LLM analysis is current"),"> No re-analysis needed.")):console.log(JSON.stringify({success:!0,action:"skip",message:"Analysis is current"})),{success:!0,message:"Analysis is current"};let a=await ee(s,e,i.git,i.stats);return t.md?console.log(y("## Analysis Payload",Ge,"### Data","```json",JSON.stringify(a),"```")):console.log(JSON.stringify({success:!0,payload:a})),{success:!0,data:a}}catch(o){return A(o)}}async saveLlmAnalysis(...e){return Le(...e)}async getLlmAnalysis(...e){return Ne(...e)}async stats(...e){return Je(...e)}async diff(...e){return _e(...e)}async seal(...e){return be(...e)}async rollback(...e){return Ce(...e)}async verify(...e){return xe(...e)}async semanticVerify(...e){return te(...e)}};export{Ue as AnalysisCommands};
@@ -5,4 +5,4 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{a,b,c}from"./chunk-YUOTOCKK.mjs";import"./chunk-AKIN5WSQ.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-SVZHJZ5T.mjs";import"./chunk-CTWZQ7YI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{a as DEFAULT_API_URL,b as DEFAULT_WEB_URL,c as default};
8
+ import{a,b,c}from"./chunk-XDBJSJOT.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{a as DEFAULT_API_URL,b as DEFAULT_WEB_URL,c as default};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{a as n}from"./chunk-5H3KJWQS.mjs";import"./chunk-ROA2AJXY.mjs";import"./chunk-DVDZA63F.mjs";import"./chunk-ZOX6OV6X.mjs";import"./chunk-ZFLIVOFX.mjs";import"./chunk-DYHYDHCW.mjs";import"./chunk-R4ILCXKE.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-OC4CYF7V.mjs";import"./chunk-3FBCOCPD.mjs";import"./chunk-XDBJSJOT.mjs";import"./chunk-XXRAQZNC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-5XA5RL5I.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-BUDZL4DW.mjs";import{a as t}from"./chunk-E66B27AL.mjs";async function c(u,o){try{let e=o??await import("./config-manager-DX5OOPW5.mjs").then(({default:a})=>a.readConfig(u).catch(()=>null));if(!e?.projectId||!e.cloud?.enabled||e.cloud.paused)return{ran:!1};if(!await n.hasAuth())return{ran:!1};let r=await n.sync(e.projectId,{include:e.cloud.include??{}});return{ran:!0,pushed:r.pushed?.count??0,pulled:r.pulled?.count??0,error:r.success?void 0:r.error}}catch{return{ran:!1}}}t(c,"flushIfLinked");export{c as flushIfLinked};
@@ -5,5 +5,5 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{a as l,b as g}from"./chunk-Y5NQV46G.mjs";import{e as c,f as d}from"./chunk-HDSS6UB3.mjs";import{a as s,b as m}from"./chunk-WUHGODSQ.mjs";import{b as u,o as v}from"./chunk-CTWZQ7YI.mjs";import{a as n}from"./chunk-E66B27AL.mjs";m();d();v();import{execFileSync as y,spawn as j}from"node:child_process";import a from"node:fs";import i from"node:path";m();d();var w="https://registry.npmjs.org/prjct-cli/latest",$=3600*1e3;async function p(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),6e3),r=await fetch(w,{signal:e.signal});if(clearTimeout(t),!r.ok)return null;let f=await r.json();return typeof f.version=="string"?f.version:null}catch{return null}}n(p,"fetchLatestVersion");var S=n(()=>i.join(s(),"state"),"stateDir"),k=n(()=>i.join(S(),"auto-update.log"),"logPath"),h=3600*1e3;function H(e){if(!e||process.env.PRJCT_NO_AUTO_UPDATE==="1"||l("auto-update")!=="on")return;let t=l("auto-update-last-check");if(t&&Date.now()-Date.parse(t)<h)return;g("auto-update-last-check",new Date().toISOString()),j(process.execPath,[process.argv[1],"__internal-auto-update",e],{detached:!0,stdio:"ignore"}).unref()}n(H,"maybeAutoUpdate");async function L(e){try{let t=await p();if(!t)return;if(c(t,e)<=0){o(`current ${e} >= latest ${t}, no-op`);return}let r=b();o(`upgrade available: ${e} \u2192 ${t} (source: ${r})`),await x(r,t),o(`upgrade complete: ${e} \u2192 ${t}`)}catch(t){o(`auto-update failed: ${t.message}`)}}n(L,"runBackgroundCheck");function b(){let e=i.join(s(),"bin","prjct");if(a.existsSync(e))try{if(a.statSync(e).size>1024*1024)return"binary"}catch{}try{let t=y("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&a.existsSync(i.join(t,"prjct-cli")))return"npm"}catch{}try{let t=y("bun",["pm","bin","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&a.existsSync(i.join(t,"prjct")))return"bun"}catch{}return"unknown"}n(b,"detectInstallSource");async function x(e,t){if(e==="binary"){o(`binary install auto-update skipped for ${t}; run the installer manually to upgrade`);return}if(e==="bun"){await u("bun",["install","-g","prjct-cli@latest"],{timeout:12e4});return}if(e==="npm"||e==="unknown"){await u("npm",["install","-g","prjct-cli@latest"],{timeout:12e4});return}}n(x,"applyUpgrade");function o(e){try{a.mkdirSync(S(),{recursive:!0}),a.appendFileSync(k(),`${new Date().toISOString()} ${e}
8
+ import{a as l,b as g}from"./chunk-Y5NQV46G.mjs";import{e as c,f as d}from"./chunk-HDSS6UB3.mjs";import{a as s,b as m}from"./chunk-WUHGODSQ.mjs";import{b as u,p as v}from"./chunk-QWQFF2UG.mjs";import{a as n}from"./chunk-E66B27AL.mjs";m();d();v();import{execFileSync as y,spawn as j}from"node:child_process";import a from"node:fs";import i from"node:path";m();d();var w="https://registry.npmjs.org/prjct-cli/latest",$=3600*1e3;async function p(){try{let e=new AbortController,t=setTimeout(()=>e.abort(),6e3),r=await fetch(w,{signal:e.signal});if(clearTimeout(t),!r.ok)return null;let f=await r.json();return typeof f.version=="string"?f.version:null}catch{return null}}n(p,"fetchLatestVersion");var S=n(()=>i.join(s(),"state"),"stateDir"),k=n(()=>i.join(S(),"auto-update.log"),"logPath"),h=3600*1e3;function H(e){if(!e||process.env.PRJCT_NO_AUTO_UPDATE==="1"||l("auto-update")!=="on")return;let t=l("auto-update-last-check");if(t&&Date.now()-Date.parse(t)<h)return;g("auto-update-last-check",new Date().toISOString()),j(process.execPath,[process.argv[1],"__internal-auto-update",e],{detached:!0,stdio:"ignore"}).unref()}n(H,"maybeAutoUpdate");async function L(e){try{let t=await p();if(!t)return;if(c(t,e)<=0){o(`current ${e} >= latest ${t}, no-op`);return}let r=b();o(`upgrade available: ${e} \u2192 ${t} (source: ${r})`),await x(r,t),o(`upgrade complete: ${e} \u2192 ${t}`)}catch(t){o(`auto-update failed: ${t.message}`)}}n(L,"runBackgroundCheck");function b(){let e=i.join(s(),"bin","prjct");if(a.existsSync(e))try{if(a.statSync(e).size>1024*1024)return"binary"}catch{}try{let t=y("npm",["root","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&a.existsSync(i.join(t,"prjct-cli")))return"npm"}catch{}try{let t=y("bun",["pm","bin","-g"],{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&a.existsSync(i.join(t,"prjct")))return"bun"}catch{}return"unknown"}n(b,"detectInstallSource");async function x(e,t){if(e==="binary"){o(`binary install auto-update skipped for ${t}; run the installer manually to upgrade`);return}if(e==="bun"){await u("bun",["install","-g","prjct-cli@latest"],{timeout:12e4});return}if(e==="npm"||e==="unknown"){await u("npm",["install","-g","prjct-cli@latest"],{timeout:12e4});return}}n(x,"applyUpgrade");function o(e){try{a.mkdirSync(S(),{recursive:!0}),a.appendFileSync(k(),`${new Date().toISOString()} ${e}
9
9
  `)}catch{}}n(o,"log");var N={fetchLatestVersion:p,detectInstallSource:b,compareSemver:c,THROTTLE_MS:h};export{N as _internal,H as maybeAutoUpdate,L as runBackgroundCheck};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{i as a}from"./chunk-PTA7DMLM.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-TXSLON7M.mjs";import"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{a as captureGate};
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{e as S,g as G}from"./chunk-UHVYBU7F.mjs";import{a as B,c as te,d as W,e as $,o as ne}from"./chunk-UH4MD3F3.mjs";import{a as d}from"./chunk-E66B27AL.mjs";te();import N from"node:fs/promises";import E from"node:path";G();function j(e,n){S.transaction(e,t=>{t.prepare("DELETE FROM code_symbols").run(),t.prepare("DELETE FROM code_symbol_edges").run();let s=t.prepare(`INSERT INTO code_symbols (id, file, kind, name, qname, start_line, end_line, exported)
9
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),i=t.prepare(`INSERT OR IGNORE INTO code_symbol_edges (src, dst, edge_type, confidence)
10
+ VALUES (?, ?, ?, ?)`);for(let r of n.symbols)s.run(r.id,r.file,r.kind,r.name,r.qname,r.startLine,r.endLine,r.exported?1:0);for(let r of n.edges)i.run(r.src,r.dst,r.edgeType,r.confidence)})}d(j,"replaceCodeGraph");function we(e){try{return S.query(e,"SELECT src, dst, edge_type, confidence FROM code_symbol_edges").map(n=>({src:n.src,dst:n.dst,edgeType:n.edge_type,confidence:n.confidence}))}catch{return[]}}d(we,"loadCodeSymbolEdges");G();ne();var D="symbol-graph",se=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".go",".rs",".java"]),re=new Set(["if","for","while","switch","catch","function","class","return","typeof","new","throw","await","void","super","this","import","require","console","Math","JSON","Object","Array","Promise","Map","Set","Date","Error","Buffer","process","describe","it","test","expect","beforeEach","afterEach","beforeAll","afterAll"]),oe=new Set(["if","for","while","switch","catch","return","await","typeof","new","throw","else","case","from","import","export","class","function","const","let","var","get","set","constructor","async","static","public","private","protected","readonly","abstract","extends","implements","interface","type","enum","default","as","of","in","do","try","finally","yield","with"]);function L(e,n){return e.slice(0,Math.min(n,e.length)).split(`
11
+ `).length}d(L,"lineOf");function ie(e,n,t,s){return`${e}#${n}:${t}@${s}`}d(ie,"symbolId");function H(e,n){return`${e.replace(/\.[^.]+$/,"").replace(/[/\\]/g,".")}.${n}`}d(H,"qnameOf");function I(e){let n=E.extname(e).toLowerCase();return se.has(n)}d(I,"isSourceFile");function O(e){let n=/\/\/[^\n]*(?:\n|$)|\/\*(?:[^*]|\*(?!\/))*(?:\*\/|$)|'(?:\\[\s\S]|[^'\\])*(?:'|$)|"(?:\\[\s\S]|[^"\\])*(?:"|$)|`(?:\\[\s\S]|[^`\\])*(?:`|$)/g;return e.replace(n,t=>t.replace(/[^\n]/g," "))}d(O,"stripNoise");function K(e){return{filePath:e,symbols:[],callNames:[],calls:[],importBindings:new Map,resolvedImports:new Map}}d(K,"emptyExtract");function z(e){let n=[...new Set(e.map(t=>t.name))];return{calls:e,callNames:n}}d(z,"finalizeCalls");function ae(e,n){let t=[],s=[],i=new Map,r=O(e),a=[{re:/export\s+(?:async\s+)?function\s+(\w+)/g,kind:"function",nameIdx:1,exported:!0},{re:/(?:^|[^\w.])(?:async\s+)?function\s+(\w+)/g,kind:"function",nameIdx:1},{re:/export\s+(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_]\w*)\s*=>/g,kind:"function",nameIdx:1,exported:!0},{re:/(?:^|[\n;])(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_]\w*)\s*=>/g,kind:"function",nameIdx:1},{re:/export\s+(?:abstract\s+)?class\s+(\w+)/g,kind:"class",nameIdx:1,exported:!0},{re:/(?:^|[^\w.])(?:abstract\s+)?class\s+(\w+)/g,kind:"class",nameIdx:1},{re:/export\s+interface\s+(\w+)/g,kind:"interface",nameIdx:1,exported:!0},{re:/(?:^|[^\w.])interface\s+(\w+)/g,kind:"interface",nameIdx:1},{re:/export\s+type\s+(\w+)\s*[=<]/g,kind:"type",nameIdx:1,exported:!0},{re:/(?:^|[^\w.])type\s+(\w+)\s*[=<]/g,kind:"type",nameIdx:1},{re:/export\s+enum\s+(\w+)/g,kind:"enum",nameIdx:1,exported:!0},{re:/(?:^|[^\w.])enum\s+(\w+)/g,kind:"enum",nameIdx:1},{re:/export\s+(?:const|let|var)\s+(\w+)\s*[:=]/g,kind:"const",nameIdx:1,exported:!0},{re:/(?:^|\n)[ \t]+(?:(?:public|private|protected|static|async|readonly)\s+)*(\w+)\s*\([^)]{0,200}\)\s*[:{]/g,kind:"method",nameIdx:1}],o=new Set;for(let{re:m,kind:y,nameIdx:b,exported:C}of a){m.lastIndex=0;for(let _ of r.matchAll(m)){let x=_[b];if(!x||x.length<2||oe.has(x))continue;let h=L(r,_.index),T=`${y}:${x}@${h}`;o.has(T)||(o.add(T),t.push({kind:y,name:x,startLine:h,endLine:null,exported:C===!0}))}}let c=/import\s+(?:type\s+)?(?:\{([^}]+)\}|(\w+)(?:\s*,\s*\{([^}]+)\})?|\*\s+as\s+(\w+))\s+from\s+['"]([^'"]+)['"]/g;for(let m of e.matchAll(c)){let y=m[5],b=d(C=>{if(C)for(let _ of C.split(",")){let x=_.trim().replace(/^type\s+/,"").split(/\s+as\s+/),h=(x[1]??x[0])?.trim();h&&/^[A-Za-z_][\w]*$/.test(h)&&i.set(h,y)}},"bindNamed");b(m[1]),b(m[3]),m[2]&&i.set(m[2],y),m[4]&&i.set(m[4],y)}let l=/(?:const|let|var)\s+(\w+)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;for(let m of e.matchAll(l))i.set(m[1],m[2]);let f=/\b([A-Za-z_][\w]*)\s*\(/g,p=400;for(let m of r.matchAll(f)){let y=m[1];if(re.has(y)||y.length<2)continue;let b=L(r,m.index);if(s.push({name:y,line:b}),s.length>=p)break}let g=/\.(?:get|post|put|patch|delete|options|head|all)\s*\(\s*['"`](\/[^'"`]*)['"`]/gi;for(let m of e.matchAll(g)){let b=m[1].replace(/[^\w/.-]/g,"").slice(0,64)||"route";t.push({kind:"route",name:b,startLine:L(e,m.index),endLine:null,exported:!0})}let w=/@(?:app|router|api|bp)\.(?:get|post|put|patch|delete|options|head|api_route)\s*\(\s*['"`](\/[^'"`]*)['"`]/gi;for(let m of e.matchAll(w)){let b=m[1].replace(/[^\w/.-]/g,"").slice(0,64)||"route";t.push({kind:"route",name:b,startLine:L(e,m.index),endLine:null,exported:!0})}if(/(?:^|\/)route\.(ts|js|tsx|jsx)$/.test(n.replace(/\\/g,"/"))){let m=/\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\b/g;for(let y of e.matchAll(m))t.push({kind:"route",name:`${y[1]} ${n.replace(/\\/g,"/")}`,startLine:L(e,y.index),endLine:null,exported:!0})}let u=z(s);return{filePath:n,symbols:t,callNames:u.callNames,calls:u.calls,importBindings:i,resolvedImports:new Map}}d(ae,"extractTsJs");function ce(e,n){let t=[],s=[],i=O(e),r=/^(?:async\s+)?def\s+(\w+)\s*\(/gm,a=/^class\s+(\w+)/gm;for(let l of i.matchAll(r))t.push({kind:"function",name:l[1],startLine:L(i,l.index),endLine:null,exported:!l[1].startsWith("_")});for(let l of i.matchAll(a))t.push({kind:"class",name:l[1],startLine:L(i,l.index),endLine:null,exported:!l[1].startsWith("_")});let o=/\b([A-Za-z_][\w]*)\s*\(/g;for(let l of i.matchAll(o)){let f=l[1];/^(if|for|while|return|print|len|range|str|int|list|dict|set|super|self)$/.test(f)||s.push({name:f,line:L(i,l.index)})}let c=z(s);return{filePath:n,symbols:t,callNames:c.callNames,calls:c.calls,importBindings:new Map,resolvedImports:new Map}}d(ce,"extractPython");function le(e,n){let t=[],s=O(e),i=/^func\s+(?:\([^)]+\)\s+)?(\w+)\s*\(/gm,r=/^type\s+(\w+)\s+(?:struct|interface)/gm;for(let a of s.matchAll(i)){let o=a[1];t.push({kind:"function",name:o,startLine:L(s,a.index),endLine:null,exported:o[0]===o[0].toUpperCase()})}for(let a of s.matchAll(r))t.push({kind:"type",name:a[1],startLine:L(s,a.index),endLine:null,exported:a[1][0]===a[1][0].toUpperCase()});return{filePath:n,symbols:t,callNames:[],calls:[],importBindings:new Map,resolvedImports:new Map}}d(le,"extractGo");function de(e,n){let t=[],s=O(e),i=/^(?:pub\s+)?(?:async\s+)?fn\s+(\w+)/gm,r=/^(?:pub\s+)?struct\s+(\w+)/gm,a=/^(?:pub\s+)?trait\s+(\w+)/gm,o=/^(?:pub\s+)?enum\s+(\w+)/gm;for(let[c,l]of[[i,"function"],[r,"class"],[a,"interface"],[o,"enum"]])for(let f of s.matchAll(c))t.push({kind:l,name:f[1],startLine:L(s,f.index),endLine:null,exported:/^pub\b/.test(f[0])});return{filePath:n,symbols:t,callNames:[],calls:[],importBindings:new Map,resolvedImports:new Map}}d(de,"extractRust");function me(e,n){let t=[],s=O(e),i=/(?:public\s+|private\s+|protected\s+)?(?:abstract\s+|final\s+)?class\s+(\w+)/g,r=/(?:public\s+)?interface\s+(\w+)/g,a=/(?:public|private|protected)\s+(?:static\s+)?(?:final\s+)?[\w.<>,[\]\s]+\s+(\w+)\s*\(/g;for(let o of s.matchAll(i))t.push({kind:"class",name:o[1],startLine:L(s,o.index),endLine:null,exported:!0});for(let o of s.matchAll(r))t.push({kind:"interface",name:o[1],startLine:L(s,o.index),endLine:null,exported:!0});for(let o of s.matchAll(a))/^(if|for|while|switch|catch|return|new)$/.test(o[1])||t.push({kind:"method",name:o[1],startLine:L(s,o.index),endLine:null,exported:!0});return{filePath:n,symbols:t,callNames:[],calls:[],importBindings:new Map,resolvedImports:new Map}}d(me,"extractJava");function ue(e,n){let t=E.extname(n).toLowerCase();return[".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(t)?ae(e,n):t===".py"?ce(e,n):t===".go"?le(e,n):t===".rs"?de(e,n):t===".java"?me(e,n):K(n)}d(ue,"extractFile");async function fe(e){let n=[];for(let t of["tsconfig.json","jsconfig.json"])try{let i=(await N.readFile(E.join(e,t),"utf-8")).replace(/\/\*[\s\S]*?\*\//g,"").replace(/\/\/[^\n]*/g,""),r=JSON.parse(i),a=r.compilerOptions?.paths,o=r.compilerOptions?.baseUrl??".";if(!a)continue;for(let[c,l]of Object.entries(a))n.push({pattern:c,targets:l.map(f=>E.posix.join(o.replace(/\\/g,"/"),f))});break}catch{}return n}d(fe,"loadTsPathMap");function ge(e,n){let t=[];for(let{pattern:s,targets:i}of n)if(s.endsWith("/*")){let r=s.slice(0,-1),a=s.slice(0,-2);if(e===a||e.startsWith(`${a}/`)){let o=e.slice(a.length).replace(/^\//,"");for(let c of i){let l=c.endsWith("/*")?c.slice(0,-1):c;t.push(E.posix.join(l.replace(/\*$/,""),o).replace(/\\/g,"/"))}}}else if(e===s)for(let r of i)t.push(r.replace(/\*$/,""));return t}d(ge,"applyTsPath");async function pe(e,n,t,s){let i=[];if(t.startsWith(".")){let r=E.dirname(E.join(e,n));i.push(E.resolve(r,t))}else if(t.startsWith("@/"))i.push(E.join(e,"src",t.slice(2))),i.push(E.join(e,t.slice(2)));else{for(let r of ge(t,s))i.push(E.join(e,r));i.push(E.join(e,"packages",t)),i.push(E.join(e,"src",t))}for(let r of i)for(let a of B){let o=r+a;try{if((await N.stat(o)).isFile())return E.relative(e,o).replace(/\\/g,"/")}catch{}}return null}d(pe,"resolveSpecifierToFile");async function ye(e,n,t){for(let[s,i]of n.importBindings){let r=await pe(e,n.filePath,i,t);r&&n.resolvedImports.set(s,r)}}d(ye,"resolveImportsForExtract");function U(e,n){let t=e.replace(/\\/g,"/"),s=n.replace(/\\/g,"/").replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"");return t===n||t.replace(/\.(ts|tsx|js|jsx|mjs|cjs)$/,"")===s||t===`${s}.ts`||t===`${s}.tsx`||t===`${s}.js`||t===`${s}.jsx`||t===`${s}/index.ts`||t===`${s}/index.tsx`||t===`${s}/index.js`}d(U,"matchFileToMod");function Y(e,n){return e.filter(s=>s.kind==="function"||s.kind==="method"||s.kind==="class").reduce((s,i)=>i.startLine<=n&&(!s||i.startLine>s.startLine)?i:s,null)}d(Y,"enclosingSymbol");function Z(e,n,t,s){let i=t.filter(o=>o.name===e);if(i.length===1)return{targets:i,confidence:.95};if(i.length>1){let o=i.filter(c=>c.exported);if(o.length===1)return{targets:o,confidence:.9}}let r=n.resolvedImports.get(e);if(r){let o=(s.get(e)??[]).filter(f=>U(f.file,r));if(o.length>0)return{targets:o,confidence:.9};let c=[...s.values()].flat().filter(f=>U(f.file,r)&&f.exported),l=c.find(f=>f.kind==="function"||f.kind==="class")??c[0];if(l)return{targets:[l],confidence:.65}}let a=s.get(e)??[];if(a.length===1)return{targets:a,confidence:.75};if(a.length>1){let o=a.filter(c=>c.exported);if(o.length===1)return{targets:o,confidence:.7}}return{targets:[],confidence:0}}d(Z,"resolveCallTargets");function J(e){let n=[],t=[],s=new Map,i=new Map;for(let o of e){let c=[];for(let l of o.symbols){let f=ie(o.filePath,l.kind,l.name,l.startLine),p={id:f,file:o.filePath,kind:l.kind,name:l.name,qname:H(o.filePath,l.name),startLine:l.startLine,endLine:l.endLine,exported:l.exported};n.push(p),c.push(p);let g=s.get(l.name)??[];g.push(p),s.set(l.name,g),t.push({src:`file:${o.filePath}`,dst:f,edgeType:"DEFINES",confidence:1})}i.set(o.filePath,c)}for(let o of e){let c=i.get(o.filePath)??[],l=new Set;for(let f of o.calls){if(c.some(m=>m.name===f.name&&m.startLine===f.line))continue;let{targets:p,confidence:g}=Z(f.name,o,c,s);if(p.length===0)continue;let u=Y(c,f.line)?.id??`file:${o.filePath}`;for(let m of p){if(m.id===u)continue;let y=`${u}|${m.id}`;l.has(y)||(l.add(y),t.push({src:u,dst:m.id,edgeType:"CALLS",confidence:g}))}}}let r=new Set,a=[];for(let o of t){let c=`${o.src}|${o.dst}|${o.edgeType}`;r.has(c)||(r.add(c),a.push(o))}return{symbols:n,edges:a,fileCount:e.length}}d(J,"buildFromExtracts");async function V(e,n){let s=(n??(await W(e)).filter(a=>I(a)&&!a.includes(".d.ts"))).filter(a=>I(a)&&!a.endsWith(".d.ts")),i=await fe(e),r=await $(s,40,async a=>{try{let o=await N.readFile(E.join(e,a),"utf-8"),c=o.length>4e5?o.slice(0,4e5):o;return ue(c,a)}catch{return K(a)}});return await $(r,40,async a=>(await ye(e,a,i),a)),r}d(V,"extractProject");function be(e,n){j(e,n);let t={symbolCount:n.symbols.length,edgeCount:n.edges.length,fileCount:n.fileCount,builtAt:new Date().toISOString()};S.setDoc(e,D,t)}d(be,"persistGraph");function he(e,n,t){let s=new Set([...n.map(c=>c.filePath),...t]);if(s.size===0)return Q(e);let i=xe(e).filter(c=>!s.has(c.file)),r=J(n);S.transaction(e,c=>{let l=c.prepare("DELETE FROM code_symbols WHERE file = ?");for(let u of s)c.prepare("DELETE FROM code_symbol_edges WHERE src LIKE ? OR dst LIKE ? OR src = ? OR dst = ?").run(`${u}#%`,`${u}#%`,`file:${u}`,`file:${u}`),l.run(u);let f=c.prepare(`INSERT INTO code_symbols (id, file, kind, name, qname, start_line, end_line, exported)
12
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`),p=c.prepare(`INSERT OR IGNORE INTO code_symbol_edges (src, dst, edge_type, confidence)
13
+ VALUES (?, ?, ?, ?)`);for(let u of r.symbols)f.run(u.id,u.file,u.kind,u.name,u.qname,u.startLine,u.endLine,u.exported?1:0);let g=new Map;for(let u of[...i,...r.symbols]){let m=g.get(u.name)??[];m.push(u),g.set(u.name,m)}let w=new Map;for(let u of[...i,...r.symbols])w.has(u.file)||w.set(u.file,[]),w.get(u.file).push(u);for(let u of n){let m=w.get(u.filePath)??[];for(let b of m.filter(C=>C.file===u.filePath))p.run(`file:${u.filePath}`,b.id,"DEFINES",1);let y=new Set;for(let b of u.calls){if(m.some(T=>T.name===b.name&&T.startLine===b.line))continue;let{targets:C,confidence:_}=Z(b.name,u,m,g);if(C.length===0)continue;let h=Y(m,b.line)?.id??`file:${u.filePath}`;for(let T of C){if(T.id===h)continue;let R=`${h}|${T.id}`;y.has(R)||(y.add(R),p.run(h,T.id,"CALLS",_))}}}});let a=S.get(e,`SELECT
14
+ (SELECT COUNT(*) FROM code_symbols) AS sc,
15
+ (SELECT COUNT(*) FROM code_symbol_edges) AS ec,
16
+ (SELECT COUNT(DISTINCT file) FROM code_symbols) AS fc`),o={symbolCount:a?.sc??0,edgeCount:a?.ec??0,fileCount:a?.fc??0,builtAt:new Date().toISOString()};return S.setDoc(e,D,o),o}d(he,"patchGraph");async function Se(e,n){let t=await V(e),s=J(t);return be(n,s),{symbolCount:s.symbols.length,edgeCount:s.edges.length,fileCount:s.fileCount,builtAt:new Date().toISOString()}}d(Se,"indexSymbols");async function Re(e,n,t,s=[]){if(!X(n))return Se(e,n);let i=t.filter(o=>I(o)&&!o.endsWith(".d.ts")),r=s.filter(o=>I(o));if(i.length===0&&r.length===0)return Q(n)??{symbolCount:0,edgeCount:0,fileCount:0,builtAt:new Date().toISOString()};let a=await V(e,i);return he(n,a,r)??{symbolCount:0,edgeCount:0,fileCount:0,builtAt:new Date().toISOString()}}d(Re,"updateSymbols");function X(e){try{return(S.get(e,"SELECT COUNT(*) AS n FROM code_symbols")?.n??0)>0}catch{return!1}}d(X,"hasSymbolIndex");function Q(e){return S.getDoc(e,D)}d(Q,"loadMeta");function A(e){return{id:e.id,file:e.file,kind:e.kind,name:e.name,qname:e.qname??H(e.file,e.name),startLine:e.start_line,endLine:e.end_line,exported:e.exported===1}}d(A,"rowToSymbol");function xe(e){try{return S.query(e,"SELECT * FROM code_symbols ORDER BY file, start_line").map(A)}catch{return[]}}d(xe,"listAllSymbols");function v(e,n,t={}){let s=t.limit??30,i=`%${n.replace(/[%_]/g,"")}%`;try{return t.kind?S.query(e,`SELECT * FROM code_symbols
17
+ WHERE name LIKE ? COLLATE NOCASE AND kind = ?
18
+ ORDER BY exported DESC, name
19
+ LIMIT ?`,i,t.kind,s).map(A):S.query(e,`SELECT * FROM code_symbols
20
+ WHERE name LIKE ? COLLATE NOCASE OR qname LIKE ? COLLATE NOCASE
21
+ ORDER BY exported DESC, name
22
+ LIMIT ?`,i,i,s).map(A)}catch{return[]}}d(v,"searchSymbols");function Ie(e,n,t=20){let s=n.split(/[^A-Za-z0-9_]+/).flatMap(r=>r.replace(/([a-z])([A-Z])/g,"$1 $2").split(/\s+/)).map(r=>r.trim()).filter(r=>r.length>2);if(s.length===0||!X(e))return[];let i=new Map;for(let r of s){let a=v(e,r,{limit:40});for(let o of a){let c=o.name.toLowerCase()===r.toLowerCase()?1:.55,l=o.exported?1.15:1,f=o.kind==="function"||o.kind==="class"||o.kind==="route"?1.1:1,p=c*l*f,g=i.get(o.file)??{score:0,names:new Set};g.score+=p,g.names.add(o.name),i.set(o.file,g)}}return Array.from(i.entries()).map(([r,a])=>({path:r,score:a.score,matchedNames:[...a.names]})).sort((r,a)=>a.score-r.score).slice(0,t)}d(Ie,"scoreFilesFromQuery");function q(e,n){try{return S.query(e,"SELECT * FROM code_symbols WHERE file = ? ORDER BY start_line",n).map(A)}catch{return[]}}d(q,"symbolsInFile");function P(e,n="CALLS"){let t=new Map,s=new Map;try{let i=S.query(e,"SELECT src, dst FROM code_symbol_edges WHERE edge_type = ?",n);for(let r of i)t.has(r.src)||t.set(r.src,[]),t.get(r.src).push(r.dst),s.has(r.dst)||s.set(r.dst,[]),s.get(r.dst).push(r.src)}catch{}return{forward:t,reverse:s}}d(P,"loadEdges");function ee(e,n){try{let t=S.get(e,"SELECT * FROM code_symbols WHERE id = ?",n);return t?A(t):null}catch{return null}}d(ee,"symbolById");function Fe(e,n,t={}){let s=t.direction??"both",i=Math.min(Math.max(t.depth??3,1),5),r=v(e,n,{limit:10}).filter(w=>w.name.toLowerCase()===n.toLowerCase()),a=r.length>0?r:v(e,n,{limit:5});if(a.length===0)return null;let{forward:o,reverse:c}=P(e,"CALLS"),l=[],f=[],p=d((w,u,m,y)=>{let b=new Set(w),C=w.map(_=>({id:_,depth:0}));for(let{id:_,depth:x}of C)if(!(x>=y))for(let h of u.get(_)??[]){if(b.has(h))continue;if(b.add(h),h.startsWith("file:")){let R=h.slice(5),F=q(e,R),k=F.find(M=>M.exported&&(M.kind==="function"||M.kind==="class"))??F.find(M=>M.kind==="function"||M.kind==="class")??F[0];k&&!b.has(k.id)&&(b.add(k.id),m.push({symbol:k,depth:x+1,via:"CALLS"}),C.push({id:k.id,depth:x+1})),C.push({id:h,depth:x+1});continue}let T=ee(e,h);T&&(m.push({symbol:T,depth:x+1,via:"CALLS"}),C.push({id:h,depth:x+1}))}},"bfs"),g=a.map(w=>w.id);return(s==="inbound"||s==="both")&&p(g,c,l,i),(s==="outbound"||s==="both")&&p(g,o,f,i),{root:a,inbound:l,outbound:f}}d(Fe,"tracePath");function $e(e,n){let t=q(e,n);if(t.length===0)return 0;let{reverse:s}=P(e,"CALLS"),i=new Set;for(let r of t)for(let a of s.get(r.id)??[])i.add(a);return i.size}d($e,"fileFanIn");function ve(e){try{let n=S.query(e,`SELECT target.file AS file, COUNT(DISTINCT edge.src) AS caller_count
23
+ FROM code_symbol_edges AS edge
24
+ JOIN code_symbols AS target ON target.id = edge.dst
25
+ WHERE edge.edge_type = 'CALLS'
26
+ GROUP BY target.file`);return new Map(n.map(t=>[t.file,t.caller_count]))}catch{return new Map}}d(ve,"fileFanInByFile");function Ne(e,n,t=2){let s=new Set(n),{reverse:i}=P(e,"CALLS"),r=new Set;for(let c of n)for(let l of q(e,c))r.add(l.id);let a=new Set,o=new Set(r);return Array.from({length:t}).reduce(c=>{let l=[];for(let f of c)for(let p of i.get(f)??[])if(!o.has(p))if(o.add(p),l.push(p),p.startsWith("file:")){let g=p.slice(5);s.has(g)||a.add(g)}else{let g=ee(e,p);g&&!s.has(g.file)&&a.add(g.file)}return l},[...r]),[...a]}d(Ne,"filesCallingInto");export{j as a,we as b,O as c,ue as d,Se as e,Re as f,X as g,Q as h,xe as i,v as j,Ie as k,q as l,Fe as m,$e as n,ve as o,Ne as p};
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{a}from"./chunk-E66B27AL.mjs";function T(n){let e=new Set;for(let t of n){let s=c(t.message)?.model??t.model;typeof s=="string"&&s.trim()&&e.add(s.trim().slice(0,120))}return e.size===0?"unknown":e.size>1?"mixed":[...e][0]}a(T,"identifyTranscriptModel");function h(n){let e=[];for(let t of n.split(`
9
+ `)){let o=t.trim();if(o)try{let s=JSON.parse(o);s&&typeof s=="object"&&e.push(s)}catch{}}return e}a(h,"parseTranscriptJsonl");function c(n){return n&&typeof n=="object"?n:null}a(c,"asRecord");function r(n){return typeof n=="number"&&Number.isFinite(n)?n:0}a(r,"num");function f(n){let e=r(n.input_tokens)+r(n.cache_creation_input_tokens)+r(n.prompt_tokens)+r(n.promptTokenCount)+r(n.inputOther)+r(n.inputCacheCreation),t=r(n.output_tokens)+r(n.completion_tokens)+r(n.candidatesTokenCount)+r(n.output),o=r(n.cache_read_input_tokens)+r(n.inputCacheRead);return{tokensIn:e,tokensOut:t,cacheRead:o}}a(f,"usagePairFrom");function l(n){return typeof n.timestamp=="string"?Date.parse(n.timestamp):typeof n.time=="number"?n.time:Number.NaN}a(l,"lineTimeMs");function g(n,e){if(!e?.sinceIso&&!e?.untilIso)return!0;let t=l(n);return!(!Number.isFinite(t)||e.sinceIso&&t<Date.parse(e.sinceIso)||e.untilIso&&t>=Date.parse(e.untilIso))}a(g,"inWindow");function I(n,e){let t=n.reduce((u,p)=>{if(!g(p,e))return u;let d=c(c(p.message)?.usage)??c(p.usage)??c(p.usageMetadata);if(!d)return u;let m=f(d);return{tokensInNew:u.tokensInNew+m.tokensIn,tokensOut:u.tokensOut+m.tokensOut,maxCacheRead:Math.max(u.maxCacheRead,m.cacheRead)}},{tokensInNew:0,tokensOut:0,maxCacheRead:0}),{tokensInNew:o,tokensOut:s,maxCacheRead:i}=t;return{tokensInNew:o,cacheReadMax:i,tokensIn:o+i,tokensOut:s}}a(I,"sumTranscriptUsageDetailed");function x(n,e){let t=I(n,e);return{tokensIn:t.tokensIn,tokensOut:t.tokensOut}}a(x,"sumTranscriptUsage");function R(n,e){let t=new Map;for(let s of n){if(!g(s,e))continue;let i=c(s.message),u=c(i?.usage)??c(s.usage)??c(s.usageMetadata);if(!u)continue;let p=i?.model??s.model,d=typeof p=="string"&&p?p:"unknown",m=f(u),k=t.get(d)??{tokensIn:0,tokensOut:0,maxCacheRead:0};k.tokensIn+=m.tokensIn,k.tokensOut+=m.tokensOut,m.cacheRead>k.maxCacheRead&&(k.maxCacheRead=m.cacheRead),t.set(d,k)}let o=new Map;for(let[s,i]of t)o.set(s,{tokensIn:i.tokensIn+i.maxCacheRead,tokensOut:i.tokensOut});return o}a(R,"sumTranscriptUsageByModel");export{T as a,h as b,I as c,x as d,R as e};
@@ -5,5 +5,5 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{c as d}from"./chunk-AOPJ4Z6O.mjs";import{e as r,g as f}from"./chunk-HDHVBB6Q.mjs";import{a as m}from"./chunk-E66B27AL.mjs";f();var u=class{static{m(this,"CustomWorkflowStorage")}createWorkflow(t,e){let n=new Date().toISOString();r.run(t,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
8
+ import{b as d}from"./chunk-QP5USCDX.mjs";import{e as r,g as f}from"./chunk-UHVYBU7F.mjs";import{a as m}from"./chunk-E66B27AL.mjs";f();var u=class{static{m(this,"CustomWorkflowStorage")}createWorkflow(t,e){let n=new Date().toISOString();r.run(t,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
9
9
  VALUES (?, ?, ?, ?, 0, 1, ?)`,e.name,e.description??null,n,n,e.metadata?JSON.stringify(e.metadata):null);let o=r.get(t,"SELECT id FROM custom_workflows WHERE name = ?",e.name);if(!o)throw new Error(`Failed to create workflow: ${e.name}`);return d({projectId:t,entityType:"custom_workflows",entityId:String(o.id),eventType:"upsert",data:{id:o.id,name:e.name,description:e.description??null,metadata:e.metadata??null,created_at:n,updated_at:n,is_builtin:0,enabled:1}}),o.id}getWorkflow(t,e){let n=r.get(t,"SELECT * FROM custom_workflows WHERE name = ?",e);return n?this.rowToWorkflow(n):null}getAllWorkflows(t,e=!1){let n=e?"SELECT * FROM custom_workflows ORDER BY is_builtin DESC, name ASC":"SELECT * FROM custom_workflows WHERE enabled = 1 ORDER BY is_builtin DESC, name ASC";return r.query(t,n).map(l=>this.rowToWorkflow(l))}updateWorkflow(t,e,n){if(!this.getWorkflow(t,e))return!1;let l=new Date().toISOString(),s=[],a=[];if(n.description!==void 0&&(s.push("description = ?"),a.push(n.description)),n.enabled!==void 0&&(s.push("enabled = ?"),a.push(n.enabled?1:0)),n.metadata!==void 0&&(s.push("metadata = ?"),a.push(JSON.stringify(n.metadata))),s.length===0)return!1;s.push("updated_at = ?"),a.push(l),a.push(e),r.run(t,`UPDATE custom_workflows SET ${s.join(", ")} WHERE name = ?`,...a);let i=this.getWorkflow(t,e);return i&&d({projectId:t,entityType:"custom_workflows",entityId:String(i.id),eventType:"upsert",data:{id:i.id,name:i.name,description:i.description??null,enabled:i.enabled?1:0,metadata:i.metadata??null,updated_at:l}}),!0}deleteWorkflow(t,e){let n=this.getWorkflow(t,e);if(!n)return!1;if(n.isBuiltin)throw new Error(`Cannot delete built-in workflow: ${e}`);return r.run(t,"UPDATE custom_workflows SET enabled = 0 WHERE name = ?",e),d({projectId:t,entityType:"custom_workflows",entityId:String(n.id),eventType:"delete",data:{id:n.id,name:e}}),!0}isBuiltin(t,e){return this.getWorkflow(t,e)?.isBuiltin??!1}isReservedName(t){let e=["task","done","ship","sync"],n=["add","rm","gate","list","create","delete","run","help","reset","init"];return e.includes(t)||n.includes(t)}isValidName(t){return/^[a-z0-9-]+$/.test(t)}rowToWorkflow(t){return{id:t.id,name:t.name,description:t.description,createdAt:t.created_at,updatedAt:t.updated_at,isBuiltin:t.is_builtin===1,enabled:t.enabled===1,metadata:t.metadata?JSON.parse(t.metadata):null}}},p=new u;export{p as a};
@@ -5,7 +5,7 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{e as c,g as S}from"./chunk-HDHVBB6Q.mjs";import{a as m}from"./chunk-E66B27AL.mjs";S();var E=45,O=1,T=.4,R=2.5,h=-2.5,x=-.5,I=-1.3,p=864e5,N=["resolves","relates","supersedes","superseded-by","duplicates","spec"],C=["corrects","contradicts"],d=/\bmem[_-](\d+)\b/g;function w(n,r){let e=new Set;for(let t of N){let s=r[t];if(s)for(let o of String(s).matchAll(d))e.add(`mem_${o[1]}`)}for(let t of n.matchAll(d))e.add(`mem_${t[1]}`);for(let t of l(r))e.delete(t);return[...e]}m(w,"extractRefIds");function l(n){let r=new Set;for(let e of C){let t=n[e];if(t)for(let s of String(t).matchAll(d))r.add(`mem_${s[1]}`)}return[...r]}m(l,"extractCorrectionIds");function g(n,r,e,t,s){c.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${t}, last_used_at)
8
+ import{e as c,g as S}from"./chunk-UHVYBU7F.mjs";import{a as m}from"./chunk-E66B27AL.mjs";S();var E=45,O=1,T=.4,R=2.5,h=-2.5,x=-.5,I=-1.3,p=864e5,N=["resolves","relates","supersedes","superseded-by","duplicates","spec"],C=["corrects","contradicts"],d=/\bmem[_-](\d+)\b/g;function w(n,r){let e=new Set;for(let t of N){let s=r[t];if(s)for(let o of String(s).matchAll(d))e.add(`mem_${o[1]}`)}for(let t of n.matchAll(d))e.add(`mem_${t[1]}`);for(let t of l(r))e.delete(t);return[...e]}m(w,"extractRefIds");function l(n){let r=new Set;for(let e of C){let t=n[e];if(t)for(let s of String(t).matchAll(d))r.add(`mem_${s[1]}`)}return[...r]}m(l,"extractCorrectionIds");function g(n,r,e,t,s){c.run(n,`INSERT INTO memory_usefulness (memory_id, score, ${t}, last_used_at)
9
9
  VALUES (?, ?, 1, ?)
10
10
  ON CONFLICT(memory_id) DO UPDATE SET
11
11
  score = score + ?, ${t} = ${t} + 1, last_used_at = excluded.last_used_at`,r,e,s,e)}m(g,"bump");function f(n,r,e,t){c.run(n,`INSERT INTO memory_usefulness (memory_id, score, last_used_at)
@@ -5,6 +5,6 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{b as k,o as w}from"./chunk-CTWZQ7YI.mjs";import{a}from"./chunk-E66B27AL.mjs";w();import{existsSync as g}from"node:fs";import{readFile as P}from"node:fs/promises";import u from"node:path";function v(n){let e=n.trim();if(!e)return null;let s=(e.split(/&&|\|\||;/)[0]?.trim()??e).split(/\s+/).filter(Boolean);if(s.length<2)return null;let r=s[0].replace(/\.cmd$/i,""),o=r==="npm"||r==="npx"?"npm":r==="pnpm"?"pnpm":r==="yarn"?"yarn":r==="bun"?"bun":null;if(!o)return null;let i=s[1];if(!(i==="install"||i==="i"||i==="add"||o==="npm"&&i==="install"||o==="yarn"&&(i==="add"||i==="install")))return null;let m=[];for(let y of s.slice(2).keys()){let c=s[y+2];if(c.startsWith("-")||c.startsWith(".")||c.startsWith("/")||c.startsWith("file:")||c.startsWith("http"))continue;let f=D(c);f&&m.push(f)}let d=[...new Set(m)];return d.length===0?null:{manager:o,packages:d}}a(v,"parsePackageInstallCommand");function D(n){if(n.startsWith("@")){let t=n.match(/^(@[\w.-]+\/[\w.-]+)/);return t?t[1]:null}let e=n.split("@")[0]??"";return!e||!/^[\w.-]+$/.test(e)?null:e}a(D,"normalizePackageToken");function I(n,e){let t=n.filter(s=>!e.has(s)).sort();return t.length===0?{risky:!1,newPackages:[],message:null}:{risky:!0,newPackages:t,message:[`Package legitimacy (pre-install): ${t.length} new package${t.length===1?"":"s"} not in package.json:`,...t.map(s=>` - ${s}`),"Verify each on the registry (age, downloads, maintainers). Do not install look-alike names.","Strict packs DENY the install until verified. Override ship later with `prjct ship --allow-new-deps` only after human consent."].join(`
8
+ import{b as k,p as w}from"./chunk-QWQFF2UG.mjs";import{a}from"./chunk-E66B27AL.mjs";w();import{existsSync as g}from"node:fs";import{readFile as P}from"node:fs/promises";import u from"node:path";function v(n){let e=n.trim();if(!e)return null;let s=(e.split(/&&|\|\||;/)[0]?.trim()??e).split(/\s+/).filter(Boolean);if(s.length<2)return null;let r=s[0].replace(/\.cmd$/i,""),o=r==="npm"||r==="npx"?"npm":r==="pnpm"?"pnpm":r==="yarn"?"yarn":r==="bun"?"bun":null;if(!o)return null;let i=s[1];if(!(i==="install"||i==="i"||i==="add"||o==="npm"&&i==="install"||o==="yarn"&&(i==="add"||i==="install")))return null;let m=[];for(let y of s.slice(2).keys()){let c=s[y+2];if(c.startsWith("-")||c.startsWith(".")||c.startsWith("/")||c.startsWith("file:")||c.startsWith("http"))continue;let f=D(c);f&&m.push(f)}let d=[...new Set(m)];return d.length===0?null:{manager:o,packages:d}}a(v,"parsePackageInstallCommand");function D(n){if(n.startsWith("@")){let t=n.match(/^(@[\w.-]+\/[\w.-]+)/);return t?t[1]:null}let e=n.split("@")[0]??"";return!e||!/^[\w.-]+$/.test(e)?null:e}a(D,"normalizePackageToken");function I(n,e){let t=n.filter(s=>!e.has(s)).sort();return t.length===0?{risky:!1,newPackages:[],message:null}:{risky:!0,newPackages:t,message:[`Package legitimacy (pre-install): ${t.length} new package${t.length===1?"":"s"} not in package.json:`,...t.map(s=>` - ${s}`),"Verify each on the registry (age, downloads, maintainers). Do not install look-alike names.","Strict packs DENY the install until verified. Override ship later with `prjct ship --allow-new-deps` only after human consent."].join(`
9
9
  `)}}a(I,"decidePackageInstall");async function $(n){let e=u.join(n,"package.json");if(!g(e))return new Set;let t=await h(e);return p(t)}a($,"loadKnownDependencyNames");function p(n){let e=new Set;if(!n)return e;for(let t of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){let s=n[t];if(s)for(let r of Object.keys(s))e.add(r)}return e}a(p,"depNames");async function h(n){try{let e=await P(n,"utf-8");return JSON.parse(e)}catch{return null}}a(h,"readJsonFile");async function b(n){try{let{stdout:e}=await k("git",["show","HEAD:package.json"],{cwd:n});return JSON.parse(e)}catch{return null}}a(b,"headPackageJson");async function R(n){let e=u.join(n,"package.json");if(!g(e))return{newDependencies:[],risky:!1,message:null};if(!g(u.join(n,".git")))return{newDependencies:[],risky:!1,message:null};let t=await h(e),s=await b(n),r=p(t),o=p(s),i=[...r].filter(l=>!o.has(l)).sort();return i.length===0?{newDependencies:[],risky:!1,message:null}:{newDependencies:i,risky:!0,message:[`Package legitimacy: ${i.length} new dependenc${i.length===1?"y":"ies"} vs HEAD:`,...i.map(l=>` - ${l}`),"Verify each on the registry (age, downloads, source). Do not substitute similar names.","Strict packs block ship until you confirm or revert.","Override with explicit consent: `prjct ship --allow-new-deps` (not `--no-spec-gate`)."].join(`
10
10
  `)}}a(R,"checkPackageLegitimacy");export{v as a,I as b,$ as c,R as d};
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{p as g,t as L,u as M}from"./chunk-A6K4H3YT.mjs";import{a as O,b as i,c as S}from"./chunk-JQE2F2RK.mjs";import{i as k,k as E,o as C}from"./chunk-UH4MD3F3.mjs";import{c as D}from"./chunk-FW4MEPTB.mjs";import{a as A}from"./chunk-SYHDEUVU.mjs";import{d as N,e as G}from"./chunk-GCDLPKOH.mjs";import{e as c,f as R}from"./chunk-BUDZL4DW.mjs";import{a,e as b}from"./chunk-E66B27AL.mjs";R();C();M();import o from"node:fs/promises";import n from"node:path";import j from"node:fs/promises";import T from"node:path";R();C();var y='<!-- prjct:start - DO NOT REMOVE THIS MARKER -->\n# p/ \u2014 Project knowledge layer\n\nprjct stores project memory (decisions, learnings, gotchas, patterns, ships, analyses) per project in SQLite and serves it to you through tools. **Query it \u2014 don\'t re-read source from scratch.**\n\nprjct remembers and shows the path; it does not own execution. Treat prjct output as durable signals (task state, memories, specs, workflows, risks, recent learnings). Claude, GPT, and other agents decide the concrete HOW with their own native tools and judgment, then persist meaningful outcomes back to prjct.\n\nYou are in a prjct project when `.prjct/` is in cwd OR `~/.prjct-cli/projects/` has an entry for the current path.\n\n## Lookup FIRST, source LAST\n\nBefore reading source code or running broad searches for ANY question about the project (architecture, conventions, decisions, recent ships, bugs, patterns, tech debt, past analyses), QUERY prjct first \u2014 bounded, ranked answers from SQLite, no markdown trees to wade through:\n\n- `prjct context memory <topic>` / `prjct search "<q>"` \u2014 captured decisions, gotchas, learnings, facts\n- `prjct context --md` \u2014 current state: active cycle, ships, recent learnings\n- architecture / conventions / patterns / anti-patterns / tech-debt / insights \u2192 MCP `prjct_analysis` (add `mode:archive` for history)\n- developer preferences \u2192 MCP `prjct_developer`; machine signals \u2192 MCP `prjct_signals`\n- specs \u2192 MCP `prjct_spec_list` / `prjct_spec_get`; per-file traps before editing \u2192 `prjct guard <file>`\n\nOnly fall through to source/repo reading when prjct does not contain the answer.\n\n**Skill \u2260 project identity.** The prjct skill is a portable multi-LLM contract (L0). Live name/stack/branch come from SessionStart + `prjct context --md` for **this cwd**. If skill text and the tree disagree, trust the cwd and the tree.\n\n## Capture analyses BACK to prjct\n\nWhen you complete substantive work \u2014 analysis, decision, learning, gotcha \u2014 persist it: `prjct remember <decision|learning|gotcha|fact> "..."` or `prjct capture "<text>" --tags k:v`. **Author every entry in ENGLISH**, whatever language the user speaks. **Default to capturing \u2014 under-capture is the failure mode that makes prjct useless.** The full verb map and task workflow live in the `prjct` skill.\n\n## Where things live\n\n- Source of truth: SQLite at `~/.prjct-cli/projects/<id>/` (don\'t read directly \u2014 use `prjct` CLI / MCP tools)\n- Project config: `.prjct/prjct.config.json` in repo root\n\n**Auto-managed by prjct-cli** | https://prjct.app\n<!-- prjct:end - DO NOT REMOVE THIS MARKER -->\n';async function P(){let u=(M(),b(L)),t=await u.getActiveProvider(),e=t.name;if(!(await u.detectProvider(e)).installed&&!t.configDir)return{success:!1,error:`${t.displayName} not detected`,action:"skipped"};try{await j.mkdir(t.configDir,{recursive:!0});let s=T.join(t.configDir,t.contextFile),m=await(async()=>{if(e==="claude")return y;let d=D(`global/${t.contextFile}`);if(d)return d;let{PACKAGE_ROOT:f}=(G(),b(N)),I=T.join(f,"templates","global",t.contextFile);return j.readFile(I,"utf-8").catch(()=>e==="gemini"?y.replace(/Claude/g,"Gemini"):y)})(),r=await k(s),p="<!-- prjct-project:start - DO NOT REMOVE THIS MARKER -->",h="<!-- prjct-project:end - DO NOT REMOVE THIS MARKER -->",x=(()=>{if(!r.content.includes(p)||!r.content.includes(h))return r.content;let d=r.content.substring(0,r.content.indexOf(p)),f=r.content.substring(r.content.indexOf(h)+h.length);return`${(d+f).replace(/\n{3,}/g,`
9
+
10
+ `).trim()}
11
+ `})(),w=A(r.exists?x:"",m,"<!-- prjct:start - DO NOT REMOVE THIS MARKER -->","<!-- prjct:end - DO NOT REMOVE THIS MARKER -->");return await j.writeFile(s,w.content,"utf-8"),{success:!0,action:w.action,path:s}}catch(s){return{success:!1,error:c(s),action:"failed"}}}a(P,"installGlobalConfig");S();async function rt(){return P()}a(rt,"installGlobalConfig");var v=class{static{a(this,"CommandInstaller")}commandsPath="";configPath="";_initialized=!1;async ensureInit(){if(this._initialized)return;let t=await g();this.configPath=t.configDir??"",this.commandsPath=this.configPath?n.join(this.configPath,"commands"):"",this._initialized=!0}async detectActiveProvider(){return await this.ensureInit(),E(this.configPath)}async installCommands(){let t=await this.detectActiveProvider(),e=await g();return t?(await this.cleanupRouter(),{success:!0,installed:[],path:this.commandsPath}):{success:!1,error:`${e.displayName} not detected. Please install it first.`}}async uninstallCommands(){try{let t=[];await this.ensureInit();for(let e of["p.md","p.toml"]){let l=n.join(this.commandsPath,e);try{await o.unlink(l),t.push(e)}catch(s){if(s.code!=="ENOENT")return{success:!1,error:c(s)}}}return{success:!0,uninstalled:t}}catch(t){return{success:!1,error:c(t)}}}async checkInstallation(){return await this.detectActiveProvider()?{installed:!0,providerDetected:!0,commands:[],path:this.commandsPath}:{installed:!1,providerDetected:!1}}async getInstallPath(){return await this.ensureInit(),this.commandsPath}async syncCommands(){if(!await this.detectActiveProvider())return{success:!1,error:"AI agent not detected",added:0,updated:0,removed:0};try{return{success:!0,added:0,updated:0,removed:await this.cleanupRouter()?1:0}}catch(e){return{success:!1,error:c(e),added:0,updated:0,removed:0}}}async cleanupRouter(){return await this.ensureInit(),(await Promise.all(["p.md","p.toml"].map(async e=>{try{return await o.unlink(n.join(this.commandsPath,e)),!0}catch{return!1}}))).some(Boolean)}async cleanupLegacyCommands(){await this.ensureInit();let t=n.join(this.commandsPath,"p");try{if((await o.stat(t).catch(()=>null))?.isDirectory())return await o.rm(t,{recursive:!0,force:!0}),!0}catch{}return!1}async installGlobalConfig(){return P()}async cleanupAllLegacy(){let t=O(),e=[],l=[n.join(t,".claude","commands","p.md"),n.join(t,".claude","commands","p.toml"),n.join(t,".gemini","commands","p.md"),n.join(t,".gemini","commands","p.toml")];for(let r of l)try{await o.unlink(r),e.push(r)}catch{}let s=[n.join(t,".claude","commands","p"),n.join(t,".gemini","commands","p")];for(let r of s)try{(await o.stat(r).catch(()=>null))?.isDirectory()&&(await o.rm(r,{recursive:!0,force:!0}),e.push(r))}catch{}let m=[n.join(t,".prjct-cli","config","homebrew-migrated")];for(let r of m)try{await o.unlink(r),e.push(r)}catch{}return{cleaned:e}}};function nt(){return{claude:{commands:i(".claude","commands"),config:i(".claude"),router:i(".claude","commands","p.md")},gemini:{commands:i(".gemini","commands"),config:i(".gemini"),router:i(".gemini","commands","p.toml")}}}a(nt,"getProviderPaths");var _=new v,st=_;export{rt as a,v as b,nt as c,st as d};
@@ -5,4 +5,4 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{c as r}from"./chunk-L4COZ7ZH.mjs";import{b as t}from"./chunk-SOPRYWUY.mjs";import{a as e}from"./chunk-E66B27AL.mjs";function u(o){let n=t(o);return n.allow?null:{deny:n.denyMessage}}e(u,"decideSecrets");function l(o=process.cwd(),n){return r({event:"PreToolUse",projectPath:o,decide:e(async c=>{try{return u(c)}catch{return null}},"decide")},n)}e(l,"runPreSecretsHook");var p={decideSecrets:u};export{u as a,l as b,p as c};
8
+ import{a as r}from"./chunk-GPZP7NXL.mjs";import{b as t}from"./chunk-XS45K7ZQ.mjs";import{a as e}from"./chunk-E66B27AL.mjs";function u(o){let n=t(o);return n.allow?null:{deny:n.denyMessage}}e(u,"decideSecrets");function l(o=process.cwd(),n){return r({event:"PreToolUse",projectPath:o,decide:e(async c=>{try{return u(c)}catch{return null}},"decide")},n)}e(l,"runPreSecretsHook");var p={decideSecrets:u};export{u as a,l as b,p as c};
@@ -5,7 +5,7 @@ import { dirname as __pathDirname } from 'path';
5
5
  const require = __createRequire(import.meta.url);
6
6
  const __filename = __fileURLToPath(import.meta.url);
7
7
  const __dirname = __pathDirname(__filename);
8
- import{a as O}from"./chunk-HZIORCPO.mjs";import{a as A}from"./chunk-WDGDFXSB.mjs";import{b as h}from"./chunk-NWY5M34K.mjs";import{c as I}from"./chunk-OGOCHZ3S.mjs";import{a as P,h as tt}from"./chunk-UUULLTQV.mjs";import{a as w,b,c as S}from"./chunk-3JUE6MNF.mjs";import{c as E}from"./chunk-YUOTOCKK.mjs";import{b as R}from"./chunk-BISPGBNN.mjs";import{a as x}from"./chunk-AOPJ4Z6O.mjs";import{a as m}from"./chunk-AUUWQH3S.mjs";import{b as N}from"./chunk-MEQS4VPO.mjs";import{a as T,b as j,e as p,g as _}from"./chunk-HDHVBB6Q.mjs";import{b as D,e as Z}from"./chunk-AKIN5WSQ.mjs";import{a as d}from"./chunk-E66B27AL.mjs";_();function g(e,t,n){return e[t]??e[n]??""}d(g,"str");var L={async upsert(e,t){let n=g(t,"id","id"),r=g(t,"entity_type","entityType"),s=g(t,"entity_id","entityId");if(!n||!r||!s||p.get(e,"SELECT id FROM archives WHERE entity_type = ? AND entity_id = ? LIMIT 1",r,s))return;let c=typeof t.entity_data=="string"?t.entity_data:t.entity_data!=null?JSON.stringify(t.entity_data):"{}",o=g(t,"archived_at","archivedAt")||g(t,"created_at","createdAt")||new Date().toISOString(),a=t.summary??null,u=g(t,"reason","reason")||"sync";try{p.run(e,`INSERT OR IGNORE INTO archives
8
+ import{a as O}from"./chunk-ROA2AJXY.mjs";import{a as A}from"./chunk-DVDZA63F.mjs";import{a as h}from"./chunk-ZOX6OV6X.mjs";import{c as I}from"./chunk-ZFLIVOFX.mjs";import{a as P,h as tt}from"./chunk-UUULLTQV.mjs";import{a as w,b,c as S}from"./chunk-OC4CYF7V.mjs";import{c as E}from"./chunk-XDBJSJOT.mjs";import{b as R}from"./chunk-XXRAQZNC.mjs";import{a as m}from"./chunk-RTEEXGEA.mjs";import{c as x}from"./chunk-M5E2YOZ4.mjs";import{b as N}from"./chunk-ABJNOG2I.mjs";import{a as T,b as j,e as p,g as _}from"./chunk-UHVYBU7F.mjs";import{b as D,h as Z}from"./chunk-A6K4H3YT.mjs";import{a as d}from"./chunk-E66B27AL.mjs";_();function g(e,t,n){return e[t]??e[n]??""}d(g,"str");var L={async upsert(e,t){let n=g(t,"id","id"),r=g(t,"entity_type","entityType"),s=g(t,"entity_id","entityId");if(!n||!r||!s||p.get(e,"SELECT id FROM archives WHERE entity_type = ? AND entity_id = ? LIMIT 1",r,s))return;let c=typeof t.entity_data=="string"?t.entity_data:t.entity_data!=null?JSON.stringify(t.entity_data):"{}",o=g(t,"archived_at","archivedAt")||g(t,"created_at","createdAt")||new Date().toISOString(),a=t.summary??null,u=g(t,"reason","reason")||"sync";try{p.run(e,`INSERT OR IGNORE INTO archives
9
9
  (id, entity_type, entity_id, entity_data, summary, archived_at, reason)
10
10
  VALUES (?, ?, ?, ?, ?, ?, ?)`,n,r,s,c,a,o,u)}catch{}},async delete(e,t){}};_();var C={async upsert(e,t){let n=t.name||"";if(!n)return;let r=t.description??null,s=et(t.metadata),i=new Date().toISOString(),c=p.get(e,"SELECT id, is_builtin FROM custom_workflows WHERE name = ?",n);if(c){if(c.is_builtin===1)return;p.run(e,"UPDATE custom_workflows SET description = ?, metadata = ?, updated_at = ? WHERE name = ? AND is_builtin = 0",r,s,i,n);return}p.run(e,`INSERT INTO custom_workflows (name, description, created_at, updated_at, is_builtin, enabled, metadata)
11
11
  VALUES (?, ?, ?, ?, 0, 0, ?)`,n,r,t.created_at||i,i,s)},async delete(e,t){}};function et(e){if(e==null)return null;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return null}}d(et,"serializeMetadata");var M={async upsert(e,t){let n=t.id||"";if(!n)return;let r=t.title||t.text||"";if(!r.trim())return;let s=t.priority||"medium",i=t.status||"active";await O.upsertIdea(e,{id:n,text:r,priority:s,status:i==="archived"?"archived":"pending",addedAt:t.created_at??t.addedAt??new Date().toISOString()})},async delete(e,t){}};j();tt();_();function nt(e){if(!e)return{};if(typeof e=="string")try{return JSON.parse(e)}catch{return{}}return typeof e=="object"?e:{}}d(nt,"asTags");function f(e,t,n){return e[t]??e[n]??""}d(f,"field");var W={async upsert(e,t){let n=f(t,"content","content"),r=f(t,"type","type");if(!n||!r)return;let s=nt(t.tags),i=f(t,"provenance","provenance")||"declared",c=t.source??null,o=T(n);if(p.get(e,"SELECT id FROM memory_entries WHERE content_hash = ? AND type = ? AND deleted_at IS NULL LIMIT 1",o,r))return;let u=t.created_at||t.createdAt||new Date().toISOString();p.appendEvent(e,`memory.${P}${r}`,{content:n,tags:s,source:c,provenance:i,content_hash:o,project_id:e,created_at:u})},async delete(e,t){let n=f(t,"id","id"),r=f(t,"content","content"),s=f(t,"type","type"),i=[];if(/^mem_\d+$/.test(n)&&i.push(n),r&&s){let o=T(r),a=p.query(e,"SELECT id FROM memory_entries WHERE content_hash = ? AND type = ? AND deleted_at IS NULL",o,s);i.push(...a.map(u=>u.id))}let c=[...new Set(i)];for(let o of c){let a=o.match(/^mem_(\d+)$/)?.[1];a&&p.run(e,"UPDATE events SET type = ? WHERE id = ?","memory.deleted.context-quality",Number(a)),p.run(e,"UPDATE memory_entries SET deleted_at = ? WHERE id = ?",Date.now(),o),p.run(e,"DELETE FROM memory_embeddings WHERE memory_id = ?",o)}}};var F={async upsert(e,t){let n=t.description||"";if(!n.trim())return;let r=t.id||"";if(!r){await h.addTask(e,{description:n,priority:t.priority||"medium",type:t.type||"feature",section:t.section||"backlog"});return}await h.upsertTask(e,{id:r,description:n,...t.priority?{priority:t.priority}:{},...t.type?{type:t.type}:{},...t.section?{section:t.section}:{}})},async delete(e,t){}};var k={async upsert(e,t){await A.addShipped(e,{name:t.name||t.title||"",version:t.version||"",description:t.description||""},t.created_at||t.shippedAt||t.shipped_at)},async delete(e,t){}};var U={async upsert(e,t){let n=t.id||"";n&&I.applyRemote(e,{id:n,title:t.title,status:t.status,content:t.content??{},tags:t.tags,created_at:t.created_at,updated_at:t.updated_at})},async delete(e,t){}};var $={async upsert(e,t){let n=t.id||"";if(!n)return;let r=t.status||"";if(r==="completed"||r==="shipped"){await R.update(e,s=>s.currentTask?.id===n?{...s,currentTask:null}:s);return}if(r==="active"||t.started_at||t.startedAt){await R.update(e,s=>({...s,currentTask:{id:n,description:t.description,startedAt:t.started_at||t.startedAt||new Date().toISOString(),sessionId:t.session_id||t.sessionId||""}}));return}(t.description||"").trim()&&await h.upsertTask(e,{id:n,description:t.description,...t.priority?{priority:t.priority}:{},...t.type?{type:t.type}:{}})},async delete(e,t){}};_();var q={async upsert(e,t){let n=Number(t.id);if(!Number.isSafeInteger(n)||n<=0)return;let r=-n;p.transaction(e,s=>{s.prepare(`INSERT INTO workflow_rules
@@ -28,4 +28,4 @@ import{a as O}from"./chunk-HZIORCPO.mjs";import{a as A}from"./chunk-WDGDFXSB.mjs
28
28
  ON CONFLICT(entity_type, entity_id) DO UPDATE SET
29
29
  content_hash = excluded.content_hash,
30
30
  applied_at = excluded.applied_at,
31
- created_at = COALESCE(excluded.created_at, sync_applied_hashes.created_at)`,t,n,r,D(),s??null)}catch{}}d(B,"recordApplied");function V(e,t,n){if(!(!t||!n))try{p.run(e,"DELETE FROM sync_applied_hashes WHERE entity_type = ? AND entity_id = ?",t,n)}catch{}}d(V,"clearApplied");var G=new Set;function rt(e){if(G.has(e))return;G.add(e);let n=Y.has(e)?"CLI does not track this entity locally yet \u2014 see Phase 2 spec":"no local handler registered";console.warn(`[sync] apply skipped: entity_type='${e}' (${n}). code=no_local_handler`)}d(rt,"warnNoLocalHandler");var J=new Set;function st(e){J.has(e)||(J.add(e),console.warn(`[sync] inbound '${e}' event has no created_at \u2014 origin chronology cannot be preserved. The producer should include created_at in its payload. code=missing_origin_created_at`))}d(st,"warnMissingCreatedAt");function it(e){let t=e.data??{},n=e.content_hash??e.contentHash;if(e.entity_type){let c=(e.event_type||"upsert")==="delete"?"delete":"upsert";return{entityType:e.entity_type,eventType:c,data:t,contentHash:n}}if(e.entityType){let c=e.eventType||"upsert";return{entityType:e.entityType,eventType:c==="delete"?"delete":"upsert",data:t,contentHash:n}}let[r,s]=(e.type||"").split("."),i=s==="deleted"||s==="archived"||s==="removed";return{entityType:w(r)||r||"unknown",eventType:i?"delete":"upsert",data:t,contentHash:n}}d(it,"normalizeEventShape");function K(e){return e instanceof Error?e.message:e&&typeof e=="object"&&"message"in e?String(e.message):"Unknown error"}d(K,"errorMessage");function X(e){if(e&&typeof e=="object"&&"code"in e)return e.code}d(X,"errorCode");var H=class{static{d(this,"SyncManager")}async hasAuth(){return await E.hasAuth()}async getStatus(t){if(!await this.hasAuth())return null;try{return await S.getStatus(t)}catch{return null}}async sync(t,n){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};let r={success:!0,skipped:!1};try{await A.republishShips(t)}catch{}let s=await this.push(t,n);s.success&&!s.skipped&&(r.pushed={count:s.count||0,syncedAt:s.syncedAt||new Date().toISOString()});let i=await this.pull(t);return i.success&&!i.skipped&&(r.pulled={count:i.count||0,syncedAt:i.syncedAt||new Date().toISOString()}),(!s.success||!i.success)&&(r.success=!1,r.error=s.error||i.error,r.code=s.code||i.code),r}async push(t,n){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};try{let r=await m.getPending(t),s=n?.include?r.filter(a=>{let u=w(a.entityType)??w(a.type?.split(".")[0]);return u?b(u,n.include):!0}):r;if(s.length===0)return{success:!0,skipped:!0,reason:"no_pending"};let i=await this.createProjectLinkEvent(t),c=i?[i,...s]:s,o=await S.pushEvents(t,c);if(o.success)return await m.clearPending(t),await m.updateLastSync(t),{success:!0,skipped:!1,count:o.processed,syncedAt:o.syncedAt};{let a=o.processed,u=o.errors.length,l=o.errors.map(y=>y.error).join(", ");return{success:!1,skipped:!1,count:a,syncedAt:o.syncedAt,error:`${u} events failed: ${l}`}}}catch(r){return{success:!1,skipped:!1,reason:"error",error:K(r),code:X(r)}}}async pull(t){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};try{let{syncCursorStorage:n}=await import("./sync-cursor-storage-2VKG757H.mjs"),r=await E.read(),s=r.deviceId??null,i=r.userId??null,o=(s?n.get(t,i,s):null)?.lastEventId??0,a=await S.pullEvents(t,o);if(a.events.length===0)return await m.updateLastSync(t),{success:!0,skipped:!1,count:0,applied:0,syncedAt:a.syncedAt};let u=await this.applyPulledEvents(t,a.events),l=a.events.flatMap(y=>[y.event_id,y.eventId]).filter(y=>typeof y=="number").reduce((y,Q)=>Math.max(y,Q),o);return s&&l>o&&n.advance(t,l,{userId:i,deviceId:s}),await m.updateLastSync(t),{success:!0,skipped:!1,count:a.events.length,applied:u,syncedAt:a.syncedAt}}catch(n){return{success:!1,skipped:!1,reason:"error",error:K(n),code:X(n)}}}async applyPulledEvents(t,n){let r=[];for(let s of n)try{await this.applyEvent(t,s),r.push(s)}catch(i){let c=s.entity_type||s.type||"unknown";console.error(`Failed to apply event ${c}:`,i)}return r.length}async applyRealtimeEvent(t,n){try{let r=await E.read(),s=r.deviceId??null,i=n.origin_device_id??n.originDeviceId;if(s&&i&&i===s)return!1;await this.applyEvent(t,n);let c=typeof n.event_id=="number"?n.event_id:typeof n.eventId=="number"?n.eventId:null;if(c!==null){let{syncCursorStorage:o}=await import("./sync-cursor-storage-2VKG757H.mjs"),a=r.userId??null,u=r.deviceId??null;if(u){let l=o.get(t,a,u);(!l||c>l.lastEventId)&&o.advance(t,c,{userId:a,deviceId:u})}}return!0}catch(r){return console.error("[realtime] apply failed:",r instanceof Error?r.message:r),!1}}async applyEvent(t,n){let{entityType:r,eventType:s,data:i,contentHash:c}=it(n),o=i.id??"",a=v[r];if(!a){rt(r);return}if(s==="delete"){await a.delete(t,i),o&&V(t,r,o);return}if(!(c&&this.alreadyApplied(t,r,o,c))&&(await a.upsert(t,i),o)){let u=i.created_at??i.createdAt??null;u||st(r);let l=c??x(i);B(t,r,o,l,u)}}alreadyApplied(t,n,r,s){if(!r)return!1;let i=z(t,n,r);return i!==null&&i===s}async createProjectLinkEvent(t){try{let n=await N(t).catch(()=>({}));return{type:"project.updated",path:["project"],data:{id:t,cli_project_id:t,meta:n},timestamp:new Date().toISOString(),projectId:t}}catch{return null}}},ot=new H,ee=ot;export{ee as a};
31
+ created_at = COALESCE(excluded.created_at, sync_applied_hashes.created_at)`,t,n,r,D(),s??null)}catch{}}d(B,"recordApplied");function V(e,t,n){if(!(!t||!n))try{p.run(e,"DELETE FROM sync_applied_hashes WHERE entity_type = ? AND entity_id = ?",t,n)}catch{}}d(V,"clearApplied");var G=new Set;function rt(e){if(G.has(e))return;G.add(e);let n=Y.has(e)?"CLI does not track this entity locally yet \u2014 see Phase 2 spec":"no local handler registered";console.warn(`[sync] apply skipped: entity_type='${e}' (${n}). code=no_local_handler`)}d(rt,"warnNoLocalHandler");var J=new Set;function st(e){J.has(e)||(J.add(e),console.warn(`[sync] inbound '${e}' event has no created_at \u2014 origin chronology cannot be preserved. The producer should include created_at in its payload. code=missing_origin_created_at`))}d(st,"warnMissingCreatedAt");function it(e){let t=e.data??{},n=e.content_hash??e.contentHash;if(e.entity_type){let c=(e.event_type||"upsert")==="delete"?"delete":"upsert";return{entityType:e.entity_type,eventType:c,data:t,contentHash:n}}if(e.entityType){let c=e.eventType||"upsert";return{entityType:e.entityType,eventType:c==="delete"?"delete":"upsert",data:t,contentHash:n}}let[r,s]=(e.type||"").split("."),i=s==="deleted"||s==="archived"||s==="removed";return{entityType:w(r)||r||"unknown",eventType:i?"delete":"upsert",data:t,contentHash:n}}d(it,"normalizeEventShape");function K(e){return e instanceof Error?e.message:e&&typeof e=="object"&&"message"in e?String(e.message):"Unknown error"}d(K,"errorMessage");function X(e){if(e&&typeof e=="object"&&"code"in e)return e.code}d(X,"errorCode");var H=class{static{d(this,"SyncManager")}async hasAuth(){return await E.hasAuth()}async getStatus(t){if(!await this.hasAuth())return null;try{return await S.getStatus(t)}catch{return null}}async sync(t,n){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};let r={success:!0,skipped:!1};try{await A.republishShips(t)}catch{}let s=await this.push(t,n);s.success&&!s.skipped&&(r.pushed={count:s.count||0,syncedAt:s.syncedAt||new Date().toISOString()});let i=await this.pull(t);return i.success&&!i.skipped&&(r.pulled={count:i.count||0,syncedAt:i.syncedAt||new Date().toISOString()}),(!s.success||!i.success)&&(r.success=!1,r.error=s.error||i.error,r.code=s.code||i.code),r}async push(t,n){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};try{let r=await m.getPending(t),s=n?.include?r.filter(a=>{let u=w(a.entityType)??w(a.type?.split(".")[0]);return u?b(u,n.include):!0}):r;if(s.length===0)return{success:!0,skipped:!0,reason:"no_pending"};let i=await this.createProjectLinkEvent(t),c=i?[i,...s]:s,o=await S.pushEvents(t,c);if(o.success)return await m.clearPending(t),await m.updateLastSync(t),{success:!0,skipped:!1,count:o.processed,syncedAt:o.syncedAt};{let a=o.processed,u=o.errors.length,l=o.errors.map(y=>y.error).join(", ");return{success:!1,skipped:!1,count:a,syncedAt:o.syncedAt,error:`${u} events failed: ${l}`}}}catch(r){return{success:!1,skipped:!1,reason:"error",error:K(r),code:X(r)}}}async pull(t){if(!await this.hasAuth())return{success:!0,skipped:!0,reason:"no_auth"};try{let{syncCursorStorage:n}=await import("./sync-cursor-storage-VVLA3L2U.mjs"),r=await E.read(),s=r.deviceId??null,i=r.userId??null,o=(s?n.get(t,i,s):null)?.lastEventId??0,a=await S.pullEvents(t,o);if(a.events.length===0)return await m.updateLastSync(t),{success:!0,skipped:!1,count:0,applied:0,syncedAt:a.syncedAt};let u=await this.applyPulledEvents(t,a.events),l=a.events.flatMap(y=>[y.event_id,y.eventId]).filter(y=>typeof y=="number").reduce((y,Q)=>Math.max(y,Q),o);return s&&l>o&&n.advance(t,l,{userId:i,deviceId:s}),await m.updateLastSync(t),{success:!0,skipped:!1,count:a.events.length,applied:u,syncedAt:a.syncedAt}}catch(n){return{success:!1,skipped:!1,reason:"error",error:K(n),code:X(n)}}}async applyPulledEvents(t,n){let r=[];for(let s of n)try{await this.applyEvent(t,s),r.push(s)}catch(i){let c=s.entity_type||s.type||"unknown";console.error(`Failed to apply event ${c}:`,i)}return r.length}async applyRealtimeEvent(t,n){try{let r=await E.read(),s=r.deviceId??null,i=n.origin_device_id??n.originDeviceId;if(s&&i&&i===s)return!1;await this.applyEvent(t,n);let c=typeof n.event_id=="number"?n.event_id:typeof n.eventId=="number"?n.eventId:null;if(c!==null){let{syncCursorStorage:o}=await import("./sync-cursor-storage-VVLA3L2U.mjs"),a=r.userId??null,u=r.deviceId??null;if(u){let l=o.get(t,a,u);(!l||c>l.lastEventId)&&o.advance(t,c,{userId:a,deviceId:u})}}return!0}catch(r){return console.error("[realtime] apply failed:",r instanceof Error?r.message:r),!1}}async applyEvent(t,n){let{entityType:r,eventType:s,data:i,contentHash:c}=it(n),o=i.id??"",a=v[r];if(!a){rt(r);return}if(s==="delete"){await a.delete(t,i),o&&V(t,r,o);return}if(!(c&&this.alreadyApplied(t,r,o,c))&&(await a.upsert(t,i),o)){let u=i.created_at??i.createdAt??null;u||st(r);let l=c??x(i);B(t,r,o,l,u)}}alreadyApplied(t,n,r,s){if(!r)return!1;let i=z(t,n,r);return i!==null&&i===s}async createProjectLinkEvent(t){try{let n=await N(t).catch(()=>({}));return{type:"project.updated",path:["project"],data:{id:t,cli_project_id:t,meta:n},timestamp:new Date().toISOString(),projectId:t}}catch{return null}}},ot=new H,ee=ot;export{ee as a};
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'module';
3
+ import { fileURLToPath as __fileURLToPath } from 'url';
4
+ import { dirname as __pathDirname } from 'path';
5
+ const require = __createRequire(import.meta.url);
6
+ const __filename = __fileURLToPath(import.meta.url);
7
+ const __dirname = __pathDirname(__filename);
8
+ import{a as h}from"./chunk-RTEEXGEA.mjs";import{c as p}from"./chunk-M5E2YOZ4.mjs";import{d as c,g}from"./chunk-UHVYBU7F.mjs";import{b as a,h as m,j as d,k as f}from"./chunk-A6K4H3YT.mjs";import{a as r}from"./chunk-E66B27AL.mjs";f();m();g();function v(i){let[e,t]=i.split(".");return e?{entityType:e.endsWith("s")?e:`${e}s`,eventType:t==="deleted"||t==="archived"||t==="removed"?"delete":"upsert"}:{}}r(v,"deriveEntityShape");function T(i){if(!i||typeof i!="object")return;let e=i;for(let t of["taskId","task_id","id","feature_id","featureId","specId","spec_id"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}}r(T,"entityIdOf");var u={value:null};async function w(){if(u.value)return u.value;try{let{default:i}=await import("./auth-config-JIITQ6GY.mjs"),e=i;if(typeof e.getDeviceId=="function"){let t=await e.getDeviceId();return u.value=t,t}return"unknown-device"}catch{return"unknown-device"}}r(w,"_resolveDeviceId");var y=class{static{r(this,"StorageManager")}filename;cache;constructor(e,t){this.filename=e,this.cache=new d({ttl:5e3,maxSize:50})}getStoreKey(){return this.filename.replace(".json","")}async read(e){if(!(process.env.PRJCT_IN_DAEMON==="1")){let n=this.cache.get(e);if(n!==null)return n}try{let n=c.getDoc(e,this.getStoreKey());if(n!==null)return this.cache.set(e,n),n}catch{}return this.getDefault()}async write(e,t){c.setDoc(e,this.getStoreKey(),t),this.cache.set(e,t)}async update(e,t){let n=this.getStoreKey(),s=c.updateDoc(e,n,t,()=>this.getDefault());return this.cache.set(e,s),s}async publishEvent(e,t,n){let s=v(t),o={type:t,path:[this.filename.replace(".json","")],data:n,timestamp:a(),projectId:e,entityType:s.entityType,entityId:T(n),eventType:s.eventType,contentHash:p(n),deviceId:await w(),revisionCount:1};await h.publish(o)}async publishEntityEvent(e,t,n,s){let o=`${t}.${n}`,l={...s,timestamp:a()};await this.publishEvent(e,o,l)}async exists(e){try{return c.hasDoc(e,this.getStoreKey())}catch{return!1}}clearCache(e){e?this.cache.delete(e):this.cache.clear()}getCacheStats(){return this.cache.stats()}};export{y as a};