prjct-cli 3.94.0 → 3.96.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 (190) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +27 -21
  3. package/dist/bin/hook-chunks/{agent-identity-45BYQBU2.mjs → agent-identity-DH6DX72X.mjs} +1 -1
  4. package/dist/bin/hook-chunks/{agent-switch-2U2LOBGR.mjs → agent-switch-I4MTVE56.mjs} +1 -1
  5. package/dist/bin/hook-chunks/{analysis-N4NYGIG3.mjs → analysis-VN7APBHR.mjs} +3 -3
  6. package/dist/bin/hook-chunks/{auth-config-SP4PBALR.mjs → auth-config-JIITQ6GY.mjs} +1 -1
  7. package/dist/bin/hook-chunks/{auto-flush-BN6L6QHO.mjs → auto-flush-DX3FVSQE.mjs} +1 -1
  8. package/dist/bin/hook-chunks/{capture-gate-FRF2G3IG.mjs → capture-gate-MEIQD7ZS.mjs} +1 -1
  9. package/dist/bin/hook-chunks/{chunk-OZJ6UKKP.mjs → chunk-22GFTUER.mjs} +1 -1
  10. package/dist/bin/hook-chunks/chunk-32RX4YGI.mjs +9 -0
  11. package/dist/bin/hook-chunks/{chunk-Q3EYM4GJ.mjs → chunk-33BHU4OM.mjs} +2 -2
  12. package/dist/bin/hook-chunks/{chunk-HNEKXKOI.mjs → chunk-3AHW4XQH.mjs} +1 -1
  13. package/dist/bin/hook-chunks/{chunk-JMCMTX6U.mjs → chunk-3CKNJ5RA.mjs} +1 -1
  14. package/dist/bin/hook-chunks/{chunk-6RLCUGGG.mjs → chunk-3FEXJUO2.mjs} +1 -1
  15. package/dist/bin/hook-chunks/{chunk-7GNWHWOO.mjs → chunk-3HGQPUKG.mjs} +1 -1
  16. package/dist/bin/hook-chunks/{chunk-D6IONKRA.mjs → chunk-3UB6SFRA.mjs} +1 -1
  17. package/dist/bin/hook-chunks/{chunk-AVRNHROK.mjs → chunk-64ZEBHDX.mjs} +1 -1
  18. package/dist/bin/hook-chunks/{chunk-MI3JEFON.mjs → chunk-7PBWIO4K.mjs} +3 -3
  19. package/dist/bin/hook-chunks/{chunk-UA4Z5TGG.mjs → chunk-7WO5CEH3.mjs} +1 -1
  20. package/dist/bin/hook-chunks/chunk-A6K4H3YT.mjs +9 -0
  21. package/dist/bin/hook-chunks/{chunk-3VWBNLBC.mjs → chunk-ADYTBOCZ.mjs} +1 -1
  22. package/dist/bin/hook-chunks/{chunk-TG5CQJD5.mjs → chunk-AORD3YDQ.mjs} +1 -1
  23. package/dist/bin/hook-chunks/{chunk-EHEQOF6Z.mjs → chunk-B36LC2JR.mjs} +1 -1
  24. package/dist/bin/hook-chunks/{chunk-FX6VHIKB.mjs → chunk-BKJHD5JI.mjs} +1 -1
  25. package/dist/bin/hook-chunks/{chunk-S7HQQILD.mjs → chunk-BVK7ZDLX.mjs} +1 -1
  26. package/dist/bin/hook-chunks/{chunk-HHIGNKDO.mjs → chunk-CPR4FPXG.mjs} +1 -1
  27. package/dist/bin/hook-chunks/{chunk-6UH244CC.mjs → chunk-D7DQABWO.mjs} +1 -1
  28. package/dist/bin/hook-chunks/{chunk-Y4DUB7UN.mjs → chunk-DB226JIV.mjs} +2 -2
  29. package/dist/bin/hook-chunks/{chunk-KOCROTRM.mjs → chunk-DCHIPMOG.mjs} +1 -1
  30. package/dist/bin/hook-chunks/{chunk-IKIB42F7.mjs → chunk-E7NA34VQ.mjs} +1 -1
  31. package/dist/bin/hook-chunks/{chunk-MHQTGU45.mjs → chunk-EGCYDLSO.mjs} +1 -1
  32. package/dist/bin/hook-chunks/{chunk-ZMKTR2IO.mjs → chunk-EI6VQZOX.mjs} +1 -1
  33. package/dist/bin/hook-chunks/{chunk-INXNK57E.mjs → chunk-ETTDRXQ6.mjs} +1 -1
  34. package/dist/bin/hook-chunks/{chunk-EQ5KNMLG.mjs → chunk-EXVL2OFE.mjs} +1 -1
  35. package/dist/bin/hook-chunks/{chunk-5EQLQ7GF.mjs → chunk-FZS3XGEA.mjs} +1 -1
  36. package/dist/bin/hook-chunks/{chunk-QYEASMFV.mjs → chunk-GSPDJSJ5.mjs} +1 -1
  37. package/dist/bin/hook-chunks/{chunk-TKWAFYF7.mjs → chunk-H2DGDAQP.mjs} +1 -1
  38. package/dist/bin/hook-chunks/chunk-H5AVBDCH.mjs +8 -0
  39. package/dist/bin/hook-chunks/{chunk-SDUS2AT7.mjs → chunk-HGZQWYBL.mjs} +1 -1
  40. package/dist/bin/hook-chunks/{chunk-EMTCZG5I.mjs → chunk-IJ523YO2.mjs} +1 -1
  41. package/dist/bin/hook-chunks/{chunk-NBKEOLDH.mjs → chunk-IWUF2LGO.mjs} +5 -5
  42. package/dist/bin/hook-chunks/chunk-JGZ3QGWX.mjs +11 -0
  43. package/dist/bin/hook-chunks/{chunk-66GE3IHX.mjs → chunk-JZDZH6IV.mjs} +1 -1
  44. package/dist/bin/hook-chunks/{chunk-PUHX3ECX.mjs → chunk-KDNUQPAK.mjs} +1 -1
  45. package/dist/bin/hook-chunks/chunk-KV4NXLPT.mjs +11 -0
  46. package/dist/bin/hook-chunks/{chunk-XE4MJNBQ.mjs → chunk-LF3S3MYE.mjs} +1 -1
  47. package/dist/bin/hook-chunks/chunk-LQLCYBFF.mjs +36 -0
  48. package/dist/bin/hook-chunks/{chunk-YUKGWWL7.mjs → chunk-LR24AIEW.mjs} +1 -1
  49. package/dist/bin/hook-chunks/{chunk-2HB2JHQE.mjs → chunk-M4YM7Z3F.mjs} +15 -15
  50. package/dist/bin/hook-chunks/{chunk-F4T7IAA7.mjs → chunk-MW54MTLB.mjs} +1 -1
  51. package/dist/bin/hook-chunks/{chunk-7O6OMD4X.mjs → chunk-NCLONKOT.mjs} +1 -1
  52. package/dist/bin/hook-chunks/{chunk-HRWXMF7P.mjs → chunk-NJ74RHNC.mjs} +1 -1
  53. package/dist/bin/hook-chunks/{chunk-JUZ5LNDI.mjs → chunk-NLL5AV2G.mjs} +2 -2
  54. package/dist/bin/hook-chunks/{chunk-OIU4Y5WL.mjs → chunk-OC4CYF7V.mjs} +1 -1
  55. package/dist/bin/hook-chunks/chunk-OLQAMCYV.mjs +18 -0
  56. package/dist/bin/hook-chunks/{chunk-C3W2HLJT.mjs → chunk-PPWPUEBH.mjs} +1 -1
  57. package/dist/bin/hook-chunks/chunk-PVCEWFHS.mjs +51 -0
  58. package/dist/bin/hook-chunks/{chunk-Y3J7UUMR.mjs → chunk-QOQZHR3E.mjs} +1 -1
  59. package/dist/bin/hook-chunks/{chunk-2UC4DTDO.mjs → chunk-QXCEBAIA.mjs} +1 -1
  60. package/dist/bin/hook-chunks/chunk-RT2DFIWF.mjs +19 -0
  61. package/dist/bin/hook-chunks/{chunk-NCOOKPXX.mjs → chunk-SQW2B7NW.mjs} +1 -1
  62. package/dist/bin/hook-chunks/{chunk-IHECXD2M.mjs → chunk-SWJ7TLBD.mjs} +1 -1
  63. package/dist/bin/hook-chunks/{chunk-X2AGNDGD.mjs → chunk-TB57OYGW.mjs} +1 -1
  64. package/dist/bin/hook-chunks/{chunk-QPRNRLG6.mjs → chunk-TF6PN7IB.mjs} +1 -1
  65. package/dist/bin/hook-chunks/{chunk-KG7Z6OMK.mjs → chunk-TKXOMN4K.mjs} +4 -4
  66. package/dist/bin/hook-chunks/chunk-UMJ5D5I6.mjs +9 -0
  67. package/dist/bin/hook-chunks/{chunk-NWIQNII6.mjs → chunk-UVATSTRF.mjs} +1 -1
  68. package/dist/bin/hook-chunks/{chunk-NHIWYDQD.mjs → chunk-WJV24WE6.mjs} +1 -1
  69. package/dist/bin/hook-chunks/{chunk-Q3Z53QTH.mjs → chunk-WL6PKX3U.mjs} +1 -1
  70. package/dist/bin/hook-chunks/chunk-WUOVBBPC.mjs +11 -0
  71. package/dist/bin/hook-chunks/{chunk-TYEAIX3X.mjs → chunk-XDBJSJOT.mjs} +1 -1
  72. package/dist/bin/hook-chunks/{chunk-JCYXFHQZ.mjs → chunk-XSJ7SPVR.mjs} +1 -1
  73. package/dist/bin/hook-chunks/{chunk-J6TAD3OZ.mjs → chunk-XV2LJVYB.mjs} +1 -1
  74. package/dist/bin/hook-chunks/{chunk-7JEKBJAP.mjs → chunk-XYKVWO23.mjs} +1 -1
  75. package/dist/bin/hook-chunks/{chunk-4O4D6DV7.mjs → chunk-Y3RHBU2R.mjs} +2 -2
  76. package/dist/bin/hook-chunks/{chunk-JPSJWCFD.mjs → chunk-Y7MZA2G4.mjs} +1 -1
  77. package/dist/bin/hook-chunks/{chunk-T2FCU3ZS.mjs → chunk-YHOZTAZH.mjs} +1 -1
  78. package/dist/bin/hook-chunks/chunk-YLOK4WRR.mjs +8 -0
  79. package/dist/bin/hook-chunks/{chunk-OENWCYLF.mjs → chunk-ZJW27EUC.mjs} +1 -1
  80. package/dist/bin/hook-chunks/{chunk-VWOIUTAX.mjs → chunk-ZQI4TJ5C.mjs} +3 -3
  81. package/dist/bin/hook-chunks/chunk-ZYCNW75E.mjs +9 -0
  82. package/dist/bin/hook-chunks/{chunk-AZHE4VOM.mjs → chunk-ZZBNFNMG.mjs} +1 -1
  83. package/dist/bin/hook-chunks/{client-ERZ5CM3D.mjs → client-K3ZA2BLB.mjs} +3 -3
  84. package/dist/bin/hook-chunks/{code-graph-cloud-4GRWQSUK.mjs → code-graph-cloud-XGQF7XYC.mjs} +1 -1
  85. package/dist/bin/hook-chunks/{codex-skill-6DYQMPDJ.mjs → codex-skill-6CRFUF3A.mjs} +1 -1
  86. package/dist/bin/hook-chunks/{command-installer-MF4KUM3X.mjs → command-installer-MUHZWDZA.mjs} +1 -1
  87. package/dist/bin/hook-chunks/{config-manager-2VZPHUDG.mjs → config-manager-2JJPCLKC.mjs} +1 -1
  88. package/dist/bin/hook-chunks/{context7-service-V7CIDF3Q.mjs → context7-service-NH4BMGSJ.mjs} +1 -1
  89. package/dist/bin/hook-chunks/{custom-workflow-storage-UOBQXY42.mjs → custom-workflow-storage-VBMWLKA7.mjs} +1 -1
  90. package/dist/bin/hook-chunks/cwd-changed-UTD6Y4MS.mjs +8 -0
  91. package/dist/bin/hook-chunks/{database-XYKQF3KR.mjs → database-ZCP76LMM.mjs} +1 -1
  92. package/dist/bin/hook-chunks/{detect-changes-DFRJOOB3.mjs → detect-changes-5W6EGEZG.mjs} +1 -1
  93. package/dist/bin/hook-chunks/{developer-evolution-SLC34HUU.mjs → developer-evolution-UTY3CWOK.mjs} +1 -1
  94. package/dist/bin/hook-chunks/{distill-U2LJGUG3.mjs → distill-5TNAM3LY.mjs} +1 -1
  95. package/dist/bin/hook-chunks/{editors-config-6XFYIOE6.mjs → editors-config-2CACBNS4.mjs} +1 -1
  96. package/dist/bin/hook-chunks/{enriched-recall-X6RDNNIE.mjs → enriched-recall-6VOIUNLN.mjs} +1 -1
  97. package/dist/bin/hook-chunks/{format-ALUX4QSI.mjs → format-IIOFTSBF.mjs} +1 -1
  98. package/dist/bin/hook-chunks/{judgment-ledger-storage-SCGU3URM.mjs → judgment-ledger-storage-7Q7AEEY6.mjs} +1 -1
  99. package/dist/bin/hook-chunks/{judgment-orchestrator-BYPG65RS.mjs → judgment-orchestrator-AAON4ZJ4.mjs} +1 -1
  100. package/dist/bin/hook-chunks/{judgment-receipt-GWSSCLAB.mjs → judgment-receipt-QLV3MYFT.mjs} +1 -1
  101. package/dist/bin/hook-chunks/{land-cue-MMISX2BI.mjs → land-cue-57B23PEL.mjs} +1 -1
  102. package/dist/bin/hook-chunks/{land-synthesis-WG5JAS7B.mjs → land-synthesis-ZVPFJERV.mjs} +1 -1
  103. package/dist/bin/hook-chunks/{legacy-crew-sweep-2WSO5KEB.mjs → legacy-crew-sweep-GR6HRSHX.mjs} +2 -2
  104. package/dist/bin/hook-chunks/{memory-index-QK5QJOFJ.mjs → memory-index-XE2MWKQS.mjs} +1 -1
  105. package/dist/bin/hook-chunks/{notification-MPVWVV52.mjs → notification-GU2ZJP5K.mjs} +1 -1
  106. package/dist/bin/hook-chunks/{pack-integrity-XRYOROK5.mjs → pack-integrity-WV5U3AFF.mjs} +1 -1
  107. package/dist/bin/hook-chunks/{pack-manager-WWGQNJDQ.mjs → pack-manager-QLFQKP24.mjs} +1 -1
  108. package/dist/bin/hook-chunks/{path-manager-ZR5RAKTK.mjs → path-manager-375HH6TB.mjs} +1 -1
  109. package/dist/bin/hook-chunks/{planning-S55KBPN2.mjs → planning-VPAX5DZL.mjs} +2 -2
  110. package/dist/bin/hook-chunks/{post-edit-QMHSZHDN.mjs → post-edit-UXCFSR3Y.mjs} +1 -1
  111. package/dist/bin/hook-chunks/{pre-bash-RAM6L3G4.mjs → pre-bash-MB4JNNYG.mjs} +1 -1
  112. package/dist/bin/hook-chunks/{pre-commit-736ZLMDL.mjs → pre-commit-U7TRFKWX.mjs} +1 -1
  113. package/dist/bin/hook-chunks/pre-edit-MDCQXI5F.mjs +11 -0
  114. package/dist/bin/hook-chunks/{pre-package-LCIAWWGK.mjs → pre-package-A6ZI5R64.mjs} +1 -1
  115. package/dist/bin/hook-chunks/{pre-search-J5EOFMYN.mjs → pre-search-ZZO3LGXJ.mjs} +1 -1
  116. package/dist/bin/hook-chunks/{pre-secrets-TSUMTXHH.mjs → pre-secrets-MWPPZPWK.mjs} +1 -1
  117. package/dist/bin/hook-chunks/{prjct-md-T2DG236Y.mjs → prjct-md-MS52YLI2.mjs} +1 -1
  118. package/dist/bin/hook-chunks/{project-agent-surfaces-VRY22I66.mjs → project-agent-surfaces-6AIW7KL6.mjs} +1 -1
  119. package/dist/bin/hook-chunks/{project-file-inventory-5DEN5VLF.mjs → project-file-inventory-HHURZTMH.mjs} +1 -1
  120. package/dist/bin/hook-chunks/project-memory-UDH56VFP.mjs +8 -0
  121. package/dist/bin/hook-chunks/{project-style-evolution-7MAUSED2.mjs → project-style-evolution-IJXT2MCP.mjs} +1 -1
  122. package/dist/bin/hook-chunks/prompt-7VZLYONO.mjs +24 -0
  123. package/dist/bin/hook-chunks/{publish-helper-G54XQV5K.mjs → publish-helper-ZSL27HSX.mjs} +1 -1
  124. package/dist/bin/hook-chunks/{purge-MC5LFSAO.mjs → purge-N2WN6NDB.mjs} +1 -1
  125. package/dist/bin/hook-chunks/retention-RET4P2RO.mjs +8 -0
  126. package/dist/bin/hook-chunks/{sdd-5UCVX43H.mjs → sdd-PB6WKSLE.mjs} +1 -1
  127. package/dist/bin/hook-chunks/{session-continuity-RKNAJJHR.mjs → session-continuity-BIJXMN44.mjs} +1 -1
  128. package/dist/bin/hook-chunks/session-start-R2VMKW2L.mjs +8 -0
  129. package/dist/bin/hook-chunks/settings-installer-CQKMGMRG.mjs +9 -0
  130. package/dist/bin/hook-chunks/{setup-WQRJ6TQL.mjs → setup-PPIZHVXS.mjs} +3 -3
  131. package/dist/bin/hook-chunks/{shipping-5D5LTJ3P.mjs → shipping-C637PCOF.mjs} +4 -4
  132. package/dist/bin/hook-chunks/{skill-index-RAVJMC4P.mjs → skill-index-55I3HLAI.mjs} +1 -1
  133. package/dist/bin/hook-chunks/{spec-context-inference-7DDSTRTV.mjs → spec-context-inference-RTTDOZZO.mjs} +1 -1
  134. package/dist/bin/hook-chunks/{spec-service-LAO5Z2M5.mjs → spec-service-ENLAAMVL.mjs} +2 -2
  135. package/dist/bin/hook-chunks/{spec-task-breakdown-K3GMQKGH.mjs → spec-task-breakdown-RUDEP3AY.mjs} +1 -1
  136. package/dist/bin/hook-chunks/{state-storage-EIFGUO7X.mjs → state-storage-AJUPG7J5.mjs} +1 -1
  137. package/dist/bin/hook-chunks/stop-DPXAWJFN.mjs +16 -0
  138. package/dist/bin/hook-chunks/subagent-start-AFHPXL2S.mjs +8 -0
  139. package/dist/bin/hook-chunks/{subagent-stop-RBD2OILE.mjs → subagent-stop-5BMV63ML.mjs} +1 -1
  140. package/dist/bin/hook-chunks/{surface-attribution-K37N2NK7.mjs → surface-attribution-EGIKCVMF.mjs} +1 -1
  141. package/dist/bin/hook-chunks/{symbol-graph-BKQIMFRG.mjs → symbol-graph-MH42JSPX.mjs} +1 -1
  142. package/dist/bin/hook-chunks/{sync-client-EGBMWF3J.mjs → sync-client-PIRHMHXL.mjs} +1 -1
  143. package/dist/bin/hook-chunks/{sync-cursor-storage-E3LMZISA.mjs → sync-cursor-storage-ZB7FGT6D.mjs} +1 -1
  144. package/dist/bin/hook-chunks/{task-orchestration-2ZYE5M6J.mjs → task-orchestration-7NGRIISS.mjs} +1 -1
  145. package/dist/bin/hook-chunks/{task-overview-ITY5OSHX.mjs → task-overview-F3GB77OA.mjs} +1 -1
  146. package/dist/bin/hook-chunks/task-service-FZABHPFV.mjs +8 -0
  147. package/dist/bin/hook-chunks/{tdd-7S55S5C3.mjs → tdd-TAMBOPN3.mjs} +1 -1
  148. package/dist/bin/hook-chunks/{template-loader-SCM4C2A3.mjs → template-loader-MXOMU4XH.mjs} +1 -1
  149. package/dist/bin/hook-chunks/{transcript-jsonl-6X4DDD6R.mjs → transcript-jsonl-7W2NOJPZ.mjs} +1 -1
  150. package/dist/bin/hook-chunks/{usefulness-SCH5ARGV.mjs → usefulness-TBD5EYAL.mjs} +1 -1
  151. package/dist/bin/hook-chunks/{vault-retire-notice-HT756AND.mjs → vault-retire-notice-7XHVNHU6.mjs} +1 -1
  152. package/dist/bin/hook-chunks/{velocity-storage-47CF3XWZ.mjs → velocity-storage-IOCVK2LU.mjs} +1 -1
  153. package/dist/bin/hook-chunks/{weak-model-mode-FLCEQ2BV.mjs → weak-model-mode-BMSPGEQY.mjs} +1 -1
  154. package/dist/bin/hook-chunks/{work-graph-JQHVVXIZ.mjs → work-graph-AVAOKY63.mjs} +1 -1
  155. package/dist/bin/hook-chunks/work-scope-YCS4GTXW.mjs +8 -0
  156. package/dist/bin/hook-chunks/{workspace-occupancy-UUW4UGGB.mjs → workspace-occupancy-JOBYNNXV.mjs} +1 -1
  157. package/dist/bin/hook-fast-darwin-arm64 +0 -0
  158. package/dist/bin/hook-fast-darwin-x64 +0 -0
  159. package/dist/bin/hook-fast-linux-x64 +0 -0
  160. package/dist/bin/prjct-core.mjs +739 -714
  161. package/dist/bin/prjct-hooks.mjs +3 -3
  162. package/dist/bin/prjct.mjs +22 -9
  163. package/dist/daemon/entry.mjs +620 -593
  164. package/dist/mcp/server.mjs +317 -303
  165. package/package.json +3 -5
  166. package/scripts/install.sh +28 -496
  167. package/dist/bin/hook-chunks/chunk-27XFSCOE.mjs +0 -43
  168. package/dist/bin/hook-chunks/chunk-4SKJWNKE.mjs +0 -11
  169. package/dist/bin/hook-chunks/chunk-AZYQFRPJ.mjs +0 -9
  170. package/dist/bin/hook-chunks/chunk-DRGI5UHQ.mjs +0 -10
  171. package/dist/bin/hook-chunks/chunk-GFY4GY3Z.mjs +0 -8
  172. package/dist/bin/hook-chunks/chunk-JAMSIKDE.mjs +0 -9
  173. package/dist/bin/hook-chunks/chunk-NUJASVHN.mjs +0 -18
  174. package/dist/bin/hook-chunks/chunk-NWZEBCTC.mjs +0 -19
  175. package/dist/bin/hook-chunks/chunk-PW3KYKVS.mjs +0 -9
  176. package/dist/bin/hook-chunks/chunk-TFCLMTJ5.mjs +0 -9
  177. package/dist/bin/hook-chunks/chunk-TRMBRDKH.mjs +0 -8
  178. package/dist/bin/hook-chunks/chunk-V2BSS7HW.mjs +0 -36
  179. package/dist/bin/hook-chunks/chunk-ZJXH76Q5.mjs +0 -11
  180. package/dist/bin/hook-chunks/cwd-changed-J6O46KS7.mjs +0 -8
  181. package/dist/bin/hook-chunks/pre-edit-GZ4QJ2MU.mjs +0 -11
  182. package/dist/bin/hook-chunks/project-memory-KKEMTEMP.mjs +0 -8
  183. package/dist/bin/hook-chunks/prompt-DVF6V2X2.mjs +0 -22
  184. package/dist/bin/hook-chunks/retention-LWETHQX3.mjs +0 -8
  185. package/dist/bin/hook-chunks/session-start-MFMFKUPK.mjs +0 -8
  186. package/dist/bin/hook-chunks/settings-installer-QDM3GB6J.mjs +0 -9
  187. package/dist/bin/hook-chunks/stop-RYLI4FGF.mjs +0 -16
  188. package/dist/bin/hook-chunks/subagent-start-CCUPSANT.mjs +0 -8
  189. package/dist/bin/hook-chunks/task-service-XREJLWEF.mjs +0 -8
  190. package/dist/bin/hook-chunks/work-scope-CDLSZ4U5.mjs +0 -8
