prjct-cli 3.95.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.
- package/CHANGELOG.md +5 -0
- package/dist/bin/hook-chunks/{agent-identity-45BYQBU2.mjs → agent-identity-DH6DX72X.mjs} +1 -1
- package/dist/bin/hook-chunks/{agent-switch-4ZJJWKMD.mjs → agent-switch-I4MTVE56.mjs} +1 -1
- package/dist/bin/hook-chunks/{analysis-UGHAG2SK.mjs → analysis-VN7APBHR.mjs} +3 -3
- package/dist/bin/hook-chunks/{auto-flush-CXWTU3RF.mjs → auto-flush-DX3FVSQE.mjs} +1 -1
- package/dist/bin/hook-chunks/{capture-gate-PS6QUXLX.mjs → capture-gate-MEIQD7ZS.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-YDBZO6I3.mjs → chunk-22GFTUER.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-OGIFB3OE.mjs → chunk-33BHU4OM.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-QL3NYJTW.mjs → chunk-3AHW4XQH.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-DCSKTMDX.mjs → chunk-3CKNJ5RA.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-ABJNOG2I.mjs → chunk-3FEXJUO2.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-22AXWLI6.mjs → chunk-3HGQPUKG.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-EWOK4VE7.mjs → chunk-3UB6SFRA.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-OUAVSD47.mjs → chunk-64ZEBHDX.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-X5W2UYQK.mjs → chunk-7PBWIO4K.mjs} +3 -3
- package/dist/bin/hook-chunks/{chunk-QP5USCDX.mjs → chunk-7WO5CEH3.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-N3L77UNM.mjs → chunk-ADYTBOCZ.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-RTEEXGEA.mjs → chunk-AORD3YDQ.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-Z6KVLCMK.mjs → chunk-BKJHD5JI.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-4NTVXJD7.mjs → chunk-BVK7ZDLX.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-IGHY4FGS.mjs → chunk-CPR4FPXG.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-XXRAQZNC.mjs → chunk-D7DQABWO.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-5H3KJWQS.mjs → chunk-DB226JIV.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-ZFLIVOFX.mjs → chunk-DCHIPMOG.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-U4OON3S7.mjs → chunk-E7NA34VQ.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-PTA7DMLM.mjs → chunk-EGCYDLSO.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-PP6DANGV.mjs → chunk-EI6VQZOX.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-5XA5RL5I.mjs → chunk-ETTDRXQ6.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-FW4MEPTB.mjs → chunk-EXVL2OFE.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-I26F7TLM.mjs → chunk-FZS3XGEA.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-IWJG7CZX.mjs → chunk-GSPDJSJ5.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-S5N2ZZDL.mjs → chunk-H2DGDAQP.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-H5AVBDCH.mjs +8 -0
- package/dist/bin/hook-chunks/{chunk-HEDZA6KC.mjs → chunk-HGZQWYBL.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-GCDLPKOH.mjs → chunk-IJ523YO2.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-6GAFRIUQ.mjs → chunk-IWUF2LGO.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-Z4X7JIAP.mjs → chunk-JGZ3QGWX.mjs} +3 -3
- package/dist/bin/hook-chunks/{chunk-ROA2AJXY.mjs → chunk-JZDZH6IV.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-BOBFTVAY.mjs → chunk-KDNUQPAK.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-KV4NXLPT.mjs +11 -0
- package/dist/bin/hook-chunks/{chunk-WGWE3CSC.mjs → chunk-LF3S3MYE.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-LQLCYBFF.mjs +36 -0
- package/dist/bin/hook-chunks/{chunk-S5ISOGDB.mjs → chunk-LR24AIEW.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-FXFG6PV6.mjs → chunk-M4YM7Z3F.mjs} +15 -15
- package/dist/bin/hook-chunks/{chunk-S6L3FECF.mjs → chunk-MW54MTLB.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-J5UQVJUW.mjs → chunk-NCLONKOT.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-QBYHZX33.mjs → chunk-NJ74RHNC.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-GDESYWTD.mjs → chunk-NLL5AV2G.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-GLPKMG5A.mjs → chunk-OLQAMCYV.mjs} +10 -10
- package/dist/bin/hook-chunks/{chunk-KSSRINDX.mjs → chunk-PPWPUEBH.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-PVCEWFHS.mjs +51 -0
- package/dist/bin/hook-chunks/{chunk-PGWFGRX4.mjs → chunk-QOQZHR3E.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-2UC4DTDO.mjs → chunk-QXCEBAIA.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-RT2DFIWF.mjs +19 -0
- package/dist/bin/hook-chunks/{chunk-BDOAQVIF.mjs → chunk-SQW2B7NW.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-NLKPAJND.mjs → chunk-SWJ7TLBD.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-GDECEHO5.mjs → chunk-TB57OYGW.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-4HAKTI36.mjs → chunk-TF6PN7IB.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-UHVYBU7F.mjs → chunk-TKXOMN4K.mjs} +4 -4
- package/dist/bin/hook-chunks/{chunk-G7QQZMAO.mjs → chunk-UMJ5D5I6.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-UYQC63MC.mjs → chunk-UVATSTRF.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-BX7VKYA7.mjs → chunk-WJV24WE6.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-76GDLA3Z.mjs → chunk-WL6PKX3U.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-WUOVBBPC.mjs +11 -0
- package/dist/bin/hook-chunks/{chunk-T6ELTQZM.mjs → chunk-XSJ7SPVR.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-DVDZA63F.mjs → chunk-XV2LJVYB.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-C4O243NG.mjs → chunk-XYKVWO23.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-MHNWIB7B.mjs → chunk-Y3RHBU2R.mjs} +2 -2
- package/dist/bin/hook-chunks/{chunk-RHKF7EJW.mjs → chunk-Y7MZA2G4.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-ZOX6OV6X.mjs → chunk-YHOZTAZH.mjs} +1 -1
- package/dist/bin/hook-chunks/chunk-YLOK4WRR.mjs +8 -0
- package/dist/bin/hook-chunks/{chunk-3WQBTXUC.mjs → chunk-ZJW27EUC.mjs} +1 -1
- package/dist/bin/hook-chunks/{chunk-J5UVRZ44.mjs → chunk-ZQI4TJ5C.mjs} +3 -3
- package/dist/bin/hook-chunks/chunk-ZYCNW75E.mjs +9 -0
- package/dist/bin/hook-chunks/{chunk-PO3QDKTE.mjs → chunk-ZZBNFNMG.mjs} +1 -1
- package/dist/bin/hook-chunks/{client-CRXA774S.mjs → client-K3ZA2BLB.mjs} +1 -1
- package/dist/bin/hook-chunks/{code-graph-cloud-GTSLO7CD.mjs → code-graph-cloud-XGQF7XYC.mjs} +1 -1
- package/dist/bin/hook-chunks/{codex-skill-NUBNPSMF.mjs → codex-skill-6CRFUF3A.mjs} +1 -1
- package/dist/bin/hook-chunks/{command-installer-UHSXC3UG.mjs → command-installer-MUHZWDZA.mjs} +1 -1
- package/dist/bin/hook-chunks/{config-manager-DX5OOPW5.mjs → config-manager-2JJPCLKC.mjs} +1 -1
- package/dist/bin/hook-chunks/{context7-service-GDJ3QICX.mjs → context7-service-NH4BMGSJ.mjs} +1 -1
- package/dist/bin/hook-chunks/{custom-workflow-storage-FD47DPA3.mjs → custom-workflow-storage-VBMWLKA7.mjs} +1 -1
- package/dist/bin/hook-chunks/cwd-changed-UTD6Y4MS.mjs +8 -0
- package/dist/bin/hook-chunks/{database-ZUC7OEZG.mjs → database-ZCP76LMM.mjs} +1 -1
- package/dist/bin/hook-chunks/{detect-changes-OJUBWWTU.mjs → detect-changes-5W6EGEZG.mjs} +1 -1
- package/dist/bin/hook-chunks/{developer-evolution-WNSTHDAA.mjs → developer-evolution-UTY3CWOK.mjs} +1 -1
- package/dist/bin/hook-chunks/{distill-GOGPFQFK.mjs → distill-5TNAM3LY.mjs} +1 -1
- package/dist/bin/hook-chunks/{enriched-recall-QF22RIK7.mjs → enriched-recall-6VOIUNLN.mjs} +1 -1
- package/dist/bin/hook-chunks/{format-J3X3R225.mjs → format-IIOFTSBF.mjs} +1 -1
- package/dist/bin/hook-chunks/{judgment-ledger-storage-FE4HXTHM.mjs → judgment-ledger-storage-7Q7AEEY6.mjs} +1 -1
- package/dist/bin/hook-chunks/{judgment-orchestrator-YDJTKNV2.mjs → judgment-orchestrator-AAON4ZJ4.mjs} +1 -1
- package/dist/bin/hook-chunks/{judgment-receipt-7A2DXVJA.mjs → judgment-receipt-QLV3MYFT.mjs} +1 -1
- package/dist/bin/hook-chunks/{land-cue-SZWJH6XP.mjs → land-cue-57B23PEL.mjs} +1 -1
- package/dist/bin/hook-chunks/{land-synthesis-JLYUBKHR.mjs → land-synthesis-ZVPFJERV.mjs} +1 -1
- package/dist/bin/hook-chunks/{legacy-crew-sweep-JXYO62UE.mjs → legacy-crew-sweep-GR6HRSHX.mjs} +2 -2
- package/dist/bin/hook-chunks/{memory-index-CIYDXN2G.mjs → memory-index-XE2MWKQS.mjs} +1 -1
- package/dist/bin/hook-chunks/{notification-UA7RTVHG.mjs → notification-GU2ZJP5K.mjs} +1 -1
- package/dist/bin/hook-chunks/{pack-integrity-GZC5NGFN.mjs → pack-integrity-WV5U3AFF.mjs} +1 -1
- package/dist/bin/hook-chunks/{pack-manager-AF5F7PRT.mjs → pack-manager-QLFQKP24.mjs} +1 -1
- package/dist/bin/hook-chunks/{planning-M3RAOZVB.mjs → planning-VPAX5DZL.mjs} +2 -2
- package/dist/bin/hook-chunks/{post-edit-QRDYPZLZ.mjs → post-edit-UXCFSR3Y.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-bash-TWWFVNQ7.mjs → pre-bash-MB4JNNYG.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-commit-PTFF7JIN.mjs → pre-commit-U7TRFKWX.mjs} +1 -1
- package/dist/bin/hook-chunks/pre-edit-MDCQXI5F.mjs +11 -0
- package/dist/bin/hook-chunks/{pre-package-325ALZKD.mjs → pre-package-A6ZI5R64.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-search-GOHVFAFH.mjs → pre-search-ZZO3LGXJ.mjs} +1 -1
- package/dist/bin/hook-chunks/{pre-secrets-MYNM5KI4.mjs → pre-secrets-MWPPZPWK.mjs} +1 -1
- package/dist/bin/hook-chunks/{prjct-md-RCB6FWD6.mjs → prjct-md-MS52YLI2.mjs} +1 -1
- package/dist/bin/hook-chunks/{project-agent-surfaces-V4P5RTUR.mjs → project-agent-surfaces-6AIW7KL6.mjs} +1 -1
- package/dist/bin/hook-chunks/{project-file-inventory-OKIP4LBO.mjs → project-file-inventory-HHURZTMH.mjs} +1 -1
- package/dist/bin/hook-chunks/project-memory-UDH56VFP.mjs +8 -0
- package/dist/bin/hook-chunks/{project-style-evolution-RPGATIYJ.mjs → project-style-evolution-IJXT2MCP.mjs} +1 -1
- package/dist/bin/hook-chunks/prompt-7VZLYONO.mjs +24 -0
- package/dist/bin/hook-chunks/{publish-helper-SX7HEV2L.mjs → publish-helper-ZSL27HSX.mjs} +1 -1
- package/dist/bin/hook-chunks/{purge-XKHUAB4H.mjs → purge-N2WN6NDB.mjs} +1 -1
- package/dist/bin/hook-chunks/retention-RET4P2RO.mjs +8 -0
- package/dist/bin/hook-chunks/{sdd-6PF7MBAY.mjs → sdd-PB6WKSLE.mjs} +1 -1
- package/dist/bin/hook-chunks/{session-continuity-UEXQDGZE.mjs → session-continuity-BIJXMN44.mjs} +1 -1
- package/dist/bin/hook-chunks/session-start-R2VMKW2L.mjs +8 -0
- package/dist/bin/hook-chunks/settings-installer-CQKMGMRG.mjs +9 -0
- package/dist/bin/hook-chunks/{setup-ZOHG6MGF.mjs → setup-PPIZHVXS.mjs} +3 -3
- package/dist/bin/hook-chunks/{shipping-QVGTOO6U.mjs → shipping-C637PCOF.mjs} +4 -4
- package/dist/bin/hook-chunks/{skill-index-FGDQVYHM.mjs → skill-index-55I3HLAI.mjs} +1 -1
- package/dist/bin/hook-chunks/{spec-context-inference-6Z52BT37.mjs → spec-context-inference-RTTDOZZO.mjs} +1 -1
- package/dist/bin/hook-chunks/{spec-service-UAQ5AEXQ.mjs → spec-service-ENLAAMVL.mjs} +2 -2
- package/dist/bin/hook-chunks/{spec-task-breakdown-LAXGVLMY.mjs → spec-task-breakdown-RUDEP3AY.mjs} +1 -1
- package/dist/bin/hook-chunks/{state-storage-XU35ZYNA.mjs → state-storage-AJUPG7J5.mjs} +1 -1
- package/dist/bin/hook-chunks/stop-DPXAWJFN.mjs +16 -0
- package/dist/bin/hook-chunks/subagent-start-AFHPXL2S.mjs +8 -0
- package/dist/bin/hook-chunks/{subagent-stop-OUG4PR7S.mjs → subagent-stop-5BMV63ML.mjs} +1 -1
- package/dist/bin/hook-chunks/{surface-attribution-A6GCGRFM.mjs → surface-attribution-EGIKCVMF.mjs} +1 -1
- package/dist/bin/hook-chunks/{symbol-graph-DMPBNBX7.mjs → symbol-graph-MH42JSPX.mjs} +1 -1
- package/dist/bin/hook-chunks/{sync-cursor-storage-VVLA3L2U.mjs → sync-cursor-storage-ZB7FGT6D.mjs} +1 -1
- package/dist/bin/hook-chunks/{task-orchestration-HFZYWYLR.mjs → task-orchestration-7NGRIISS.mjs} +1 -1
- package/dist/bin/hook-chunks/{task-overview-PCUZWL5Q.mjs → task-overview-F3GB77OA.mjs} +1 -1
- package/dist/bin/hook-chunks/task-service-FZABHPFV.mjs +8 -0
- package/dist/bin/hook-chunks/{tdd-QZL4OSM7.mjs → tdd-TAMBOPN3.mjs} +1 -1
- package/dist/bin/hook-chunks/{template-loader-SKXILJLJ.mjs → template-loader-MXOMU4XH.mjs} +1 -1
- package/dist/bin/hook-chunks/{usefulness-SZLG6LVC.mjs → usefulness-TBD5EYAL.mjs} +1 -1
- package/dist/bin/hook-chunks/{vault-retire-notice-HOXPURNQ.mjs → vault-retire-notice-7XHVNHU6.mjs} +1 -1
- package/dist/bin/hook-chunks/{velocity-storage-5J6BAMCW.mjs → velocity-storage-IOCVK2LU.mjs} +1 -1
- package/dist/bin/hook-chunks/{weak-model-mode-ZRNKFTFF.mjs → weak-model-mode-BMSPGEQY.mjs} +1 -1
- package/dist/bin/hook-chunks/{work-graph-PGYHFLEL.mjs → work-graph-AVAOKY63.mjs} +1 -1
- package/dist/bin/hook-chunks/{work-scope-FIB6LBKE.mjs → work-scope-YCS4GTXW.mjs} +1 -1
- package/dist/bin/hook-chunks/{workspace-occupancy-3D4OKQRB.mjs → workspace-occupancy-JOBYNNXV.mjs} +1 -1
- package/dist/bin/hook-fast-darwin-arm64 +0 -0
- package/dist/bin/hook-fast-darwin-x64 +0 -0
- package/dist/bin/hook-fast-linux-x64 +0 -0
- package/dist/bin/prjct-core.mjs +724 -712
- package/dist/bin/prjct-hooks.mjs +3 -3
- package/dist/bin/prjct.mjs +21 -8
- package/dist/daemon/entry.mjs +617 -603
- package/dist/mcp/server.mjs +315 -301
- package/package.json +3 -5
- package/scripts/install.sh +28 -496
- package/dist/bin/hook-chunks/chunk-4KXXDQYI.mjs +0 -11
- package/dist/bin/hook-chunks/chunk-BU22R6JX.mjs +0 -9
- package/dist/bin/hook-chunks/chunk-CYZ7ST2P.mjs +0 -36
- package/dist/bin/hook-chunks/chunk-GPZP7NXL.mjs +0 -11
- package/dist/bin/hook-chunks/chunk-KHLYWNHT.mjs +0 -8
- package/dist/bin/hook-chunks/chunk-TRMBRDKH.mjs +0 -8
- package/dist/bin/hook-chunks/chunk-TXSLON7M.mjs +0 -19
- package/dist/bin/hook-chunks/chunk-V2FR2NPL.mjs +0 -43
- package/dist/bin/hook-chunks/cwd-changed-EP3UIRK6.mjs +0 -8
- package/dist/bin/hook-chunks/pre-edit-PMMWDR2B.mjs +0 -11
- package/dist/bin/hook-chunks/project-memory-JK2MXRJB.mjs +0 -8
- package/dist/bin/hook-chunks/prompt-DOENKHLQ.mjs +0 -24
- package/dist/bin/hook-chunks/retention-C3NQT65W.mjs +0 -8
- package/dist/bin/hook-chunks/session-start-B4P7L33E.mjs +0 -8
- package/dist/bin/hook-chunks/settings-installer-QDM3GB6J.mjs +0 -9
- package/dist/bin/hook-chunks/stop-CFB2H3XC.mjs +0 -16
- package/dist/bin/hook-chunks/subagent-start-KFAZZUHS.mjs +0 -8
- package/dist/bin/hook-chunks/task-service-PXCDU55T.mjs +0 -8
|
@@ -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-PGWFGRX4.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-G7QQZMAO.mjs";import{a as Ke}from"./chunk-ROA2AJXY.mjs";import{a as qe}from"./chunk-DVDZA63F.mjs";import{a as Ye}from"./chunk-ZOX6OV6X.mjs";import{a as Qe,b as At}from"./chunk-MHNWIB7B.mjs";import{a as gt,b as ht}from"./chunk-GDESYWTD.mjs";import{d as yt}from"./chunk-UYQC63MC.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-IGHY4FGS.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-22AXWLI6.mjs";import{a as mt}from"./chunk-J5UVRZ44.mjs";import{i as pt}from"./chunk-6GAFRIUQ.mjs";import{a as rt}from"./chunk-KHLYWNHT.mjs";import{b as Ze,c as et,d as tt}from"./chunk-DCSKTMDX.mjs";import{b as se}from"./chunk-R4ILCXKE.mjs";import{a as Xe}from"./chunk-S5ISOGDB.mjs";import{a as ne,b as I}from"./chunk-XXRAQZNC.mjs";import{a as Be}from"./chunk-5XA5RL5I.mjs";import{c as Je}from"./chunk-I26F7TLM.mjs";import{b as Ve}from"./chunk-QP5USCDX.mjs";import{a as We,b as Ue}from"./chunk-M5E2YOZ4.mjs";import{b as M}from"./chunk-PO3QDKTE.mjs";import{d as b,e as T,g as B}from"./chunk-UHVYBU7F.mjs";import{d as re}from"./chunk-4KXXDQYI.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-A6K4H3YT.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-FW4MEPTB.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-GTSLO7CD.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-PIRHMHXL.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 C 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 C.join(Ot(),".claude","skills")}i(Kr,"claudeSkillsRoot");function Yr(){let r=Ot();return[C.join(r,".codex","skills"),C.join(r,".gemini","skills"),C.join(r,".gemini","antigravity","global_skills"),C.join(r,".agents","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=C.join(t,o.name),l=C.join(c,"SKILL.md");await F.mkdir(c,{recursive:!0}),await F.writeFile(l,n,"utf-8"),o.reference&&o.referenceFile&&await F.writeFile(C.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=C.join(o,"prjct"),c=C.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(C.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-5J6BAMCW.mjs");await d.recompute(r)}catch(d){p.debug("Failed to recompute velocity",{error:k(d)})}let c=await import("./developer-evolution-WNSTHDAA.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-FGDQVYHM.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-JXYO62UE.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-OKIP4LBO.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:x,error:U})=>{p.debug("sync post-index work settled",{projectId:g,uploadToCloud:A,totalMs:x,...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-RPGATIYJ.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-C3NQT65W.mjs"),x=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-XKHUAB4H.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:x.evaluated,active:x.active,archive:x.wouldArchive,delete:x.wouldDelete,archived:x.archived,deleted:x.deleted,inboxMerged:U,inboxArchived:br,dryRun:S,samples:x.samples.map(j=>({id:j.id,type:j.type,verdict:j.verdict,score:j.score,reasons:j.reasons,excess:j.excess})),referenceSize:x.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,b as c,c as d,e as k,f as s,g as l,j as f}from"./chunk-Z4X7JIAP.mjs";import{a as u}from"./chunk-E66B27AL.mjs";function m(t){return typeof t=="string"?`${t}
|
|
9
|
-
`:`${JSON.stringify(t)}
|
|
10
|
-
`}u(m,"payloadLine");async function g(t,n){let i=t.projectPath??process.cwd();if(n){try{let e=n.hookHost??c(),r=n.input;if(n.afterEmitOnly){t.afterEmit&&n.detachAfterEmit(()=>t.afterEmit(r,i));return}let o=t.decide?await t.decide(r,i):null;if(o){n.sink(m(d(a(t.event,o.deny),e)));return}let H=t.build?await t.build(r,i,e):null;n.sink(m(d(f(t.event,H),e))),t.afterEmit&&n.detachAfterEmit(()=>t.afterEmit(r,i))}catch{n.sink(`{}
|
|
11
|
-
`)}return}await l(async()=>{let e=k(),r=t.decide?await t.decide(e,i):null;if(r){s(a(t.event,r.deny));return}let o=t.build?await t.build(e,i,c()):null;s(f(t.event,o)),t.afterEmit&&await t.afterEmit(e,i)})}u(g,"runHook");export{g 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{b as x}from"./chunk-SJ75V4WG.mjs";import{d as M}from"./chunk-C4O243NG.mjs";import{a as f}from"./chunk-V2FR2NPL.mjs";import{a as C}from"./chunk-QP5USCDX.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-C3NQT65W.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,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,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-V2FR2NPL.mjs";import{c as l}from"./chunk-I26F7TLM.mjs";import{e as a,g as p}from"./chunk-UHVYBU7F.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-GOGPFQFK.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-GOGPFQFK.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,43 +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}from"./chunk-S5ISOGDB.mjs";import{a as I,b as O,h as B}from"./chunk-UUULLTQV.mjs";import{a as D}from"./chunk-GAOQHD5S.mjs";import{a as T,b as W,e as u,g as k}from"./chunk-UHVYBU7F.mjs";import{c as S,d as v,e as N,f as w,g as M}from"./chunk-GCKILEXJ.mjs";import{a as h}from"./chunk-E66B27AL.mjs";k();W();B();var H=25,$=4,q=100,C=["supersedes","duplicates","superseded-by"];function L(r,e,t){let n=r.get(e);if(n!==void 0)return n;let i=t();return r.set(e,i),i}h(L,"getOrCreateMapValue");function U(r){try{let e=C.map(()=>"?").join(","),t=u.query(r,`SELECT t.entry_id, t.key, t.value
|
|
9
|
-
FROM memory_entry_tags t
|
|
10
|
-
JOIN memory_entries m ON m.id = t.entry_id
|
|
11
|
-
WHERE m.deleted_at IS NULL
|
|
12
|
-
AND t.is_machine = 0
|
|
13
|
-
AND t.key IN (${e})`,...C),n=new Map;for(let o of t){let a=L(n,o.entry_id,()=>({}));a[o.key]=o.value}let i=[...n.entries()].map(([o,a])=>({id:o,tags:a}));return M(i)}catch{return new Set}}h(U,"collectMirrorSupersededIds");function b(r,e){let t=new Map;if(e.length===0)return t;let n=e.map(()=>"?").join(","),i=u.query(r,`SELECT entry_id, key, value FROM memory_entry_tags WHERE entry_id IN (${n})`,...e);for(let o of i){let a=L(t,o.entry_id,()=>({}));a[o.key]=o.value}return t}h(b,"batchTagsByEntryId");function _(r,e,...t){let n=u.query(r,`SELECT id, type, content, provenance, created_at
|
|
14
|
-
FROM memory_entries
|
|
15
|
-
WHERE deleted_at IS NULL ${e}`,...t);if(n.length===0)return[];let i=b(r,n.map(o=>o.id));return n.map(o=>({id:o.id,type:o.type,content:o.content,tags:i.get(o.id)??{},rememberedAt:new Date(o.created_at).toISOString(),provenance:o.provenance??"declared"}))}h(_,"loadV2Entries");function x(r,e,t){if(t&&t.length>0){let n=t.map(()=>"?").join(",");return _(r,`AND type IN (${n}) ORDER BY created_at DESC, rowid DESC LIMIT ?`,...t,e)}return _(r,"ORDER BY created_at DESC, rowid DESC LIMIT ?",e)}h(x,"recallEntriesFromV2");var Y={applyTopicSupersession(r,e,t,n){try{let i=u.get(r,`SELECT COUNT(*) AS c FROM memory_entries
|
|
16
|
-
WHERE project_id = ? AND type = ? AND content_hash != ?
|
|
17
|
-
AND (topic_key = ? OR id IN (
|
|
18
|
-
SELECT entry_id FROM memory_entry_tags WHERE key IN ('topic', 'key') AND value = ?
|
|
19
|
-
))`,r,e,t,n,n)?.c??0;u.run(r,`UPDATE memory_entries SET topic_key = ?, revision_count = ?
|
|
20
|
-
WHERE project_id = ? AND type = ? AND content_hash = ? AND deleted_at IS NULL`,n,i,r,e,t),u.run(r,`UPDATE memory_entries SET deleted_at = ?
|
|
21
|
-
WHERE project_id = ? AND type = ? AND deleted_at IS NULL AND content_hash != ?
|
|
22
|
-
AND (topic_key = ? OR id IN (
|
|
23
|
-
SELECT entry_id FROM memory_entry_tags WHERE key IN ('topic', 'key') AND value = ?
|
|
24
|
-
))`,Date.now(),r,e,t,n,n)}catch{}},async remember(r,e){let t={...e.tags??{}},n=e.provenance??"declared",i=T(e.content);{let c=await import("./trust-boundary-EX65SUYR.mjs").then(l=>l.evaluateMemoryContent).catch(()=>null);if(c){let l=c(e.content,{force:e.force});if(!l.allow){if(e.requireWrite)throw new Error(l.denyMessage);return}}}let{classifyCapturePrecision:o}=await import("./precision-classifier-IVVAXE26.mjs"),a=o(e.content,e.type,{force:e.force===!0});if(a.action==="refuse"){if(e.requireWrite)throw new Error(`precision refuse (${a.reasonCode}): ${a.reason}`);return}a.action==="demote"&&a.demoteTo&&(t.shape_demoted="true",t.original_type=e.type,t.precision_reason=a.reasonCode),e.force&&(t["precision:force"]="true");let m=a.action==="demote"&&a.demoteTo?a.demoteTo:e.type,d=e.projectId??await(async()=>{try{let{default:c}=await import("./config-manager-DX5OOPW5.mjs");return(await c.readConfig(r))?.projectId}catch{return}})();if(!t.file)try{let{inferMemoryFileTag:c}=await import("./infer-memory-file-PIAZ542H.mjs"),l=d?await(async()=>{try{let{stateStorage:E}=await import("./state-storage-XU35ZYNA.mjs"),p=(await E.getCurrentTask(d))?.likelyFiles;return Array.isArray(p)?p.map(f=>typeof f=="string"?f:f?.path).filter(f=>typeof f=="string"&&f.length>0):null}catch{return null}})():null,R=c({content:e.content,tags:t,projectPath:r,cycleFiles:l});R&&(t.file=R,t.file_source="inferred")}catch{}let y=t.topic??t.key;if(d){try{if(u.get(d,"SELECT id FROM memory_entries WHERE content_hash = ? AND type = ? AND deleted_at IS NULL LIMIT 1",i,m)){y&&this.applyTopicSupersession(d,m,i,y);return}}catch{}try{let{captureGate:c}=await import("./capture-gate-PS6QUXLX.mjs"),l=c(d,m,e.content,t);if(!l.accept){if(e.requireWrite)throw new Error(`capture refused: ${l.reason}`);return}}catch(c){if(e.requireWrite&&c instanceof Error&&c.message.startsWith("capture refused"))throw c}}let s=await A.log(r,`${I}${m}`,{content:e.content,tags:t,source:e.source,provenance:n,content_hash:i,...d?{project_id:d}:{}},void 0,d||e.requireWrite?{...d?{projectId:d}:{},required:e.requireWrite}:void 0),g=d??s?.projectId;if(g&&y&&s?.eventId!=null&&this.applyTopicSupersession(g,m,i,y),s?.projectId)try{let{usefulnessService:c}=await import("./usefulness-SZLG6LVC.mjs");c.recordReferences(s.projectId,e.content,t),c.recordCorrection(s.projectId,t)}catch{}if(g)try{let{publishCRUD:c}=await import("./publish-helper-SX7HEV2L.mjs"),l=t.spec_id??t.task_id??t.id??e.source??`mem-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;await c({projectId:g,entityType:"memories",entityId:l,eventType:"upsert",data:{id:l,type:m,content:e.content,tags:t,source:e.source??null,provenance:n,created_at:new Date().toISOString(),rememberedAt:new Date().toISOString()}})}catch{}},searchFts(r,e,t){if(e.length===0||t<=0)return[];let n=e.map(s=>D(s).replace(/[^a-z0-9-]/gi,"")).filter(s=>s.length>=2);if(n.length===0)return[];let i=n.map(s=>`"${s}"*`).join(" OR "),o=(()=>{try{return u.query(r,`SELECT m.id, m.content, m.type, m.provenance, m.created_at
|
|
25
|
-
FROM memory_entries_fts ft
|
|
26
|
-
JOIN memory_entries m ON m.rowid = ft.rowid
|
|
27
|
-
WHERE memory_entries_fts MATCH ?
|
|
28
|
-
AND m.deleted_at IS NULL
|
|
29
|
-
ORDER BY bm25(memory_entries_fts) ASC, m.created_at DESC
|
|
30
|
-
LIMIT ?`,i,t*2)}catch{return[]}})();if(o.length===0)return[];let a=b(r,o.map(s=>s.id)),m=o.map(s=>({id:s.id,type:s.type??"fact",content:s.content,tags:a.get(s.id)??{},rememberedAt:new Date(s.created_at).toISOString(),provenance:s.provenance??"declared"})),d=U(r);return(d.size>0?m.filter(s=>!d.has(s.id)):m).slice(0,t)},recall(r,e={}){let t=e.limit??H,n=Math.max(t*$,q),i=e.types&&e.types.length>0?new Set(e.types):null,o=i?i.has("shipped"):!0,a=i?[...i].some(p=>p!=="shipped"):!0,m=i?[...i].filter(p=>p!=="shipped"):void 0,d=a?x(r,n,m):[],y=o?u.query(r,"SELECT id, name, type, shipped_at, data FROM shipped_features ORDER BY shipped_at DESC LIMIT ?",n):[],s=[...d,...y.map(S)],g=i?s.filter(p=>i.has(p.type)):s,c=e.tags?g.filter(p=>N(p,e.tags??{})):g,R=[...e.topic?c.filter(p=>v(p,e.topic)):c].sort((p,f)=>f.rememberedAt.localeCompare(p.rememberedAt)),E=e.dedupeByKey!==!1?w(R):R;return(()=>{if(e.pruneSuperseded===!1)return E;let p=M(E);return p.size>0?E.filter(f=>!p.has(f.id)):E})().slice(0,t)},recallForFile(r,e,t=3,n={}){if(!e)return[];let i=e.split("/").pop()??e,o=h(c=>c.type==="gotcha"||c.type==="red-herring"||c.type==="anti-pattern"||c.tags?.pattern==="recurring-bug","isPreventive"),a=Math.max(t*5,15),m=(()=>{try{return _(r,`AND file IS NOT NULL
|
|
31
|
-
AND (file = ? OR ? LIKE '%/' || file OR file = ? OR file LIKE '%/' || ?)
|
|
32
|
-
ORDER BY created_at DESC, rowid DESC
|
|
33
|
-
LIMIT ?`,e,e,i,i,a).filter(o)}catch{return[]}})(),d=n.preventiveOnly?[]:(()=>{try{return _(r,"AND type = ? ORDER BY created_at DESC, rowid DESC LIMIT 200","context").filter(l=>(l.tags?.files??"").split(",").map(E=>E.trim()).some(E=>E===e||E===i||E.endsWith(`/${i}`)))}catch{return[]}})(),y=[...m,...d],s=M(y);return(s.size>0?y.filter(c=>!s.has(c.id)):y).slice(0,t)},getById(r,e){let t=String(e).trim().match(/^(?:mem[_-])?(\d+)$/i);if(!t)return null;try{return _(r,"AND id = ?",`mem_${t[1]}`)[0]??null}catch{return null}},countByType(r,e){try{return u.get(r,"SELECT COUNT(*) AS n FROM memory_entries WHERE project_id IN (?, 'local') AND type = ? AND deleted_at IS NULL",r,e)?.n??0}catch{return 0}},recallByType(r,e,t){if(t<=0)return[];try{return _(r,"AND type = ? ORDER BY created_at DESC, rowid DESC LIMIT ?",e,t)}catch{return[]}},forget(r,e){let t=String(e).trim().match(/^(?:mem[_-])?(\d+)$/i);if(!t)return!1;let n=Number(t[1]),i=`mem_${n}`,o=(()=>{try{return u.get(r,"SELECT id FROM events WHERE id = ? AND type LIKE ?",n,`${O}%`)?(u.run(r,"DELETE FROM events WHERE id = ?",n),!0):!1}catch{return!1}})();try{u.run(r,"DELETE FROM memory_embeddings WHERE memory_id = ?",i)}catch{}let a=(()=>{try{return u.run(r,"UPDATE memory_entries SET deleted_at = ? WHERE id = ? AND deleted_at IS NULL",Date.now(),i).changes>0}catch{return!1}})();return o||a},expandWithLinks(r,e,t=5){if(e.length===0||t<=0)return[];let n=/\bmem[_-](\d+)\b/g,i=["resolves","relates","supersedes","superseded-by","duplicates","spec"],o=new Set(e.map(m=>m.id)),a=[];for(let m of e){if(a.length>=t)break;let d=new Set;for(let y of i){let s=m.tags?.[y];if(s)for(let g of String(s).matchAll(n))d.add(`mem_${g[1]}`)}for(let y of m.content.matchAll(n))d.add(`mem_${y[1]}`);for(let y of d){if(a.length>=t)break;if(o.has(y))continue;o.add(y);let s=Y.getById(r,y);s&&a.push(s)}}return a},unembeddedEntriesForIndex(r,e){try{let t=_(r,`AND type != ?
|
|
34
|
-
AND NOT EXISTS (
|
|
35
|
-
SELECT 1 FROM memory_embeddings me
|
|
36
|
-
WHERE me.memory_id = memory_entries.id AND me.model = ?
|
|
37
|
-
)
|
|
38
|
-
ORDER BY created_at DESC, rowid DESC`,"improvement-signal",e),n=u.query(r,`SELECT s.id, s.name, s.type, s.shipped_at, s.data FROM shipped_features s
|
|
39
|
-
WHERE NOT EXISTS (
|
|
40
|
-
SELECT 1 FROM memory_embeddings me
|
|
41
|
-
WHERE me.memory_id = 'ship_' || s.id AND me.model = ?
|
|
42
|
-
)
|
|
43
|
-
ORDER BY s.shipped_at DESC`,e);return[...t,...n.map(S)]}catch{return[]}},allEntriesForIndex(r){try{let e=_(r,"ORDER BY created_at DESC, rowid DESC"),t=u.query(r,"SELECT id, name, type, shipped_at, data FROM shipped_features ORDER BY shipped_at DESC");return[...e,...t.map(S)]}catch{return[]}}};export{Y 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-GLPKMG5A.mjs";import"./chunk-QBYHZX33.mjs";import{a as n}from"./chunk-GPZP7NXL.mjs";import"./chunk-2UC4DTDO.mjs";import"./chunk-BOBFTVAY.mjs";import"./chunk-OGIFB3OE.mjs";import"./chunk-BU22R6JX.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-IGHY4FGS.mjs";import"./chunk-22AXWLI6.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-4HAKTI36.mjs";import"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-Z4X7JIAP.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{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-4NTVXJD7.mjs";import{a as E}from"./chunk-5WAONIPX.mjs";import{a as A}from"./chunk-GPZP7NXL.mjs";import{a as x}from"./chunk-N3L77UNM.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-PP6DANGV.mjs";import"./chunk-4HAKTI36.mjs";import{b as I,c as S,d as $}from"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as L}from"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import{b as v}from"./chunk-XXRAQZNC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-5XA5RL5I.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-XS45K7ZQ.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-4KVPAHFV.mjs";import{i as p}from"./chunk-Z4X7JIAP.mjs";import"./chunk-GAOQHD5S.mjs";import{b as h}from"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{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-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{a as projectMemory};
|
|
@@ -1,24 +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 J}from"./chunk-MXHX44WF.mjs";import{a as X}from"./chunk-BDOAQVIF.mjs";import{a as K}from"./chunk-5WAONIPX.mjs";import{a as z,d as W}from"./chunk-GLPKMG5A.mjs";import"./chunk-QBYHZX33.mjs";import{a as V}from"./chunk-GPZP7NXL.mjs";import{b as x}from"./chunk-2UC4DTDO.mjs";import"./chunk-BOBFTVAY.mjs";import{a as F}from"./chunk-5TBQNW2G.mjs";import{a as q}from"./chunk-N3L77UNM.mjs";import{a as M}from"./chunk-DVDZA63F.mjs";import{a as B}from"./chunk-EWOK4VE7.mjs";import{a as N}from"./chunk-ZOX6OV6X.mjs";import{b as O}from"./chunk-WGWE3CSC.mjs";import"./chunk-T6ELTQZM.mjs";import{b as U}from"./chunk-RHKF7EJW.mjs";import"./chunk-TPESWBA7.mjs";import"./chunk-GDESYWTD.mjs";import{a as H,g as L}from"./chunk-J5UQVJUW.mjs";import"./chunk-YDBZO6I3.mjs";import"./chunk-YQ55MHKL.mjs";import"./chunk-QSAA6LZF.mjs";import"./chunk-KOGZCFBC.mjs";import"./chunk-Z6KVLCMK.mjs";import"./chunk-OGIFB3OE.mjs";import"./chunk-BU22R6JX.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-IGHY4FGS.mjs";import"./chunk-22AXWLI6.mjs";import"./chunk-KEJ5RMAI.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-DCSKTMDX.mjs";import"./chunk-R4ILCXKE.mjs";import"./chunk-4HAKTI36.mjs";import{d as v}from"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import{a as w}from"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import{b as j}from"./chunk-XXRAQZNC.mjs";import"./chunk-OUAS3LZ3.mjs";import"./chunk-5XA5RL5I.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import{h as $,i as k}from"./chunk-Z4X7JIAP.mjs";import"./chunk-GAOQHD5S.mjs";import{b as S}from"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import{d as _,g as at}from"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import{k as R,o as ct}from"./chunk-UH4MD3F3.mjs";import{b as G,p as ot}from"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a as d}from"./chunk-E66B27AL.mjs";import{createHash as D}from"node:crypto";import y from"node:fs/promises";import h from"node:path";var ut=15;function Y(e){let i=[],t=[];e.loop?.stopped&&e.loop.message&&(i.push("loop-hard-stop"),t.push(e.loop.message)),e.pressure?.level==="critical"&&e.pressure.cue?(i.push("context-pressure-critical"),t.push(e.pressure.cue)):e.pressure?.level==="warn"&&e.pressure.cue&&(i.push("context-pressure-warn"),t.push(e.pressure.cue)),e.qualityInject?.trim()&&(i.push("quality-ledger"),t.push(e.qualityInject.trim()));let r=e.turns??0,n=e.stuckThreshold??ut;if(!e.loop?.stopped&&r>=n&&(i.push("stuck-cycle"),t.push(`\u26A0 ${r} 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.`)),t.length===0)return{level:"ok",markdown:null,cues:[]};let c=i.some(l=>["loop-hard-stop","context-pressure-critical","context-pressure-warn"].includes(l)),s=i.some(l=>["quality-ledger","stuck-cycle"].includes(l)),u=c?"hard":s?"warn":"ok",g=u==="hard"?"# prjct: alignment (MUST \u2014 hard gate)":"# prjct: alignment (mid-cycle)",p=t.join(`
|
|
9
|
-
|
|
10
|
-
`),o=i.includes("quality-ledger")&&!p.includes("prjct ship")?`
|
|
11
|
-
|
|
12
|
-
_${H}_`:"";return{level:u,cues:i,markdown:`${g}
|
|
13
|
-
|
|
14
|
-
${p}${o}`}}d(Y,"buildAlignmentCard");at();ot();ct();var T=1500,lt=T+2100,Z=15,P=8,Q=420,dt=2,pt=15e3;var gt=new Set(["address","apply","check","continue","create","current","description","feedback","handle","merge","monitor","please","review","should","title","watch","write"]),C=new WeakMap,b=new Map;async function tt(e,i){let t=i!==void 0?i:await S.readConfig(e);if(!t?.projectId)return null;let r=mt(t,e),n=["# prjct: project state"];try{let s=await B(t.projectId,e);if(s.current){let g=nt(s.current.startedAt);n.push(`- Active work cycle: "${s.current.description}" (${g}) [${s.current.label}]`),(t.land?.mode??"advisory")!=="off"&&n.push(' \u21B3 Before session end: `prjct land` \xB7 hand-off `prjct remember context "Session close: \u2026"`');let{turns:p,loopVerdict:o,currentTask:l}=(()=>{try{let a=s.mainTaskRaw;return{turns:a?.turnCount??0,currentTask:a,loopVerdict:K(t,a)}}catch{return{turns:0,currentTask:null,loopVerdict:null}}})();!o?.stopped&&p<Z&&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 a=t.maxTokensPerCycle??0;if(a>0&&l){let m=(l.tokensIn??0)+(l.tokensOut??0);m>=a?n.push(` \u26A0 Token budget: ${m.toLocaleString()} of ${a.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>=a*.8&&n.push(` \u21B3 Token budget: ${m.toLocaleString()} of ${a.toLocaleString()} (${Math.round(m/a*100)}%). Plan the close: prefer finishing over expanding scope.`)}}catch{}try{let a=s.current.startedAt;if(a){let m=_.get(t.projectId,`SELECT COUNT(DISTINCT json_extract(data, '$.file')) AS c
|
|
15
|
-
FROM events WHERE type = 'memory.post_edit' AND timestamp >= ?`,a)?.c??0,f=U(m);f&&n.push(` ${f}`)}}catch{}try{let a=F(t,l),m=L(t.projectId),f=Y({loop:o,pressure:a,qualityInject:m,turns:p,stuckThreshold:Z});f.markdown&&(n.push(""),n.push(f.markdown))}catch{}l?.ownerAgent&&n.push(`- Owner: ${l.ownerAgent}${l.ownerIdentity?`/${l.ownerIdentity}`:""}${l.yieldStatus==="yielded"?" (yielded \u2014 awaiting accept)":""}`)}let u=s.all.filter(g=>!g.isCurrent);u.length>0&&n.push(`- ${u.length} task(s) active in other workspace(s)`),!s.current&&u.length>0&&n.push("- This workspace idle but siblings busy \u2014 `prjct work` auto-isolates to a worktree when needed")}catch{}let c=await r;for(let s of c)s&&n.push(s);return n.length===1?null:n.join(`
|
|
16
|
-
`)}d(tt,"buildProjectState");function mt(e,i){return Promise.all([(async()=>{try{let{formatPendingHandoffCue:t}=await import("./agent-switch-4ZJJWKMD.mjs"),r=t(e.projectId);return r?`- ${r.replace(/\n/g,`
|
|
17
|
-
- `)}`:null}catch{return null}})(),(async()=>{try{let t=await N.getActiveTasks(e.projectId);return t.length>0?`- Pending: ${t.length} \xB7 Next: "${t[0].description}"`:null}catch{return null}})(),(async()=>{try{if(!await R(h.join(i,".git")))return null;let t=await It(i);if(!t.branch)return null;let r=[];t.modified>0&&r.push(`${t.modified} modified`),t.staged>0&&r.push(`${t.staged} staged`),t.untracked>0&&r.push(`${t.untracked} untracked`);let n=r.length>0?` \u2014 working tree ${r.join(", ")}`:"",c=t.ahead>0?`${n?",":" \u2014"} ${t.ahead} unpushed`:"";return`- Branch: ${t.branch}${n}${c}`}catch{return null}})(),(async()=>{try{let t=await M.getRecent(e.projectId,1);if(t.length===0)return null;let r=t[0],n=nt(r.shippedAt??"");return`- Last ship: ${r.version?`v${r.version}`:r.name} (${n})`}catch{return null}})(),(async()=>{try{let t=w.countByType(e.projectId,"inbox");return t>0?`- Inbox: ${t} items pending`:null}catch{return null}})()])}d(mt,"collectSecondarySignals");function ht(e){return e.type==="voice"||e.type==="glossary"?!0:e.type==="example"&&!!e.tags.domain&&(e.tags.polarity==="good"||e.tags.polarity==="bad")}d(ht,"isValidGuidanceEntry");function ft(e,i){try{let t=A(i),r=$(i).filter(o=>o.length>=5&&!gt.has(o)),n=r.length>0?w.searchFts(e,r,P*2):[],c=t?w.recall(e,{types:["voice","glossary","example"],limit:P*2}).filter(o=>o.tags.domain==="delivery"||o.tags.domain===t):[],s=new Map([...n,...c].map(o=>[o.id,o])),u=new Map([["voice",0],["glossary",1],["example",2]]),g=[...s.values()].filter(ht).sort((o,l)=>(u.get(o.type)??3)-(u.get(l.type)??3)).slice(0,dt);if(g.length===0)return null;let p=["# prjct: selective guidance"];for(let o of g){let l=o.type==="example"?` ${o.tags.polarity}/${o.tags.domain}`:o.tags.domain?` ${o.tags.domain}`:"",a=Q-p.join(`
|
|
18
|
-
`).length-l.length-8;if(a<24)break;let m=k(o.content.replace(/\s+/g," ").trim(),Math.min(150,a));p.push(`- ${o.type}${l}: ${m}`)}return p.length===1?null:{text:k(p.join(`
|
|
19
|
-
`),Q),memoryIds:g.slice(0,p.length-1).map(o=>o.id)}}catch{return null}}d(ft,"buildSelectiveGuidance");function yt(e,i,t=T){if(!i)return e;let r=e?`${e}
|
|
20
|
-
|
|
21
|
-
${i}`:i;return r.length<=t?r:null}d(yt,"appendPromptSection");function et(e,i){try{let t=$(i);if(t.length===0)return null;let r=w.searchFts(e,t,P),n=r.find(c=>c.type==="decision"||c.type==="gotcha"||c.type==="fact")??r.find(c=>c.type==="anti-pattern"||c.type==="pattern")??r.find(c=>c.type==="gotcha"||c.type==="anti-pattern");return n?n.type==="decision"||n.type==="gotcha"||n.type==="fact"?{cue:`> Tip\u2192user (SoT): ${v(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): ${v(n)} \`${n.id}\` \u2014 propose the live change in chat, then apply when editing`,memoryId:n.id}:{cue:`> Tip\u2192user: ${v(n)} \`${n.id}\``,memoryId:n.id}:null}catch{return null}}d(et,"buildTopicalCueResult");function Qt(e,i,t){return et(e,i)?.cue??null}d(Qt,"buildTopicalCue");var I=new Map,E={skipDiskSnapshotOnce:!1};function te(){I.clear(),E.skipDiskSnapshotOnce=!0}d(te,"_resetGitSnapshotCacheForTests");async function It(e){let i=await y.stat(h.join(e,".git","index")).then(s=>s.mtimeMs).catch(()=>0),t=I.get(e);if(t&&t.expiresAt>Date.now()&&t.indexMtimeMs===i)return t.snapshot;let r=wt(e);if(!t&&!E.skipDiskSnapshotOnce){let s=await y.readFile(r,"utf-8").then(u=>JSON.parse(u)).catch(()=>null);if(s&&s.expiresAt>Date.now()&&s.indexMtimeMs===i)return I.set(e,s),s.snapshot}E.skipDiskSnapshotOnce=!1;let n=await vt(e);I.size>32&&I.clear();let c={snapshot:n,expiresAt:Date.now()+pt,indexMtimeMs:i};return I.set(e,c),y.mkdir(h.dirname(r),{recursive:!0}).then(()=>y.writeFile(r,JSON.stringify(c))).catch(()=>{}),n}d(It,"captureGit");function wt(e){let i=D("sha1").update(h.resolve(e)).digest("hex").slice(0,16);return h.join(x.runDir(),`prompt-git-${i}.json`)}d(wt,"gitSnapshotPath");function kt(e,i){let t=D("sha1").update(h.resolve(i)).digest("hex").slice(0,12);return`${e.replace(/[^a-zA-Z0-9._-]/g,"_")}-${t}`}d(kt,"promptHashKey");async function St(e,i,t){let r=kt(e,i),n=D("sha256").update(t).digest("hex");if(b.get(r)===n)return null;b.size>64&&b.clear(),b.set(r,n);let c=h.join(x.runDir(),`prompt-state-${r}.hash`);return(await y.readFile(c,"utf-8").catch(()=>"")).trim()===n?null:(await y.mkdir(h.dirname(c),{recursive:!0}).then(()=>y.writeFile(c,n)).catch(()=>{}),t)}d(St,"dedupePromptPayload");async function vt(e){let i={branch:"",modified:0,staged:0,untracked:0,ahead:0},t=d(async o=>{try{return(await G("git",o,{cwd:e,timeout:2e3})).stdout.trim()}catch{return""}},"safe"),[r,n,c]=await Promise.all([t(["branch","--show-current"]),t(["status","--porcelain"]),t(["rev-list","--count","@{u}..HEAD"])]);if(!r)return i;let{modified:s,staged:u,untracked:g}=n.split(`
|
|
22
|
-
`).filter(Boolean).reduce((o,l)=>{let a=l.slice(0,2);return a.startsWith("??")?o.untracked++:(a[0]!==" "&&a[0]!=="?"&&o.staged++,a[1]!==" "&&o.modified++),o},{modified:0,staged:0,untracked:0}),p=Number.parseInt(c,10)||0;return{branch:r,modified:s,staged:u,untracked:g,ahead:p}}d(vt,"captureGitUncached");function nt(e){if(!e)return"unknown";let i=Date.parse(e);if(Number.isNaN(i))return"unknown";let t=Math.max(0,Math.floor((Date.now()-i)/864e5));return t<1?"today":t<2?"yesterday":t<30?`${t}d ago`:`${Math.floor(t/30)}mo ago`}d(nt,"formatRelative");function rt(e,i,t,r=T){let n=et(e,i),c=O(e,i),s=J(i),u=ft(e,i),g=[n?.cue,s,u?.text,c].filter(a=>!!a).reduce((a,m)=>yt(a,m,r)??a,k(t,r)),p=!!(u?.text&&g.includes(u.text)),l=!!(s&&g.includes(s))?`delivery:${A(i)??"unknown"}`:p?u?.memoryIds[0]??null:null;return{prioritized:g,cueResult:n,guidance:u,guidanceIncluded:p,guidanceRuleId:l}}d(rt,"computePromptGuidance");function ee(e=process.cwd(),i){return V({event:"UserPromptSubmit",projectPath:e,build:d(async(t,r,n)=>{let c=(t.prompt??"").trim();if(!c)return null;let s=await S.readConfig(r);if(!s?.projectId)return null;let u=await tt(r,s),g=n==="kimi"?await W(s.projectId,t.session_id).catch(()=>null):null,p=g?await z(r,s,{digest:g==="digest"}).catch(()=>null):null;if(!u&&!p)return null;let o=[p,u].filter(Boolean).join(`
|
|
23
|
-
|
|
24
|
-
`),l=p?lt:T,{prioritized:a,cueResult:m,guidance:f,guidanceIncluded:it,guidanceRuleId:st}=rt(s.projectId,c,o,l);return C.set(t,{projectId:s.projectId,projectPath:r,bumpTurn:!!u?.includes("Active work cycle:"),surfacedIds:[...m?[m.memoryId]:[],...it?f?.memoryIds??[]:[]],guidanceRuleId:st}),St(s.projectId,r,a)},"build"),afterEmit:d(async(t,r)=>{let n=C.get(t)??await bt(t,r);C.delete(t),n&&await Promise.all([n.bumpTurn?j.bumpTurnCount(n.projectId).then(()=>{}):Promise.resolve(),n.surfacedIds.length>0?q(n.projectId,n.projectPath,n.surfacedIds):Promise.resolve(),n.guidanceRuleId?Promise.resolve(X.recordGuidanceActivation(n.projectId,{ruleId:n.guidanceRuleId})).then(()=>{}):Promise.resolve()])},"afterEmit")},i)}d(ee,"runPromptHook");async function bt(e,i){let t=(e.prompt??"").trim();if(!t)return null;let r=await S.readConfig(i).catch(()=>null);if(!r?.projectId)return null;let[n,c]=await Promise.all([j.getCurrentTask(r.projectId).catch(()=>null),tt(i,r)]),{cueResult:s,guidance:u,guidanceIncluded:g,guidanceRuleId:p}=rt(r.projectId,t,c??"");return{projectId:r.projectId,projectPath:i,bumpTurn:!!n,surfacedIds:[...s?[s.memoryId]:[],...g?u?.memoryIds??[]:[]],guidanceRuleId:p}}d(bt,"rebuildPromptAfterEmit");export{te as _resetGitSnapshotCacheForTests,J as buildDeliveryGuidance,tt as buildProjectState,ft as buildSelectiveGuidance,Qt as buildTopicalCue,A as classifyDeliveryIntent,ee 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-KHLYWNHT.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-SJ75V4WG.mjs";import{b as P}from"./chunk-DCSKTMDX.mjs";import"./chunk-R4ILCXKE.mjs";import{b as O,c as U}from"./chunk-4HAKTI36.mjs";import{a as Y}from"./chunk-S5N2ZZDL.mjs";import"./chunk-C4O243NG.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-PTA7DMLM.mjs";import"./chunk-X5W2UYQK.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-TXSLON7M.mjs";import{a as x}from"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import{c as A}from"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import{a as w,b as V,e as D,g as B}from"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import{b as M,g as F}from"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.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,e}from"./chunk-GLPKMG5A.mjs";import"./chunk-QBYHZX33.mjs";import"./chunk-GPZP7NXL.mjs";import"./chunk-2UC4DTDO.mjs";import"./chunk-BOBFTVAY.mjs";import"./chunk-OGIFB3OE.mjs";import"./chunk-BU22R6JX.mjs";import"./chunk-JR542RI2.mjs";import"./chunk-IGHY4FGS.mjs";import"./chunk-22AXWLI6.mjs";import"./chunk-ZMLA5SKR.mjs";import"./chunk-4HAKTI36.mjs";import"./chunk-C4O243NG.mjs";import"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import"./chunk-DXQMKW2B.mjs";import"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import"./chunk-UUULLTQV.mjs";import"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import"./chunk-GVNMXVVA.mjs";import"./chunk-Z4X7JIAP.mjs";import"./chunk-GAOQHD5S.mjs";import"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import"./chunk-UH4MD3F3.mjs";import"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import"./chunk-E66B27AL.mjs";export{c as buildProjectIdentityLine,a as buildSessionContext,b as buildSubagentDigest,d as consumeKimiSessionInjection,e as runSessionStartHook};
|
|
@@ -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 r}from"./chunk-E66B27AL.mjs";import{existsSync as S}from"node:fs";import k from"node:fs/promises";import O from"node:os";import l from"node:path";function f(){let t=process.env.HOME||O.homedir();return l.join(t,".claude","settings.json")}r(f,"settingsPath");var p="_prjctManaged",j=10,g=[{event:"SessionStart",matcher:"",subcommand:"session-start"},{event:"UserPromptSubmit",matcher:"",subcommand:"prompt"},{event:"PreToolUse",matcher:"Bash",subcommand:"pre-bash"},{event:"PreToolUse",matcher:"Edit|Write",subcommand:"pre-edit"},{event:"PreToolUse",matcher:"Grep|Glob",subcommand:"pre-search"},{event:"PostToolUse",matcher:"Edit|Write",subcommand:"post-edit"},{event:"Stop",matcher:"",subcommand:"stop"},{event:"SubagentStart",matcher:"",subcommand:"subagent-start"},{event:"SubagentStop",matcher:"",subcommand:"subagent-stop"},{event:"Notification",matcher:"",subcommand:"notification"},{event:"CwdChanged",matcher:"",subcommand:"cwd-changed"}];function y(t){let e=t.command?.match(/\bhook\s+(\S+)/);return e?e[1]:null}r(y,"subcommandOf");function w(t){let e=new Set(g.map(s=>s.subcommand)),o=[];for(let s of Object.keys(t)){let c=t[s],n=[];for(let a of c)a.hooks=a.hooks.filter(m=>{if(!d(m))return!0;let u=y(m);return u&&!e.has(u)?(o.push(m),!1):!0}),a.hooks.length>0&&n.push(a);n.length>0?t[s]=n:delete t[s]}return o.length}r(w,"pruneOrphanedManagedHooks");async function b(){try{let t=await k.readFile(f(),"utf-8"),e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch(t){if(t.code==="ENOENT")return{};throw t}}r(b,"readSettings");async function P(t){await k.mkdir(l.dirname(f()),{recursive:!0}),await k.writeFile(f(),`${JSON.stringify(t,null,2)}
|
|
9
|
-
`,"utf-8")}r(P,"writeSettings");function x(){if(process.platform==="win32")return null;let t=process.execPath;if(!t)return null;let e=__dirname,o=[l.join(e,"prjct.mjs"),l.resolve(e,"..","prjct.mjs"),l.resolve(e,"..","..","dist","bin","prjct.mjs")].find(c=>S(c));return o?`${l.basename(t).includes("bun")?"":'NODE_OPTIONS="--experimental-sqlite${NODE_OPTIONS:+ $NODE_OPTIONS}" '}"${t}" "${o}"`:null}r(x,"directHookPrefix");function R(){if(process.platform==="win32")return null;let t=__dirname,e=`hook-fast-${process.platform}-${process.arch}`;return[l.join(t,e),l.resolve(t,"..",e),l.resolve(t,"..","..","dist","bin",e)].find(o=>S(o))??null}r(R,"nativeHookFastBinary");function $(t){let e=process.env.PRJCT_BIN??"prjct",o=`command -v ${e} >/dev/null 2>&1 && ${e} hook ${t} || exit 0`;if(process.env.PRJCT_BIN)return o;let s=x();if(!s)return o;let c=`${s} hook ${t}`,n=R();return`${n?`"${n}" ${t} || ${c}`:c} || { ${o.replace(" || exit 0","")}; } || exit 0`}r($,"hookCommand");function d(t){return t[p]===!0}r(d,"isPrjctHook");function N(t){if(t[p]===!0)return!1;let e=t.command?.trim()??"";return/(^|\/|\s)prjct\s+hook\s+\S+/.test(e)}r(N,"isLegacyPrjctHook");function v(t){let e={type:"command",command:$(t.subcommand),timeout:j,[p]:!0},o="ifClause"in t?t.ifClause:void 0;return typeof o=="string"&&o&&(e.if=o),e}r(v,"hookEntryFor");async function F(){let t=await b(),e=t.hooks??{},o=[],s=[];for(let n of g){let a=e[n.event]??[],m=a.find(i=>(i.matcher??"")===n.matcher),u=m??{matcher:n.matcher,hooks:[]};m||a.push(u);let H=u.hooks.length;u.hooks=u.hooks.filter(i=>!N(i));let E=H-u.hooks.length,h=u.hooks.find(i=>d(i)&&y(i)===n.subcommand);if(h){let i=v(n);h.command===i.command&&h.if===i.if&&h.timeout===i.timeout&&E===0?s.push(n):(h.command=i.command,h.if=i.if,h.timeout=i.timeout,o.push(n))}else u.hooks.push(v(n)),o.push(n);e[n.event]=a}let c=w(e);return t.hooks=e,await P(t),{settingsPath:f(),hooksWritten:o.length,alreadyPresent:s.length,hooksPruned:c}}r(F,"install");async function I(){let t=await b();if(!t.hooks)return{settingsPath:f(),hooksRemoved:0};let e=[];for(let[o,s]of Object.entries(t.hooks)){let c=[];for(let n of s){let a=n.hooks.filter(m=>d(m)?(e.push(m),!1):!0);a.length>0&&c.push({...n,hooks:a})}c.length>0?t.hooks[o]=c:delete t.hooks[o]}return Object.keys(t.hooks).length===0&&delete t.hooks,await P(t),{settingsPath:f(),hooksRemoved:e.length}}r(I,"uninstall");async function U(){let e=(await b()).hooks??{};return{installed:Object.values(e).flat().flatMap(s=>s.hooks).filter(d).length,expected:g.length}}r(U,"status");export{j as HOOK_TIMEOUT_SECONDS,g as PRJCT_HOOKS,F as install,U as status,I as uninstall};
|
|
@@ -1,16 +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 ue,b as T,d as W}from"./chunk-32RX4YGI.mjs";import{a as L}from"./chunk-BDOAQVIF.mjs";import{b as ae}from"./chunk-QBYHZX33.mjs";import{a as ce}from"./chunk-GPZP7NXL.mjs";import{b as q}from"./chunk-2UC4DTDO.mjs";import{a as J}from"./chunk-PGWFGRX4.mjs";import{a as ie,b as oe}from"./chunk-TRMBRDKH.mjs";import"./chunk-TPESWBA7.mjs";import{b as se}from"./chunk-FEFP6JOL.mjs";import{c as M}from"./chunk-4HAKTI36.mjs";import{c as re}from"./chunk-X5W2UYQK.mjs";import"./chunk-Y5NQV46G.mjs";import{a as m}from"./chunk-V2FR2NPL.mjs";import"./chunk-S5ISOGDB.mjs";import{g as at,h as ct}from"./chunk-UUULLTQV.mjs";import{a as ne,c as G}from"./chunk-I26F7TLM.mjs";import"./chunk-QP5USCDX.mjs";import"./chunk-RTEEXGEA.mjs";import"./chunk-M5E2YOZ4.mjs";import{b as Y}from"./chunk-Z4X7JIAP.mjs";import"./chunk-GAOQHD5S.mjs";import{b as v}from"./chunk-PO3QDKTE.mjs";import"./chunk-ABJNOG2I.mjs";import{a as te,b as it,e as b,f as ot,g as B}from"./chunk-UHVYBU7F.mjs";import"./chunk-CE4RCNC7.mjs";import{b as Q,h as tt,v as ee,w as st}from"./chunk-A6K4H3YT.mjs";import"./chunk-HDSS6UB3.mjs";import{b as U,c as rt}from"./chunk-JQE2F2RK.mjs";import"./chunk-WUHGODSQ.mjs";import{k as Z,o as nt}from"./chunk-UH4MD3F3.mjs";import{e as A,g as P,l as C,p as V}from"./chunk-QWQFF2UG.mjs";import"./chunk-GCKILEXJ.mjs";import"./chunk-GCDLPKOH.mjs";import"./chunk-PKDYFXMI.mjs";import"./chunk-BUDZL4DW.mjs";import{a,b as K,e as z}from"./chunk-E66B27AL.mjs";import S from"node:fs/promises";import Qe from"node:path";import ut from"node:crypto";import lt from"node:fs/promises";function D(n){return typeof n=="string"?n:Array.isArray(n)?n.map(t=>{if(typeof t=="string")return t;if(t&&typeof t=="object"&&"text"in t){let e=t.text;return typeof e=="string"?e:""}return""}).join(`
|
|
9
|
-
`).trim():""}a(D,"textOf");function I(n){try{let t=K("node:fs"),s=K("node:path").join(n,".prjct","prjct.config.json"),r=t.readFileSync(s,"utf-8");return JSON.parse(r).projectId??null}catch{return null}}a(I,"projectIdFromPath");var fe="friction-detector",le="friction-promote",pe=5,de=400,ge=160,pt=[/^\s*no[,.!\s]/i,/^\s*nope\b/i,/^\s*stop\b/i,/^\s*wait\b/i,/^\s*cancel\b/i],dt=[/\bshould be\b/i,/\brather than\b/i,/\binstead\b/i],ft=[/\bdoesn'?t work\b/i,/\bbroken\b/i,/\bagain\b.*\bsame\b/i];async function me(n,t,e,s={}){let r=s.preloadedLines?s.preloadedLines:await lt.readFile(t,"utf-8").then(gt).catch(()=>null);if(!r)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let i=mt(r);if(i.length===0)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let o=i.slice(0,pe).map(l=>({category:l.category,expectedBehavior:"Follow the user constraint without requiring correction.",observedBehavior:`The assistant response triggered user ${l.category}.`,relatedRuleId:null})),u=kt(n),c=I(n)??void 0;return{...await i.slice(0,pe).reduce(async(l,f)=>{let d=await l,y=ye(f.excerpt).slice(0,12);if(u.has(y))return await wt(n,c,f).catch(()=>{}),{...d,signalsSkipped:d.signalsSkipped+1};try{return await m.remember(n,{type:"improvement-signal",content:yt(f),tags:{source:fe,category:f.category,...s.runtime?{runtime:s.runtime}:{},...s.model?{model:s.model}:{},...e?{session:e}:{},key:y},provenance:"extracted",projectId:c}),u.add(y),{...d,signalsRecorded:d.signalsRecorded+1}}catch{return{...d,signalsSkipped:d.signalsSkipped+1}}},Promise.resolve({signalsRecorded:0,signalsSkipped:0})),failures:o}}a(me,"detectFriction");function gt(n){return T(n)}a(gt,"parseJsonl");function mt(n){let t={signals:[],lastAssistantText:""};for(let e of n){let s=e.role??e.message?.role,r=D(e.content??e.message?.content);if(!r)continue;if(s==="assistant"){t.lastAssistantText=r;continue}if(s!=="user")continue;let i=ht(r.slice(0,300));i&&t.signals.push({excerpt:r.slice(0,de).trim(),category:i,precedingAssistantPreview:t.lastAssistantText.slice(0,de).trim()})}return t.signals}a(mt,"extractSignals");function ht(n){return ft.some(t=>t.test(n))?"complaint":pt.some(t=>t.test(n))?"negation":dt.some(t=>t.test(n))?"correction":null}a(ht,"classify");function yt(n){let t=bt(n.category),e=he(n.excerpt),s=e?`Obey developer constraint: ${e}`:t.lesson,r=e?`Always: ${e}`:t.nextAction;return[`[${n.category}] Lesson: ${s}`,"What happened: The user pushed back after the assistant response.",`Why it mattered: ${t.why}`,`Pattern: ${t.pattern}`,`Anti-pattern: ${t.antiPattern}`,`Next action: ${r}`].join(`
|
|
10
|
-
`)}a(yt,"formatSignal");function he(n){let t=n.replace(/\s+/g," ").trim();if(!t)return null;let e=t.replace(/^\s*(?:nope|no|stop|wait|cancel)[,.!\s:—-]*/i,"").trim(),s=e.match(/\bshould be\b\s+(.+?)$/i);if(s?.[1])return E(`Prefer ${s[1]}`);let r=e.match(/^(.+?)\s+rather than\s+(.+?)$/i);if(r?.[1]&&r[2])return E(`Prefer ${r[1].trim()} rather than ${r[2].trim()}`);let i=e.match(/\b(?:use|prefer|do|run|ship|write|keep)\s+(.+?)\s+instead(?:\s+of\s+(.+))?$/i);if(i?.[1]){let p=i[2]?` instead of ${i[2].trim()}`:" instead";return E(`Use ${i[1].trim()}${p}`)}let o=e.match(/\binstead of\b\s+(.+?)$/i);if(o?.[1])return E(`Avoid ${o[1].trim()}`);let u=e.match(/\b(?:don'?t|do not|never)\s+(.+?)$/i);if(u?.[1])return E(`Never ${u[1].trim()}`);let c=e.match(/\balways\s+(.+?)$/i);if(c?.[1])return E(`Always ${c[1].trim()}`);if(e.length>=12&&e.length<=ge&&/^(?:run|use|do|ship|write|keep|add|fix|remove|prefer|test|check|verify|read|ask|stop|start)\b/i.test(e)){let p=e.charAt(0).toUpperCase()+e.slice(1);return E(p.replace(/[.!?]+$/,""))}return null}a(he,"extractSpecificConstraint");function E(n){let t=n.replace(/\s+/g," ").trim().replace(/^[-*•]\s+/,"").replace(/[.!?]+$/,"").slice(0,ge);return t.length<12||/^(?:nope|no|stop|wait|cancel)\b/i.test(t)?null:t}a(E,"cleanConstraint");async function wt(n,t,e){if(!t)return;let s=he(e.excerpt);if(!s)return;let r=`Always: ${s}`,i=`fp:${ye(s).slice(0,12)}`;try{if(m.recall(t,{types:["feedback"],tags:{source:le,key:i},limit:1,dedupeByKey:!1}).length>0)return;await m.remember(n,{type:"feedback",content:r,tags:{source:le,key:i,category:e.category,from:"recurring-friction"},provenance:"extracted",projectId:t})}catch{}}a(wt,"maybePromoteStandingPreference");function bt(n){return n==="complaint"?{lesson:"Treat explicit failure complaints as evidence that the last result needs diagnosis, not repetition.",why:"The user reported that the delivered behavior or command did not work.",pattern:"User names a broken or non-working result after an assistant action.",antiPattern:"Retrying the same path or moving on without isolating the failure.",nextAction:"Stop, inspect the failing output or assumption, and propose the smallest verifiable fix."}:n==="correction"?{lesson:"Update the working assumption when the user corrects the intended direction.",why:"The assistant was using an assumption that did not match what the user wanted.",pattern:"User redirects the implementation or workflow with a correction.",antiPattern:"Continuing with the original plan after the user clarified a different target.",nextAction:"Restate the corrected target as an actionable rule before continuing."}:{lesson:"Recalibrate before continuing when the user rejects the assistant\u2019s last step.",why:"The assistant likely violated sequencing, scope, or approval expectations.",pattern:"User immediately rejects an assistant action or proposed next step.",antiPattern:"Treating the rejected action as acceptable and continuing without changing course.",nextAction:"Pause, convert the pushback into a workflow constraint, and adjust the next tool use."}}a(bt,"lessonTemplate");function ye(n){let t=n.toLowerCase().replace(/\s+/g," ").trim();return ut.createHash("sha256").update(t).digest("hex")}a(ye,"hashSignal");function kt(n){try{let t=I(n);if(!t)return new Set;let e=m.recall(t,{types:["improvement-signal"],tags:{source:fe},limit:100,dedupeByKey:!1}),s=new Set;for(let r of e){let i=r.tags.key;i&&s.add(i)}return s}catch{return new Set}}a(kt,"projectMemoryHashes");var St=32;function we(n={}){let e=(n.hookHost===void 0?process.env.PRJCT_HOOK_HOST:n.hookHost)?.trim().toLowerCase().slice(0,St);return e&&ie.has(e)?e:n.detectedRuntime??oe()}a(we,"resolveInstructionRuntime");V();function be(n){try{return JSON.parse(n)}catch{return null}}a(be,"safeJsonParse");function k(n,t,e,s){let r=[];try{let{prjctDb:i}=(B(),z(ot)),o=i.query(n,t,...e);for(let u of o){let c=be(u.data);if(!c||typeof c!="object")continue;let p=c.tags;if(!p)continue;let l=s(p,c);l!==void 0&&r.push(l)}}catch{}return r}a(k,"collectFromPersistedEvents");var Se="lean-detector",vt="lean-debt-growth",Tt=3,ke=["off","lite","full","ultra"];function Rt(n){let t=n?.lean?.mode;if(t&&ke.includes(t))return t;let e=process.env.PRJCT_LEAN_MODE?.toLowerCase();return e&&ke.includes(e)?e:"off"}a(Rt,"effectiveMode");async function ve(n,t){let e={active:!1,total:0,previous:0,persisted:!1},s=t!==void 0?t:await v.readConfig(n).catch(()=>null);if(!s?.projectId||Rt(s)==="off")return e;e.active=!0;try{let r=await Et(n);if(e.total=r,r===0)return e;let i=_t(s.projectId);e.previous=i;let o=r-i;i>0&&o>=Tt&&(await m.remember(n,{type:"lean-debt",content:`Lean debt growing: \`lean:\` markers rose by ${o} (now ${r}, was ${i}). Deferred simplifications are accumulating \u2014 consider a leaning pass via \`prjct lean debt\`.`,tags:{source:Se,pattern:vt,total:String(r),previous:String(i),delta:String(o)},provenance:"inferred",projectId:s.projectId}),e.persisted=!0)}catch{}return e}a(ve,"detectAndPersistLeanDebt");async function Et(n){let t=await A(["grep","-cI","-e","lean:"],{cwd:n,maxBuffer:16777216});if(!t.ok){if(P(t,1))return 0;C(t)}return t.stdout.split(`
|
|
11
|
-
`).reduce((e,s)=>{let r=s.lastIndexOf(":");if(r<=0)return e;let i=Number.parseInt(s.slice(r+1),10);return Number.isFinite(i)?e+i:e},0)}a(Et,"measureLeanMarkers");function _t(n){return k(n,"SELECT data FROM events WHERE type = 'memory.remember.lean-debt' ORDER BY id DESC LIMIT 50",[],e=>{if(e.source!==Se)return;let s=typeof e.total=="string"?Number.parseInt(e.total,10):0;return Number.isFinite(s)?s:void 0})[0]??0}a(_t,"collectPreviousSnapshot");import At from"node:path";V();var Ct="hot-file",Te="pattern-detector-auto",It="recurring-bug",Re="pattern-detector-recurring",xt="tech-debt-growth",Ee="pattern-detector-debt",O=7,Pt=3,N=30,Mt=2,Lt=5,Dt=[/^package(-lock)?\.json$/,/^bun\.lock(b)?$/,/^pnpm-lock\.yaml$/,/^yarn\.lock$/,/^CHANGELOG\.md$/,/^\.gitignore$/,/\.snap$/,/^dist\//,/^node_modules\//];async function _e(n,t){let e={scanned:0,hotFiles:[],persisted:0,skipped:[],errors:[]},s=t!==void 0?t:await v.readConfig(n).catch(()=>null);if(!s?.projectId)return e.errors.push("no project config"),e;try{let r=await Ot(n);if(e.scanned+=r.length,e.hotFiles=r,r.length>0){let i=jt(s.projectId);for(let o of r){if(i.has(o.path)){e.skipped.push({reason:"already-marked-this-window",file:o.path});continue}try{await m.remember(n,{type:"learning",content:`Hot file: \`${o.path}\` \u2014 ${o.touches} touches in the last ${O} days. Worth a refactor pass or a deliberate decision about why it churns this often.`,tags:{source:Te,pattern:Ct,file:o.path,touches:String(o.touches),window_days:String(O)},provenance:"inferred"}),e.persisted+=1}catch(u){e.errors.push(`remember failed for ${o.path}: ${u.message}`)}}}}catch(r){e.errors.push(`hot-file detection failed: ${r.message}`)}try{let r=$t(s.projectId);if(r.length>0){let i=Ut(s.projectId);for(let o of r){if(i.has(o.topic)){e.skipped.push({reason:"recurring-bug-already-marked",file:o.topic});continue}try{await m.remember(n,{type:"learning",content:`Recurring bug pattern: gotchas tagged \`topic:${o.topic}\` reported ${o.occurrences} times in the last ${N} days. Likely a real underlying issue \u2014 consider a focused investigation before patching the next instance.`,tags:{source:Re,pattern:It,topic:o.topic,occurrences:String(o.occurrences),window_days:String(N)},provenance:"inferred"}),e.persisted+=1}catch(u){e.errors.push(`remember failed for recurring ${o.topic}: ${u.message}`)}}}}catch(r){e.errors.push(`recurring-bug detection failed: ${r.message}`)}try{let r=await Ht(n);if(r.totalCount>0){let i=Ft(s.projectId),o=r.totalCount-i;if(i>0&&o>=Lt)try{await m.remember(n,{type:"learning",content:`Tech debt growing: TODO/FIXME/XXX count rose by ${o} (now ${r.totalCount}, was ${i}). Consider a focused debt-reduction pass before adding more features.`,tags:{source:Ee,pattern:xt,total:String(r.totalCount),previous:String(i),delta:String(o)},provenance:"inferred"}),e.persisted+=1}catch(u){e.errors.push(`remember failed for tech-debt: ${u.message}`)}}}catch(r){e.errors.push(`tech-debt detection failed: ${r.message}`)}return e}a(_e,"detectAndPersistPatterns");async function Ot(n){let t=await A(["log",`--since=${O}.days.ago`,"--name-only","--pretty=format:","-z"],{cwd:n,maxBuffer:16777216,timeoutMs:15e3});if(!t.ok){if(t.kind==="exit")return[];C(t)}let e=new Map;for(let r of t.stdout.split("\0")){let i=r.trim();i&&(Nt(i)||e.set(i,(e.get(i)??0)+1))}let s=[];for(let[r,i]of e)i<Pt||s.push({path:r,touches:i});return s.sort((r,i)=>i.touches-r.touches),s}a(Ot,"detectHotFiles");function Nt(n){let t=At.basename(n);for(let e of Dt)if(e.test(n)||e.test(t))return!0;return!1}a(Nt,"isIgnored");function $t(n){let t=new Date(Date.now()-N*24*60*60*1e3).toISOString(),e=k(n,"SELECT data, timestamp FROM events WHERE type = 'memory.remember.gotcha' AND timestamp >= ? ORDER BY id DESC LIMIT 500",[t],i=>{if(i.source==="transcript-auto")return;let o=typeof i.topic=="string"?i.topic:void 0,u=typeof i.area=="string"?i.area:void 0;return(o??u)||void 0}),s=new Map;for(let i of e)s.set(i,(s.get(i)??0)+1);let r=[];for(let[i,o]of s)o<Mt||r.push({topic:i,occurrences:o});return r.sort((i,o)=>o.occurrences-i.occurrences),r}a($t,"detectRecurringBugs");async function Ht(n){let t=await A(["grep","-cE","\\b(TODO|FIXME|XXX)\\b"],{cwd:n,maxBuffer:16777216});if(!t.ok){if(P(t,1))return{totalCount:0};C(t)}return{totalCount:t.stdout.split(`
|
|
12
|
-
`).reduce((s,r)=>{let i=r.lastIndexOf(":");if(i<=0)return s;let o=Number.parseInt(r.slice(i+1),10);return Number.isFinite(o)?s+o:s},0)}}a(Ht,"measureTechDebt");function Ft(n){return k(n,"SELECT data FROM events WHERE type = 'memory.remember.learning' ORDER BY id DESC LIMIT 50",[],e=>{if(e.source!==Ee)return;let s=typeof e.total=="string"?Number.parseInt(e.total,10):0;return Number.isFinite(s)?s:void 0})[0]??0}a(Ft,"collectPreviousDebtSnapshot");function jt(n){let t=Date.now()-O*24*60*60*1e3,e=k(n,"SELECT data FROM events WHERE type = 'memory.remember.learning' ORDER BY id DESC LIMIT 200",[],(s,r)=>{if(s.source!==Te)return;let i=s.file,o=r.rememberedAt;if(typeof i=="string"){if(typeof o=="string"){let u=Date.parse(o);if(!Number.isNaN(u)&&u<t)return}return i}});return new Set(e)}a(jt,"collectAlreadyMarkedHotFiles");function Ut(n){let t=Date.now()-N*24*60*60*1e3,e=k(n,"SELECT data FROM events WHERE type = 'memory.remember.learning' ORDER BY id DESC LIMIT 200",[],(s,r)=>{if(s.source!==Re)return;let i=s.topic,o=r.rememberedAt;if(typeof i=="string"){if(typeof o=="string"){let u=Date.parse(o);if(!Number.isNaN(u)&&u<t)return}return i}});return new Set(e)}a(Ut,"collectAlreadyMarkedRecurringBugs");st();it();import x from"node:fs/promises";import Ae from"node:path";B();var Bt={conservative:{inboxDays:30,archivesDays:180,checkpointsDays:null},standard:{inboxDays:14,archivesDays:90,checkpointsDays:30},aggressive:{inboxDays:7,archivesDays:30,checkpointsDays:14}};function Gt(n=process.env){let t=(n.PRJCT_CLEANUP_AGGRESSIVENESS??"standard").toLowerCase();return Bt[t==="conservative"||t==="standard"||t==="aggressive"?t:"standard"]}a(Gt,"resolveProfile");async function Jt(n,t){let e=Date.now()-t*24*60*60*1e3,r=m.recall(n,{types:["inbox"],limit:200}).filter(o=>Date.parse(o.rememberedAt)<e);if(r.length===0)return 0;let i=[];for(let o of r)try{G.archive(n,{entityType:"memory_entry",entityId:o.id,entityData:{type:o.type,content:o.content,tags:o.tags,rememberedAt:o.rememberedAt},summary:o.content.slice(0,80),reason:`inbox-age-out (>${t}d)`});let u=o.id.startsWith("mem_")?o.id.slice(4):null;u&&b.run(n,"UPDATE events SET type = ? WHERE id = ?","memory.archived.inbox",Number(u)),b.run(n,"UPDATE memory_entries SET deleted_at = ? WHERE id = ?",Date.now(),o.id),i.push(o.id)}catch{}return i.length}a(Jt,"archiveAgedInbox");async function Wt(n,t){if(t===null)return 0;let e=Ae.join(ee.getGlobalProjectPath(n),"checkpoints"),s=await x.readdir(e).catch(()=>null);if(!s)return 0;let r=Date.now()-t*24*60*60*1e3,i=[];for(let o of s){if(!o.endsWith(".json"))continue;let u=Ae.join(e,o);try{(await x.stat(u)).mtimeMs<r&&(await x.unlink(u),i.push(u))}catch{}}return i.length}a(Wt,"pruneOldCheckpoints");async function Xt(){let{getVerifyCachePath:n}=await import("./context7-service-GDJ3QICX.mjs"),t=n();try{let e=await x.stat(t);if((Date.now()-e.mtimeMs)/(1440*60*1e3)>7)return await x.unlink(t),!0}catch{}return!1}a(Xt,"rotateContext7Cache");async function Ce(n){let t=Gt(),e={inboxArchived:0,archivesPruned:0,checkpointsRemoved:0,context7CacheRotated:!1};try{e.inboxArchived=await Jt(n,t.inboxDays)}catch{}try{e.archivesPruned=G.pruneOldArchives(n,t.archivesDays)}catch{}try{e.checkpointsRemoved=await Wt(n,t.checkpointsDays)}catch{}try{e.context7CacheRotated=await Xt()}catch{}return e}a(Ce,"runSessionCleanup");async function Ie(n,t){if(t.inboxArchived+t.archivesPruned+t.checkpointsRemoved+(t.context7CacheRotated?1:0)===0)return;let r=`Session cleanup: ${[t.inboxArchived>0?`${t.inboxArchived} inbox archived`:null,t.archivesPruned>0?`${t.archivesPruned} archives pruned`:null,t.checkpointsRemoved>0?`${t.checkpointsRemoved} checkpoints removed`:null,t.context7CacheRotated?"context7 cache rotated":null].filter(i=>!!i).join(", ")}`;b.appendEvent(n,"memory.remember.system-event",{content:r,tags:{source:"session-cleanup",key:"last-cleanup"},provenance:"extracted",content_hash:te(r),project_id:n})}a(Ie,"recordCleanupReport");import Kt from"node:crypto";import zt from"node:fs/promises";import{z as w}from"zod";tt();B();var Pe="crew-run:",xe=w.object({id:w.string().min(1),spec_id:w.string().nullable().default(null),task_id:w.string().nullable().default(null),started_at:w.string().min(1),ended_at:w.string().min(1),implementer_summary:w.string().default(""),files_touched:w.array(w.string()).default([]),reviewer_verdict:w.enum(["APPROVED","CHANGES_REQUESTED"]),reviewer_notes:w.string().nullable().default(null)});function $(n){return`${Pe}${n}`}a($,"keyFor");var X=class{static{a(this,"CrewRunStorage")}record(t,e){let s=e.runId??ne(),r=b.getDoc(t,$(s));if(r)return r;let i=Q(),o=xe.parse({id:s,spec_id:e.specId??null,task_id:e.taskId??null,started_at:e.startedAt??i,ended_at:e.endedAt??i,implementer_summary:e.implementerSummary,files_touched:e.filesTouched,reviewer_verdict:e.reviewerVerdict,reviewer_notes:e.reviewerNotes??null});return b.setDoc(t,$(s),o),o}get(t,e){return b.getDoc(t,$(e))}list(t){return b.listDocsByPrefix(t,Pe).map(s=>xe.parse(s.data))}delete(t,e){b.deleteDoc(t,$(e))}},Me=new X;var Ne="skill-miss-detector",Le=3,Yt=280,qt=["decision","gotcha","anti-pattern"],Vt=5400*1e3,Qt=360*60*1e3,Zt=2,$e=5,en=8,He=new Set(["should","because","project","prjct","instead","always","never","using","value","state","change","changes","update","updated","function","return","returns","error","errors","tests","testing","config","default","import","export","before","after","without"]);async function Fe(n,t,e,s={}){let r=s.preloadedLines?s.preloadedLines:await zt.readFile(t,"utf-8").then(nn).catch(()=>null);if(!r)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let i=I(n);if(!i)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let o=rn(r);if(!o)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let u=(()=>{try{return cn(i,e)}catch{return null}})();if(!u)return{signalsRecorded:0,signalsSkipped:0,failures:[]};if(u.length===0)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let c=await se(n).catch(()=>[]),p=(()=>{try{let h=Date.now()-Qt;return new Set(Me.list(i).filter(g=>Date.parse(g.ended_at)>h).flatMap(g=>g.files_touched))}catch{return new Set}})(),l=tn(o,c,u,p);if(l.length===0)return{signalsRecorded:0,signalsSkipped:0,failures:[]};let f=un(i),d=[];for(let h of l.slice(0,Le)){let g=an(h.memId,h.excerpt).slice(0,12);if(f.has(g)){d.push("skipped");continue}try{await m.remember(n,{type:"improvement-signal",content:on(h),tags:{source:Ne,kind:"skill-miss",category:"skill-miss",...s.runtime?{runtime:s.runtime}:{},...s.model?{model:s.model}:{},relates:h.memId,file:h.evidenceFile,key:g,...e?{session:e}:{}},provenance:"extracted",projectId:i}),M.penalizeSkillMiss(i,h.memId),d.push("recorded")}catch{d.push("skipped")}}let y=d.filter(h=>h==="recorded").length,R=d.filter(h=>h==="skipped").length;return{signalsRecorded:y,signalsSkipped:R,failures:l.slice(0,Le).map(h=>({category:"skill-miss",expectedBehavior:`Apply relevant project rule ${h.memId}.`,observedBehavior:"Relevant project knowledge was not referenced in the session.",relatedRuleId:h.memId}))}}a(Fe,"detectSkillMisses");function tn(n,t,e,s=new Set){let r=De(n);if(r.size===0)return[];let i=t.filter(c=>!s.has(c)),o=H(i),u=[];for(let c of e){let p=De(`${c.content} ${c.fileTag}`);if(p.size===0)continue;let l=c.fileTag!==""&&i.some(g=>Oe(g,c.fileTag))||[...o].some(g=>p.has(g)),f=sn(p),d=[...p].filter(g=>!f.has(g)&&r.has(g)).length;if(!(l||d>=Zt)||[...f].some(g=>r.has(g)))continue;let h=c.fileTag!==""&&i.some(g=>Oe(g,c.fileTag))?c.fileTag:i.find(g=>[...H([g])].some(et=>p.has(et)))??"";u.push({miss:{memId:c.id,memType:c.type,excerpt:c.content.replace(/\s+/g," ").trim().slice(0,Yt),evidenceFile:h,reason:l?"path-overlap-unused":"topic-overlap-unused"},rank:l?2:1,overlap:d})}return u.sort((c,p)=>p.rank-c.rank||p.overlap-c.overlap),u.map(c=>c.miss)}a(tn,"analyze");function nn(n){return T(n)}a(nn,"parseJsonl");function rn(n){let t=[];for(let e of n){let s=e.role??e.message?.role;if(s!=="user"&&s!=="assistant")continue;let r=D(e.content??e.message?.content);r&&t.push(r)}return t.join(`
|
|
13
|
-
`).toLowerCase()}a(rn,"transcriptTextOf");function De(n){let t=new Set;for(let e of n.toLowerCase().split(/[^a-z0-9]+/))e.length<$e||He.has(e)||t.add(e);return t}a(De,"tokenize");function sn(n){let t=[...n].filter(s=>s.length>=en);if(t.length>0)return new Set(t);let e=[...n].sort((s,r)=>r.length-s.length||s.localeCompare(r))[0]??"";return e?new Set([e]):new Set}a(sn,"signatureOf");function H(n){let t=new Set;for(let e of n)for(let s of e.split("/")){let r=s.replace(/\.[a-z0-9]+$/i,"").toLowerCase();r.length>=$e&&!He.has(r)&&t.add(r)}return t}a(H,"fileStems");function Oe(n,t){let e=H([n]);for(let s of H([t]))if(e.has(s))return!0;return!1}a(Oe,"sharesStem");function on(n){let t=n.evidenceFile!==""?`touched \`${n.evidenceFile}\``:"worked the same area";return[`[skill-miss] Unused project knowledge (${n.memType}, ${n.memId}): "${n.excerpt}"`,`This session ${t} but never referenced it. Apply it, or supersede it via: prjct remember decision "<resolution>" --tags resolves:skill-miss,relates:${n.memId}`].join(`
|
|
14
|
-
`)}a(on,"formatSkillMiss");function an(n,t){let e=`${n}::${t.toLowerCase().replace(/\s+/g," ").trim()}`;return Kt.createHash("sha256").update(e).digest("hex")}a(an,"hashKey");function cn(n,t){let e=m.recall(n,{types:[...qt],limit:120}),s=Date.now()-Vt,r=[];for(let i of e)i.provenance!=="inferred"&&(Date.parse(i.rememberedAt)>s||t&&i.tags.session===t||r.push({id:i.id,type:i.type,content:i.content,fileTag:i.tags.file??"",rememberedAt:i.rememberedAt,provenance:i.provenance,session:i.tags.session??""}));return r}a(cn,"recallCandidates");function un(n){try{let t=m.recall(n,{types:["improvement-signal"],tags:{source:Ne},limit:100,dedupeByKey:!1}),e=new Set;for(let s of t)s.tags.key&&e.add(s.tags.key);return e}catch{return new Set}}a(un,"existingSkillMissKeys");import ln from"node:crypto";import pn from"node:fs/promises";var Be="transcript-auto",dn="v2",Ge=80,Je=20,F=1500,fn=12,je=4,gn=[{phrase:"decided to",type:"decision"},{phrase:"we chose",type:"decision"},{phrase:"going with",type:"decision"},{phrase:"the right call",type:"decision"},{phrase:"best approach is",type:"decision"},{phrase:"we will use",type:"decision"},{phrase:"shipping with",type:"decision"},{phrase:"turns out that",type:"learning"},{phrase:"now i understand",type:"learning"},{phrase:"the key insight",type:"learning"},{phrase:"i learned that",type:"learning"},{phrase:"discovered that",type:"learning"},{phrase:"root cause is",type:"learning"},{phrase:"root cause was",type:"learning"},{phrase:"the fix is",type:"learning"},{phrase:"gotcha:",type:"gotcha"},{phrase:"bug:",type:"gotcha"},{phrase:"fails when",type:"gotcha"},{phrase:"breaks when",type:"gotcha"},{phrase:"be careful",type:"gotcha"},{phrase:"never do this",type:"gotcha"},{phrase:"trap:",type:"gotcha"},{phrase:"important:",type:"fact"},{phrase:"always use",type:"fact"},{phrase:"never write",type:"fact"},{phrase:"the pattern is",type:"pattern"},{phrase:"anti-pattern:",type:"anti-pattern"},{phrase:"antipattern:",type:"anti-pattern"}],We=[{re:/^(?:[-*•]\s+)?(?:\*\*)?decision(?:\*\*)?\s*[:—-]\s+/i,type:"decision",phrase:"label:decision"},{re:/^(?:[-*•]\s+)?(?:\*\*)?(learning|insight)(?:\*\*)?\s*[:—-]\s+/i,type:"learning",phrase:"label:learning"},{re:/^(?:[-*•]\s+)?(?:\*\*)?(gotcha|trap|warning)(?:\*\*)?\s*[:—-]\s+/i,type:"gotcha",phrase:"label:gotcha"},{re:/^(?:[-*•]\s+)?(?:\*\*)?(fact|note)(?:\*\*)?\s*[:—-]\s+/i,type:"fact",phrase:"label:fact"},{re:/^(?:[-*•]\s+)?(?:\*\*)?root\s*cause(?:\*\*)?\s*[:—-]\s+/i,type:"learning",phrase:"label:root-cause"},{re:/^(?:[-*•]\s+)?(?:\*\*)?pattern(?:\*\*)?\s*[:—-]\s+/i,type:"pattern",phrase:"label:pattern"},{re:/^(?:[-*•]\s+)?(?:\*\*)?anti[- ]?pattern(?:\*\*)?\s*[:—-]\s+/i,type:"anti-pattern",phrase:"label:anti-pattern"}];async function Xe(n,t,e,s={}){let r={scanned:0,ingested:0,skipped:[],errors:[]},i=s.preloadedConfig!==void 0?s.preloadedConfig:await v.readConfig(n).catch(()=>null);if(!i?.projectId)return r.errors.push("no project config"),r;let o=await(async()=>{if(s.preloadedLines)return s.preloadedLines;try{return T(await pn.readFile(t,"utf-8"))}catch(d){return r.errors.push(`transcript read failed: ${d.message}`),null}})();if(o===null)return r;let u=mn(o),c=hn(o);if(r.scanned=u.length+c.length,u.length===0&&c.length===0)return r;let p=[...kn(u),...wn(c)];if(p.length===0)return r;let l=vn(i.projectId),f=e?e.slice(0,12):"unknown";for(let d of p){if(l.has(d.hash)){r.skipped.push({reason:"duplicate",phrase:d.matchedPhrase});continue}try{await m.remember(n,{type:d.type,content:d.content,tags:{source:Be,capture:dn,session:f,hash:d.hash,phrase:d.matchedPhrase},provenance:"inferred",projectId:i.projectId}),r.ingested+=1}catch(y){r.errors.push(`remember failed: ${y.message}`)}}return r}a(Xe,"ingestTranscript");function mn(n){let t=[];for(let e of n){let s=Ke(e);if(s!=="assistant")continue;let r=ze(e);!r||r.length<Ge||t.push({role:s,text:r})}return t}a(mn,"projectMessages");function hn(n){let t=[];for(let e of n){let s=Ke(e);if(s!=="user")continue;let r=ze(e);!r||r.length<Je||t.push({role:s,text:r})}return t}a(hn,"projectUserMessages");var yn=[{re:/^(?:please\s+)?always\b/i,phrase:"user:always"},{re:/^(?:please\s+)?never\b/i,phrase:"user:never"},{re:/\bi (?:always|never|prefer)\b/i,phrase:"user:i-prefer"},{re:/^(?:rule|preference)\s*[:—-]/i,phrase:"user:rule"},{re:/\bno more\s+(?:features?|feature\s+creep)\b/i,phrase:"user:no-more-features"},{re:/\bdon'?t add (?:more )?(?:features?|surface)\b/i,phrase:"user:dont-add-features"}];function wn(n){let t=[],e=new Set;for(let s of n){if(t.length>=je)break;let r=s.text.split(/\n/).map(o=>o.replace(/^[-*•]\s+/,"").trim()).filter(o=>o.length>=Je),i=r.length>0?r:[s.text.trim()];for(let o of i){if(t.length>=je)break;let u=yn.find(l=>l.re.test(o));if(!u)continue;let c=o.length>F?`${o.slice(0,F)}\u2026`:o,p=Ye(c);e.has(p)||(e.add(p),t.push({type:"feedback",content:c,hash:p,matchedPhrase:u.phrase}))}}return t}a(wn,"extractUserPreferenceCandidates");function Ke(n){let t=n.role;if(typeof t=="string")return Ue(t);let e=n.message;if(e&&typeof e=="object"&&"role"in e){let r=e.role;if(typeof r=="string")return Ue(r)}let s=n.type;return s==="assistant"||s==="user"||s==="system"?s:null}a(Ke,"inferRole");function Ue(n){let t=n.toLowerCase();return t==="assistant"||t==="user"||t==="system"?t:null}a(Ue,"normalizeRole");function ze(n){let t=n.content===void 0&&n.message&&typeof n.message=="object"?n.message.content:n.content;if(typeof t=="string")return t.trim();if(Array.isArray(t)){let e=[];for(let s of t){if(!s||typeof s!="object")continue;let r=s;r.type==="text"&&typeof r.text=="string"&&e.push(r.text)}return e.join(`
|
|
15
|
-
`).trim()}return""}a(ze,"extractText");function bn(n){let t=n.trim();if(t.length<Ge)return null;for(let r of We)if(r.re.test(t))return{type:r.type,matchedPhrase:r.phrase};let e=t.toLowerCase(),s=gn.find(r=>e.includes(r.phrase));return s?{type:s.type,matchedPhrase:s.phrase}:null}a(bn,"classifyCaptureParagraph");function kn(n){let t=[],e=new Set;for(let s of n){let r=Sn(s.text);for(let i of r){if(t.length>=fn)return t;let o=bn(i);if(!o)continue;let u=i.length>F?`${i.slice(0,F)}\u2026`:i,c=Ye(u);e.has(c)||(e.add(c),t.push({type:o.type,content:u,hash:c,matchedPhrase:o.matchedPhrase}))}}return t}a(kn,"extractCandidates");function Sn(n){let t=n.split(/\n\s*\n/).map(s=>s.trim()).filter(Boolean),e=[];for(let s of t){let r=s.split(`
|
|
16
|
-
`).map(o=>o.trim()).filter(Boolean);if(r.some(o=>We.some(u=>u.re.test(o)))&&r.length>1)for(let o of r)e.push(o);else e.push(s)}return e}a(Sn,"splitParagraphs");function Ye(n){return ln.createHash("sha256").update(n.toLowerCase().trim()).digest("hex").slice(0,16)}a(Ye,"hashContent");function vn(n){try{let{REMEMBER_EVENT_RANGE:t}=(ct(),z(at)),e=k(n,"SELECT data FROM events WHERE type >= ? AND type < ? ORDER BY id DESC LIMIT 500",[...t],s=>{if(s.source!==Be)return;let r=s.hash;return typeof r=="string"?r:void 0});return new Set(e)}catch{return new Set}}a(vn,"collectExistingAutoHashes");rt();nt();import Tn from"node:fs/promises";import qe from"node:path";function Rn(){return process.env.PRJCT_TEST_MODE==="1"?qe.join(U(".prjct-tests"),"kimi-code","sessions"):U(".kimi-code","sessions")}a(Rn,"getKimiSessionsRoot");async function Ve(n,t=Rn()){let e=n.replace(/[^a-zA-Z0-9_-]/g,"");if(!e)return;let s=e.startsWith("session_")?[e]:[e,`session_${e}`],r=await Tn.readdir(t,{withFileTypes:!0}).catch(()=>[]);for(let i of r)if(i.isDirectory())for(let o of s){let u=qe.join(t,i.name,o,"agents","main","wire.jsonl");if(await Z(u))return u}}a(Ve,"resolveKimiTranscriptPath");var j=600*1e3,_=new Map;function En(n){let t=n.replace(/[^a-zA-Z0-9._-]/g,"_");return Qe.join(q.runDir(),`stop-heavy-${t}.stamp`)}a(En,"heavyStepStampPath");async function Ze(n,t,e=!0){if(await S.stat(n).then(i=>t-i.mtimeMs<j).catch(()=>!1))return!1;let r=`${n}.lock`;try{await S.mkdir(r)}catch(i){if(i.code!=="EEXIST")throw i;return!await S.stat(r).then(u=>t-u.mtimeMs>=j).catch(()=>!1)||!e?!1:(await S.rmdir(r).catch(()=>{}),Ze(n,t,!1))}try{return await S.stat(n).then(o=>t-o.mtimeMs<j).catch(()=>!1)?!1:(await S.writeFile(n,String(t)),!0)}finally{await S.rmdir(r).catch(()=>{})}}a(Ze,"claimHeavyStep");async function _n(n){let t=Date.now(),e=_.get(n)??0;if(t-e<j)return!1;try{let s=En(n);await S.mkdir(Qe.dirname(s),{recursive:!0});let r=await Ze(s,t);return _.size>32&&_.clear(),_.set(n,t),r}catch{}return _.size>32&&_.clear(),_.set(n,t),!0}a(_n,"heavyStepsDue");function cs(n=process.cwd(),t){return ce({event:"Stop",projectPath:n,afterEmit:a(async(e,s)=>{let r=await v.readConfig(s).catch(()=>null);if(!r?.projectId)return;let i=we(),o=e.transcript_path??(Y()==="kimi"&&e.session_id?await Ve(e.session_id).catch(()=>{}):void 0),u=await _n(r.projectId),c={};if(u&&o){let l=await S.readFile(o,"utf-8").catch(()=>null);l!==null&&(c.transcriptLines=T(l))}let p=ue(c.transcriptLines??[]);if(u)try{let{collectActiveTasks:l}=await import("./task-overview-PCUZWL5Q.mjs"),f=await l(r.projectId,s);c.activeTaskId=f.current?.id,c.activeTaskDescription=f.current?.description,c.activeTaskStartedAt=f.current?.startedAt}catch{}if(c.transcriptLines&&c.transcriptLines.length>0)try{if(c.transcriptUsage=W(c.transcriptLines),c.transcriptUsage.tokensIn+c.transcriptUsage.tokensOut>0){let l=c.activeTaskStartedAt?{sinceIso:c.activeTaskStartedAt}:void 0,f=W(c.transcriptLines,l);if(c.activeTaskId&&f.tokensIn+f.tokensOut>0){J(r.projectId,c.activeTaskId,f.tokensIn,f.tokensOut,{description:c.activeTaskDescription,agent:i,source:`${i}-transcript`});try{let{sumTranscriptUsageByModel:d}=await import("./transcript-jsonl-7W2NOJPZ.mjs");for(let[y,R]of d(c.transcriptLines,l))R.tokensIn+R.tokensOut<=0||J(r.projectId,c.activeTaskId,R.tokensIn,R.tokensOut,{model:y,agent:i,source:`${i}-transcript:${y}`})}catch{}}}}catch{}if(ae({projectId:r.projectId,sessionId:e.session_id,directory:s,taskId:c.activeTaskId,goal:c.activeTaskDescription,tokensIn:c.transcriptUsage?.tokensIn,tokensOut:c.transcriptUsage?.tokensOut,agent:i,model:p}),u&&o)try{await Xe(s,o,e.session_id??null,{preloadedConfig:r,preloadedLines:c.transcriptLines})}catch{}if(u){try{await _e(s,r)}catch{}try{await ve(s,r)}catch{}try{let l=await Ce(r.projectId);await Ie(r.projectId,l),L.pruneRetained(r.projectId)}catch{}}if(u&&o)try{let l=await me(s,o,e.session_id??null,{preloadedLines:c.transcriptLines,runtime:i,model:p});for(let f of l.failures)try{L.record(r.projectId,{source:"friction-detector",runtime:i,model:p,sessionId:e.session_id??null,taskId:c.activeTaskId??null,...f})}catch{}l.signalsRecorded>0&&c.activeTaskId&&M.penalizeSurfaced(r.projectId,c.activeTaskId)}catch{}if(u&&o)try{let l=await Fe(s,o,e.session_id??null,{preloadedLines:c.transcriptLines,runtime:i,model:p});for(let f of l.failures)try{L.record(r.projectId,{source:"skill-miss-detector",runtime:i,model:p,sessionId:e.session_id??null,taskId:c.activeTaskId??null,...f})}catch{}}catch{}if(u)try{await re.backfill(r.projectId,r,new Date().toISOString())}catch{}if(u&&c.activeTaskId){let l={projectId:r.projectId,projectPath:s,cycleDescription:c.activeTaskDescription??null,cycleId:c.activeTaskId,tokensIn:c.transcriptUsage?.tokensIn,tokensOut:c.transcriptUsage?.tokensOut,model:p},f=a(async d=>{try{await d()}catch{}},"runBestEffort");await f(async()=>{let{synthesizeLandHandoff:d}=await import("./land-synthesis-JLYUBKHR.mjs");await d(l)}),await f(async()=>{let{synthesizeJudgmentReceipt:d}=await import("./judgment-receipt-7A2DXVJA.mjs");await d(l)})}try{let{flushIfLinked:l}=await import("./auto-flush-CXWTU3RF.mjs");await l(s,r)}catch{}},"afterEmit")},t)}a(cs,"runStopHook");export{En as heavyStepStampPath,_n as heavyStepsDue,cs as runStopHook};
|