@@ -1,9 +0,0 @@
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{d as u,g as L}from"./chunk-KG7Z6OMK.mjs";import{b as f,h as P}from"./chunk-JAMSIKDE.mjs";import{a as c}from"./chunk-E66B27AL.mjs";P();L();function b(t,e,n){let s=t.prepare("INSERT INTO analysis_finding (id, analysis_id, kind, title, detail, severity, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)"),o=[],i=c((a,m,p,j)=>{if(!m)return;let k=o.length,S=`${e}-f${k}`;s.run(S,e,a,m,p,j,k),o.push(S)},"addFinding");for(let a of n.patterns??[])i("pattern",a.name,a.description,null);for(let a of n.antiPatterns??[])i("anti_pattern",a.issue,a.suggestion,a.severity);for(let a of n.techDebt??[])i("tech_debt",a.description,`${a.area}: ${a.impact}`,a.priority);for(let a of n.riskAreas??[])i("risk_area",a.path,`${a.reason} \u2014 ${a.risk}`,a.severity);for(let a of n.refactorSuggestions??[])i("refactor",a.description,a.benefit,null);for(let a of n.projectInsights??[])i("insight",a,null,null);for(let a of n.architecture?.insights??[])i("insight",a,null,null);let l=t.prepare("INSERT INTO analysis_convention (id, analysis_id, rule, sort_order) VALUES (?, ?, ?, ?)");(n.conventions??[]).forEach((a,m)=>{l.run(`${e}-c${m}`,e,a.rule,m)});let g=t.prepare("INSERT INTO analysis_stack_item (id, analysis_id, kind, name) VALUES (?, ?, ?, ?)");[...(n.stack?.languages??[]).map(a=>({kind:"language",name:a})),...(n.stack?.frameworks??[]).map(a=>({kind:"framework",name:a}))].forEach((a,m)=>{g.run(`${e}-s${m}`,e,a.kind,a.name)});let d=t.prepare("INSERT INTO analysis_command (id, analysis_id, name, command, purpose) VALUES (?, ?, ?, ?, ?)");Object.entries(n.commands??{}).filter(a=>!!a[1]).forEach(([a,m],p)=>{d.run(`${e}-cmd${p}`,e,a,m,null)});let v=t.prepare("INSERT INTO analysis_domain (id, analysis_id, name, paths) VALUES (?, ?, ?, ?)");(n.architecture?.domains??[]).forEach((a,m)=>{v.run(`${e}-d${m}`,e,a,null)})}c(b,"writeAnalysisChildren");var h=class{static{c(this,"LLMAnalysisStorage")}save(e,n){let s=u.getDb(e),o=f();s.transaction(()=>{s.prepare("UPDATE llm_analysis SET status = 'superseded', superseded_at = ? WHERE status = 'active'").run(o);let i=s.prepare("INSERT INTO llm_analysis (commit_hash, status, analysis, analyzed_at) VALUES (?, ?, ?, ?)").run(n.commitHash??null,"active",JSON.stringify(n),n.analyzedAt);b(s,String(i.lastInsertRowid),n)})()}getActiveRelational(e){let n=u.get(e,"SELECT id FROM llm_analysis WHERE status = 'active' LIMIT 1");if(!n)return null;let s=String(n.id),o=u.query(e,"SELECT kind, title, detail FROM analysis_finding WHERE analysis_id = ? ORDER BY kind, sort_order",s),i=u.query(e,"SELECT rule FROM analysis_convention WHERE analysis_id = ? ORDER BY sort_order",s).map(d=>d.rule),l=u.query(e,"SELECT kind, name FROM analysis_stack_item WHERE analysis_id = ?",s),g=u.query(e,"SELECT name FROM analysis_domain WHERE analysis_id = ?",s).map(d=>d.name),r=u.query(e,"SELECT name, command FROM analysis_command WHERE analysis_id = ?",s);return o.length===0&&i.length===0&&l.length===0?null:{findings:o,conventions:i,stack:l,domains:g,commands:r}}getActive(e){let n=u.get(e,"SELECT analysis FROM llm_analysis WHERE status = 'active' LIMIT 1");return n?JSON.parse(n.analysis):null}getActiveSummary(e){let n=this.getActive(e);return n?{commitHash:n.commitHash,architectureStyle:n.architecture.style,patternCount:n.patterns.length,antiPatternCount:n.antiPatterns.length,analyzedAt:n.analyzedAt}:null}isCurrent(e,n){return n?u.get(e,"SELECT commit_hash FROM llm_analysis WHERE status = 'active' LIMIT 1")?.commit_hash===n:!1}getAllFull(e){return u.query(e,"SELECT id, commit_hash, status, analyzed_at, superseded_at, analysis FROM llm_analysis ORDER BY id DESC").map(s=>({id:s.id,status:s.status,commitHash:s.commit_hash,analyzedAt:s.analyzed_at,supersededAt:s.superseded_at,analysis:JSON.parse(s.analysis)}))}getHistory(e,n=10){return u.query(e,"SELECT id, commit_hash, status, analyzed_at, analysis FROM llm_analysis ORDER BY id DESC LIMIT ?",n).map(o=>{let i=JSON.parse(o.analysis);return{id:o.id,commitHash:o.commit_hash,status:o.status,analyzedAt:o.analyzed_at,patternCount:i.patterns.length}})}},C=new h,B=C;P();var R=["zod","better-sqlite3","@modelcontextprotocol/sdk","@modelcontextprotocol/client","@modelcontextprotocol/server","chalk","chokidar","commander","express","fastify","hono","react","next","vue","vitest","jest","typescript","biome","lefthook","drizzle-orm","prisma","@prisma/client"];function y(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||"item"}c(y,"stableStyleKey");function _(t){return t?!!(t.architecture?.style&&t.architecture.style!=="unknown"||(t.patterns?.length??0)>0||(t.conventions?.length??0)>0||(t.antiPatterns?.length??0)>0||(t.stack?.frameworks?.length??0)>0||(t.stack?.languages?.length??0)>0):!1}c(_,"isRichLlmAnalysis");function W(t){return!_(t)}c(W,"isThinLlmAnalysis");function M(t){let e=T(t),n=w(t.commands),s=_(t.llmAnalysis)?t.llmAnalysis:null,o=z(s?.conventions?.map(r=>({key:y(r.category?`${r.category}-${r.rule}`:r.rule),rule:r.rule,category:r.category}))??[],t.memoryConventions?.map(r=>({key:y(r.category?`${r.category}-${r.rule}`:r.rule),rule:r.rule,category:r.category}))??[]),i=D(s?.patterns?.map(r=>({key:y(r.name),name:r.name,description:r.description,locations:r.locations,category:r.category}))??[],t.memoryPatterns?.map(r=>({key:y(r.name),name:r.name,description:r.description}))??[]),l=N(s?.antiPatterns?.map(r=>({key:y(r.issue),issue:r.issue,suggestion:r.suggestion,severity:r.severity}))??[],t.memoryAntiPatterns?.map(r=>({key:y(r.issue),issue:r.issue,suggestion:r.suggestion}))??[]);if(s?.stack?.languages?.length)for(let r of s.stack.languages)e.languages.includes(r)||e.languages.push(r);if(s?.stack?.frameworks?.length)for(let r of s.stack.frameworks)e.frameworks.includes(r)||e.frameworks.push(r);s?.stack?.packageManager&&!e.packageManager&&(e.packageManager=s.stack.packageManager);let g={symbols:t.structural?.symbols??0,files:t.structural?.files??t.stats.fileCount??0,packages:t.structural?.packages??[]};return{payloadVersion:1,stack:e,commands:n,conventions:o,patterns:i,antiPatterns:l,structural:g,metrics:{...t.metrics??{}}}}c(M,"buildProjectStylePayload");function J(t){let e=M(t),n=t.capturedAt??f();return{id:t.id??`style_${n.replace(/[^0-9]/g,"").slice(0,14)}_${Math.random().toString(36).slice(2,8)}`,capturedAt:n,commitHash:t.commitHash??null,source:t.source??"sync-mechanical",patternCount:e.patterns.length,antiPatternCount:e.antiPatterns.length,conventionCount:e.conventions.length,frameworkCount:e.stack.frameworks.length,symbolCount:e.structural.symbols,fileCount:e.structural.files,summary:$(e),payload:e}}c(J,"buildProjectStyleSnapshot");function $(t){let e=[t.stack.ecosystem!=="unknown"?t.stack.ecosystem:null,t.stack.languages.slice(0,2).join("+")||null,t.stack.frameworks.slice(0,3).join(", ")||null].filter(Boolean);return`${e.length>0?e.join(" \xB7 "):"stack unknown"}; ${t.patterns.length} patterns, ${t.antiPatterns.length} anti-patterns, ${t.conventions.length} conventions; ${t.structural.files} files`+(t.structural.symbols>0?`, ${t.structural.symbols} symbols`:"")}c($,"buildStyleSummary");function T(t){let e=A([...t.stack.frameworks??[],...t.stats.frameworks??[]]),n=A([...t.stats.languages??[]]),s=x(t.packageDeps??{}),o=t.packageDeps??{};for(let l of s)["Hono","Express","Fastify","React","Next.js","Vue","NestJS"].includes(l)&&!e.includes(l)&&e.push(l);let i=t.stack.hasTesting===!0||!!(o.vitest||o.jest||o.mocha||o["bun-types"]||o["@types/bun"]||s.includes("Vitest")||s.includes("Jest"))||!!(t.commands?.test&&/test/i.test(t.commands.test));return{ecosystem:t.stats.ecosystem||"unknown",languages:n,frameworks:e,packageManager:t.packageManager??void 0,keyLibraries:s,hasTests:i,hasDocker:t.stack.hasDocker===!0}}c(T,"buildStack");function w(t){return t?{test:t.test,lint:t.lint,build:t.build,dev:t.dev,install:t.install,format:t.format}:{}}c(w,"buildCommands");function x(t){let e=new Set;for(let n of R)t[n]&&e.add(O(n));return[...e].slice(0,16)}c(x,"collectKeyLibraries");function O(t){return{hono:"Hono",express:"Express",fastify:"Fastify",react:"React",next:"Next.js",vue:"Vue",vitest:"Vitest",jest:"Jest",typescript:"TypeScript",zod:"Zod","better-sqlite3":"better-sqlite3","@modelcontextprotocol/sdk":"MCP SDK","@modelcontextprotocol/client":"MCP SDK","@modelcontextprotocol/server":"MCP SDK",biome:"Biome",lefthook:"Lefthook","drizzle-orm":"Drizzle",prisma:"Prisma","@prisma/client":"Prisma"}[t]??t}c(O,"displayLibName");function z(t,e){let n=new Map;for(let s of[...t,...e])n.has(s.key)||n.set(s.key,s);return[...n.values()].slice(0,40)}c(z,"mergeConventions");function D(t,e){let n=new Map;for(let s of[...t,...e])n.has(s.key)||n.set(s.key,s);return[...n.values()].slice(0,40)}c(D,"mergePatterns");function N(t,e){let n=new Map;for(let s of[...t,...e])n.has(s.key)||n.set(s.key,s);return[...n.values()].slice(0,40)}c(N,"mergeAntiPatterns");function A(t){let e=[],n=new Set;for(let s of t){let o=s.trim();if(!o)continue;let i=o.toLowerCase();n.has(i)||(n.add(i),e.push(o))}return e}c(A,"unique");function U(t,e={}){if(!t)return null;let n=e.maxConventions??5,s=e.maxPatterns??4,o=e.maxAnti??3,i=t.payload,l=["## How this repo works (project style)",""],g=[i.stack.ecosystem!=="unknown"?i.stack.ecosystem:null,i.stack.languages.join(", ")||null,i.stack.frameworks.join(", ")||null,i.stack.keyLibraries.slice(0,6).join(", ")||null].filter(Boolean);if(g.length>0&&l.push(`**Stack:** ${g.join(" \xB7 ")}`),i.conventions.length>0){l.push("","**Conventions (match):**");for(let r of i.conventions.slice(0,n))l.push(`- ${r.rule}`)}if(i.patterns.length>0){l.push("","**Patterns (match):**");for(let r of i.patterns.slice(0,s))l.push(`- **${r.name}** \u2014 ${E(r.description,120)}`)}if(i.antiPatterns.length>0){l.push("","**Anti-patterns (avoid):**");for(let r of i.antiPatterns.slice(0,o))l.push(`- ${r.issue}${r.suggestion?` \u2192 ${E(r.suggestion,80)}`:""}`)}return i.conventions.length===0&&i.patterns.length===0&&i.antiPatterns.length===0&&l.push("","_No durable house patterns yet \u2014 open a neighbor file and match local idiom. Prefer `prjct sync` + structured analysis-save-llm JSON to enrich._"),l.push("",`_${t.summary}_`),l.join(`
9
- `)}c(U,"formatProjectStyleDigest");function E(t,e){let n=t.replace(/\s+/g," ").trim();return n.length>e?`${n.slice(0,e-1)}\u2026`:n}c(E,"truncate");export{B as a,_ as b,W as c,J as d,U as e};
@@ -1,10 +0,0 @@
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-GAOQHD5S.mjs";import{a as r}from"./chunk-E66B27AL.mjs";import{readSync as c}from"node:fs";import{isatty as d}from"node:tty";var p=new Set(["SessionStart","UserPromptSubmit","PreToolUse","PostToolUse"]);function T(e,t){return{hookSpecificOutput:{hookEventName:e,permissionDecision:"deny",permissionDecisionReason:u(t)}}}r(T,"buildDenyOutput");function f(){let e=(process.env.PRJCT_HOOK_HOST??"claude").toLowerCase();return e==="gemini"||e==="codex"||e==="cursor"?e:"claude"}r(f,"currentHookHost");function l(e,t=f()){return t==="claude"||t==="codex"||!e||Object.keys(e).length===0?e:t==="gemini"?g(e):t==="cursor"?m(e):e}r(l,"adaptHookOutputForHost");function g(e){let t=e;if(t.hookSpecificOutput?.permissionDecision==="deny")return{decision:"deny",reason:t.hookSpecificOutput.permissionDecisionReason??"blocked by prjct"};let n=e,o=n.hookSpecificOutput;return o?.additionalContext?{hookSpecificOutput:{hookEventName:h(o.hookEventName),additionalContext:o.additionalContext}}:n.systemMessage?{systemMessage:n.systemMessage}:e}r(g,"adaptForGemini");function m(e){let t=e;if(t.hookSpecificOutput?.permissionDecision==="deny")return{decision:"deny",reason:t.hookSpecificOutput.permissionDecisionReason??"blocked by prjct",permissionDecision:"deny",permissionDecisionReason:t.hookSpecificOutput.permissionDecisionReason??"blocked by prjct"};let n=e,o=n.hookSpecificOutput;return o?.additionalContext?{hookSpecificOutput:{hookEventName:k(o.hookEventName),additionalContext:o.additionalContext,additional_context:o.additionalContext},additional_context:o.additionalContext}:n.systemMessage?{systemMessage:n.systemMessage}:e}r(m,"adaptForCursor");function h(e){switch(e){case"UserPromptSubmit":return"BeforeAgent";case"PreToolUse":return"BeforeTool";case"PostToolUse":return"AfterTool";case"Stop":return"AfterAgent";default:return e}}r(h,"mapClaudeEventToGemini");function k(e){switch(e){case"SessionStart":return"sessionStart";case"UserPromptSubmit":return"beforeSubmitPrompt";case"PreToolUse":return"preToolUse";case"PostToolUse":return"postToolUse";case"Stop":return"stop";case"SubagentStart":return"subagentStart";case"SubagentStop":return"subagentStop";default:return e.charAt(0).toLowerCase()+e.slice(1)}}r(k,"mapClaudeEventToCursor");function y(e){if(d(0))return Buffer.alloc(0);try{process.stdin.fd}catch{}let t=Date.now()+e,n=new Int32Array(new SharedArrayBuffer(4)),o=Buffer.alloc(65536),i=[];for(;;)try{let s=c(0,o,0,o.length,null);if(s===0)break;i.push(Buffer.from(o.subarray(0,s)))}catch(s){if(s.code==="EAGAIN"&&Date.now()<t){Atomics.wait(n,0,0,1);continue}break}return Buffer.concat(i)}r(y,"readStdinRaw");function R(){try{let e=y(200).toString("utf-8").trim();return e?JSON.parse(e):{}}catch{return{}}}r(R,"readStdinSafe");function S(e){let t=l(e);process.stdout.write(`${JSON.stringify(t)}
9
- `)}r(S,"emit");function O(){S({})}r(O,"emitEmpty");async function C(e){try{await e()}catch{O()}}r(C,"safeRun");var w=new Set(["this","that","with","from","have","your","please","would","about","there","these","those","what","when","where","which","while","will","been","were","they","them","their","que","como","cuando","donde","porque","para","pero","por","con","sin","los","las","del","una","uno","unos","unas","este","esta","esto","estos","estas","eso","esos","esas","mas","muy","todo","toda","todos","todas","sobre","entre","hasta","desde","hace","hacer","tiene","tienen","debe","deben","puede","pueden","estan","ser","son","algo","ahora","aqui","bien","cada","dale"]);function H(e,t=8){let n=a(e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2")).toLowerCase(),o=new Set,i=[];for(let s of n.split(/[^\p{L}\p{N}]+/u))if(!(s.length<3)&&!w.has(s)&&!o.has(s)&&(o.add(s),i.push(s),i.length>=t))break;return i}r(H,"extractKeywords");function u(e){return e.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,"\uFFFD")}r(u,"stripLoneSurrogates");function v(e,t,n=`
10
- \u2026 [truncated]`){if(e.length<=t)return e;let o=Math.max(0,t-n.length),i=e.charCodeAt(o-1),s=i>=55296&&i<=56319?o-1:o;return e.slice(0,Math.max(0,s))+n}r(v,"safeTruncate");function E(e,t){if(!t)return{};let n=u(t);return p.has(e)?{hookSpecificOutput:{hookEventName:e,additionalContext:n}}:{systemMessage:n}}r(E,"buildHookOutput");export{T as a,l as b,y as c,R as d,S as e,C as f,H as g,v as h,E as i};
@@ -1,8 +0,0 @@
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{b as x}from"./chunk-SJ75V4WG.mjs";import{d as M}from"./chunk-7JEKBJAP.mjs";import{a as f}from"./chunk-27XFSCOE.mjs";import{a as C}from"./chunk-UA4Z5TGG.mjs";import{a as o}from"./chunk-E66B27AL.mjs";var q=new Set(["pattern-detector-auto","pattern-detector-recurring","skill-miss-detector","friction-detector"]);function E(t){if(t.type==="improvement-signal")return!0;let e=t.tags?.source;return e!==void 0&&q.has(e)}o(E,"isSignalEntry");var R=85,S=2;async function K(t,e,n={}){let a=n.threshold??R,d=n.maxIterations??S,i=await import("./retention-LWETHQX3.mjs").then(({evaluateRetention:s})=>s(e,Date.now()).byId).catch(()=>null),h=o(async(s,c,g,m)=>{if(s>=d||c.score>=a)return{...c,irrelevantRemoved:g,repairEntriesCreated:m};let r=f.allEntriesForIndex(e),p=r.filter(l=>{if(!w(l))return!1;let b=i?.get(l.id);return!(b&&b.verdict==="active"&&b.score>=70)}),u=I(r)?0:1;u>0&&await f.remember(t,{type:"context",content:_(r,c),tags:{context_schema:"living-v2",synthesis:"model-authored",feature:"context-quality-cleanup",key_data:`quality_score=${c.score}; threshold=${a}; irrelevant=${p.length}`,model:"prjct sync context-quality analyzer",token_usage:"0 deterministic sync tokens",source:"sync-context-quality"},provenance:"inferred",projectId:e});let y=[];for(let l of p)f.forget(e,l.id)&&(y.push(l.id),await C({projectId:e,entityType:"memories",entityId:l.id,eventType:"delete",data:{id:l.id,type:l.type,content:l.content,tags:l.tags,reason:"context-quality-cleanup"}}));let $={...k(e,a),iterations:s+1,irrelevantRemoved:g+y.length,repairEntriesCreated:m+u};return p.length===0&&u===0?$:h(s+1,$,g+y.length,m+u)},"repairIteration");return h(0,k(e,a),0,0)}o(K,"repairContextQuality");function k(t,e=R){let n=f.allEntriesForIndex(t),a=n.filter(r=>r.type==="context"),d=a.filter(v),i=a.filter(r=>!v(r)),h=n.filter(w),s=[],c=[];n.length>0&&d.length===0&&(c.push(35),s.push("missing living-v2 context synthesis")),h.length>0&&(c.push(Math.min(40,h.length*8)),s.push(`${h.length} irrelevant generated entries in active context`)),i.length>0&&(c.push(Math.min(20,i.length*5)),s.push(`${i.length} legacy context entries need cleanup`));let g=d[0];if(g){let r=x(g.content),u=[r.contextSynthesis,r.keyData,r.model,r.tokenUsage,r.nextImplication].filter(y=>!y).length;u>0&&(c.push(u*4),s.push("latest living context is missing structured UI/LLM fields"))}let m=Math.max(0,Math.min(100,100-c.reduce((r,p)=>r+p,0)));return{score:m,threshold:e,passed:m>=e,iterations:0,livingContextCount:d.length,legacyContextCount:i.length,irrelevantRemoved:0,repairEntriesCreated:0,issues:s}}o(k,"evaluateContextQuality");function w(t){return E(t)?!0:t.tags?.source==="sync-context-quality"||t.type!=="context"||v(t)?!1:L(t)}o(w,"isIrrelevantGeneratedContext");function v(t){if(t.tags?.context_schema==="living-v2")return!0;let e=x(t.content);return!!(e.contextSynthesis&&e.keyData)}o(v,"isLivingV2Context");function I(t){return t.some(e=>e.type==="context"&&v(e))}o(I,"hasUsableLivingContext");function L(t){let e=t.content.trim();if(e.length<260||/User pushback:|raw quote|transcript|hot file|skill-miss/i.test(e))return!0;let n=x(e);return[n.whatHappened,n.whyItMattered,n.pattern,n.antiPattern,n.outcome,n.nextImplication].filter(Boolean).length<3}o(L,"isLowValueLegacyContext");function _(t,e){let n=t.filter(i=>!w(i)).filter(i=>["decision","gotcha","learning","context","shipped"].includes(i.type)).slice(0,8),a=n.length>0?n.map(i=>`${i.type}:${M(i)}`).join("; "):"No high-quality prior context survived cleanup.";return["Context synthesis: Sync repaired historical low-quality project context by removing generated telemetry and preserving the useful project knowledge as a living-v2 synthesis. Future agents should trust this synthesized layer over old raw detector rows or legacy context snippets.",`Key data: ${[`quality_score=${e.score}`,`threshold=${e.threshold}`,`legacy_context=${e.legacyContextCount}`,`issues=${e.issues.join("|")||"none"}`].join("; ")}`,"What happened: prjct sync detected that active context quality was below the required threshold and generated a replacement synthesis before deleting irrelevant generated entries.","Why it mattered: Existing users had accumulated low-signal context over time; leaving it active makes the second brain noisy for both the UI and LLM retrieval.","Who/author: prjct sync","Model: prjct sync context-quality analyzer","Token usage: 0 deterministic sync tokens","Sentiment: cleanup required because raw generated context had become product debt","Related files: generated from existing project memory during sync","Feature/domain: context-quality-cleanup","Pattern: Keep structured key data for UI representation and synthesized context for humans/LLMs.","Anti-pattern: Surfacing raw detector rows, hot-file counters, or short legacy snippets as durable project knowledge.","Decision/trap: Generated garbage is hard-deleted from active recall/vault/search; user-authored decisions, gotchas, learnings, and facts are preserved.",`Outcome: Repair synthesis created from surviving highlights: ${a}`,"Next implication: If quality remains below threshold, run full sync/analysis and inspect remaining user-authored entries manually instead of deleting them blindly."].join(" \xB7 ")}o(_,"buildRepairContext");export{K as a,w as b};
@@ -1,9 +0,0 @@
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{c as y,d as D,e as Q,f as vt}from"./chunk-HDSS6UB3.mjs";import{a as Y,b as m,c as q,d as wt}from"./chunk-JQE2F2RK.mjs";import{a as K,b as Dt}from"./chunk-WUHGODSQ.mjs";import{g as W,k as u,l as N,m as P,o as S}from"./chunk-UH4MD3F3.mjs";import{a as z,b as A,p as J}from"./chunk-QWQFF2UG.mjs";import{a as i,c as h,d as yt,e as F}from"./chunk-E66B27AL.mjs";function $t(e){let t=e.getFullYear(),n=(e.getMonth()+1).toString().padStart(2,"0"),r=e.getDate().toString().padStart(2,"0");return`${t}-${n}-${r}`}function X(e){return{year:e.getFullYear().toString(),month:(e.getMonth()+1).toString().padStart(2,"0"),day:e.getDate().toString().padStart(2,"0")}}function _t(){return new Date().toISOString()}function xt(e){let t=new Date;return t.setDate(t.getDate()-e),t}function Bt(e){return xt(e).toISOString()}function Lt(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?e:null}function Ut(e,t){if(!e||!t)return null;let n=Date.parse(e),r=Date.parse(t);return!Number.isFinite(n)||!Number.isFinite(r)||r<n?null:Math.round((r-n)/6e4)}function Vt(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60),s=Math.floor(r/24);return s>0?`${s}d ${r%24}h`:r>0?`${r}h ${n%60}m`:n>0?`${n}m`:`${t}s`}var zt,Z=h(()=>{"use strict";i($t,"formatDate");i(X,"getYearMonthDay");i(_t,"getTimestamp");i(xt,"getDaysAgo");i(Bt,"sinceIso");i(Lt,"nullableNumber");i(Ut,"durationMinutes");i(Vt,"formatDuration");zt=new Intl.RelativeTimeFormat("en",{numeric:"always"})});import St from"node:fs";import w from"node:fs/promises";import l from"node:path";async function R(e){let t={isMonorepo:!1,type:null,rootPath:e,packages:[]},n=[{file:"pnpm-workspace.yaml",type:"pnpm"},{file:"lerna.json",type:"lerna"},{file:"nx.json",type:"nx"},{file:"rush.json",type:"rush"},{file:"turbo.json",type:"turborepo"}];for(let r of n)if(await u(l.join(e,r.file))){t.isMonorepo=!0,t.type=r.type;break}if(!t.isMonorepo){let r=l.join(e,"package.json");if(await u(r))try{JSON.parse(await w.readFile(r,"utf-8")).workspaces&&(t.isMonorepo=!0,t.type="npm")}catch{}}return t.isMonorepo&&(t.packages=await T(e,t.type)),t}async function T(e,t){let n=[];try{let r=await(async()=>{if(t==="pnpm"){let g=(await w.readFile(l.join(e,"pnpm-workspace.yaml"),"utf-8")).match(/packages:\s*\n((?:\s*-\s*.+\n?)+)/);return g?g[1].split(`
9
- `).map(c=>c.replace(/^\s*-\s*['"]?|['"]?\s*$/g,"")).filter(Boolean):[]}if(t==="npm"||t==="lerna"){let a=l.join(e,"package.json"),g=JSON.parse(await w.readFile(a,"utf-8")),c=Array.isArray(g.workspaces)?g.workspaces:g.workspaces?.packages??[];if(t==="lerna"){let d=l.join(e,"lerna.json");if(await u(d)){let p=JSON.parse(await w.readFile(d,"utf-8"));if(p.packages)return p.packages}}return c}if(t==="nx")return["apps/*","libs/*","packages/*"];if(t==="turborepo"){let a=JSON.parse(await w.readFile(l.join(e,"package.json"),"utf-8"));return Array.isArray(a.workspaces)?a.workspaces:[]}return[]})(),s=r.length>0?r:["packages/*","apps/*","libs/*"];for(let a of s){if(a.startsWith("!"))continue;let g=Ct(a,{cwd:e});for(let c of g){let d=l.join(e,c),p=l.join(d,"package.json");if(await u(p))try{let f=JSON.parse(await w.readFile(p,"utf-8")),j=l.join(d,"PRJCT.md");n.push({name:f.name||l.basename(c),path:d,relativePath:c,hasPrjctMd:await u(j)})}catch{}}}}catch{}return n}async function tt(e,t){if(!t.isMonorepo)return null;let n=l.resolve(e);for(let r of t.packages){let s=l.resolve(r.path);if(n.startsWith(s))return r}return null}async function E(e){let t=l.resolve(e),n=l.parse(t).root;return t===n?null:(await R(t)).isMonorepo?t:E(l.dirname(t))}var Ct,et=h(()=>{"use strict";S();Ct=St.globSync;i(R,"detectMonorepo");i(T,"discoverMonorepoPackages");i(tt,"findContainingPackage");i(E,"findMonorepoRoot")});function rt(e,t){let n=typeof e=="string"?new Date(e).getTime():e;return Date.now()-n>t}var nt,it=h(()=>{"use strict";i(rt,"isExpired");nt=class{static{i(this,"TTLCache")}cache=new Map;ttl;maxSize;constructor(t={}){this.ttl=t.ttl??5e3,this.maxSize=t.maxSize??50}isValid(t){let n=this.cache.get(t);return n?Date.now()-n.timestamp<this.ttl:!1}get(t){let n=this.cache.get(t);return n?this.isValid(t)?n.data:(this.cache.delete(t),null):null}set(t,n){this.cache.set(t,{data:n,timestamp:Date.now()}),this.evictOldEntries()}delete(t){this.cache.delete(t)}clear(){this.cache.clear()}has(t){return this.cache.has(t)}get size(){return this.cache.size}evictOldEntries(){if(this.cache.size<=this.maxSize)return;let n=Array.from(this.cache.entries()).sort((r,s)=>r[1].timestamp-s[1].timestamp).slice(0,this.cache.size-this.maxSize);for(let[r]of n)this.cache.delete(r)}stats(){return{size:this.cache.size,maxSize:this.maxSize,ttl:this.ttl}}prune(){let t=[...this.cache.keys()].filter(n=>!this.isValid(n));for(let n of t)this.cache.delete(n);return t.length}}});import kt from"node:fs/promises";import Mt from"node:path";async function st(){try{let e=await kt.readFile(ot(),"utf-8"),t=JSON.parse(e);return!t.timestamp||!t.detection||!t.detection.claude||!t.detection.gemini||!t.detection.codex||rt(t.timestamp,It)?null:t.detection}catch{return null}}async function at(e){let t={timestamp:new Date().toISOString(),detection:e};await W(ot(),t)}var ot,It,ct=h(()=>{"use strict";ut();it();S();ot=i(()=>Mt.join(lt.getCachePath(),"providers.json"),"cacheFile"),It=600*1e3;i(st,"readProviderCache");i(at,"writeProviderCache")});import{execFileSync as G}from"node:child_process";function x(e){for(let t of e.split(/\r?\n/)){let n=t.trim();if(n)return n}return null}function gt(e){if(!e||e.includes("\0"))return null;try{if(process.platform==="win32"){let t=G("where.exe",[e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],windowsHide:!0});return x(t)}try{let t=G("which",[e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return x(t)}catch{let t=G("/bin/sh",["-c",`command -v ${JSON.stringify(e)}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]});return x(t)}}catch{return null}}async function H(e){if(!e||e.includes("\0"))return null;try{if(process.platform==="win32"){let{stdout:t}=await A("where.exe",[e],{encoding:"utf-8",windowsHide:!0});return x(String(t))}try{let{stdout:t}=await A("which",[e]);return x(String(t))}catch{return gt(e)}}catch{return null}}function le(e){return gt(e)!==null}var mt=h(()=>{"use strict";J();i(x,"firstNonEmptyLine");i(gt,"whichSync");i(H,"whichAsync");i(le,"commandOnPath")});var k={};yt(k,{ClaudeProvider:()=>C,CursorProvider:()=>pt,GeminiProvider:()=>_,Providers:()=>v,detectAllProviders:()=>U,detectAntigravity:()=>Tt,detectCodex:()=>ht,detectKimi:()=>Et,detectProvider:()=>$,getActiveProvider:()=>Nt,getProviderBranding:()=>Rt,selectProvider:()=>Gt,validateCliVersion:()=>ft});import O from"node:path";async function L(e){let t=await H(e);return t||(process.platform==="win32"?H(`${e}.cmd`):null)}async function At(e){try{let{stdout:t}=await z(`${e} --version`,{timeout:2e3}),n=t.match(/\d+\.\d+\.\d+/);return n?n[0]:t.trim()}catch{return null}}async function $(e){let t=v[e];if(!t.cliCommand)return{installed:!1};let n=await L(t.cliCommand);if(!n)return{installed:!1};let r=await At(t.cliCommand),s=ft(e,r||void 0);return{installed:!0,version:r||void 0,path:n,versionWarning:s||void 0}}function ft(e,t){let n=v[e];return!n.minCliVersion||!t?null:Q(t,n.minCliVersion)<0?`\u26A0\uFE0F ${n.displayName} v${t} is below minimum v${n.minCliVersion}. Some features may not work correctly.`:null}async function U(e=!1){if(!e){let g=await st();if(g)return g}let[t,n,r]=await Promise.all([$("claude"),$("gemini"),ht()]),s={installed:r.installed},a={claude:t,gemini:n,codex:s};return await at(a).catch(()=>{}),a}async function Nt(e){if(e&&v[e])return v[e];let t=await U(),n=[t.claude.installed?"claude":null,t.gemini.installed?"gemini":null,t.codex.installed?"codex":null].filter(Boolean);return n.length===1?v[n[0]]:t.claude.installed?C:t.gemini.installed?_:t.codex.installed?B:C}function Rt(e){return{commitFooter:"Generated with [p/](https://www.prjct.app/)",signature:{claude:"\u26A1 prjct + Claude",gemini:"\u26A1 prjct + Gemini",cursor:"\u26A1 prjct + Cursor",antigravity:"\u26A1 prjct + Antigravity",codex:"\u26A1 prjct + Codex"}[e]||"\u26A1 prjct"}}async function Tt(){let e=dt.configDir;if(!e)return{installed:!1,skillInstalled:!1};let t=O.join(e,"skills","prjct","SKILL.md"),[n,r]=await Promise.all([u(e),u(t)]);return{installed:n,skillInstalled:r,configPath:n?e:void 0}}async function ht(){let e=B.configDir;if(!e)return{installed:!1,skillInstalled:!1};let t=await L("codex"),n=O.join(e,"skills","prjct","SKILL.md"),r=await u(n),s=!!t||await u(O.join(e,"auth.json"));return{installed:s,skillInstalled:r,configPath:s?e:void 0}}async function Et(){let e=m(".kimi"),[t,n]=await Promise.all([L("kimi"),u(e)]),r=!!t||n;return{installed:r,configPath:r?e:void 0}}async function Gt(){let e=await U();return{provider:e.claude.installed?"claude":e.gemini.installed?"gemini":e.codex.installed?"codex":"claude",detection:e}}var C,_,dt,pt,B,v,M=h(()=>{"use strict";wt();vt();J();S();ct();mt();q();C={name:"claude",displayName:"Claude Code",cliCommand:"claude",get configDir(){return m(".claude")},contextFile:"CLAUDE.md",get skillsDir(){return m(".claude","skills")},commandsDir:".claude/commands",commandFormat:"md",settingsFile:"settings.json",projectSettingsFile:"settings.local.json",ignoreFile:".claudeignore",websiteUrl:"https://www.anthropic.com/claude",docsUrl:"https://docs.anthropic.com/claude-code",get defaultModel(){return D(this.name)},get supportedModels(){return y(this.name)},minCliVersion:"1.0.0"},_={name:"gemini",displayName:"Gemini CLI",cliCommand:"gemini",get configDir(){return m(".gemini")},contextFile:"GEMINI.md",get skillsDir(){return m(".gemini","skills")},commandsDir:".gemini/commands",commandFormat:"toml",settingsFile:"settings.json",projectSettingsFile:"settings.json",ignoreFile:".geminiignore",websiteUrl:"https://geminicli.com",docsUrl:"https://geminicli.com/docs",get defaultModel(){return D(this.name)},get supportedModels(){return y(this.name)},minCliVersion:"1.0.0"},dt={name:"antigravity",displayName:"Google Antigravity",cliCommand:null,get configDir(){return m(".gemini","antigravity")},contextFile:"ANTIGRAVITY.md",get skillsDir(){return m(".gemini","antigravity","global_skills")},commandsDir:".agent/skills",commandFormat:"md",settingsFile:"mcp_config.json",projectSettingsFile:null,ignoreFile:".agentignore",websiteUrl:"https://gemini.google.com/app/antigravity",docsUrl:"https://gemini.google.com/app/antigravity",get defaultModel(){return D(this.name)},get supportedModels(){return y(this.name)},minCliVersion:null},pt={name:"cursor",displayName:"Cursor IDE",cliCommand:null,configDir:null,contextFile:"prjct.mdc",skillsDir:null,commandsDir:".cursor/commands",rulesDir:".cursor/rules",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".cursorignore",isProjectLevel:!0,websiteUrl:"https://cursor.com",docsUrl:"https://cursor.com/docs",get defaultModel(){return D(this.name)},get supportedModels(){return y(this.name)},minCliVersion:null},B={name:"codex",displayName:"OpenAI Codex",cliCommand:"codex",get configDir(){return m(".codex")},contextFile:"AGENTS.md",get skillsDir(){return m(".codex","skills")},commandsDir:".agents/skills",commandFormat:"md",settingsFile:null,projectSettingsFile:null,ignoreFile:".codexignore",websiteUrl:"https://openai.com/codex",docsUrl:"https://github.com/openai/codex",get defaultModel(){return D(this.name)},get supportedModels(){return y(this.name)},minCliVersion:null},v={claude:C,gemini:_,cursor:pt,antigravity:dt,codex:B};i(L,"whichCommand");i(At,"getCliVersion");i($,"detectProvider");i(ft,"validateCliVersion");i(U,"detectAllProviders");i(Nt,"getActiveProvider");i(Rt,"getProviderBranding");i(Tt,"detectAntigravity");i(ht,"detectCodex");i(Et,"detectKimi");i(Gt,"selectProvider")});import Ht from"node:crypto";import I from"node:fs/promises";import o from"node:path";var V,Ot,lt,ut=h(()=>{Z();S();Dt();et();q();V=class{static{i(this,"PathManager")}globalBaseDir;globalConfigDir;constructor(){this.globalBaseDir=K(),this.globalConfigDir=o.join(this.globalBaseDir,"config")}get globalProjectsDir(){let t=process.env.PRJCT_PROJECTS_DIR;return t?o.resolve(t):o.join(this.globalBaseDir,"projects")}setGlobalBaseDir(t){this.globalBaseDir=o.resolve(t),this.globalConfigDir=o.join(this.globalBaseDir,"config")}generateProjectId(t){return Ht.randomUUID()}getGlobalBasePath(){return this.globalBaseDir}getGlobalProjectPath(t){return o.join(this.globalProjectsDir,t)}getLocalConfigPath(t){return o.join(t,".prjct","prjct.config.json")}getGlobalProjectConfigPath(t){return o.join(this.getGlobalProjectPath(t),"project.json")}getLegacyPrjctPath(t){return o.join(t,".prjct")}async hasLegacyStructure(t){return await N(this.getLegacyPrjctPath(t))}async hasConfig(t){return await u(this.getLocalConfigPath(t))}async ensureGlobalStructure(){await P(this.globalBaseDir),await P(this.globalProjectsDir),await P(this.globalConfigDir)}async ensureProjectStructure(t){await this.ensureGlobalStructure();let n=this.getGlobalProjectPath(t),r=["analysis","memory"];for(let s of r)await P(o.join(n,s));return await P(o.join(n,"sessions")),n}getSessionPath(t,n=new Date){let{year:r,month:s,day:a}=X(n);return o.join(this.getGlobalProjectPath(t),"sessions",r,s,a)}getCurrentSessionPath(t){return this.getSessionPath(t,new Date)}async ensureSessionPath(t,n=new Date){let r=this.getSessionPath(t,n);return await P(r),r}async listSessions(t,n=null,r=null){let s=o.join(this.getGlobalProjectPath(t),"sessions"),a=[];try{let g=await I.readdir(s,{withFileTypes:!0});for(let c of g){if(!c.isDirectory()||n&&c.name!==n.toString())continue;let d=o.join(s,c.name),p=await I.readdir(d,{withFileTypes:!0});for(let f of p){if(!f.isDirectory()||r&&f.name!==r.toString().padStart(2,"0"))continue;let j=o.join(d,f.name),Pt=await I.readdir(j,{withFileTypes:!0});for(let b of Pt)b.isDirectory()&&a.push({year:c.name,month:f.name,day:b.name,path:o.join(j,b.name),date:new Date(`${c.name}-${f.name}-${b.name}`)})}}return a.sort((c,d)=>d.date.getTime()-c.date.getTime()),a}catch{return[]}}async getSessionsInRange(t,n,r=new Date){return(await this.listSessions(t)).filter(a=>a.date>=n&&a.date<=r)}getFilePath(t,n,r){return o.join(this.getGlobalProjectPath(t),n,r)}async listProjects(){try{return await this.ensureGlobalStructure(),(await I.readdir(this.globalProjectsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name)}catch{return[]}}async projectExists(t){return await N(this.getGlobalProjectPath(t))}getDisplayPath(t){let n=Y();return t.startsWith(n)?t.replace(n,"~"):t}getAuthConfigPath(){return o.join(this.globalConfigDir,"auth.json")}getSyncPendingPath(t){return o.join(this.getGlobalProjectPath(t),"sync","pending.json")}getLastSyncPath(t){return o.join(this.getGlobalProjectPath(t),"sync","last-sync.json")}getRunningStatusPath(){return o.join(this.globalBaseDir,".running")}getCachePath(){return o.join(this.globalBaseDir,"cache")}getStatePath(){return o.join(this.globalBaseDir,"state")}getStatusLinePath(){return o.join(this.globalBaseDir,"statusline")}async getAgentDir(){return(await(M(),F(k)).getActiveProvider()).configDir}async getAgentSettingsPath(){let t=await(M(),F(k)).getActiveProvider();return(M(),F(k)).getGlobalSettingsPath(t.name)}getClaudeDir(){return m(".claude")}getClaudeSettingsPath(){return o.join(this.getClaudeDir(),"settings.json")}getStoragePath(t,n){return o.join(this.getGlobalProjectPath(t),"storage",n)}getContextPath(t){return o.join(this.getGlobalProjectPath(t),"context")}async detectMonorepo(t){return R(t)}async discoverMonorepoPackages(t,n){return T(t,n)}async findContainingPackage(t,n){return tt(t,n)}async findMonorepoRoot(t){return E(t)}},Ot=new V,lt=Ot});export{$t as a,_t as b,xt as c,Bt as d,Lt as e,Ut as f,Vt as g,Z as h,rt as i,nt as j,it as k,H as l,le as m,mt as n,v as o,Nt as p,Rt as q,ht as r,Et as s,k as t,M as u,lt as v,ut as w};
@@ -1,18 +0,0 @@
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 K}from"./chunk-HRWXMF7P.mjs";import{a as X}from"./chunk-ZJXH76Q5.mjs";import{a as q,j as H}from"./chunk-PUHX3ECX.mjs";import{a as J}from"./chunk-Q3EYM4GJ.mjs";import{e as Y}from"./chunk-AZYQFRPJ.mjs";import{c as P}from"./chunk-QPRNRLG6.mjs";import{d as M,e as I}from"./chunk-7JEKBJAP.mjs";import{a as x}from"./chunk-27XFSCOE.mjs";import{h as j}from"./chunk-DRGI5UHQ.mjs";import{b as E}from"./chunk-AZHE4VOM.mjs";import{d as f,g as G}from"./chunk-KG7Z6OMK.mjs";import{b,g as A,h as ct,i as W,k as ut,v as B,w as mt}from"./chunk-JAMSIKDE.mjs";import{d as lt}from"./chunk-JQE2F2RK.mjs";import{e as k,p as ot}from"./chunk-QWQFF2UG.mjs";import{b as _,e as dt}from"./chunk-EMTCZG5I.mjs";import{e as U,f as at}from"./chunk-BUDZL4DW.mjs";import{a as l}from"./chunk-E66B27AL.mjs";mt();import L from"node:fs";import pt from"node:path";var V=l(()=>B.getStatePath(),"stampDir"),z=l(()=>pt.join(V(),"installed-version"),"stampPath");function ft(){try{return L.readFileSync(z(),"utf-8").trim()}catch{return null}}l(ft,"readStamp");function ht(i){try{L.mkdirSync(V(),{recursive:!0}),L.writeFileSync(z(),i,"utf-8")}catch{}}l(ht,"writeStamp");function Q(i){return i?ft()===i:!0}l(Q,"isSyncCurrent");async function Z(i){if(i&&process.env.PRJCT_NO_SELF_SYNC!=="1"){try{let{installGlobalConfig:e}=await import("./command-installer-MF4KUM3X.mjs");await e()}catch{}try{await(await import("./settings-installer-QDM3GB6J.mjs")).install()}catch{}try{let{SetupCommands:e}=await import("./setup-WQRJ6TQL.mjs");await new e().installStatusLine()}catch{}ht(i)}}l(Z,"runSelfHeal");G();at();ot();lt();G();ut();ct();var gt=50,N=class{static{l(this,"SessionTracker")}currentRow(e){try{return f.get(e,"SELECT * FROM cli_sessions WHERE status = 'active' ORDER BY last_activity DESC LIMIT 1")??null}catch{return null}}isExpired(e){return W(e,18e5)}toSessionData(e,t){return{id:t.id,projectId:e,status:t.status,createdAt:t.created_at,lastActivity:t.last_activity,commands:[],files:[]}}async touch(e){let t=b(),n=this.currentRow(e);if(n&&!this.isExpired(n.last_activity))return f.run(e,"UPDATE cli_sessions SET last_activity = ? WHERE id = ?",t,n.id),this.toSessionData(e,{...n,last_activity:t});n&&f.run(e,"UPDATE cli_sessions SET status = 'expired' WHERE id = ?",n.id);let s=crypto.randomUUID();return f.run(e,"INSERT INTO cli_sessions (id, status, created_at, last_activity) VALUES (?, 'active', ?, ?)",s,t,t),this.toSessionData(e,{id:s,status:"active",created_at:t,last_activity:t})}async trackCommand(e,t,n){let s=this.currentRow(e);if(!s)return;let o=b();try{f.run(e,"INSERT INTO cli_session_commands (session_id, command, timestamp, duration_ms) VALUES (?, ?, ?, ?)",s.id,t,o,Math.round(n)),f.run(e,"UPDATE cli_sessions SET last_activity = ? WHERE id = ?",o,s.id)}catch{}}async getInfo(e){let t=this.currentRow(e);if(!t||this.isExpired(t.last_activity))return{active:!1,id:null,duration:null,idleSince:null,idleMs:0,expiresIn:null,commandCount:0,commands:[],filesRead:0,filesWritten:0};let n=Date.now(),s=new Date(t.created_at).getTime(),o=new Date(t.last_activity).getTime(),c=n-o,a=Math.max(0,18e5-c),r=f.query(e,"SELECT command FROM cli_session_commands WHERE session_id = ? ORDER BY timestamp DESC LIMIT ?",t.id,gt);return{active:!0,id:t.id,duration:A(n-s),idleSince:t.last_activity,idleMs:c,expiresIn:A(a),commandCount:r.length,commands:r.map(m=>m.command).reverse(),filesRead:0,filesWritten:0}}async expire(e){try{f.run(e,"UPDATE cli_sessions SET status = 'expired' WHERE status = 'active'")}catch{}}async expireIfStale(e){let t=this.currentRow(e);return t&&this.isExpired(t.last_activity)?(f.run(e,"UPDATE cli_sessions SET status = 'expired' WHERE id = ?",t.id),!0):!1}},et=new N;var yt={commitThreshold:10,dayThreshold:3,significantFiles:["package.json","tsconfig.json","Cargo.toml","go.mod","requirements.txt","pyproject.toml",".env.example","docker-compose.yml","Dockerfile"]},F=class{static{l(this,"StalenessChecker")}projectPath;config;constructor(e,t={}){this.projectPath=e,this.config={...yt,...t}}async check(e){let t={isStale:!1,reason:null,lastSyncCommit:null,currentCommit:null,commitsSinceSync:0,daysSinceSync:0,changedFiles:[],significantChanges:[]};try{let n=(()=>{try{return f.getDoc(e,"project")}catch{return null}})();if(!n)return t.isStale=!0,t.reason="No sync history found. Run `prjct sync` to initialize.",t;t.lastSyncCommit=n.lastSyncCommit||null;let s=n.lastSync;if(!t.lastSyncCommit)return t.isStale=!0,t.reason="No sync commit recorded. Run `prjct sync` to track.",t;let c={cwd:this.projectPath,timeoutMs:3e3,maxBuffer:1024*256},a=`${t.lastSyncCommit}..HEAD`,[r,m]=await Promise.all([k(["rev-parse","--short","HEAD"],c),k(["rev-list","--count",a],c)]);if(!r.ok)return t.reason=r.kind==="exit"?"Not a git repository":`git ${r.kind} \u2014 staleness unknown`,t;if(t.currentCommit=r.stdout.trim(),t.lastSyncCommit===t.currentCommit)return t.reason="Context is up to date",t;if(!m.ok)return m.kind==="exit"?(t.isStale=!0,t.reason="Sync commit no longer exists (history changed). Run `prjct sync`."):t.reason=`git ${m.kind} reading history \u2014 staleness unknown. Retry shortly.`,t;if(t.commitsSinceSync=parseInt(m.stdout.trim(),10)||0,s){let y=new Date(s),g=new Date;t.daysSinceSync=Math.floor((g.getTime()-y.getTime())/(1e3*60*60*24))}if(t.commitsSinceSync>0&&t.commitsSinceSync<this.config.commitThreshold){let y=await k(["diff","--name-only",a],c),g=y.ok?y.stdout.trim().split(`
9
- `).filter(Boolean).slice(0,200):[];t.changedFiles=g,t.significantChanges=g.filter(d=>this.config.significantFiles.some(p=>d.endsWith(p)||d.includes(p)))}else t.changedFiles=[],t.significantChanges=[];return t.commitsSinceSync>=this.config.commitThreshold?(t.isStale=!0,t.reason=`${t.commitsSinceSync} commits since last sync (threshold: ${this.config.commitThreshold})`):t.daysSinceSync>=this.config.dayThreshold?(t.isStale=!0,t.reason=`${t.daysSinceSync} days since last sync (threshold: ${this.config.dayThreshold})`):t.significantChanges.length>0?(t.isStale=!0,t.reason=`Significant files changed: ${t.significantChanges.join(", ")}`):t.commitsSinceSync>0?t.reason=`${t.commitsSinceSync} commits since sync (threshold: ${this.config.commitThreshold})`:t.reason="Context is up to date",t}catch(n){return t.reason=`Error checking staleness: ${U(n)}`,t}}formatStatus(e){let t=[];e.isStale?t.push("CLAUDE.md status: \u26A0\uFE0F STALE"):t.push("CLAUDE.md status: \u2713 Fresh");let n=[];if(e.lastSyncCommit&&n.push(`Last sync: ${e.lastSyncCommit}`),e.currentCommit&&n.push(`Current: ${e.currentCommit}`),e.commitsSinceSync>0&&n.push(`Commits since: ${e.commitsSinceSync}`),e.daysSinceSync>0&&n.push(`Days since: ${e.daysSinceSync}`),e.changedFiles.length>0&&n.push(`Files changed: ${e.changedFiles.length}`),n.length>0&&t.push(...nt(n)),e.significantChanges.length>0){t.push(""),t.push("Significant changes:");for(let s of e.significantChanges.slice(0,5))t.push(` \u2022 ${s}`);e.significantChanges.length>5&&t.push(` ... and ${e.significantChanges.length-5} more`)}return e.reason&&(t.push(""),t.push(e.reason)),e.isStale&&(t.push(""),t.push("Run `prjct sync` to update context")),t.join(`
10
- `)}async getSessionInfo(e){return et.getInfo(e)}formatSessionInfo(e){let t=[];if(!e.active)return t.push("Session: \u25CB No active session"),t.join(`
11
- `);t.push(`Session: \u25B6 Active (${e.duration})`);let n=[];if(e.commandCount>0){let s=new Set,o=[];for(let c of e.commands)s.has(c)||(s.add(c),o.push(c));n.push(`Commands: ${o.join(" \u2192 ")} (${e.commandCount} total)`)}return(e.filesRead>0||e.filesWritten>0)&&n.push(`Files: ${e.filesRead} read, ${e.filesWritten} written`),n.push(`Idle: ${e.expiresIn} until timeout`),n.length>0&&t.push(...nt(n)),t.join(`
12
- `)}getWarning(e){return e.isStale?e.commitsSinceSync>0?`\u26A0\uFE0F Context stale (${e.commitsSinceSync} commits behind). Run \`prjct sync\``:e.daysSinceSync>0?`\u26A0\uFE0F Context stale (${e.daysSinceSync} days old). Run \`prjct sync\``:"\u26A0\uFE0F Context may be stale. Run `prjct sync`":null}};function nt(i){let e=Math.max(...i.map(n=>n.length)),t="\u2500".repeat(e+2);return[`\u250C${t}\u2510`,...i.map(n=>`\u2502 ${n.padEnd(e)} \u2502`),`\u2514${t}\u2518`]}l(nt,"boxLines");var st=l((i,e)=>new F(i,e),"createStalenessChecker");dt();var St=1600,R=3,Ct=4,O={minTeaser:24,maxTeaser:90};async function wt(i,e,t={}){let n=e??await E.readConfig(i);if(!n?.projectId)return null;let s=n.persona,o=t.digest?await(async()=>{try{let{memoryL0IndexForSession:h}=await import("./memory-index-QK5QJOFJ.mjs");return h(n.projectId,{rebuildIfStale:!0})||it(n.projectId)}catch{return it(n.projectId)}})():null,c=vt(i,n.projectId),a=import("./vault-retire-notice-HT756AND.mjs").then(({vaultRetirementNotice:h})=>h(n,n.projectId)),r=(async()=>{try{let{buildLandCue:h}=await import("./land-cue-MMISX2BI.mjs");return await h(n.projectId,i,n)}catch{return null}})(),m=(async()=>{try{let{effectiveWeakModelMode:h,weakModelBanner:C}=await import("./weak-model-mode-FLCEQ2BV.mjs");return h(n)==="on"?C():null}catch{return null}})(),w=t.digest?(async()=>{try{let{formatPendingHandoffCue:h}=await import("./agent-switch-2U2LOBGR.mjs"),C=h(n.projectId);return C?`# prjct: pending handoff
13
- ${C}`:null}catch{return null}})():Promise.resolve(null),y=t.digest?(async()=>{try{let{loadSessionContinuity:h,formatContinuitySessionCue:C}=await import("./session-continuity-RKNAJJHR.mjs");return C(h(n.projectId))}catch{return null}})():Promise.resolve(null),g=Tt(i,n.projectId),[d,p,S,v,T,$,D]=await Promise.all([c,a,r,m,w,y,g]);if(!D&&!s&&!o&&!d&&!p&&!S&&!v&&!T&&!$)return null;let u=["# prjct: project context",""];return D&&u.push(D,""),s&&u.push(xt(s),"","> Exposed as state, not prescription. Decide whether any of this matters for the current turn."),o&&(s&&u.push(""),u.push(o)),d&&((s||o)&&u.push(""),u.push(d)),p&&((s||o||d)&&u.push(""),u.push(p)),S&&((s||o||d||p)&&u.push(""),u.push(S)),v&&((s||o||d||p||S)&&u.push(""),u.push(v)),T&&((s||o||d||p||S||v)&&u.push(""),u.push(T)),$&&((s||o||d||p||S||v||T)&&u.push(""),u.push($)),u.join(`
14
- `)}l(wt,"buildSessionContext");async function vt(i,e){try{let t=st(i),n=await t.check(e);if(!n.isStale||n.commitsSinceSync<=0)return null;let s=t.getWarning(n);if(!s)return null;try{let c=await import("node:path"),a=await import("node:os"),{maybeDetachDriftRefresh:r,readDriftStamp:m,formatDriftNotice:w,driftStaleResolved:y}=await import("./drift-refresh-TD3PYPJN.mjs"),g=process.env.PRJCT_CLI_HOME?c.resolve(process.env.PRJCT_CLI_HOME):c.join(a.homedir(),".prjct-cli"),d=m(g);if(y(d))return w({warning:s,commitsSinceSync:n.commitsSinceSync,stamp:d,refreshScheduled:!1});let p=r({projectPath:i,cliHome:g,commitsSinceSync:n.commitsSinceSync}),S=m(g);return w({warning:s,commitsSinceSync:n.commitsSinceSync,stamp:S,refreshScheduled:p})}catch{}let o=await(async()=>{try{let{hasSymbolIndex:c,loadMeta:a}=await import("./symbol-graph-BKQIMFRG.mjs");if(!c(e))return" Code graph empty \u2014 `prjct code reindex` (or `prjct sync`) before trace/impact.";if(n.commitsSinceSync<5)return"";let r=a(e);return` Symbol index may lag${r?.builtAt?` (index ${r.builtAt.slice(0,10)})`:""} \u2014 prefer \`prjct code reindex\` after big pulls.`}catch{return""}})();return`**Understanding may be stale:** ${s} \u2014 run \`prjct sync\` before big calls.${o}`}catch{return null}}l(vt,"buildStalenessNotice");function it(i){let e=(()=>{try{let r=P.rerank(i,x.recall(i,{types:["gotcha","anti-pattern"],limit:R*4})).slice(0,R),m=P.rerank(i,x.recall(i,{types:["decision"],limit:R*4})).slice(0,R);return{gotchas:r,decisions:m}}catch{return null}})();if(!e)return null;let{gotchas:t,decisions:n}=e,s=(()=>{try{let r=x.recall(i,{types:["feedback","improvement-signal"],limit:40,dedupeByKey:!1});return q(r,Ct)}catch{return[]}})(),o=H(i,new Set([...t,...n].map(r=>r.id))),c=(()=>{try{let r=J(i);return r?Y(r,{maxConventions:4,maxPatterns:3,maxAnti:2}):null}catch{return null}})();if(t.length===0&&n.length===0&&!o&&s.length===0&&!c)return null;let a=["## What this project already knows",""];if(a.push("> Carried across sessions and model updates \u2014 this survived even if your conversation context did not. Apply these; do not re-derive from source."),s.length>0){a.push("","**How this developer works (act as them):**");for(let r of s){let m=r.rule.length>140?`${r.rule.slice(0,139)}\u2026`:r.rule;a.push(`- ${m} \`${r.sourceId}\``)}}if(c){let r=c.replace(/^## How this repo works \(project style\)\n?/,"").trim();r&&a.push("","**How this repo works (match house style):**",r)}if(t.length>0){a.push("","**Traps to avoid:**");for(let r of t)a.push(`- ${I(r,O)}`)}if(n.length>0){a.push("","**Decisions in force:**");for(let r of n)a.push(`- ${I(r,O)}`)}return o&&a.push("","**Keeps being missed:**",`- ${I(o.entry,O)} \u2014 flagged relevant-but-unused ${o.count}\xD7. Apply it or supersede it.`),a.push("","> Resolve any `mem_id` with `prjct search <id>`. Full developer model: MCP `prjct_developer`. Project style: `prjct analysis` / sync evolution."),j(a.join(`
15
- `),St)}l(it,"buildKnowledgeDigest");var Et=500,rt=2;async function ne(i){let e=await E.readConfig(i).catch(()=>null);if(!e?.projectId)return null;let t=["# prjct: subagent context"];e.persona?.role&&t.push(`Role in this project: ${e.persona.role}`);try{let{resolveActiveTask:n}=await import("./task-service-XREJLWEF.mjs"),s=await n(e.projectId,i);s&&t.push(`Active work cycle (this worktree): ${s.description}`)}catch{}try{let n=P.rerank(e.projectId,x.recall(e.projectId,{types:["gotcha","anti-pattern"],limit:rt*4})).slice(0,rt);if(n.length>0){t.push("Traps to avoid:");for(let o of n)t.push(`- ${M(o)} \`${o.id}\``)}let s=H(e.projectId,new Set(n.map(o=>o.id)));s&&t.push(`Keeps being missed: ${M(s.entry)} \`${s.entry.id}\``)}catch{}return t.length<=1?null:j(t.join(`
16
- `),Et)}l(ne,"buildSubagentDigest");function xt(i){let e=[];return e.push(`## Your role in this project: **${i.role}**`),i.focus&&e.push(`Focus: ${i.focus}`),i.mcps&&i.mcps.length>0&&e.push(`Available MCPs this project expects: ${i.mcps.join(", ")}`),i.packs&&i.packs.length>0&&e.push(`Active packs: ${i.packs.join(", ")}`),e.join(`
17
- `)}l(xt,"formatPersona");async function Tt(i,e){try{let t=await import("node:path"),{execFileAsync:n}=await import("./exec-2P5VOBHM.mjs"),s=t.basename(i),o=await(async()=>{try{let{stdout:r}=await n("git",["branch","--show-current"],{cwd:i});return r.trim()}catch{return""}})(),c=e.length>12?`${e.slice(0,8)}\u2026`:e,a=["## Project identity (cwd)",`- **${s}** \xB7 id \`${c}\``];return o&&a.push(`- Branch: \`${o}\``),a.push("- Skill is portable L0 \u2014 if skill text names another project, ignore it; trust this block + `prjct context --md`."),a.join(`
18
- `)}catch{return null}}l(Tt,"buildProjectIdentityLine");function se(i=process.cwd(),e){let t=E.readConfig(i).catch(()=>null);return X({event:"SessionStart",projectPath:i,build:l(async(n,s)=>{let o=s===i?await t:await E.readConfig(s).catch(()=>null),c=n.source??"startup";return wt(s,o,{digest:c==="startup"||c==="clear"||c==="compact"})},"build"),afterEmit:l(async(n,s)=>{let o=await t;if(o?.projectId){let c=await(async()=>{try{let{collectActiveTasks:a}=await import("./task-overview-ITY5OSHX.mjs"),r=await a(o.projectId,s);return{taskId:r.current?.id??null,goal:r.current?.description??n.source??null}}catch{return{taskId:null,goal:n.source??null}}})();K({projectId:o.projectId,sessionId:n.session_id,directory:s,taskId:c.taskId,goal:c.goal})}Q(_)||await Z(_).catch(()=>{});try{let{maybeAutoUpdate:c}=await import("./auto-updater-4TIXYSEX.mjs");c(_)}catch{}},"afterEmit")},e)}l(se,"runSessionStartHook");export{wt as a,ne as b,Tt as c,se as d};
@@ -1,19 +0,0 @@
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 d}from"./chunk-27XFSCOE.mjs";import{c as l}from"./chunk-5EQLQ7GF.mjs";import{e as a,g as p}from"./chunk-KG7Z6OMK.mjs";import{a as m}from"./chunk-E66B27AL.mjs";p();var E=7,T=90,f=20,A=["pattern-detector","transcript-auto","skill-miss","friction","land-auto","sync-context-quality"];function h(e){return e?A.some(t=>e===t||e.startsWith(`${t}-`)||e.startsWith(t)):!1}m(h,"isAutoSource");function L(e,t=E,o=500){let u=Date.now()-t*864e5;try{let n=a.query(e,`SELECT id FROM memory_entries
9
- WHERE deleted_at IS NOT NULL AND deleted_at < ?
10
- ORDER BY deleted_at ASC
11
- LIMIT ?`,u,o);return n.length===0?0:(a.transaction(e,s=>{let i=s.prepare("DELETE FROM memory_embeddings WHERE memory_id = ?"),r=s.prepare("DELETE FROM memory_entries WHERE id = ?");for(let c of n){try{i.run(c.id)}catch{}r.run(c.id)}}),n.length)}catch{return 0}}m(L,"purgeSoftDeleted");function O(e,t=E,o=500){let u=new Date(Date.now()-t*864e5).toISOString();try{let n=a.query(e,`SELECT e.id FROM events e
12
- WHERE e.type LIKE 'memory.remember.%'
13
- AND e.timestamp < ?
14
- AND NOT EXISTS (
15
- SELECT 1 FROM memory_entries m
16
- WHERE m.id = 'mem_' || e.id AND m.deleted_at IS NULL
17
- )
18
- ORDER BY e.id ASC
19
- LIMIT ?`,u,o);return n.length===0?0:(a.transaction(e,s=>{let i=s.prepare("DELETE FROM events WHERE id = ?");for(let r of n)i.run(r.id)}),n.length)}catch{return 0}}m(O,"purgeOrphanRememberEvents");function g(e,t=f){if(t<=0)return 0;let o=[];try{let u=d.allEntriesForIndex(e),n=new Map;for(let s of u){let i=s.tags?.source;if(!h(i))continue;let r=i,c=n.get(r)??[];c.push(s),n.set(r,c)}for(let[,s]of n){if(s.length<=t)continue;s.sort((r,c)=>r.rememberedAt.localeCompare(c.rememberedAt));let i=s.slice(0,s.length-t);for(let r of i){try{l.archive(e,{entityType:"memory_entry",entityId:r.id,entityData:{id:r.id,type:r.type,content:r.content,tags:r.tags,rememberedAt:r.rememberedAt},summary:r.content.slice(0,80),reason:`auto-source-cap (>${t})`})}catch{}d.forget(e,r.id)&&o.push(r)}}}catch{return o.length}return o.length}m(g,"trimAutoSourceCap");function F(e){let t=a.get(e,"SELECT COUNT(*) AS c FROM memory_entries WHERE deleted_at IS NULL")?.c??0,o=a.get(e,"SELECT COUNT(*) AS c FROM memory_entries WHERE deleted_at IS NOT NULL")?.c??0,u=a.get(e,"SELECT COUNT(*) AS c FROM archives")?.c??0,n=a.get(e,"SELECT COUNT(*) AS c FROM events WHERE type LIKE 'memory.remember.%'")?.c??0,s=(()=>{try{return d.allEntriesForIndex(e).filter(i=>h(i.tags?.source)).length}catch{return 0}})();return{live:t,softDeleted:o,archives:u,rememberEvents:n,autoSourceLive:s}}m(F,"vaultHealth");async function N(e,t={}){let o=t.softDeletedPurgeDays??E,u=t.archivePruneDays??T,n=t.autoSourceMaxLive??f;if(t.dryRun===!0)return{softDeletedPurged:0,orphanEventsPurged:0,archivesPruned:0,autoSourceTrimmed:0,distilledDiscarded:0,digestsWritten:0};let i=await(async()=>{if(t.projectPath)try{let{distillAndDiscardAllAutoSources:_}=await import("./distill-U2LJGUG3.mjs"),y=await _(t.projectPath,e,n);return{distilledDiscarded:y.discarded,digestsWritten:y.digests}}catch{return g(e,n),{distilledDiscarded:0,digestsWritten:0}}else return g(e,n),{distilledDiscarded:0,digestsWritten:0}})(),{distilledDiscarded:r,digestsWritten:c}=i,{eliminateSoftDeletedNoValue:D}=await import("./distill-U2LJGUG3.mjs"),b=D(e,o).purged||L(e,o),S=O(e,o),R=(()=>{try{return l.pruneOldArchives(e,u)}catch{return 0}})();return{softDeletedPurged:b,orphanEventsPurged:S,archivesPruned:R,autoSourceTrimmed:r,distilledDiscarded:r,digestsWritten:c}}m(N,"runVaultPurge");export{E as a,T as b,f as c,A as d,h as e,L as f,O as g,g as h,F as i,N as j};
@@ -1,9 +0,0 @@
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 l(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(l,"identifyTranscriptModel");function I(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(I,"parseTranscriptJsonl");function c(n){return n&&typeof n=="object"?n:null}a(c,"asRecord");function p(n){return typeof n=="number"&&Number.isFinite(n)?n:0}a(p,"num");function d(n){let e=p(n.input_tokens)+p(n.cache_creation_input_tokens)+p(n.prompt_tokens)+p(n.promptTokenCount),t=p(n.output_tokens)+p(n.completion_tokens)+p(n.candidatesTokenCount),o=p(n.cache_read_input_tokens);return{tokensIn:e,tokensOut:t,cacheRead:o}}a(d,"usagePairFrom");function f(n,e){if(!e?.sinceIso&&!e?.untilIso)return!0;let t=typeof n.timestamp=="string"?Date.parse(n.timestamp):Number.NaN;return!(!Number.isFinite(t)||e.sinceIso&&t<Date.parse(e.sinceIso)||e.untilIso&&t>=Date.parse(e.untilIso))}a(f,"inWindow");function g(n,e){let t=n.reduce((u,m)=>{if(!f(m,e))return u;let k=c(c(m.message)?.usage)??c(m.usage)??c(m.usageMetadata);if(!k)return u;let i=d(k);return{tokensInNew:u.tokensInNew+i.tokensIn,tokensOut:u.tokensOut+i.tokensOut,maxCacheRead:Math.max(u.maxCacheRead,i.cacheRead)}},{tokensInNew:0,tokensOut:0,maxCacheRead:0}),{tokensInNew:o,tokensOut:s,maxCacheRead:r}=t;return{tokensInNew:o,cacheReadMax:r,tokensIn:o+r,tokensOut:s}}a(g,"sumTranscriptUsageDetailed");function x(n,e){let t=g(n,e);return{tokensIn:t.tokensIn,tokensOut:t.tokensOut}}a(x,"sumTranscriptUsage");function T(n,e){let t=new Map;for(let s of n){if(!f(s,e))continue;let r=c(s.message),u=c(r?.usage)??c(s.usage)??c(s.usageMetadata);if(!u)continue;let m=typeof r?.model=="string"&&r.model?r.model:"unknown",k=d(u),i=t.get(m)??{tokensIn:0,tokensOut:0,maxCacheRead:0};i.tokensIn+=k.tokensIn,i.tokensOut+=k.tokensOut,k.cacheRead>i.maxCacheRead&&(i.maxCacheRead=k.cacheRead),t.set(m,i)}let o=new Map;for(let[s,r]of t)o.set(s,{tokensIn:r.tokensIn+r.maxCacheRead,tokensOut:r.tokensOut});return o}a(T,"sumTranscriptUsageByModel");export{l as a,I as b,g as c,x as d,T as e};
@@ -1,9 +0,0 @@
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 i,b as g,c,d as p,e as m,f as u,i as l}from"./chunk-NBKEOLDH.mjs";import{r as d,s as f,u as M}from"./chunk-JAMSIKDE.mjs";import{b as s,c as j}from"./chunk-JQE2F2RK.mjs";import{e as n,f as y}from"./chunk-BUDZL4DW.mjs";import{a as r}from"./chunk-E66B27AL.mjs";M();y();j();function v(){return process.env.PRJCT_TEST_MODE==="1"?s(".prjct-tests","kimi","mcp.json"):s(".kimi","mcp.json")}r(v,"getKimiMcpConfigPath");async function C(t=v()){let e=await c("context7",i.context7,t),o=await c("prjct",i.prjct,t);return{path:t,changed:e.changed||o.changed}}r(C,"ensureKimiMcpServer");var h=[{name:"prjct",ready:"\u2705 prjct MCP already configured",added:"\u2705 prjct MCP added to mcp.json",failed:"prjct MCP setup failed",manual:" Run `prjct start` again to retry."}];async function b(t={}){t.silent||console.log(`
9
- \u{1F50C} Configuring MCP servers...`);try{await l.install();let e=t.verifyContext7===!1?null:await l.verify();t.silent||(e?.verified?console.log("\u2705 Context7 MCP ready (framework API lookups)"):(console.log(`\u26A0\uFE0F Context7 configured but not yet verified: ${e?.message||""}`),console.log(" It will activate on the next time you open your AI client.")))}catch(e){t.silent||(console.log(`\u26A0\uFE0F Context7 MCP setup failed: ${n(e)}`),console.log(" Run `prjct start` again to retry."))}for(let e of h)try{let o=g(),a=await p(e.name,o),x=await c(e.name,i[e.name],o);a&&!x.changed?t.silent||console.log(e.ready):t.silent||console.log(e.added)}catch(o){t.silent||(console.log(`\u26A0\uFE0F ${e.failed}: ${n(o)}`),console.log(e.manual))}try{if((await d()).installed){let o=await m(),a=await u();t.silent||(o.skipped==="user-managed"?console.log("\u2705 prjct Codex config ready (MCP user-managed)"):o.changed||a.changed?console.log("\u2705 prjct Codex config updated in ~/.codex/config.toml"):console.log("\u2705 prjct Codex config already ready"))}}catch(e){t.silent||(console.log(`\u26A0\uFE0F Codex config setup failed: ${n(e)}`),console.log(" Run `prjct start` again to retry."))}try{if((await f()).installed){let o=await C();t.silent||console.log(o.changed?"\u2705 prjct Kimi config updated in ~/.kimi/mcp.json":"\u2705 prjct Kimi config already ready")}}catch(e){t.silent||(console.log(`\u26A0\uFE0F Kimi config setup failed: ${n(e)}`),console.log(" Run `prjct start` again to retry."))}}r(b,"setupMcpServers");export{b as a};
@@ -1,8 +0,0 @@
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 o}from"./chunk-TPESWBA7.mjs";import{a as r}from"./chunk-E66B27AL.mjs";var c=new Set(["claude","codex","gemini","grok","cursor","opencode","pi","antigravity","unknown"]);function p(){let n=process.env.PRJCT_AGENT_RUNTIME?.trim().toLowerCase();return n&&c.has(n)?n:n?n.slice(0,32):process.env.CLAUDE_AGENT||process.env.ANTHROPIC_CLAUDE||process.env.CLAUDECODE?"claude":process.env.CODEX_SANDBOX||process.env.PRJCT_SANDBOX==="1"?"codex":process.env.GEMINI_CLI||process.env.GEMINI_API_KEY?"gemini":process.env.CURSOR_TRACE_ID||process.env.CURSOR_AGENT||process.env.CURSOR_SESSION_ID?"cursor":process.env.GROK_API_KEY||process.env.XAI_API_KEY||process.env.GROK_SESSION?"grok":process.env.OPENCODE||process.env.OPENCODE_SESSION||process.env.OPENCODE_CONFIG?"opencode":process.env.PI_CODING_AGENT_DIR||process.env.PI_SESSION||process.env.PI_AGENT?"pi":"unknown"}r(p,"detectRuntimeAgent");function u(n="session"){let e=p(),s=process.env.CLAUDE_SESSION_ID||process.env.CODEX_SESSION_ID||process.env.PRJCT_SESSION_ID||void 0,t=process.env.PRJCT_AGENT?.trim(),i=t&&t.length>0?t:o(`identity:${e}:${n}`);return{agent:e,identity:i,sessionId:s}}r(u,"resolveCallerIdentity");function d(n){let e=n.trim().toLowerCase();return e==="claude-code"||e==="anthropic"?"claude":e==="openai"||e==="oai"?"codex":e==="google"?"gemini":e==="xai"||e==="grok-build"?"grok":e==="opencode-ai"||e==="open-code"?"opencode":e==="pi-coding-agent"||e==="pi-agent"?"pi":e.slice(0,32)}r(d,"normalizeAgentName");function E(n,e){return n?!!(n.ownerSessionId&&e.sessionId&&n.ownerSessionId===e.sessionId||n.ownerIdentity&&e.identity&&n.ownerIdentity===e.identity):!1}r(E,"sameOwner");export{c as a,p as b,u as c,d,E as e};
@@ -1,36 +0,0 @@
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{b as jt}from"./chunk-Y3J7UUMR.mjs";import{a as St,b as wt,c as kt,d as vt,e as bt}from"./chunk-TXJT3G53.mjs";import{a as ft}from"./chunk-TFCLMTJ5.mjs";import{a as Ke}from"./chunk-66GE3IHX.mjs";import{a as qe}from"./chunk-J6TAD3OZ.mjs";import{a as Ye}from"./chunk-T2FCU3ZS.mjs";import{a as Qe,b as At}from"./chunk-4O4D6DV7.mjs";import{a as gt,b as ht}from"./chunk-JUZ5LNDI.mjs";import{d as yt}from"./chunk-NWIQNII6.mjs";import{a as Pt,b as Ct,c as xt,d as Dt}from"./chunk-LNB2GLYI.mjs";import{a as p}from"./chunk-DYHYDHCW.mjs";import{a as ut}from"./chunk-JR542RI2.mjs";import{b as q,c as st,d as nt}from"./chunk-HHIGNKDO.mjs";import{a as at,b as ot,e as it,f as ct,g as ae,h as lt,i as dt}from"./chunk-7GNWHWOO.mjs";import{a as mt}from"./chunk-VWOIUTAX.mjs";import{i as pt}from"./chunk-NBKEOLDH.mjs";import{a as rt}from"./chunk-GFY4GY3Z.mjs";import{b as Ze,c as et,d as tt}from"./chunk-JMCMTX6U.mjs";import{b as se}from"./chunk-R4ILCXKE.mjs";import{a as Xe}from"./chunk-YUKGWWL7.mjs";import{a as ne,b as I}from"./chunk-6UH244CC.mjs";import{a as Be}from"./chunk-INXNK57E.mjs";import{c as Je}from"./chunk-5EQLQ7GF.mjs";import{b as Ve}from"./chunk-UA4Z5TGG.mjs";import{a as We,b as Ue}from"./chunk-M5E2YOZ4.mjs";import{b as M}from"./chunk-AZHE4VOM.mjs";import{d as b,e as T,g as B}from"./chunk-KG7Z6OMK.mjs";import{d as re}from"./chunk-4SKJWNKE.mjs";import{b as v,h as te,p as He,r as Le,u as Ar,v as J,w as Ge}from"./chunk-JAMSIKDE.mjs";import{b as Ne,f as jr}from"./chunk-HDSS6UB3.mjs";import{d as _e,e as $e,f as Oe,k as N,o as V}from"./chunk-UH4MD3F3.mjs";import{a as Me,p as Dr}from"./chunk-QWQFF2UG.mjs";import{a as ze}from"./chunk-EQ5KNMLG.mjs";import{d as w}from"./chunk-PKDYFXMI.mjs";import{a as R,d as Fe,e as k,f as $}from"./chunk-BUDZL4DW.mjs";import{a as i}from"./chunk-E66B27AL.mjs";function It(r,e){let t=[];H("Languages",r.languages,e.languages,t),H("Frameworks",r.frameworks,e.frameworks,t),(r.packageManager??"")!==(e.packageManager??"")&&t.push({field:"Package manager",type:"changed",before:r.packageManager??"(none)",after:e.packageManager??"(none)"}),(r.sourceDir??"")!==(e.sourceDir??"")&&t.push({field:"Source directory",type:"changed",before:r.sourceDir??"(none)",after:e.sourceDir??"(none)"}),(r.testDir??"")!==(e.testDir??"")&&t.push({field:"Test directory",type:"changed",before:r.testDir??"(none)",after:e.testDir??"(none)"}),H("Config files",r.configFiles,e.configFiles,t),r.fileCount!==e.fileCount&&t.push({field:"File count",type:"changed",before:String(r.fileCount),after:String(e.fileCount)});let s=r.patterns.map(c=>c.name),a=e.patterns.map(c=>c.name);H("Patterns",s,a,t);let o=r.antiPatterns.map(c=>c.issue),n=e.antiPatterns.map(c=>c.issue);return H("Anti-patterns",o,n,t),ut(t,r.commitHash??null,e.commitHash??null)}i(It,"generateAnalysisDiff");function vs(r){if(!r.hasChanges)return`## Analysis Diff
9
-
10
- No changes between runs.`;let e=[];e.push("## Analysis Diff"),(r.beforeCommit||r.afterCommit)&&e.push(`> \`${r.beforeCommit?.substring(0,7)??"(none)"}\` \u2192 \`${r.afterCommit?.substring(0,7)??"(none)"}\``),e.push(""),e.push("| Change | Field | Detail |"),e.push("|--------|-------|--------|");for(let s of r.items){let a=s.type==="added"?"+":s.type==="removed"?"-":"~",o=s.type==="changed"?`${s.before} \u2192 ${s.after}`:s.after??s.before??"";e.push(`| ${a} | ${s.field} | ${o} |`)}e.push("");let t=[];return r.summary.added>0&&t.push(`${r.summary.added} added`),r.summary.removed>0&&t.push(`${r.summary.removed} removed`),r.summary.changed>0&&t.push(`${r.summary.changed} changed`),e.push(`**Summary**: ${t.join(", ")}`),e.join(`
11
- `)}i(vs,"formatAnalysisDiffMd");function bs(r){if(!r.hasChanges)return"No changes between analysis runs.";let e=[];(r.beforeCommit||r.afterCommit)&&(e.push(` ${r.beforeCommit?.substring(0,7)??"(none)"} \u2192 ${r.afterCommit?.substring(0,7)??"(none)"}`),e.push(""));for(let t of r.items)t.type==="added"?e.push(` + ${t.field}: ${t.after}`):t.type==="removed"?e.push(` - ${t.field}: ${t.before}`):e.push(` ~ ${t.field}: ${t.before} \u2192 ${t.after}`);return e.join(`
12
- `)}i(bs,"formatAnalysisDiffText");function H(r,e,t,s){let a=new Set(e),o=new Set(t);for(let n of t)a.has(n)||s.push({field:r,type:"added",after:n});for(let n of e)o.has(n)||s.push({field:r,type:"removed",before:n})}i(H,"diffStringArray");$();V();import oe from"node:fs/promises";import E from"node:path";import{z as f}from"zod";function K(r,e){let t=r.filter(a=>!a.passed).length,s=r.filter(a=>a.passed).length;return{passed:t===0,checks:r,totalMs:Date.now()-e,failedCount:t,passedCount:s}}i(K,"summarizeChecks");jr();var Ir=f.enum(["draft","verified","sealed"]),Et=f.object({severity:f.enum(["low","medium","high"]).optional(),language:f.string().optional(),framework:f.string().optional(),source:f.enum(["baseline","repo","context7","feedback"]).optional(),confidence:f.number().min(0).max(1).optional()}),Er=f.object({name:f.string(),description:f.string(),location:f.string().optional()}).extend(Et.shape),Rr=f.object({issue:f.string(),file:f.string(),suggestion:f.string()}).extend(Et.shape),ie=f.object({projectId:f.string(),languages:f.array(f.string()),frameworks:f.array(f.string()),packageManager:f.string().optional(),sourceDir:f.string().optional(),testDir:f.string().optional(),configFiles:f.array(f.string()),fileCount:f.number(),patterns:f.array(Er),antiPatterns:f.array(Rr),analyzedAt:f.string(),modelMetadata:Ne.optional(),status:Ir.default("draft"),commitHash:f.string().optional(),signature:f.string().optional(),sealedAt:f.string().optional(),verifiedAt:f.string().optional()});var Tr={TypeScript:[".ts",".tsx",".mts",".cts"],JavaScript:[".js",".jsx",".mjs",".cjs"],Python:[".py",".pyw"],Java:[".java"],Go:[".go"],Rust:[".rs"],Ruby:[".rb"],PHP:[".php"],Swift:[".swift"],Kotlin:[".kt",".kts"],"C++":[".cpp",".cc",".cxx",".hpp",".h"],C:[".c",".h"],"C#":[".cs"],Elixir:[".ex",".exs"],Scala:[".scala"]};async function Mr(r,e){let t=Date.now();if(r.frameworks.length===0)return{name:"Framework verification",passed:!0,output:"No frameworks declared (skipped)",durationMs:Date.now()-t};try{let s=E.join(e,"package.json"),a=await oe.readFile(s,"utf-8"),o=JSON.parse(a),n={...o.dependencies,...o.devDependencies},c=[],l=[];for(let d of r.frameworks){let m=d.toLowerCase();Object.keys(n).some(y=>y.toLowerCase().includes(m))?l.push(d):c.push(d)}return c.length===0?{name:"Framework verification",passed:!0,output:`${l.length} framework(s) verified in dependencies`,durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Frameworks not found in dependencies: ${c.join(", ")}`,durationMs:Date.now()-t}}catch(s){return R(s)?{name:"Framework verification",passed:!1,error:"package.json not found (cannot verify frameworks)",durationMs:Date.now()-t}:{name:"Framework verification",passed:!1,error:`Failed to read package.json: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i(Mr,"verifyFrameworks");async function Fr(r,e){let t=Date.now();if(r.languages.length===0)return{name:"Language verification",passed:!0,output:"No languages declared (skipped)",durationMs:Date.now()-t};try{let s=await Nr(e),a=new Set(s),o=[],n=[];for(let c of r.languages){let l=Tr[c];if(!l)continue;l.some(m=>a.has(m))?o.push(c):n.push(c)}return n.length===0?{name:"Language verification",passed:!0,output:`${o.length} language(s) verified with matching files`,durationMs:Date.now()-t}:{name:"Language verification",passed:!1,error:`Languages without matching files: ${n.join(", ")}`,durationMs:Date.now()-t}}catch(s){return{name:"Language verification",passed:!1,error:`Failed to scan project files: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i(Fr,"verifyLanguages");async function _r(r,e){let t=Date.now(),s=r.patterns.filter(n=>n.location);if(s.length===0)return{name:"Pattern location verification",passed:!0,output:"No pattern locations specified (skipped)",durationMs:Date.now()-t};let a=[],o=[];for(let n of s){let c=n.location,l=E.join(e,c);await N(l)?o.push(c):a.push(`${n.name} (${c})`)}return a.length===0?{name:"Pattern location verification",passed:!0,output:`${o.length} pattern location(s) verified`,durationMs:Date.now()-t}:{name:"Pattern location verification",passed:!1,error:`Pattern locations not found: ${a.join(", ")}`,durationMs:Date.now()-t}}i(_r,"verifyPatternLocations");async function $r(r,e){let t=Date.now();try{let s=await Hr(e),a=r.fileCount,o=.1,n=Math.abs(s-a),c=a*o;return n<=c?{name:"File count verification",passed:!0,output:`File count accurate (declared: ${a}, actual: ${s})`,durationMs:Date.now()-t}:{name:"File count verification",passed:!1,error:`File count mismatch: declared ${a}, actual ${s} (diff: ${n})`,durationMs:Date.now()-t}}catch(s){return{name:"File count verification",passed:!1,error:`Failed to count files: ${s instanceof Error?s.message:"unknown error"}`,durationMs:Date.now()-t}}}i($r,"verifyFileCount");async function Or(r,e){let t=Date.now();if(r.antiPatterns.length===0)return{name:"Anti-pattern file verification",passed:!0,output:"No anti-patterns declared (skipped)",durationMs:Date.now()-t};let s=[],a=[];for(let o of r.antiPatterns){let n=E.join(e,o.file);await N(n)?a.push(o.file):s.push(`${o.issue} (${o.file})`)}return s.length===0?{name:"Anti-pattern file verification",passed:!0,output:`${a.length} anti-pattern file(s) verified`,durationMs:Date.now()-t}:{name:"Anti-pattern file verification",passed:!1,error:`Anti-pattern files not found: ${s.join(", ")}`,durationMs:Date.now()-t}}i(Or,"verifyAntiPatternFiles");async function Rt(r,e){let t=Date.now(),s=await Promise.all([Mr(r,e),Fr(r,e),_r(r,e),$r(r,e),Or(r,e)]);return K(s,t)}i(Rt,"semanticVerify");async function Nr(r){let e=new Set,t=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function s(a){try{let o=await oe.readdir(a,{withFileTypes:!0});for(let n of o){let c=E.join(a,n.name),l=E.relative(r,c);if(!t.some(d=>d.test(l))){if(n.isDirectory())await s(c);else if(n.isFile()){let d=E.extname(n.name);d&&e.add(d)}}}}catch{}}return i(s,"scanDir"),await s(r),Array.from(e)}i(Nr,"getProjectExtensions");async function Hr(r){let e=[/node_modules/,/\.git/,/dist/,/build/,/\.next/,/\.turbo/,/coverage/];async function t(s){try{let a=await oe.readdir(s,{withFileTypes:!0});return(await Promise.all(a.map(async n=>{let c=E.join(s,n.name),l=E.relative(r,c);return e.some(d=>d.test(l))?0:n.isDirectory()?t(c):n.isFile()?1:0}))).reduce((n,c)=>n+c,0)}catch{return 0}}return i(t,"scanDir"),t(r)}i(Hr,"countProjectFiles");te();var ce=class extends Be{static{i(this,"AnalysisStorage")}constructor(){super("analysis.json")}getDefault(){return{draft:null,sealed:null,previousSealed:null,lastUpdated:""}}getEventType(e){return`analysis.${e}d`}async saveDraft(e,t){let s={...t,status:"draft"};ie.parse(s),await this.update(e,a=>({...a,draft:s,lastUpdated:v()})),this.publishAnalysis(e,s)}publishAnalysis(e,t){Ve({projectId:e,entityType:"analysis",entityId:e,eventType:"upsert",data:{...t,id:e}})}async seal(e){let t=await this.read(e);if(!t.draft)return{success:!1,error:"No draft analysis to seal. Run `p. sync` first."};if(t.draft.status==="sealed")return{success:!1,error:"Draft is already sealed."};let s=this.computeSignature(t.draft),a=v(),o={...t.draft,status:"sealed",signature:s,sealedAt:a};return ie.parse(o),await this.write(e,{draft:null,sealed:o,previousSealed:t.sealed,lastUpdated:a}),this.publishAnalysis(e,o),{success:!0,signature:s}}async getSealed(e){return(await this.read(e)).sealed}async getDraft(e){return(await this.read(e)).draft}async getActive(e){let t=await this.read(e);return t.sealed??t.draft}async getStatus(e){let t=await this.read(e);return{hasSealed:t.sealed!==null,hasDraft:t.draft!==null,hasPreviousSealed:t.previousSealed!==null,sealedCommit:t.sealed?.commitHash??null,draftCommit:t.draft?.commitHash??null,previousSealedCommit:t.previousSealed?.commitHash??null,sealedAt:t.sealed?.sealedAt??null}}async rollback(e){let t=await this.read(e);if(!t.previousSealed)return{success:!1,error:"No previous sealed version to rollback to."};let s=v();return await this.write(e,{draft:t.sealed,sealed:t.previousSealed,previousSealed:null,lastUpdated:s}),this.publishAnalysis(e,t.previousSealed),{success:!0,restoredSignature:t.previousSealed.signature}}async diff(e){let t=await this.read(e);return!t.sealed||!t.draft?null:It(t.sealed,t.draft)}checkStaleness(e,t){return e?t?e!==t?{isStale:!0,sealedCommit:e,currentCommit:t,message:`Analysis is stale: sealed at ${e}, HEAD is ${t}. Run \`p. sync\` + \`p. seal\` to update.`}:{isStale:!1,sealedCommit:e,currentCommit:t,message:"Analysis is current."}:{isStale:!0,sealedCommit:e,currentCommit:null,message:"Cannot determine current commit. Analysis may be stale."}:{isStale:!1,sealedCommit:null,currentCommit:t,message:"No sealed analysis. Run `p. sync` then `p. seal`."}}async verify(e){let t=await this.read(e);if(!t.sealed)return{valid:!1,message:"No sealed analysis to verify."};if(!t.sealed.signature)return{valid:!1,message:"Sealed analysis has no signature."};let s=this.computeSignature({...t.sealed,signature:void 0,sealedAt:void 0});return s===t.sealed.signature?{valid:!0,message:"Signature verified. Analysis integrity confirmed."}:{valid:!1,message:`Signature mismatch. Expected ${s}, got ${t.sealed.signature}. Analysis may have been modified.`}}async semanticVerify(e,t){let s=await this.read(e),a=s.sealed??s.draft;return a?await Rt(a,t):{passed:!1,checks:[{name:"Analysis availability",passed:!1,error:"No analysis available. Run `p. sync` to generate.",durationMs:0}],totalMs:0,failedCount:1,passedCount:0}}computeSignature(e){let t={projectId:e.projectId,languages:e.languages,frameworks:e.frameworks,packageManager:e.packageManager,sourceDir:e.sourceDir,testDir:e.testDir,configFiles:e.configFiles,fileCount:e.fileCount,patterns:e.patterns,antiPatterns:e.antiPatterns,analyzedAt:e.analyzedAt,commitHash:e.commitHash};return We(JSON.stringify(t))}},Y=new ce;import hs from"node:fs/promises";import Z from"node:path";Ar();Ge();V();import le from"node:fs/promises";import Tt from"node:path";import{gunzipSync as Lr,gzipSync as Gr}from"node:zlib";Ge();B();var zr="code-graph.json.gz";function Mt(r){return Tt.join(J.getGlobalProjectPath(r),zr)}i(Mt,"artifactPath");async function Wr(r){if(!ae(r))return null;let e=dt(r),t=ot(r),s=lt(r)??{symbolCount:e.length,edgeCount:t.length,fileCount:new Set(e.map(l=>l.file)).size,builtAt:new Date().toISOString()},a={version:1,projectId:r,exportedAt:new Date().toISOString(),meta:s,symbols:e,edges:t},o=Buffer.from(JSON.stringify(a),"utf-8"),n=Gr(o,{level:6}),c=Mt(r);return await le.mkdir(Tt.dirname(c),{recursive:!0}),await le.writeFile(c,n),{path:c,bytes:n.length,symbols:e.length,edges:t.length}}i(Wr,"exportCodeGraphArtifact");async function Ur(r){let e=Mt(r),t=await le.readFile(e).catch(()=>null);if(!t)return{imported:!1,symbols:0,edges:0,reason:"no per-project artifact"};let s=(()=>{try{let o=Lr(t).toString("utf-8");return{payload:JSON.parse(o)}}catch(o){return{error:`corrupt artifact: ${o instanceof Error?o.message:String(o)}`}}})();if("error"in s)return{imported:!1,symbols:0,edges:0,reason:s.error};let a=s.payload;return a.version!==1||!Array.isArray(a.symbols)?{imported:!1,symbols:0,edges:0,reason:"unsupported artifact version"}:a.projectId&&a.projectId!==r?{imported:!1,symbols:0,edges:0,reason:`artifact projectId mismatch (got ${a.projectId}, expected ${r})`}:(at(r,{symbols:a.symbols,edges:a.edges}),T.setDoc(r,"symbol-graph",{...a.meta,builtAt:a.meta.builtAt??a.exportedAt}),{imported:!0,symbols:a.symbols.length,edges:a.edges.length})}i(Ur,"importCodeGraphArtifact");async function Ft(r){if(ae(r))return{bootstrapped:!1,detail:"local index already present"};let e=await Ur(r);return e.imported?{bootstrapped:!0,detail:`imported ${e.symbols} symbols / ${e.edges} edges from per-project cache`}:{bootstrapped:!1,detail:e.reason??"import failed"}}i(Ft,"bootstrapCodeGraphFromArtifact");function _t(r){return r?.cloud?.enabled===!0&&r.cloud.paused!==!0}i(_t,"shouldAutoUploadCodeGraph");async function $t(r,e){try{await Wr(r)}catch{}if(e.uploadToCloud)try{await Vr(r,e.uploadDependencies)}catch{}}i($t,"maybeExportAfterIndex");async function Vr(r,e={}){let t=await import("./code-graph-cloud-4GRWQSUK.mjs"),s=(e.buildSnapshot??t.buildCloudCodeGraphSnapshot)(r);if(!t.isUploadableGraph(s))return{uploaded:!1,reason:"no symbol index or empty graph"};try{let o=await(e.upload??(async(n,c)=>{let{default:l}=await import("./sync-client-EGBMWF3J.mjs");return l.uploadCodeGraph(n,c)}))(r,s);return o.ok?{uploaded:!0,nodes:o.nodes??s.nodes.length,links:o.links??s.links.length}:{uploaded:!1,reason:o.reason??"upload failed or unauthenticated",nodes:s.nodes.length,links:s.links.length}}catch(a){return{uploaded:!1,reason:a instanceof Error?a.message:String(a)}}}i(Vr,"maybeUploadCodeGraphToCloud");import F from"node:fs/promises";import Jr from"node:os";import x from"node:path";var de=[{name:"prjct",description:St,allowedTools:[...wt],body:i(()=>vt(),"body"),reference:i(()=>bt(),"reference"),referenceFile:kt}];function Br(r){let e=r.userInvocable!==!1;return`---
13
- description: "${r.description}"
14
- allowed-tools: [${r.allowedTools.map(t=>`"${t}"`).join(", ")}]
15
- user-invocable: ${e}
16
- ---`}i(Br,"buildFrontmatter");function qr(r){return`${Br(r)}
17
-
18
- ${r.body()}`}i(qr,"buildSkillContent");function Ot(){return process.env.HOME||Jr.homedir()}i(Ot,"homeDir");function Kr(){return x.join(Ot(),".claude","skills")}i(Kr,"claudeSkillsRoot");function Yr(){let r=Ot();return[x.join(r,".codex","skills"),x.join(r,".gemini","skills"),x.join(r,".gemini","antigravity","global_skills")]}i(Yr,"compactSkillRoots");function Qr(r){return!!(/^# [^\n]+\n[^\n]*\|\s*\d+\s+files\s*\|/m.test(r)||/## Recent Deliveries/m.test(r)||/## Velocity/m.test(r)&&/pts\/sprint/m.test(r))}i(Qr,"skillBodyHasProjectStamp");var ue=class{static{i(this,"SkillGenerator")}async generateAndInstall(){let e={generated:[],skipped:[]},t=Kr();for(let o of de)try{let n=qr(o);if(Qr(n))throw new Error("refusing to install project-stamped skill body (isolation guard)");let c=x.join(t,o.name),l=x.join(c,"SKILL.md");await F.mkdir(c,{recursive:!0}),await F.writeFile(l,n,"utf-8"),o.reference&&o.referenceFile&&await F.writeFile(x.join(c,o.referenceFile),o.reference(),"utf-8"),e.generated.push({name:o.name,path:l})}catch(n){p.debug(`Failed to generate skill ${o.name}`,{error:w(n)}),e.skipped.push({name:o.name,reason:w(n)})}let s=ze();for(let o of Yr())try{let n=x.join(o,"prjct"),c=x.join(n,"SKILL.md");await F.mkdir(n,{recursive:!0}),await F.writeFile(c,s,"utf-8"),e.generated.push({name:"prjct-compact",path:c})}catch(n){p.debug("Compact skill install skipped",{root:o,error:w(n)})}let a=new Set(de.map(o=>o.name));try{let o=await F.readdir(t,{withFileTypes:!0}).catch(()=>[]);for(let n of o)n.isDirectory()&&n.name.startsWith("prjct-")&&!a.has(n.name)&&await F.rm(x.join(t,n.name),{recursive:!0,force:!0}).catch(()=>{})}catch{}return e.generated.length>0&&p.info("Generated portable multi-host skills",{count:e.generated.length,skills:e.generated.map(o=>o.name)}),e}getDefinitions(){return de}},Nt=new ue;function me(){return{branch:"main",commits:0,contributors:0,hasChanges:!1,stagedFiles:[],modifiedFiles:[],untrackedFiles:[],recentCommits:[],weeklyCommits:0}}i(me,"emptyGitData");function pe(){return{fileCount:0,version:"0.0.0",name:"unknown",ecosystem:"unknown",projectType:"simple",languages:[],frameworks:[]}}i(pe,"emptyStats");function fe(){return{install:"npm install",run:"npm run",test:"npm test",build:"npm run build",dev:"npm run dev",lint:"npm run lint",format:"npm run format"}}i(fe,"emptyCommands");function ge(){return{hasFrontend:!1,hasBackend:!1,hasDatabase:!1,hasDocker:!1,hasTesting:!1,frontendType:null,frameworks:[]}}i(ge,"emptyStack");function Ht(r,e){let t=[...r.added,...r.modified],s=new Set(t),a=new Set,o=q(e);if(o)for(let l of t){let d=o.reverse[l];if(d)for(let m of d)s.has(m)||a.add(m)}let n=Array.from(a),c=[...t,...n];return{directlyChanged:t,affectedByImports:n,deleted:r.deleted,allAffected:c}}i(Ht,"propagateChanges");function Lt(r){let e=new Set;for(let t of r){let s=t.toLowerCase();(s.endsWith(".tsx")||s.endsWith(".jsx")||s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".vue")||s.endsWith(".svelte")||s.includes("/components/")||s.includes("/pages/")||s.includes("/app/"))&&(e.add("frontend"),e.add("uxui")),(s.includes(".test.")||s.includes(".spec.")||s.includes("__tests__")||s.includes("/test/"))&&e.add("testing"),(s.includes("dockerfile")||s.includes("docker-compose")||s.includes(".dockerignore")||s.includes(".github/")||s.includes("ci/")||s.includes("cd/"))&&e.add("devops"),(s.endsWith(".sql")||s.includes("prisma")||s.includes("drizzle")||s.includes("migration")||s.includes("/db/"))&&e.add("database"),(s.endsWith(".ts")||s.endsWith(".js"))&&!s.includes(".test.")&&!s.includes(".spec.")&&!s.endsWith(".d.ts")&&e.add("backend")}return e}i(Lt,"affectedDomains");B();V();import Gt from"node:fs/promises";import Xr from"node:path";function Zr(r){return typeof Bun<"u"&&Bun.hash?`xxh64:${Bun.hash(r).toString(36)}`:`fnv1a:${([...r].reduce((t,s)=>Math.imul(t^s.charCodeAt(0),16777619),2166136261)>>>0).toString(36)}`}i(Zr,"hashContent");async function es(r,e={}){let t=await _e(r,{skipDotfiles:!0,dotfileAllowlist:[".env.example"]}),s=new Map,a=e.changedFilesHint?.length?new Set(e.changedFilesHint):null,o=await $e(t,100,async n=>{try{let c=Xr.join(r,n),l=await Gt.stat(c),d=l.mtime.toISOString(),m=e.storedHashes?.get(n),h=a?.has(n)??!1;if(m&&!h&&m.size===l.size&&m.mtime===d&&m.hash)return{path:n,hash:m.hash,size:l.size,mtime:d};let y=await Gt.readFile(c,"utf-8");return{path:n,hash:Zr(y),size:l.size,mtime:d}}catch{return null}});for(let n of o)s.set(n.path,n);return s}i(es,"computeHashes");function ts(r,e){let t=[],s=[],a=[];for(let[n,c]of r){let l=e.get(n);l?l.hash!==c.hash?s.push(n):a.push(n):t.push(n)}let o=[];for(let n of e.keys())r.has(n)||o.push(n);return{added:t,modified:s,deleted:o,unchanged:a}}i(ts,"diffHashes");function he(r,e){let t=T.getDb(r);t.transaction(()=>{t.prepare("DELETE FROM index_checksums").run();let s=t.prepare("INSERT INTO index_checksums (path, checksum, size, mtime) VALUES (?, ?, ?, ?)");for(let[,a]of e)s.run(a.path,a.hash,a.size,a.mtime)})(),T.setDoc(r,"file-hashes-meta",{fileCount:e.size,builtAt:new Date().toISOString()})}i(he,"saveHashes");function rs(r){let e=new Map;try{let t=T.query(r,"SELECT path, checksum, size, mtime FROM index_checksums");for(let s of t)e.set(s.path,{path:s.path,hash:s.checksum,size:s.size||0,mtime:s.mtime||""})}catch{}return e}i(rs,"loadHashes");async function ye(r,e,t){let s=rs(e),a=await es(r,{storedHashes:s,changedFilesHint:t});return{diff:ts(a,s),currentHashes:a}}i(ye,"detectChanges");function zt(r){return T.hasDoc(r,"file-hashes-meta")}i(zt,"hasHashRegistry");$();var ss=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs"]);async function Wt(r){let{projectId:e,projectPath:t,isFullSync:s,changedFilesHint:a}=r,o={shouldRebuildIndexes:!0,changedDomains:new Set,incrementalInfo:void 0,changedSourceFiles:[],deletedSourceFiles:[]};if(!s&&zt(e)){try{let{diff:n,currentHashes:c}=await ye(t,e,a),l=n.added.length+n.modified.length+n.deleted.length,d=(()=>{if(l===0&&!a?.length)return{shouldRebuildIndexes:!1,changedDomains:new Set,incrementalInfo:{isIncremental:!0,filesChanged:0,filesUnchanged:n.unchanged.length,indexesRebuilt:!1,affectedDomains:[]},changedSourceFiles:[],deletedSourceFiles:[]};let m=Ht(n,e),h=Lt(m.allAffected),y=m.allAffected.some(Se);return{shouldRebuildIndexes:y,changedDomains:h,incrementalInfo:{isIncremental:!0,filesChanged:l,filesUnchanged:n.unchanged.length,indexesRebuilt:y,affectedDomains:Array.from(h)},changedSourceFiles:[...n.added,...n.modified].filter(Se),deletedSourceFiles:n.deleted.filter(Se)}})();return he(e,c),d}catch(n){p.debug("Incremental detection failed, falling back to full sync",{error:k(n)})}return o}try{let{currentHashes:n}=await ye(t,e,a);he(e,n)}catch(n){p.debug("Hash computation failed (non-critical)",{error:k(n)})}return o}i(Wt,"detectIncrementalChanges");function Se(r){let e=r.substring(r.lastIndexOf("."));return ss.has(e)}i(Se,"isSourceFile");import{z as D}from"zod";var jn=D.object({date:D.string(),tokensSaved:D.number(),syncs:D.number(),avgCompressionRate:D.number(),totalDuration:D.number()}),An=D.object({agentName:D.string(),usageCount:D.number(),tokensSaved:D.number()}),Ut={"claude-opus-4.5":.005,"claude-sonnet-4.5":.003,"claude-haiku-4.5":.001,"claude-opus-4":.015,"claude-sonnet-4":.003,"gpt-4o":.0025,"gemini-pro":.00125,default:.003};function Vt(r,e="default"){let t=Ut[e]||Ut.default;return r/1e3*t}i(Vt,"estimateCostSaved");function In(r){return r<.01?`$${(r*100).toFixed(2)}\xA2`:`$${r.toFixed(2)}`}i(In,"formatCost");B();var ns=i(r=>({date:r.date,tokensSaved:r.tokens_saved,syncs:r.syncs,avgCompressionRate:r.avg_compression_rate,totalDuration:r.total_duration}),"rowToDaily"),Q=i(r=>{let e=new Date;return e.setDate(e.getDate()-r),e.toISOString().split("T")[0]},"dayCutoff"),we=class{static{i(this,"MetricsStorage")}async recordSync(e,t){let s=Math.max(0,t.originalSize-t.filteredSize),a=t.originalSize>0?s/t.originalSize:0,o=new Date().toISOString().split("T")[0];if(b.run(e,`INSERT INTO metrics_daily (date, tokens_saved, syncs, avg_compression_rate, total_duration)
19
- VALUES (?, ?, 1, ?, ?)
20
- ON CONFLICT(date) DO UPDATE SET
21
- tokens_saved = metrics_daily.tokens_saved + excluded.tokens_saved,
22
- avg_compression_rate =
23
- (metrics_daily.avg_compression_rate * metrics_daily.syncs + excluded.avg_compression_rate)
24
- / (metrics_daily.syncs + 1),
25
- syncs = metrics_daily.syncs + 1,
26
- total_duration = metrics_daily.total_duration + excluded.total_duration`,o,s,a,t.duration),t.agents?.length){let n=Math.floor(s/t.agents.length);for(let c of t.agents)b.run(e,`INSERT INTO metrics_agent_usage (agent_name, usage_count, tokens_saved)
27
- VALUES (?, 1, ?)
28
- ON CONFLICT(agent_name) DO UPDATE SET
29
- usage_count = metrics_agent_usage.usage_count + 1,
30
- tokens_saved = metrics_agent_usage.tokens_saved + excluded.tokens_saved`,c,n)}}async getSummary(e){let t=b.get(e,`SELECT COALESCE(SUM(tokens_saved), 0) AS tokens,
31
- COALESCE(SUM(syncs), 0) AS syncs,
32
- COALESCE(SUM(total_duration), 0) AS duration,
33
- COALESCE(SUM(avg_compression_rate * syncs), 0) AS weighted_rate
34
- FROM metrics_daily`),s=t?.syncs??0,a=t?.tokens??0,o=i((m,h)=>b.get(e,h?"SELECT COALESCE(SUM(tokens_saved), 0) AS t FROM metrics_daily WHERE date >= ? AND date < ?":"SELECT COALESCE(SUM(tokens_saved), 0) AS t FROM metrics_daily WHERE date >= ?",...h?[m,h]:[m])?.t??0,"rangeTokens"),n=o(Q(30)),c=o(Q(60),Q(30)),l=c>0?(n-c)/c*100:0,d=b.query(e,"SELECT * FROM metrics_agent_usage ORDER BY usage_count DESC LIMIT 5").map(m=>({agentName:m.agent_name,usageCount:m.usage_count,tokensSaved:m.tokens_saved}));return{totalTokensSaved:a,estimatedCostSaved:Vt(a),compressionRate:s>0?(t?.weighted_rate??0)/s:0,syncCount:s,avgSyncDuration:s>0?(t?.duration??0)/s:0,topAgents:d,last30DaysTokens:n,trend:l}}async getDailyStats(e,t=30){return b.query(e,"SELECT * FROM metrics_daily WHERE date >= ? ORDER BY date ASC",Q(t)).map(ns)}async getFirstSyncDate(e){return b.get(e,"SELECT MIN(date) AS d FROM metrics_daily")?.d??""}},Jt=new we;$();te();import as from"node:path";function os(r){return Ue(as.resolve(r))}i(os,"repoHash");function L(r){return r.toLowerCase().replace(/[^a-z0-9]+/g,"")}i(L,"normalizeKey");function is(r){return se(r,e=>`${L(e.name)}::${L(e.source)}`)}i(is,"dedupePatterns");function cs(r){return se(r,e=>`${L(e.issue)}::${L(e.file)}::${L(e.source)}`)}i(cs,"dedupeAntiPatterns");var ke=class{static{i(this,"PatternExtractor")}async extract(e){let t=os(e.projectPath),s=[];if(e.context7Verified)for(let l of e.frameworks)s.push({name:`${l} API validation via Context7`,description:`Validate ${l} APIs against current documentation through Context7 before implementation.`,framework:l,source:"context7",confidence:.7});let a=(e.feedback?.patternsDiscovered||[]).map(l=>({name:l,description:`Confirmed during completed tasks: ${l}`,source:"feedback",confidence:.75})),o=(e.feedback?.knownGotchas||[]).map(l=>({issue:l,file:"multiple",suggestion:`Recurring gotcha. Prevent this pattern during implementation: ${l}`,source:"feedback",severity:"medium",confidence:.7})),n=is([...s,...a]),c=cs([...o]);return{patterns:n,antiPatterns:c,repoPathHash:t}}},ls=new ke,Bt=ls;var qt=200;async function Kt(r,e,t){let{bm25Index:s,originalSize:a}=(()=>{try{let d=Ze(r),m=d?Object.values(d.documents).reduce((h,y)=>h+y.length,0):0;return{bm25Index:d,originalSize:m||e.fileCount*qt}}catch(d){return p.debug("Could not load BM25 index for metrics",{error:k(d)}),{bm25Index:null,originalSize:e.fileCount*qt}}})(),o=0,n=a>0?Math.max(0,(a-o)/a):0;try{await Jt.recordSync(r,{originalSize:a,filteredSize:o,duration:t,isWatch:!1})}catch(d){p.debug("Failed to record sync metrics",{error:k(d)})}try{let{velocityStorage:d}=await import("./velocity-storage-47CF3XWZ.mjs");await d.recompute(r)}catch(d){p.debug("Failed to recompute velocity",{error:k(d)})}let c=await import("./developer-evolution-SLC34HUU.mjs").then(({captureDeveloperSnapshot:d})=>d(r)).catch(d=>(p.debug("Failed to capture dev snapshot",{error:k(d)}),!1)),l={};try{let d=s;d&&(l.bm25Files=d.totalDocs,l.bm25AvgTokens=Math.round(d.avgDocLength),l.bm25VocabSize=Object.keys(d.invertedIndex).length);let m=q(r);m&&(l.importEdges=m.edgeCount,l.importFiles=m.fileCount);let h=gt(r);h&&(l.cochangeCommits=h.commitsAnalyzed,l.cochangeFiles=h.filesAnalyzed)}catch(d){p.debug("Could not load index stats",{error:k(d)})}return{duration:t,originalSize:a,filteredSize:o,compressionRate:n,indexes:l,developerSnapshotCaptured:c}}i(Kt,"recordSyncMetrics");async function Yt(r,e,t,s,a,o){try{let n=t.recentCommits[0]?.hash||null,c=await I.getAggregatedFeedback(r).catch(()=>{});try{let{refreshSkillIndex:d}=await import("./skill-index-RAVJMC4P.mjs");await d(r,e)}catch{}let l=await Bt.extract({projectId:r,projectPath:e,languages:s.languages,frameworks:Array.from(new Set([...s.frameworks,...a.frameworks])),feedback:c,context7Verified:o});await Y.saveDraft(r,{projectId:r,languages:s.languages,frameworks:s.frameworks,configFiles:[],fileCount:s.fileCount,patterns:l.patterns,antiPatterns:l.antiPatterns,analyzedAt:v(),status:"draft",commitHash:n??void 0})}catch(n){p.debug("Failed to save draft analysis (non-critical)",{error:k(n)})}}i(Yt,"saveDraftAnalysis");async function Qt(r){try{let[e,t,s,a,o]=await Promise.all([qe.archiveOldShipped(r).catch(()=>0),Ke.markDormantIdeas(r).catch(()=>0),Ye.removeStaleCompleted(r).catch(()=>0),I.archiveStalePausedTasks(r).catch(()=>[]),Xe.capEntries(r).catch(()=>0)]),n=e+t+s+a.length+o;if(n>0){p.info("Archived stale data",{shipped:e,dormant:t,staleQueue:s,stalePaused:a.length,memoryCapped:o,total:n});let c=Je.getStats(r);p.debug("Archive stats",c)}}catch(e){p.debug("Archival failed (non-critical)",{error:k(e)})}}i(Qt,"archiveStaleData");var us=6e4,ve=class extends Error{static{i(this,"SyncPhaseTimeoutError")}phase;timeoutMs;constructor(e,t){super(`sync phase '${e}' timed out after ${t}ms. Set PRJCT_SYNC_PHASE_TIMEOUT_MS to tune this guard, or run \`prjct sync --full --md\` if incremental state looks stale.`),this.name="SyncPhaseTimeoutError",this.phase=e,this.timeoutMs=t}};function ms(){return Number(process.env.PRJCT_SYNC_PHASE_TIMEOUT_MS)||us}i(ms,"syncPhaseTimeoutMs");function Xt(r,e){let t=ms(),s=(()=>{let a=Promise.withResolvers(),o=setTimeout(()=>a.reject(new ve(e,t)),t);return{promise:a.promise,cancel:i(()=>clearTimeout(o),"cancel")}})();return Promise.race([r,s.promise]).finally(s.cancel)}i(Xt,"withPhaseTimeout");async function Zt(r,e,t){let s=Date.now();p.debug("sync phase start",{phase:r});try{let a=await e(),o=Date.now()-s;return p.debug("sync phase done",{phase:r,ms:o}),t?.push({phase:r,ms:o}),a}catch(a){let o=Date.now()-s;throw p.debug("sync phase failed",{phase:r,ms:o,error:w(a)}),t?.push({phase:r,ms:o}),a}}i(Zt,"runSyncPhase");function er(r,e={}){let t=e.now??Date.now,s=t(),o=(()=>{try{return r().then(()=>({}),n=>({error:n}))}catch(n){return Promise.resolve({error:n})}})().then(n=>{try{e.onComplete?.({totalMs:t()-s,...n})}catch{}});return{async settle(){await o}}}i(er,"startPostIndexWork");B();import ps from"node:fs/promises";import fs from"node:path";$();te();$();V();import be from"node:fs/promises";import X from"node:path";var Pe=".prjct/.prjct-state.md",Ce=class{static{i(this,"LocalStateGenerator")}async generate(e,t){let s=X.join(e,Pe);await be.mkdir(X.dirname(s),{recursive:!0});let a=this.toMarkdown(t);await be.writeFile(s,a,"utf-8")}async remove(e){try{await be.unlink(X.join(e,Pe))}catch(t){if(!R(t))throw t}}async exists(e){let t=X.join(e,Pe);return N(t)}toMarkdown(e){let t=["<!-- Auto-generated by prjct - DO NOT EDIT -->","<!-- This file provides local state persistence for AI tools -->","","# prjct State",""];if(e.currentTask){let s=e.currentTask;if(t.push("## Current Work Cycle"),t.push(""),t.push(`**${s.description}**`),t.push(""),t.push(`- Started: ${s.startedAt}`),s.linearId&&t.push(`- Linear: ${s.linearId}`),s.branch&&t.push(`- Branch: ${s.branch}`),t.push(`- Status: ${s.status||"active"}`),t.push(""),s.subtasks&&s.subtasks.length>0){t.push("### Subtasks"),t.push(""),s.subtasks.forEach((c,l)=>{let d=c.status==="completed"?"\u2705":c.status==="in_progress"?"\u25B6\uFE0F":"\u23F3",m=l===s.currentSubtaskIndex?" \u2190 **Active**":"";t.push(`${l+1}. ${d} ${c.description}${m}`)}),t.push("");let a=s.subtasks.filter(c=>c.status==="completed").length,o=s.subtasks.length,n=Math.round(a/o*100);t.push(`**Progress**: ${a}/${o} (${n}%)`),t.push("")}}else t.push("*No active work cycle*"),t.push(""),t.push('Start work with `p. work "intent"`'),t.push("");if(e.previousTask){let s=e.previousTask;t.push("---"),t.push(""),t.push("## Previous Work Cycle"),t.push(""),t.push(`**${s.description}**`),t.push(""),t.push(`- Status: ${s.status}`),s.prUrl&&t.push(`- PR: ${s.prUrl}`),t.push("")}return t.push("---"),t.push(`*Last updated: ${e.lastUpdated||new Date().toISOString()}*`),t.push(""),t.join(`
35
- `)}},tr=new Ce;var gs=["storage","context","memory","analysis","config","sync"];async function rr(r){try{await Promise.all(gs.map(e=>ps.mkdir(fs.join(r,e),{recursive:!0})))}catch(e){throw new Error(Fe(e,r,"project directories"))}}i(rr,"ensureProjectDirectories");async function sr(r){let{projectId:e,projectPath:t,cliVersion:s,git:a,stats:o}=r,n=b.getDoc(e,"project")||{},c={...n,projectId:e,repoPath:t,name:o.name,version:o.version,cliVersion:s,techStack:o.frameworks,fileCount:o.fileCount,commitCount:a.commits,stack:o.ecosystem,currentBranch:a.branch,hasUncommittedChanges:a.hasChanges,createdAt:n.createdAt||v(),lastSync:v(),lastSyncCommit:a.recentCommits[0]?.hash||null,lastSyncBranch:a.branch};b.setDoc(e,"project",c)}i(sr,"updateProjectDoc");async function nr(r){let{projectId:e,projectPath:t,stats:s,stack:a}=r,n={...await I.read(e)};n.projectId=e,n.stack={language:s.languages[0]||"Unknown",framework:s.frameworks[0]||null},n.domains={hasFrontend:a.hasFrontend,hasBackend:a.hasBackend,hasDatabase:a.hasDatabase,hasTesting:a.hasTesting,hasDocker:a.hasDocker},n.projectType=s.projectType,n.metrics={totalFiles:s.fileCount},n.lastSync=v(),n.lastUpdated=v(),n.context={...n.context||{},lastSession:v(),lastAction:"Synced project",nextAction:'Run `p. work "intent"` to start a work cycle'},await I.write(e,n);try{await tr.remove(t)}catch(c){p.debug("Legacy local state cleanup failed (optional)",{error:k(c)})}}i(nr,"updateStateDoc");function ar(r,e,t){b.appendEvent(r,"sync",{branch:e.branch,uncommitted:e.hasChanges,fileCount:t.fileCount,commitCount:e.commits})}i(ar,"logSyncEvent");import or from"node:fs/promises";import xe from"node:path";$();Dr();var ir={async jsonFilesValid(r){let e=Date.now(),t=[],s=xe.basename(r);try{await I.read(s)}catch(a){R(a)||t.push(`state: ${k(a)}`)}return{name:"State data valid",passed:t.length===0,output:t.length===0?"1 store validated":void 0,error:t.length>0?t.join("; "):void 0,durationMs:Date.now()-e}},async noSensitiveData(r){let e=Date.now(),t=xe.join(r,"context"),s=[/(?:api[_-]?key|apikey)\s*[:=]\s*['"][^'"]{10,}/i,/(?:password|passwd|pwd)\s*[:=]\s*['"][^'"]{4,}/i,/(?:secret|token)\s*[:=]\s*['"][^'"]{10,}/i],a=[];try{let o=await or.readdir(t);for(let n of o){if(!n.endsWith(".md"))continue;let c=await or.readFile(xe.join(t,n),"utf-8");for(let l of s)if(l.test(c)){a.push(`${n}: potential sensitive data detected`);break}}}catch(o){if(!R(o))return{name:"No sensitive data",passed:!1,error:`Could not scan: ${k(o)}`,durationMs:Date.now()-e}}return{name:"No sensitive data",passed:a.length===0,output:a.length===0?"No sensitive patterns found":void 0,error:a.length>0?a.join("; "):void 0,durationMs:Date.now()-e}}},De=class{static{i(this,"SyncVerifier")}async verify(e,t,s){let a=Date.now(),o=[],n=s?.failFast??!1,c=[],l=[ir.jsonFilesValid(t),ir.noSensitiveData(t)];for(let m of l){let h=await m;if(o.push(h),!h.passed&&n){c.push(...s?.checks?.filter(y=>y.enabled!==!1).map(y=>y.name)??[]);break}}if((!n||o.every(m=>m.passed))&&s?.checks)for(let m of s.checks){if(m.enabled===!1){c.push(m.name);continue}let h=await this.runCustomCheck(m,e);if(o.push(h),!h.passed&&n){let y=s.checks.slice(s.checks.indexOf(m)+1);c.push(...y.filter(P=>P.enabled!==!1).map(P=>P.name));break}}return{...K(o,a),skippedCount:c.length}}async runCustomCheck(e,t){let s=Date.now(),a=e.command||(e.script?`sh ${e.script}`:null);if(!a)return{name:e.name,passed:!1,error:"No command or script specified",durationMs:Date.now()-s};try{let{stdout:o,stderr:n}=await Me(a,{cwd:t,timeout:3e4});return{name:e.name,passed:!0,output:(o.trim()||n.trim()).slice(0,200)||void 0,durationMs:Date.now()-s}}catch(o){let n=o;return{name:e.name,passed:!1,error:(n.stderr?.trim()||n.message).slice(0,200),durationMs:Date.now()-s}}}},cr=new De;var je=class{static{i(this,"SyncService")}projectPath;projectId=null;globalPath="";cliVersion="0.0.0";constructor(){this.projectPath=process.cwd()}async sync(e=process.cwd(),t={}){this.projectPath=e;let s=Date.now(),a=[],o=i((l,d)=>Zt(l,d,a),"phase"),n={installed:!1,verified:!1,configPath:"",message:""},c=[];try{if(this.projectId=await M.getProjectId(e),!this.projectId)return{success:!1,projectId:"",cliVersion:"",git:me(),stats:pe(),commands:fe(),stack:ge(),context7:{installed:!1,verified:!1},error:"No prjct project. Run p. init first."};if(this.globalPath=J.getGlobalProjectPath(this.projectId),this.cliVersion=await this.getCliVersion(),await hs.rm(Z.join(this.globalPath,"agents"),{recursive:!0,force:!0}).catch(()=>{}),(await Le()).installed){let u=await yt({autoRepair:!0});u.verified||p.warn(`Codex p. router not ready: ${u.message||"verification failed"}`)}await o("mcp-defaults",()=>ft({silent:!0,verifyContext7:!1}));let m=(await He().catch(()=>null))?.name??"claude";try{Object.assign(n,await o("context7",()=>pt.ensureReady(m)))}catch(u){let g=w(u);p.warn(`Context7 MCP not ready (continuing sync): ${g}`),Object.assign(n,{verified:!1,message:g})}await rr(this.globalPath),process.env.PRJCT_SKIP_CREW_SWEEP!=="1"&&await o("legacy-crew-sweep",async()=>{try{let{legacyCrewSweep:u}=await import("./legacy-crew-sweep-2WSO5KEB.mjs"),g=await u(this.projectPath,this.projectId);(g.checkpointsMigrated||g.teamMigrated||g.checkpointsHandEditWarned||g.teamHandEditWarned||g.ghostDirsPurged.length>0||g.agentFilesRepaired.length>0||g.clientPrjctJunkPurged.length>0||g.errors.length>0)&&p.info("Legacy crew sweep ran",{checkpointsMigrated:g.checkpointsMigrated,teamMigrated:g.teamMigrated,checkpointsHandEditWarned:g.checkpointsHandEditWarned,teamHandEditWarned:g.teamHandEditWarned,ghostDirsPurged:g.ghostDirsPurged,agentFilesRepaired:g.agentFilesRepaired,ghostFilesIngested:g.ghostFilesIngested,clientPrjctJunkPurged:g.clientPrjctJunkPurged,errors:g.errors.length})}catch(u){p.debug("Legacy crew sweep failed (non-critical)",{error:w(u)})}});let[y,P,Ee,G]=await o("gather",()=>Xt(Promise.all([Pt(this.projectPath),Ct(this.projectPath),xt(this.projectPath),Dt(this.projectPath)]),"gather")),{shouldRebuildIndexes:ur,changedDomains:ws,incrementalInfo:Re,changedSourceFiles:z,deletedSourceFiles:W}=await o("incremental",()=>Wt({projectId:this.projectId,projectPath:this.projectPath,isFullSync:t.full===!0,changedFilesHint:t.changedFiles}));try{let{refreshFileInventory:u}=await import("./project-file-inventory-5DEN5VLF.mjs");await u(this.projectId,this.projectPath)}catch{}try{await Ft(this.projectId)}catch{}ur&&await o("index",async()=>{try{let u=Re?.isIncremental&&(z.length>0||W.length>0);await Promise.all([u?tt(this.projectPath,this.projectId,z,W):et(this.projectPath,this.projectId),u?nt(this.projectPath,this.projectId,z,W):st(this.projectPath,this.projectId),u?ct(this.projectPath,this.projectId,z,W):it(this.projectPath,this.projectId),ht(this.projectPath,this.projectId)]);let g=this.projectId,S=this.projectPath,O=await M.readConfig(S).catch(()=>null),A=_t(O);c.push(er(()=>$t(g,{uploadToCloud:A}),{onComplete:i(({totalMs:C,error:U})=>{p.debug("sync post-index work settled",{projectId:g,uploadToCloud:A,totalMs:C,...U===void 0?{}:{error:w(U)}})},"onComplete")}))}catch(u){p.debug("File ranking index build failed (non-critical)",{error:w(u)})}});let mr=Date.now();p.debug("sync phase start",{phase:"skills"});let pr=await Nt.generateAndInstall().catch(u=>{p.debug("Native skill generation failed (non-critical)",{error:w(u)})});p.debug("sync phase done",{phase:"skills",ms:Date.now()-mr}),await o("update-files",()=>Promise.all([sr({projectId:this.projectId,projectPath:this.projectPath,cliVersion:this.cliVersion,git:y,stats:P}),nr({projectId:this.projectId,projectPath:this.projectPath,stats:P,stack:G}),Promise.resolve(ar(this.projectId,y,P)),Yt(this.projectId,this.projectPath,y,P,G,n.verified)]));let ee=await Y.getActive(this.projectId),fr={patterns:ee?.patterns?.length||0,antiPatterns:ee?.antiPatterns?.length||0,criticalAntiPatterns:ee?.antiPatterns?.filter(u=>u.severity==="high").length||0},gr=Date.now()-s,Te=await o("metrics",()=>Kt(this.projectId,P,gr)),hr=Te.developerSnapshotCaptured===!0,yr=await(async()=>{try{let{recomputeProjectStyle:u,formatProjectStyleForSync:g}=await import("./project-style-evolution-7MAUSED2.mjs"),S=await o("project-style",()=>u({projectId:this.projectId,projectPath:this.projectPath,stats:P,stack:G,commands:Ee,commitHash:y.recentCommits[0]?.hash??null,source:"sync-mechanical"})),O=g(S),A=S.snapshot.payload.metrics.styleCoverage;return{summary:S.snapshot.summary,evolutionMd:O.evolutionMd,patternCount:S.snapshot.patternCount,antiPatternCount:S.snapshot.antiPatternCount,conventionCount:S.snapshot.conventionCount,styleCoverage:typeof A=="number"?A:Number(A)||0,isFirst:S.isFirst,hasChanges:S.delta.hasChanges}}catch(u){p.debug("Project style recompute failed (non-critical)",{error:w(u)});return}})(),Sr=await o("work-cost",()=>jt(this.projectId));await o("archive",()=>Qt(this.projectId));let wr=await o("context-quality",()=>rt(this.projectPath,this.projectId)),kr=await o("retention",async()=>{try{let u=await M.readConfig(this.projectPath).catch(()=>null),g=u?.retention?.mode??"apply";if(g==="off")return;let S=g==="dry-run",{applyRetention:O,triageInbox:A}=await import("./retention-LWETHQX3.mjs"),C=O(this.projectId,{dryRun:S,maxArchive:u?.retention?.maxArchive,maxDelete:u?.retention?.maxDelete}),{inboxMerged:U,inboxArchived:br}=S?{inboxMerged:0,inboxArchived:0}:(()=>{let j=A(this.projectId);return{inboxMerged:j.merged,inboxArchived:j.archived}})(),{runVaultPurge:Pr,vaultHealth:Cr}=await import("./purge-MC5LFSAO.mjs"),_=await Pr(this.projectId,{projectPath:this.projectPath,dryRun:S,softDeletedPurgeDays:u?.retention?.softDeletedPurgeDays,archivePruneDays:u?.retention?.archivePruneDays,autoSourceMaxLive:u?.retention?.autoSourceMaxLive}),xr=Cr(this.projectId);return{evaluated:C.evaluated,active:C.active,archive:C.wouldArchive,delete:C.wouldDelete,archived:C.archived,deleted:C.deleted,inboxMerged:U,inboxArchived:br,dryRun:S,samples:C.samples.map(j=>({id:j.id,type:j.type,verdict:j.verdict,score:j.score,reasons:j.reasons,excess:j.excess})),referenceSize:C.referenceSize,vault:{...xr,softDeletedPurged:_.softDeletedPurged,orphanEventsPurged:_.orphanEventsPurged,archivesPruned:_.archivesPruned,autoSourceTrimmed:_.autoSourceTrimmed,distilledDiscarded:_.distilledDiscarded,digestsWritten:_.digestsWritten}}}catch(u){p.debug("retention phase failed",{error:w(u)});return}});await o("install-global",async()=>{await re.installGlobalConfig(),await re.syncCommands()}),await o("install-agent-surfaces",async()=>{let{detectInstalledAgents:u}=await import("./detection-QRVSNMKL.mjs"),g=await u(this.projectPath).catch(()=>[]);await mt(this.projectPath,{refreshIfAdopted:!0,agents:g})});let vr=await o("verify",async()=>{try{let u=await M.readConfig(this.projectPath);return await cr.verify(this.projectPath,this.globalPath,u?.verification)}catch(u){p.debug("Verification failed (non-critical)",{error:w(u)});return}});if(process.env.PRJCT_WORLD_MODEL_REFRESH==="1"||process.env.PRJCT_DRIFT_REFRESH==="1")try{let u=await import("node:os"),{markDriftRefreshApplied:g}=await import("./drift-refresh-TD3PYPJN.mjs"),S=process.env.PRJCT_CLI_HOME?Z.resolve(process.env.PRJCT_CLI_HOME):Z.join(u.homedir(),".prjct-cli");g(S)}catch{}return await Promise.all(c.map(u=>u.settle())),{success:!0,projectId:this.projectId,cliVersion:this.cliVersion,git:y,stats:P,commands:Ee,stack:G,context7:{installed:n.installed,verified:n.verified,message:n.message},analysisSummary:fr,contextQuality:wr,retentionDryRun:kr,syncMetrics:Te,workCost:Sr,verification:vr,incremental:Re,projectStyle:yr,developerSnapshotCaptured:hr,generatedSkills:pr,phaseTimings:a}}catch(l){return{success:!1,projectId:this.projectId||"",cliVersion:this.cliVersion,git:me(),stats:pe(),commands:fe(),stack:ge(),context7:{installed:n.installed,verified:n.verified,message:n.message},error:w(l)}}}async getCliVersion(){try{let e=Z.join(__dirname,"..","..","package.json");return(await Oe(e))?.version||"0.0.0"}catch(e){return p.debug("Failed to read CLI version",{error:w(e)}),"0.0.0"}}},co=new je;import Ae from"chalk";var lr={task:"Start new work cycle",done:"Complete current work",pause:"Pause and switch context",resume:"Continue paused task",ship:"Ship the feature",reopen:"Reopen for rework",next:"View task queue",sync:"Analyze project",bug:"Report a bug",idea:"Capture an idea"},ys={task:"work"};function Ie(r){return ys[r]??r}i(Ie,"publicCommand");var dr={task:"working",done:"completed","done-subtask":"working",pause:"paused",resume:"working",ship:"shipped",reopen:"working",next:"idle",sync:"idle",init:"idle",bug:"working",idea:"idle"};function fo(r,e={}){if(e.quiet)return;let t=dr[r]||"idle",s=ne.getValidCommands(t);if(s.length===0)return;let a=s.map(o=>({cmd:`p. ${Ie(o)}`,desc:lr[o]||o}));console.log(Ae.dim(`
36
- Next:`));for(let o of a){let n=Ae.cyan(o.cmd.padEnd(12));console.log(Ae.dim(` ${n} \u2192 ${o.desc}`))}}i(fo,"showNextSteps");function go(r,e=!1){let t=dr[r]||"idle";return ne.getValidCommands(t).map(a=>({cmd:e?`prjct ${Ie(a)} --md`:`p. ${Ie(a)}`,desc:lr[a]||a}))}i(go,"getNextSteps");async function Ss(r,e={}){let t=await M.getProjectId(r);return t?{ok:!0,value:t}:(e.md?console.log("> No project ID found. Run `prjct init` first."):Qe.failWithHint("NO_PROJECT_ID"),{ok:!1,result:{success:!1,error:"No project ID found"}})}i(Ss,"requireProjectId");async function Io(r,e={}){let t=await At.ensureInit(r);return t.success?Ss(r,e):{ok:!1,result:t}}i(Io,"requireProject");export{vs as a,bs as b,Y as c,In as d,Jt as e,co as f,fo as g,go as h,Io as i};
@@ -1,11 +0,0 @@
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 c,b as o,d as l,e as u,f as s,i as d}from"./chunk-DRGI5UHQ.mjs";import{a as f}from"./chunk-E66B27AL.mjs";async function E(t,n){let e=t.projectPath??process.cwd();if(n){try{let i=n.input;if(n.afterEmitOnly){t.afterEmit&&n.detachAfterEmit(()=>t.afterEmit(i,e));return}let r=t.decide?await t.decide(i,e):null;if(r){let k=o(c(t.event,r.deny));n.sink(`${JSON.stringify(k)}
9
- `);return}let a=t.build?await t.build(i,e):null,m=o(d(t.event,a));n.sink(`${JSON.stringify(m)}
10
- `),t.afterEmit&&n.detachAfterEmit(()=>t.afterEmit(i,e))}catch{n.sink(`{}
11
- `)}return}await s(async()=>{let i=l(),r=t.decide?await t.decide(i,e):null;if(r){u(c(t.event,r.deny));return}let a=t.build?await t.build(i,e):null;u(d(t.event,a)),t.afterEmit&&await t.afterEmit(i,e)})}f(E,"runHook");export{E as a};
@@ -1,8 +0,0 @@
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 t}from"./chunk-NUJASVHN.mjs";import"./chunk-HRWXMF7P.mjs";import{a as n}from"./chunk-ZJXH76Q5.mjs";import"./chunk-PUHX3ECX.mjs";import"./chunk-Q3EYM4GJ.mjs";import"./chunk-AZYQFRPJ.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-HHIGNKDO.mjs";import"./chunk-7GNWHWOO.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-QPRNRLG6.mjs";import"./chunk-7JEKBJAP.mjs";import"./chunk-MI3JEFON.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-DRGI5UHQ.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.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-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as o}from"./chunk-E66B27AL.mjs";function p(r=process.cwd(),e){return n({event:"CwdChanged",projectPath:r,build:o(async(d,i)=>{let c=d.cwd||i;return t(c)},"build")},e)}o(p,"runCwdChangedHook");export{p as runCwdChangedHook};
@@ -1,11 +0,0 @@
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 R}from"./chunk-S7HQQILD.mjs";import{a as E}from"./chunk-5WAONIPX.mjs";import{a as A}from"./chunk-ZJXH76Q5.mjs";import{a as x}from"./chunk-3VWBNLBC.mjs";import{a as b,b as M,c as T,d as C,e as g,f as k,g as m,i as w}from"./chunk-ZMKTR2IO.mjs";import"./chunk-QPRNRLG6.mjs";import{b as I,c as S,d as $}from"./chunk-7JEKBJAP.mjs";import"./chunk-MI3JEFON.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as L}from"./chunk-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import{b as v}from"./chunk-6UH244CC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-INXNK57E.mjs";import"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-XS45K7ZQ.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-4KVPAHFV.mjs";import{h as p}from"./chunk-DRGI5UHQ.mjs";import"./chunk-GAOQHD5S.mjs";import{b as h}from"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.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-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as i}from"./chunk-E66B27AL.mjs";var O=new Set(["decision","gotcha","fact","spec","identity","voice","glossary"]);function N(r){return O.has(r)}i(N,"isSotBindType");function V(r,o){let n=new Set(o??[]);return r.filter(e=>N(e.type)&&e.confidence==="high"&&e.id&&!n.has(e.id))}i(V,"filterSotCandidates");function H(r){let o=V(r.candidates,r.overriddenIds);if(o.length===0)return{action:"none",reason:"no-sot",memoryIds:[],message:""};let n=r.harnessLevel??null,e=r.fileLabel?` on \`${r.fileLabel}\``:"",t=o[0],a=o.map(s=>s.id),l='To supersede: `prjct remember decision "\u2026why\u2026" --tags supersedes:'+t.id+'`. To lift for this memory: `prjct remember feedback "override conflict '+t.id+': <why>" --tags conflict:override,memory:'+t.id+"`.";if(n==="H2"||n==="H3"){let s=`SoT hard-bind (${n})${e}: must not contradict [${t.type}] ${B(t.content,80)} (\`${t.id}\`)`;return{action:"deny",reason:"h2-sot-deny",memoryIds:a,message:[`\u26D4 prjct SoT bind: ${s}`,`Memories: ${a.join(", ")}`,l,"H2+ work is bound to living Source-of-Truth. Supersede or override before Edit|Write."].join(" ")}}return n==="H1"?{action:"warn",reason:"h1-sot-warn",memoryIds:a,message:["# prjct: SoT soft-bind (H1)","",`High-confidence SoT on this file${e}:`,...o.slice(0,3).map(s=>`- **[${s.type}]** ${B(s.content,100)} \`${s.id}\``),"",l,"","> H2+ would hard-block. On H1 this is advisory \u2014 supersede if intentional."].join(`
9
- `)}:{action:"none",reason:"none",memoryIds:a,message:""}}i(H,"sotBindVerdict");function B(r,o){let n=r.replace(/\s+/g," ").trim();return n.length>o?`${n.slice(0,o-1)}\u2026`:n}i(B,"truncate");function F(r,o){if(o.length===0)return null;let n=[`# prjct: heads-up before editing \`${r}\``,"",`${o.length} preventive trap(s) recorded against this file:`,""];for(let e of o)n.push(`- **[${e.type}]** ${e.title} \`${e.id}\``);return n.push(""),n.push("> Dynasty trap-before-edit: surface is mandatory. Apply if it still holds; supersede if not."),n.join(`
10
- `)}i(F,"formatTrapSurfaceMessage");var y=1200,_=new Map;function D(r,o){let n=`${r}\0${o}`,e=_.get(n);if(e)return e;let t=(()=>{try{return L.recallForFile(r,o,M,{preventiveOnly:!0})}catch{return[]}})();return _.set(n,t),t}i(D,"recallPreventiveOnce");function P(){_.clear()}i(P,"clearPreventiveCache");function U(r,o){let n=F(o,r.map(t=>({id:t.id,type:I(t),title:`${$(t)} \u2014 ${S(t.content)}`})));if(n)return p(n,y);let e=[`# prjct: heads-up before editing \`${o}\``,""];e.push(`${r.length} preventive memory entr${r.length===1?"y":"ies"} recorded against this file:`),e.push("");for(let t of r)e.push(`- **[${I(t)}] ${$(t)}** \u2014 ${S(t.content)} \`${t.id}\``);return e.push(""),e.push("> Nudge, not block. Apply if it still holds; proceed if not."),p(e.join(`
11
- `),y)}i(U,"headsUpMessage");async function W(r,o){let n=Date.now(),e=await h.readConfig(r);if(!e?.projectId)return null;let t=D(e.projectId,o);if(m(n)||t.length===0)return null;x(e.projectId,r,t.map(f=>f.id));let a=w(e),l=C(e.projectId),s=k(t),u=o.split("/").pop()??o,d=T({mode:a,candidates:s,overriddenIds:l,fileLabel:u});if(m(n))return null;try{let f=await v.getCurrentTask(e.projectId),c=H({harnessLevel:f?.harness?.level??null,candidates:s,overriddenIds:l,fileLabel:u});if(c.action==="warn"&&c.message)return p(c.message,y)}catch{}return d.action==="warn"&&d.message?(g(r,e.projectId,"warn",d.memoryIds,d.reason),p(d.message,y)):a==="off"||d.action==="none"||t.length>0?U(t,u):null}i(W,"buildPreEditContext");async function G(r,o){let n=Date.now();try{let e=await h.readConfig(r);if(!e?.projectId)return null;let t=await v.getCurrentTask(e.projectId);if(e.maxTurnsPerCycle){let j=E(e,t);if(j.stopped)return{deny:j.message}}if(!o||m(n,b))return null;let a=D(e.projectId,o);if(a.length===0||m(n,b))return null;let l=C(e.projectId),s=o.split("/").pop()??o,u=k(a),d=H({harnessLevel:t?.harness?.level??null,candidates:u,overriddenIds:l,fileLabel:s});if(d.action==="deny"&&d.message)return g(r,e.projectId,"deny",d.memoryIds,d.reason),{deny:d.message};let f=w(e);if(f!=="strict")return null;let c=T({mode:f,candidates:u,overriddenIds:l,fileLabel:s});return c.action==="deny"&&c.message?(g(r,e.projectId,"deny",c.memoryIds,c.reason),{deny:c.message}):null}catch{return null}}i(G,"decideHardStop");function ce(r=process.cwd(),o){return A({event:"PreToolUse",projectPath:r,decide:i(async(n,e)=>{P();let t=R(n);return t||G(e,n.tool_input?.file_path?.trim())},"decide"),build:i(async(n,e)=>{try{let t=n.tool_input?.file_path?.trim();return t?W(e,t):null}finally{P()}},"build")},o)}i(ce,"runPreEditHook");export{ce as runPreEditHook};
@@ -1,8 +0,0 @@
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-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.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-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{a as projectMemory};
@@ -1,22 +0,0 @@
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 A,b as z}from"./chunk-MXHX44WF.mjs";import{a as K}from"./chunk-NCOOKPXX.mjs";import{a as V}from"./chunk-5WAONIPX.mjs";import{a as q}from"./chunk-ZJXH76Q5.mjs";import{b as x}from"./chunk-2UC4DTDO.mjs";import{a as F}from"./chunk-5TBQNW2G.mjs";import{a as B}from"./chunk-3VWBNLBC.mjs";import{a as _}from"./chunk-J6TAD3OZ.mjs";import{a as U}from"./chunk-D6IONKRA.mjs";import{a as M}from"./chunk-T2FCU3ZS.mjs";import{b as N}from"./chunk-XE4MJNBQ.mjs";import"./chunk-JCYXFHQZ.mjs";import{b as O}from"./chunk-JPSJWCFD.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-JUZ5LNDI.mjs";import{a as H,g as L}from"./chunk-7O6OMD4X.mjs";import"./chunk-OZJ6UKKP.mjs";import"./chunk-YQ55MHKL.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-KOGZCFBC.mjs";import"./chunk-FX6VHIKB.mjs";import"./chunk-HHIGNKDO.mjs";import"./chunk-7GNWHWOO.mjs";import"./chunk-KEJ5RMAI.mjs";import"./chunk-JMCMTX6U.mjs";import"./chunk-R4ILCXKE.mjs";import"./chunk-QPRNRLG6.mjs";import{d as S}from"./chunk-7JEKBJAP.mjs";import"./chunk-MI3JEFON.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as I}from"./chunk-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import{b as $}from"./chunk-6UH244CC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-INXNK57E.mjs";import"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import{g as T,h as k}from"./chunk-DRGI5UHQ.mjs";import"./chunk-GAOQHD5S.mjs";import{b as v}from"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import{d as R,g as ie}from"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import{k as G,o as re}from"./chunk-UH4MD3F3.mjs";import{b as D,p as ne}from"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as l}from"./chunk-E66B27AL.mjs";import{createHash as E}from"node:crypto";import f from"node:fs/promises";import h from"node:path";var se=15;function W(t){let r=[],e=[];t.loop?.stopped&&t.loop.message&&(r.push("loop-hard-stop"),e.push(t.loop.message)),t.pressure?.level==="critical"&&t.pressure.cue?(r.push("context-pressure-critical"),e.push(t.pressure.cue)):t.pressure?.level==="warn"&&t.pressure.cue&&(r.push("context-pressure-warn"),e.push(t.pressure.cue)),t.qualityInject?.trim()&&(r.push("quality-ledger"),e.push(t.qualityInject.trim()));let i=t.turns??0,n=t.stuckThreshold??se;if(!t.loop?.stopped&&i>=n&&(r.push("stuck-cycle"),e.push(`\u26A0 ${i} turns on this cycle and it is still open. If you are not nearly done, STOP looping: split it, ship the slice that works, or check in with the user \u2014 then \`prjct status done\`. A re-plan beats another grinding turn.`)),e.length===0)return{level:"ok",markdown:null,cues:[]};let s=r.some(a=>["loop-hard-stop","context-pressure-critical","context-pressure-warn"].includes(a)),o=r.some(a=>["quality-ledger","stuck-cycle"].includes(a)),d=s?"hard":o?"warn":"ok",p=d==="hard"?"# prjct: alignment (MUST \u2014 hard gate)":"# prjct: alignment (mid-cycle)",g=e.join(`
9
-
10
- `),c=r.includes("quality-ledger")&&!g.includes("prjct ship")?`
11
-
12
- _${H}_`:"";return{level:d,cues:r,markdown:`${p}
13
-
14
- ${g}${c}`}}l(W,"buildAlignmentCard");ie();ne();re();var Y=1500,J=15,C=8,X=420,oe=2,ce=15e3;var ae=new Set(["address","apply","check","continue","create","current","description","feedback","handle","merge","monitor","please","review","should","title","watch","write"]),j=new WeakMap,b=new Map;async function Z(t,r){let e=r!==void 0?r:await v.readConfig(t);if(!e?.projectId)return null;let i=ue(e,t),n=["# prjct: project state"];try{let o=await U(e.projectId,t);if(o.current){let p=ee(o.current.startedAt);n.push(`- Active work cycle: "${o.current.description}" (${p}) [${o.current.label}]`),(e.land?.mode??"advisory")!=="off"&&n.push(' \u21B3 Before session end: `prjct land` \xB7 hand-off `prjct remember context "Session close: \u2026"`');let{turns:g,loopVerdict:c,currentTask:a}=(()=>{try{let u=o.mainTaskRaw;return{turns:u?.turnCount??0,currentTask:u,loopVerdict:V(e,u)}}catch{return{turns:0,currentTask:null,loopVerdict:null}}})();!c?.stopped&&g<J&&n.push(" \u21B3 Stay on this goal. Each turn, before acting: is this step ADVANCING it? If you have hit the same wall twice, or you are exploring rather than progressing, STOP \u2014 re-plan, split the cycle, or ask the user. Do not loop; finish the cycle, then `prjct status done`.");try{let u=e.maxTokensPerCycle??0;if(u>0&&a){let m=(a.tokensIn??0)+(a.tokensOut??0);m>=u?n.push(` \u26A0 Token budget: ${m.toLocaleString()} of ${u.toLocaleString()} spent on this cycle. STOP growing it \u2014 ship the working slice, split the remainder into a new cycle, or check in with the user.`):m>=u*.8&&n.push(` \u21B3 Token budget: ${m.toLocaleString()} of ${u.toLocaleString()} (${Math.round(m/u*100)}%). Plan the close: prefer finishing over expanding scope.`)}}catch{}try{let u=o.current.startedAt;if(u){let m=R.get(e.projectId,`SELECT COUNT(DISTINCT json_extract(data, '$.file')) AS c
15
- FROM events WHERE type = 'memory.post_edit' AND timestamp >= ?`,u)?.c??0,w=O(m);w&&n.push(` ${w}`)}}catch{}try{let u=F(e,a),m=L(e.projectId),w=W({loop:c,pressure:u,qualityInject:m,turns:g,stuckThreshold:J});w.markdown&&(n.push(""),n.push(w.markdown))}catch{}a?.ownerAgent&&n.push(`- Owner: ${a.ownerAgent}${a.ownerIdentity?`/${a.ownerIdentity}`:""}${a.yieldStatus==="yielded"?" (yielded \u2014 awaiting accept)":""}`)}let d=o.all.filter(p=>!p.isCurrent);d.length>0&&n.push(`- ${d.length} task(s) active in other workspace(s)`),!o.current&&d.length>0&&n.push("- This workspace idle but siblings busy \u2014 `prjct work` auto-isolates to a worktree when needed")}catch{}let s=await i;for(let o of s)o&&n.push(o);return n.length===1?null:n.join(`
16
- `)}l(Z,"buildProjectState");function ue(t,r){return Promise.all([(async()=>{try{let{formatPendingHandoffCue:e}=await import("./agent-switch-2U2LOBGR.mjs"),i=e(t.projectId);return i?`- ${i.replace(/\n/g,`
17
- - `)}`:null}catch{return null}})(),(async()=>{try{let e=await M.getActiveTasks(t.projectId);return e.length>0?`- Pending: ${e.length} \xB7 Next: "${e[0].description}"`:null}catch{return null}})(),(async()=>{try{if(!await G(h.join(r,".git")))return null;let e=await ge(r);if(!e.branch)return null;let i=[];e.modified>0&&i.push(`${e.modified} modified`),e.staged>0&&i.push(`${e.staged} staged`),e.untracked>0&&i.push(`${e.untracked} untracked`);let n=i.length>0?` \u2014 working tree ${i.join(", ")}`:"",s=e.ahead>0?`${n?",":" \u2014"} ${e.ahead} unpushed`:"";return`- Branch: ${e.branch}${n}${s}`}catch{return null}})(),(async()=>{try{let e=await _.getRecent(t.projectId,1);if(e.length===0)return null;let i=e[0],n=ee(i.shippedAt??"");return`- Last ship: ${i.version?`v${i.version}`:i.name} (${n})`}catch{return null}})(),(async()=>{try{let e=I.countByType(t.projectId,"inbox");return e>0?`- Inbox: ${e} items pending`:null}catch{return null}})()])}l(ue,"collectSecondarySignals");function le(t){return t.type==="voice"||t.type==="glossary"?!0:t.type==="example"&&!!t.tags.domain&&(t.tags.polarity==="good"||t.tags.polarity==="bad")}l(le,"isValidGuidanceEntry");function de(t,r){try{let e=A(r),i=T(r).filter(c=>c.length>=5&&!ae.has(c)),n=i.length>0?I.searchFts(t,i,C*2):[],s=e?I.recall(t,{types:["voice","glossary","example"],limit:C*2}).filter(c=>c.tags.domain==="delivery"||c.tags.domain===e):[],o=new Map([...n,...s].map(c=>[c.id,c])),d=new Map([["voice",0],["glossary",1],["example",2]]),p=[...o.values()].filter(le).sort((c,a)=>(d.get(c.type)??3)-(d.get(a.type)??3)).slice(0,oe);if(p.length===0)return null;let g=["# prjct: selective guidance"];for(let c of p){let a=c.type==="example"?` ${c.tags.polarity}/${c.tags.domain}`:c.tags.domain?` ${c.tags.domain}`:"",u=X-g.join(`
18
- `).length-a.length-8;if(u<24)break;let m=k(c.content.replace(/\s+/g," ").trim(),Math.min(150,u));g.push(`- ${c.type}${a}: ${m}`)}return g.length===1?null:{text:k(g.join(`
19
- `),X),memoryIds:p.slice(0,g.length-1).map(c=>c.id)}}catch{return null}}l(de,"buildSelectiveGuidance");function pe(t,r){if(!r)return t;let e=t?`${t}
20
-
21
- ${r}`:r;return e.length<=Y?e:null}l(pe,"appendPromptSection");function Q(t,r){try{let e=T(r);if(e.length===0)return null;let i=I.searchFts(t,e,C),n=i.find(s=>s.type==="decision"||s.type==="gotcha"||s.type==="fact")??i.find(s=>s.type==="anti-pattern"||s.type==="pattern")??i.find(s=>s.type==="gotcha"||s.type==="anti-pattern");return n?n.type==="decision"||n.type==="gotcha"||n.type==="fact"?{cue:`> Tip\u2192user (SoT): ${S(n)} \`${n.id}\` \u2014 say it briefly in chat; binding \u2014 do not contradict without superseding`,memoryId:n.id}:n.type==="anti-pattern"||n.type==="pattern"?{cue:`> Tip\u2192user (suggest): ${S(n)} \`${n.id}\` \u2014 propose the live change in chat, then apply when editing`,memoryId:n.id}:{cue:`> Tip\u2192user: ${S(n)} \`${n.id}\``,memoryId:n.id}:null}catch{return null}}l(Q,"buildTopicalCueResult");function Ke(t,r,e){return Q(t,r)?.cue??null}l(Ke,"buildTopicalCue");var y=new Map,P={skipDiskSnapshotOnce:!1};function We(){y.clear(),P.skipDiskSnapshotOnce=!0}l(We,"_resetGitSnapshotCacheForTests");async function ge(t){let r=await f.stat(h.join(t,".git","index")).then(o=>o.mtimeMs).catch(()=>0),e=y.get(t);if(e&&e.expiresAt>Date.now()&&e.indexMtimeMs===r)return e.snapshot;let i=me(t);if(!e&&!P.skipDiskSnapshotOnce){let o=await f.readFile(i,"utf-8").then(d=>JSON.parse(d)).catch(()=>null);if(o&&o.expiresAt>Date.now()&&o.indexMtimeMs===r)return y.set(t,o),o.snapshot}P.skipDiskSnapshotOnce=!1;let n=await ye(t);y.size>32&&y.clear();let s={snapshot:n,expiresAt:Date.now()+ce,indexMtimeMs:r};return y.set(t,s),f.mkdir(h.dirname(i),{recursive:!0}).then(()=>f.writeFile(i,JSON.stringify(s))).catch(()=>{}),n}l(ge,"captureGit");function me(t){let r=E("sha1").update(h.resolve(t)).digest("hex").slice(0,16);return h.join(x.runDir(),`prompt-git-${r}.json`)}l(me,"gitSnapshotPath");function he(t,r){let e=E("sha1").update(h.resolve(r)).digest("hex").slice(0,12);return`${t.replace(/[^a-zA-Z0-9._-]/g,"_")}-${e}`}l(he,"promptHashKey");async function fe(t,r,e){let i=he(t,r),n=E("sha256").update(e).digest("hex");if(b.get(i)===n)return null;b.size>64&&b.clear(),b.set(i,n);let s=h.join(x.runDir(),`prompt-state-${i}.hash`);return(await f.readFile(s,"utf-8").catch(()=>"")).trim()===n?null:(await f.mkdir(h.dirname(s),{recursive:!0}).then(()=>f.writeFile(s,n)).catch(()=>{}),e)}l(fe,"dedupePromptPayload");async function ye(t){let r={branch:"",modified:0,staged:0,untracked:0,ahead:0},e=l(async c=>{try{return(await D("git",c,{cwd:t,timeout:2e3})).stdout.trim()}catch{return""}},"safe"),[i,n,s]=await Promise.all([e(["branch","--show-current"]),e(["status","--porcelain"]),e(["rev-list","--count","@{u}..HEAD"])]);if(!i)return r;let{modified:o,staged:d,untracked:p}=n.split(`
22
- `).filter(Boolean).reduce((c,a)=>{let u=a.slice(0,2);return u.startsWith("??")?c.untracked++:(u[0]!==" "&&u[0]!=="?"&&c.staged++,u[1]!==" "&&c.modified++),c},{modified:0,staged:0,untracked:0}),g=Number.parseInt(s,10)||0;return{branch:i,modified:o,staged:d,untracked:p,ahead:g}}l(ye,"captureGitUncached");function ee(t){if(!t)return"unknown";let r=Date.parse(t);if(Number.isNaN(r))return"unknown";let e=Math.max(0,Math.floor((Date.now()-r)/864e5));return e<1?"today":e<2?"yesterday":e<30?`${e}d ago`:`${Math.floor(e/30)}mo ago`}l(ee,"formatRelative");function te(t,r,e){let i=Q(t,r),n=N(t,r),s=z(r),o=de(t,r),d=[i?.cue,s,o?.text,n].filter(a=>!!a).reduce((a,u)=>pe(a,u)??a,k(e,Y)),p=!!(o?.text&&d.includes(o.text)),c=!!(s&&d.includes(s))?`delivery:${A(r)??"unknown"}`:p?o?.memoryIds[0]??null:null;return{prioritized:d,cueResult:i,guidance:o,guidanceIncluded:p,guidanceRuleId:c}}l(te,"computePromptGuidance");function Je(t=process.cwd(),r){return q({event:"UserPromptSubmit",projectPath:t,build:l(async(e,i)=>{let n=(e.prompt??"").trim();if(!n)return null;let s=await v.readConfig(i);if(!s?.projectId)return null;let o=await Z(i,s);if(!o)return null;let{prioritized:d,cueResult:p,guidance:g,guidanceIncluded:c,guidanceRuleId:a}=te(s.projectId,n,o);return j.set(e,{projectId:s.projectId,projectPath:i,bumpTurn:o.includes("Active work cycle:"),surfacedIds:[...p?[p.memoryId]:[],...c?g?.memoryIds??[]:[]],guidanceRuleId:a}),fe(s.projectId,i,d)},"build"),afterEmit:l(async(e,i)=>{let n=j.get(e)??await we(e,i);j.delete(e),n&&await Promise.all([n.bumpTurn?$.bumpTurnCount(n.projectId).then(()=>{}):Promise.resolve(),n.surfacedIds.length>0?B(n.projectId,n.projectPath,n.surfacedIds):Promise.resolve(),n.guidanceRuleId?Promise.resolve(K.recordGuidanceActivation(n.projectId,{ruleId:n.guidanceRuleId})).then(()=>{}):Promise.resolve()])},"afterEmit")},r)}l(Je,"runPromptHook");async function we(t,r){let e=(t.prompt??"").trim();if(!e)return null;let i=await v.readConfig(r).catch(()=>null);if(!i?.projectId)return null;let[n,s]=await Promise.all([$.getCurrentTask(i.projectId).catch(()=>null),Z(r,i)]),{cueResult:o,guidance:d,guidanceIncluded:p,guidanceRuleId:g}=te(i.projectId,e,s??"");return{projectId:i.projectId,projectPath:r,bumpTurn:!!n,surfacedIds:[...o?[o.memoryId]:[],...p?d?.memoryIds??[]:[]],guidanceRuleId:g}}l(we,"rebuildPromptAfterEmit");export{We as _resetGitSnapshotCacheForTests,z as buildDeliveryGuidance,Z as buildProjectState,de as buildSelectiveGuidance,Ke as buildTopicalCue,A as classifyDeliveryIntent,Je as runPromptHook};
@@ -1,8 +0,0 @@
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{b as k}from"./chunk-GFY4GY3Z.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-SJ75V4WG.mjs";import{b as P}from"./chunk-JMCMTX6U.mjs";import"./chunk-R4ILCXKE.mjs";import{b as O,c as U}from"./chunk-QPRNRLG6.mjs";import{a as Y}from"./chunk-TKWAFYF7.mjs";import"./chunk-7JEKBJAP.mjs";import{a as Z,b as j,c as S,d as ee,e as te,f as C,g as T,h as ne,i as re}from"./chunk-MHQTGU45.mjs";import"./chunk-MI3JEFON.mjs";import"./chunk-Y5NQV46G.mjs";import{a as I,h as L}from"./chunk-DXQMKW2B.mjs";import{a as H,e as G,f as z,g as J,h as q,i as K,j as Q}from"./chunk-NWZEBCTC.mjs";import{a as x}from"./chunk-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import{c as A}from"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import{a as w,b as V,e as D,g as B}from"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import{b as M,g as F}from"./chunk-GCKILEXJ.mjs";import"./chunk-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as p}from"./chunk-E66B27AL.mjs";V();B();var W=new Set(["decision","gotcha","learning","feedback","fact","shipped","spec"]),se=30,oe=50,ie=20,ce=45,ae=25,de=15,ue=180,$=90,le=25,pe=.12,me=40,fe=40,he=30,ge=20,xe=35,Ee=.12,ye=864e5,Re=100,ve=50,be=25,_e=15,De=/\b[\w.-]+(?:\/[\w.-]+)+\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|sh|toml|yml|yaml)\b/g;function Ae(e,t){let o=x.allEntriesForIndex(e),r=new Set;for(let c of o)for(let l of O(c.tags))r.add(l);let n=(()=>{try{let c=P(e);return c?new Set(Object.keys(c.documents)):null}catch{return null}})(),a=S(o),i=C(a);return{entries:o,usefulness:U.decayedScores(e,t),supersededIds:F(o),correctedIds:r,indexedPaths:n,nowMs:t,refIndex:i}}p(Ae,"collectRetentionInputs");function Se(e){let t=new Map,o=new Set,r=[...e].sort((n,a)=>a.rememberedAt.localeCompare(n.rememberedAt));for(let n of r){let a=w(n.content);t.has(a)?o.add(n.id):t.set(a,n)}return o}p(Se,"collectDuplicateIds");function Me(e,t){let o=e.content.match(De);return!o||o.length===0?!1:!o.some(r=>t.has(r))}p(Me,"isUngrounded");function Ie(e,t,o){let r=[],n=T(e.content,t.refIndex,e.id),a=o.has(e.id);a&&!n.exactDup&&r.push("duplicate of newer entry"),r.push(`excess ${n.excess.toFixed(2)} (sim ${n.maxSim.toFixed(2)})`);let i=n.exactDup||n.nearDup||n.excess<Ee;i&&r.push(n.exactDup?`exact dup of ${n.nearestId}`:n.nearDup?`near-dup of ${n.nearestId}`:"low excess vs reference");let c=t.usefulness.get(e.id)??0,l=Math.min(ae,Math.max(0,c*8));c>0&&r.push(`used (+${Math.round(l)})`);let u=Math.max(0,(t.nowMs-Date.parse(e.rememberedAt))/ye),h=Number.isFinite(u)?Math.max(0,de*(1-u/ue)):0,s=c<=0&&Number.isFinite(u)&&u>$?Math.min(le,(u-$)*pe):0;s>0&&r.push(`idle ${Math.round(u)}d`);let f=t.supersededIds.has(e.id);f&&r.push("superseded");let m=t.correctedIds.has(e.id);m&&r.push("corrected");let b=!M(e)||k(e);b&&r.push("generated noise");let E=!!(t.indexedPaths&&Me(e,t.indexedPaths));E&&r.push("cites files missing at HEAD");let g=Math.max(0,Math.min(100,n.excess*ce+l+h-(i?xe:0)-s-(f?me:0)-(m?fe:0)-(b?he:0)-(E?ge:0)-(a?20:0))),R=g>=oe?"active":g>=ie?"archive":"delete",_=a||n.exactDup||n.nearDup||f,y=R!=="active"&&u<se&&!_?"active":R;y!==R&&r.push("grace period");let d=y==="delete"&&W.has(e.type)?"archive":y;return d!==y&&r.push("protected type"),{id:e.id,type:e.type,verdict:d,score:Math.round(g),reasons:r,excess:n.excess,maxSim:n.maxSim,nearestId:n.nearestId}}p(Ie,"scoreEntry");function X(e,t){let o=Ae(e,t),r=Se(o.entries),n={evaluated:o.entries.length,active:0,archive:0,delete:0,referenceSize:o.refIndex.entries.length,flagged:[],byId:new Map};for(let a of o.entries){let i=Ie(a,o,r);n[i.verdict]++,n.byId.set(i.id,i),i.verdict!=="active"&&n.flagged.push(i)}return n.flagged.sort((a,i)=>a.score-i.score),n}p(X,"evaluateRetention");function Be(e,t){return!(!M(e)||e.content.trim().length===0||t&&t.verdict!=="active"||t&&t.excess!==void 0&&t.excess<.05)}p(Be,"shouldEmbedEntry");function v(e,t){if(t.startsWith("ship_"))return Ce(e,t);if(x.forget(e,t))return!0;try{return(D.run(e,"UPDATE memory_entries SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL",Date.now(),t).changes??0)>0}catch{return!1}}p(v,"forgetEntry");function N(e){return e.startsWith("mem_")||e.startsWith("ship_")||/^\d+$/.test(e)}p(N,"isRetentionRemovableId");function Ce(e,t){let o=t.startsWith("ship_")?t.slice(5):t;if(!o)return!1;try{let r=D.get(e,"SELECT * FROM shipped_features WHERE id = ?",o);if(!r)return!1;try{A.archive(e,{entityType:"shipped",entityId:o,entityData:r,summary:`retention archive shipped [${r.name}]`,reason:"retention-archive"})}catch{}return(D.run(e,"DELETE FROM shipped_features WHERE id = ?",o).changes??0)>0}catch{return!1}}p(Ce,"forgetShippedFeature");function Te(e,t={}){let o=t.dryRun===!0,r=t.nowMs??Date.now(),n=t.maxArchive??Re,a=t.maxDelete??ve,i=X(e,r),c=i.flagged.filter(s=>s.verdict==="archive"&&N(s.id)),l=i.flagged.filter(s=>s.verdict==="delete"&&N(s.id)),u=i.flagged.filter(s=>(s.verdict==="archive"||s.verdict==="delete")&&!N(s.id)).length,h=o?{archived:0,deleted:0,skipped:u}:(()=>{let s=c.slice(0,n),f=s.map(d=>{if(!d.id.startsWith("ship_"))try{A.archive(e,{entityType:"memory_entry",entityId:d.id,entityData:{id:d.id,type:d.type,score:d.score,excess:d.excess,reasons:d.reasons,verdict:d.verdict},summary:`retention archive [${d.type}] excess=${d.excess?.toFixed(2)??"?"} score=${d.score}`,reason:"retention-archive"})}catch{}return v(e,d.id)}),m=f.filter(Boolean).length,b=Math.max(0,c.length-s.length)+f.filter(d=>!d).length,E=l.slice(0,a),g=E.filter(d=>!W.has(d.type)).map(d=>d.id),R=E.length-g.length,_=g.length>0?Y(e,g):0,y=Math.max(0,l.length-E.length)+R+g.length-_;return{archived:m,deleted:_,skipped:u+b+y}})();return{evaluated:i.evaluated,active:i.active,wouldArchive:c.length,wouldDelete:l.length,archived:h.archived,deleted:h.deleted,skipped:h.skipped,dryRun:o,samples:i.flagged.slice(0,10),referenceSize:i.referenceSize}}p(Te,"applyRetention");function He(e){return Te(e,{maxArchive:be,maxDelete:_e})}p(He,"applyRetentionIncremental");function Ge(e,t={}){let o=t.max??50,r=t.types??["inbox","context","idea","todo","question","gotcha","spec"],n=[],a=[];try{let i=x.allEntriesForIndex(e);for(let c of i){if(n.length>=o)break;if(!r.includes(c.type))continue;let l=I(c.content,c.type),u=L(c.content,c.type);(l.junk||u.action==="refuse"||c.type==="gotcha"&&u.action==="demote")&&v(e,c.id)&&(n.push(c),a.length<8&&a.push(`${c.id}:${l.junk?l.reason:u.reasonCode}`))}}catch{return{forgotten:0,samples:[]}}return{forgotten:n.length,samples:a}}p(Ge,"forgetJunkCaptures");function ze(e,t=Date.now()){let r=x.allEntriesForIndex(e).filter(s=>s.type==="inbox");if(r.length===0)return{merged:0,archived:0,junkForgotten:0};let n=r.filter(s=>I(s.content,s.type).junk&&v(e,s.id)).length,a=x.allEntriesForIndex(e).filter(s=>s.type==="inbox");if(a.length===0)return{merged:0,archived:0,junkForgotten:n};let i=S(x.allEntriesForIndex(e)),c=C(i),l=X(e,t),u=[],h=[];for(let s of a){let f=T(s.content,c);if(f.exactDup||f.nearDup||f.excess<.15){v(e,s.id)&&u.push(s.id);continue}let m=l.byId.get(s.id);if(m&&m.verdict!=="active"){try{A.archive(e,{entityType:"memory_entry",entityId:s.id,entityData:{id:s.id,type:"inbox",score:m.score,excess:m.excess,reasons:m.reasons},summary:`inbox triage excess=${m.excess?.toFixed(2)??"?"}`,reason:"retention-inbox"})}catch{}v(e,s.id)&&h.push(s.id)}}return{merged:u.length,archived:h.length,junkForgotten:n}}p(ze,"triageInbox");export{te as CAPTURE_MIN_EXCESS,H as DEFAULT_SOFT_DELETED_PURGE_DAYS,ee as NEAR_DUP_SIM,W as PROTECTED_TYPES,Z as REFERENCE_CAP,Te as applyRetention,He as applyRetentionIncremental,S as buildReferenceModel,re as captureGate,Se as collectDuplicateIds,Ae as collectRetentionInputs,ne as computeExcess,X as evaluateRetention,Ge as forgetJunkCaptures,Ce as forgetShippedFeature,G as isAutoSource,j as isReferenceEligible,N as isRetentionRemovableId,J as purgeOrphanRememberEvents,z as purgeSoftDeleted,Q as runVaultPurge,Ie as scoreEntry,Be as shouldEmbedEntry,ze as triageInbox,q as trimAutoSourceCap,K as vaultHealth};
@@ -1,8 +0,0 @@
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,b,c,d}from"./chunk-NUJASVHN.mjs";import"./chunk-HRWXMF7P.mjs";import"./chunk-ZJXH76Q5.mjs";import"./chunk-PUHX3ECX.mjs";import"./chunk-Q3EYM4GJ.mjs";import"./chunk-AZYQFRPJ.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-HHIGNKDO.mjs";import"./chunk-7GNWHWOO.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-QPRNRLG6.mjs";import"./chunk-7JEKBJAP.mjs";import"./chunk-MI3JEFON.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-27XFSCOE.mjs";import"./chunk-YUKGWWL7.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-5EQLQ7GF.mjs";import"./chunk-UA4Z5TGG.mjs";import"./chunk-TG5CQJD5.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-DRGI5UHQ.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-AZHE4VOM.mjs";import"./chunk-6RLCUGGG.mjs";import"./chunk-KG7Z6OMK.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-JAMSIKDE.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-EMTCZG5I.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{c as buildProjectIdentityLine,a as buildSessionContext,b as buildSubagentDigest,d as runSessionStartHook};