agentix-cli 0.26.0 → 0.28.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/README.md +67 -118
- package/apps/mac-helper/Sources/AgentXHelper/AXTree.swift +159 -0
- package/apps/mac-helper/Sources/AgentXHelper/Brand.swift +63 -0
- package/apps/mac-helper/Sources/AgentXHelper/Focus.swift +97 -0
- package/apps/mac-helper/Sources/AgentXHelper/HUD.swift +179 -0
- package/apps/mac-helper/Sources/AgentXHelper/OCR.swift +117 -0
- package/apps/mac-helper/Sources/AgentXHelper/Pointer.swift +309 -0
- package/apps/mac-helper/Sources/AgentXHelper/Screens.swift +67 -0
- package/apps/mac-helper/Sources/AgentXHelper/Typer.swift +185 -0
- package/apps/mac-helper/Sources/AgentXHelper/Vision.swift +201 -0
- package/apps/mac-helper/Sources/AgentXHelper/main.swift +265 -0
- package/apps/mac-helper/build.sh +39 -0
- package/apps/mac-voice/Resources/Info.plist +18 -0
- package/apps/mac-voice/Sources/AgentXVoice/AgentClient.swift +108 -0
- package/apps/mac-voice/Sources/AgentXVoice/Brand.swift +123 -0
- package/apps/mac-voice/Sources/AgentXVoice/Config.swift +68 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hold.swift +74 -0
- package/apps/mac-voice/Sources/AgentXVoice/Hotkey.swift +76 -0
- package/apps/mac-voice/Sources/AgentXVoice/Markdown.swift +140 -0
- package/apps/mac-voice/Sources/AgentXVoice/Panel.swift +275 -0
- package/apps/mac-voice/Sources/AgentXVoice/Progress.swift +147 -0
- package/apps/mac-voice/Sources/AgentXVoice/Recorder.swift +139 -0
- package/apps/mac-voice/Sources/AgentXVoice/ResultCard.swift +162 -0
- package/apps/mac-voice/Sources/AgentXVoice/SmartPaste.swift +72 -0
- package/apps/mac-voice/Sources/AgentXVoice/Speech.swift +192 -0
- package/apps/mac-voice/Sources/AgentXVoice/StepLabel.swift +159 -0
- package/apps/mac-voice/Sources/AgentXVoice/main.swift +380 -0
- package/apps/mac-voice/build.sh +32 -0
- package/dist/{App-BPNHIGUX.js → App-CKPH3HHF.js} +2 -2
- package/dist/{ChatApp-6XSSZB4U.js → ChatApp-MX7IG4K2.js} +2 -2
- package/dist/agent-2U574KBZ.js +2 -0
- package/dist/article-fields-L4D2BOGY.js +2 -0
- package/dist/article-quality-44ONVGLN.js +3 -0
- package/dist/article-quality-44ONVGLN.js.map +1 -0
- package/dist/{audit-JU3HWISB.js → audit-4245CX6P.js} +2 -2
- package/dist/backfill-MTD2B62I.js +6 -0
- package/dist/backfill-MTD2B62I.js.map +1 -0
- package/dist/{board-dashboard-M3372FLO.js → board-dashboard-QR7CVTKA.js} +1411 -453
- package/dist/board-dashboard-QR7CVTKA.js.map +1 -0
- package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
- package/dist/calibration-ILS5OI44.js +2 -0
- package/dist/{chunk-V3U4OF7L.js → chunk-3LYM22IV.js} +46 -48
- package/dist/chunk-3LYM22IV.js.map +1 -0
- package/dist/chunk-3SCPRYJB.js +5 -0
- package/dist/chunk-3SCPRYJB.js.map +1 -0
- package/dist/chunk-4BR7D2OU.js +36 -0
- package/dist/chunk-4BR7D2OU.js.map +1 -0
- package/dist/{chunk-P4VWIVKN.js → chunk-52ZPELD2.js} +403 -29
- package/dist/chunk-52ZPELD2.js.map +1 -0
- package/dist/chunk-5IA2CYHN.js +5 -0
- package/dist/{chunk-O6YPEOQF.js.map → chunk-5IA2CYHN.js.map} +1 -1
- package/dist/chunk-64CAIB3C.js +9 -0
- package/dist/chunk-64CAIB3C.js.map +1 -0
- package/dist/{chunk-5U35WAZF.js → chunk-77OV7346.js} +6 -6
- package/dist/chunk-77OV7346.js.map +1 -0
- package/dist/chunk-AJ5RMU7X.js +2 -0
- package/dist/chunk-AJ5RMU7X.js.map +1 -0
- package/dist/chunk-AJONZWLT.js +2 -0
- package/dist/chunk-AJONZWLT.js.map +1 -0
- package/dist/chunk-BH3GTCZ6.js +2 -0
- package/dist/chunk-BH3GTCZ6.js.map +1 -0
- package/dist/chunk-E3UJHQGN.js +1189 -0
- package/dist/chunk-E3UJHQGN.js.map +1 -0
- package/dist/chunk-EVWEG3VD.js +3 -0
- package/dist/chunk-EVWEG3VD.js.map +1 -0
- package/dist/chunk-F4HZTZHW.js +2 -0
- package/dist/chunk-F4HZTZHW.js.map +1 -0
- package/dist/chunk-F6CNF7V3.js +25 -0
- package/dist/chunk-F6CNF7V3.js.map +1 -0
- package/dist/chunk-FIOB3MEX.js +2 -0
- package/dist/{chunk-H5D7ATXS.js → chunk-FKBGJYWQ.js} +5 -5
- package/dist/chunk-FKBGJYWQ.js.map +1 -0
- package/dist/{chunk-BVGJSPW4.js → chunk-G2HMRDUQ.js} +7 -7
- package/dist/chunk-G2HMRDUQ.js.map +1 -0
- package/dist/chunk-H2QQU2XV.js +109 -0
- package/dist/chunk-H2QQU2XV.js.map +1 -0
- package/dist/{chunk-LDHPMJ7M.js → chunk-IWMW5432.js} +3 -3
- package/dist/chunk-IWMW5432.js.map +1 -0
- package/dist/chunk-K33GIBSE.js +2 -0
- package/dist/chunk-K33GIBSE.js.map +1 -0
- package/dist/chunk-L2WSPY6S.js +2 -0
- package/dist/chunk-L2WSPY6S.js.map +1 -0
- package/dist/chunk-LCIREYTD.js +54 -0
- package/dist/chunk-LCIREYTD.js.map +1 -0
- package/dist/chunk-MHIMGM4G.js +126 -0
- package/dist/chunk-MHIMGM4G.js.map +1 -0
- package/dist/chunk-P5ZBBEPL.js +13 -0
- package/dist/chunk-P5ZBBEPL.js.map +1 -0
- package/dist/{chunk-JTJIPNXY.js → chunk-PNWNVOEZ.js} +1 -1
- package/dist/chunk-PNWNVOEZ.js.map +1 -0
- package/dist/chunk-QHTQPBHU.js +45 -0
- package/dist/chunk-QHTQPBHU.js.map +1 -0
- package/dist/chunk-S2MNL5V6.js +2 -0
- package/dist/chunk-S2MNL5V6.js.map +1 -0
- package/dist/chunk-SCTIUFL4.js +5 -0
- package/dist/{chunk-K2CAPYES.js.map → chunk-SCTIUFL4.js.map} +1 -1
- package/dist/chunk-ULLAE6LE.js +157 -0
- package/dist/chunk-ULLAE6LE.js.map +1 -0
- package/dist/{chunk-DJEZ2HVU.js → chunk-VDMYBPYB.js} +1 -1
- package/dist/chunk-VDMYBPYB.js.map +1 -0
- package/dist/chunk-VIH7ARPF.js +547 -0
- package/dist/chunk-VIH7ARPF.js.map +1 -0
- package/dist/chunk-W5C2GDNC.js +32 -0
- package/dist/{chunk-JP5IEXR7.js.map → chunk-W5C2GDNC.js.map} +1 -1
- package/dist/chunk-WPMX3VGI.js +3 -0
- package/dist/chunk-WPMX3VGI.js.map +1 -0
- package/dist/chunk-YLBERT7N.js +24 -0
- package/dist/chunk-YLBERT7N.js.map +1 -0
- package/dist/chunk-YLGIZRHV.js +114 -0
- package/dist/chunk-YLGIZRHV.js.map +1 -0
- package/dist/chunk-ZMYGXHPT.js +121 -0
- package/dist/chunk-ZMYGXHPT.js.map +1 -0
- package/dist/chunk-ZTEU5JVQ.js +2 -0
- package/dist/chunk-ZTEU5JVQ.js.map +1 -0
- package/dist/{chunk-2WVX3LEC.js → chunk-ZVP6GB4G.js} +1 -1
- package/dist/chunk-ZVP6GB4G.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/client-ZLSXGPTV.js +2 -0
- package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
- package/dist/config-HMW3EBZL.js +2 -0
- package/dist/config-mutator-4SZ5YEVD.js +2 -0
- package/dist/{conflict-detector-D7VIYPDI.js → conflict-detector-ZPOT3M2C.js} +2 -2
- package/dist/conflict-detector-ZPOT3M2C.js.map +1 -0
- package/dist/context-planner-AQHJMVY2.js +17 -0
- package/dist/context-planner-AQHJMVY2.js.map +1 -0
- package/dist/debug-3MEUO2P2.js +2 -0
- package/dist/{discover-XJXQXXIO.js → discover-D4VVRNAI.js} +2 -2
- package/dist/discover-D4VVRNAI.js.map +1 -0
- package/dist/doctor-LRYV3QLK.js +2 -0
- package/dist/editor-chat-OB7IQOB5.js +137 -0
- package/dist/editor-chat-OB7IQOB5.js.map +1 -0
- package/dist/entry-triage-LK34TSQD.js +2 -0
- package/dist/entry-triage-LK34TSQD.js.map +1 -0
- package/dist/facts-YVEJOM7O.js +22 -0
- package/dist/facts-YVEJOM7O.js.map +1 -0
- package/dist/heal-FVLBHYP7.js +2 -0
- package/dist/index.d.ts +1040 -64
- package/dist/index.js +12 -19
- package/dist/index.js.map +1 -1
- package/dist/{ingest-whatsapp-LZE62INA.js → ingest-whatsapp-NS4OWDOU.js} +2 -2
- package/dist/loader-4ZGTK7LD.js +2 -0
- package/dist/loader-BOKE5M5S.js +2 -0
- package/dist/memory-extract-F5ZHWY5E.js +2 -0
- package/dist/{migrate-v2-QO7SLKIM.js → migrate-v2-V4WN2VVM.js} +2 -2
- package/dist/ntfy-X7EPB3TG.js +4 -0
- package/dist/ntfy-X7EPB3TG.js.map +1 -0
- package/dist/processes-WU23U2OJ.js +2 -0
- package/dist/program-GSZ5AYAM.js +2 -0
- package/dist/{projects-api-KRME2YKZ.js → projects-api-QE6L65SK.js} +2 -2
- package/dist/{projects-mutate-3NHVG437.js → projects-mutate-MY7JTLSZ.js} +2 -2
- package/dist/providers-KO2DODIO.js +2 -0
- package/dist/query-SQDHE4HV.js +2 -0
- package/dist/questions-4B4KSPXG.js +3 -0
- package/dist/questions-4B4KSPXG.js.map +1 -0
- package/dist/recipes-7S4MC5OJ.js +2 -0
- package/dist/registry-LE6FWYZC.js +2 -0
- package/dist/review-candidates-RQU5KNZM.js +4 -0
- package/dist/review-candidates-RQU5KNZM.js.map +1 -0
- package/dist/review-store-B4YE3EFK.js +4 -0
- package/dist/review-store-B4YE3EFK.js.map +1 -0
- package/dist/{rotation-memo-B3EXXSEH.js → rotation-memo-7T75BLEX.js} +2 -2
- package/dist/routing-ILERJXB6.js +2 -0
- package/dist/runner-YRBVNYTY.js +2 -0
- package/dist/scheduler-BFM3EINS.js +2 -0
- package/dist/seat-7WM7II2B.js +2 -0
- package/dist/select-X4KVMOP5.js +2 -0
- package/dist/select-X4KVMOP5.js.map +1 -0
- package/dist/store-MCOA6N4F.js +2 -0
- package/dist/{subagent-WV7QKQ3L.js → subagent-2SJHSSJS.js} +2 -2
- package/dist/{surface-usage-PRL6Z4U3.js → surface-usage-NS74AXSE.js} +2 -2
- package/dist/timers-PCB4ZIBD.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js +2 -0
- package/dist/triage-backtest-JNO7RKX7.js.map +1 -0
- package/dist/types-H5ENIUIT.js +2 -0
- package/dist/types-OIFU3KSQ.js +2 -0
- package/dist/types-OIFU3KSQ.js.map +1 -0
- package/dist/web/workflow-editor.global.js +1542 -0
- package/dist/web/workflow-editor.global.js.map +1 -0
- package/dist/{whatsapp-state-XMTCSRXU.js → whatsapp-state-6D6FHHD2.js} +2 -2
- package/dist/wiki-2AUFSIKO.js +2 -0
- package/dist/wiki-2AUFSIKO.js.map +1 -0
- package/dist/workflows/templates/branching.yaml +1 -1
- package/dist/{workspace-setup-TBQAHYHJ.js → workspace-setup-B3F3TUDE.js} +2 -2
- package/dist/workspace-setup-B3F3TUDE.js.map +1 -0
- package/package.json +14 -3
- package/scripts/postinstall.mjs +80 -0
- package/dist/agent-5QMITZT6.js +0 -2
- package/dist/architect-SEPWMWS4.js +0 -2
- package/dist/board-dashboard-M3372FLO.js.map +0 -1
- package/dist/chunk-2WVX3LEC.js.map +0 -1
- package/dist/chunk-3WQFCIB6.js +0 -24
- package/dist/chunk-3WQFCIB6.js.map +0 -1
- package/dist/chunk-4YCH6IZV.js +0 -2
- package/dist/chunk-53NRX2NA.js +0 -2
- package/dist/chunk-53NRX2NA.js.map +0 -1
- package/dist/chunk-5U35WAZF.js.map +0 -1
- package/dist/chunk-BFXONUUN.js +0 -108
- package/dist/chunk-BFXONUUN.js.map +0 -1
- package/dist/chunk-BFZUG66X.js +0 -45
- package/dist/chunk-BFZUG66X.js.map +0 -1
- package/dist/chunk-BTHHSY7D.js +0 -13
- package/dist/chunk-BTHHSY7D.js.map +0 -1
- package/dist/chunk-BVGJSPW4.js.map +0 -1
- package/dist/chunk-D46VZ7K7.js +0 -116
- package/dist/chunk-D46VZ7K7.js.map +0 -1
- package/dist/chunk-DJEZ2HVU.js.map +0 -1
- package/dist/chunk-E5CXCI33.js +0 -155
- package/dist/chunk-E5CXCI33.js.map +0 -1
- package/dist/chunk-FDWOECJY.js +0 -54
- package/dist/chunk-FDWOECJY.js.map +0 -1
- package/dist/chunk-H5D7ATXS.js.map +0 -1
- package/dist/chunk-HR4JSRZS.js +0 -3
- package/dist/chunk-HR4JSRZS.js.map +0 -1
- package/dist/chunk-ISEBLHWX.js +0 -118
- package/dist/chunk-ISEBLHWX.js.map +0 -1
- package/dist/chunk-JP5IEXR7.js +0 -32
- package/dist/chunk-JTJIPNXY.js.map +0 -1
- package/dist/chunk-K2CAPYES.js +0 -5
- package/dist/chunk-LDHPMJ7M.js.map +0 -1
- package/dist/chunk-METYYZKQ.js +0 -1115
- package/dist/chunk-METYYZKQ.js.map +0 -1
- package/dist/chunk-MTAPOCGA.js +0 -47
- package/dist/chunk-MTAPOCGA.js.map +0 -1
- package/dist/chunk-O6YPEOQF.js +0 -5
- package/dist/chunk-P4VWIVKN.js.map +0 -1
- package/dist/chunk-SR3X25TN.js +0 -3
- package/dist/chunk-SR3X25TN.js.map +0 -1
- package/dist/chunk-UHE5FCPB.js +0 -431
- package/dist/chunk-UHE5FCPB.js.map +0 -1
- package/dist/chunk-V3U4OF7L.js.map +0 -1
- package/dist/chunk-VJUTQAPJ.js +0 -2
- package/dist/chunk-VJUTQAPJ.js.map +0 -1
- package/dist/chunk-VT5XYFDD.js +0 -126
- package/dist/chunk-VT5XYFDD.js.map +0 -1
- package/dist/client-HGKAC6VP.js +0 -2
- package/dist/config-A4RWEJHV.js +0 -2
- package/dist/config-mutator-MNSFUN7D.js +0 -2
- package/dist/conflict-detector-D7VIYPDI.js.map +0 -1
- package/dist/context-planner-45GEWKGL.js +0 -17
- package/dist/context-planner-45GEWKGL.js.map +0 -1
- package/dist/debug-N3B5NVJU.js +0 -2
- package/dist/discover-XJXQXXIO.js.map +0 -1
- package/dist/doctor-3Q36ZFE6.js +0 -2
- package/dist/heal-HZ3EQD52.js +0 -2
- package/dist/loader-5CA3O5GM.js +0 -2
- package/dist/loader-6IHUCPVO.js +0 -2
- package/dist/memory-extract-AENFVVO5.js +0 -2
- package/dist/processes-UIC4XXA6.js +0 -2
- package/dist/program-SAUNRCCD.js +0 -2
- package/dist/providers-L27BJ5A6.js +0 -2
- package/dist/query-HZYYRCLU.js +0 -2
- package/dist/recipes-EPLE2SNT.js +0 -2
- package/dist/registry-HK3WQ7BS.js +0 -2
- package/dist/runner-BFYDWPUO.js +0 -2
- package/dist/scheduler-6T2SU5ST.js +0 -2
- package/dist/store-I3HEWVLQ.js +0 -2
- package/dist/timers-5LPZN55J.js +0 -2
- package/dist/types-VECTMYTO.js +0 -2
- package/dist/types-Y6ZCZ52Z.js +0 -2
- package/dist/wiki-M6YNRFC4.js +0 -2
- /package/dist/{App-BPNHIGUX.js.map → App-CKPH3HHF.js.map} +0 -0
- /package/dist/{ChatApp-6XSSZB4U.js.map → ChatApp-MX7IG4K2.js.map} +0 -0
- /package/dist/{agent-5QMITZT6.js.map → agent-2U574KBZ.js.map} +0 -0
- /package/dist/{architect-SEPWMWS4.js.map → article-fields-L4D2BOGY.js.map} +0 -0
- /package/dist/{audit-JU3HWISB.js.map → audit-4245CX6P.js.map} +0 -0
- /package/dist/{builtin-FRKAQMFS.js.map → builtin-B67DMJ3M.js.map} +0 -0
- /package/dist/{chunk-4YCH6IZV.js.map → calibration-ILS5OI44.js.map} +0 -0
- /package/dist/{client-HGKAC6VP.js.map → chunk-FIOB3MEX.js.map} +0 -0
- /package/dist/{config-A4RWEJHV.js.map → client-ZLSXGPTV.js.map} +0 -0
- /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
- /package/dist/{config-mutator-MNSFUN7D.js.map → config-HMW3EBZL.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-4SZ5YEVD.js.map} +0 -0
- /package/dist/{doctor-3Q36ZFE6.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-HZ3EQD52.js.map → doctor-LRYV3QLK.js.map} +0 -0
- /package/dist/{loader-5CA3O5GM.js.map → heal-FVLBHYP7.js.map} +0 -0
- /package/dist/{ingest-whatsapp-LZE62INA.js.map → ingest-whatsapp-NS4OWDOU.js.map} +0 -0
- /package/dist/{loader-6IHUCPVO.js.map → loader-4ZGTK7LD.js.map} +0 -0
- /package/dist/{memory-extract-AENFVVO5.js.map → loader-BOKE5M5S.js.map} +0 -0
- /package/dist/{processes-UIC4XXA6.js.map → memory-extract-F5ZHWY5E.js.map} +0 -0
- /package/dist/{migrate-v2-QO7SLKIM.js.map → migrate-v2-V4WN2VVM.js.map} +0 -0
- /package/dist/{program-SAUNRCCD.js.map → processes-WU23U2OJ.js.map} +0 -0
- /package/dist/{providers-L27BJ5A6.js.map → program-GSZ5AYAM.js.map} +0 -0
- /package/dist/{projects-api-KRME2YKZ.js.map → projects-api-QE6L65SK.js.map} +0 -0
- /package/dist/{projects-mutate-3NHVG437.js.map → projects-mutate-MY7JTLSZ.js.map} +0 -0
- /package/dist/{query-HZYYRCLU.js.map → providers-KO2DODIO.js.map} +0 -0
- /package/dist/{recipes-EPLE2SNT.js.map → query-SQDHE4HV.js.map} +0 -0
- /package/dist/{registry-HK3WQ7BS.js.map → recipes-7S4MC5OJ.js.map} +0 -0
- /package/dist/{runner-BFYDWPUO.js.map → registry-LE6FWYZC.js.map} +0 -0
- /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
- /package/dist/{scheduler-6T2SU5ST.js.map → routing-ILERJXB6.js.map} +0 -0
- /package/dist/{store-I3HEWVLQ.js.map → runner-YRBVNYTY.js.map} +0 -0
- /package/dist/{surface-usage-PRL6Z4U3.js.map → scheduler-BFM3EINS.js.map} +0 -0
- /package/dist/{timers-5LPZN55J.js.map → seat-7WM7II2B.js.map} +0 -0
- /package/dist/{types-VECTMYTO.js.map → store-MCOA6N4F.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
- /package/dist/{types-Y6ZCZ52Z.js.map → surface-usage-NS74AXSE.js.map} +0 -0
- /package/dist/{wiki-M6YNRFC4.js.map → timers-PCB4ZIBD.js.map} +0 -0
- /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-H5ENIUIT.js.map} +0 -0
- /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/crons/scheduler.ts","../src/intent/mode.ts","../src/intent/ledger.ts","../src/intent/instance.ts","../src/intent/governance.ts","../src/intent/decide.ts","../src/intent/divergence.ts","../src/intent/sources/cron.ts"],"sourcesContent":["import type { DaemonConfig, CronJobDef } from \"@/daemon/config\"\nimport type { AgentRegistry } from \"@/agents/registry\"\nimport type { HookRegistry } from \"@/hooks\"\nimport type { CronJobState, CronRunResult } from \"./types\"\nimport { execFile } from \"child_process\"\nimport { writeFileSync, mkdirSync, existsSync, readFileSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { applyConfigMutation, setAtPath } from \"@/daemon/config-mutator\"\nimport { getLedgerMode } from \"@/intent/mode\"\nimport { getDefaultLedger } from \"@/intent/instance\"\nimport { recordCronDispatch } from \"@/intent/sources/cron\"\n\n// --- Cron Scheduler: lightweight cron engine with timezone support ---\n// No external dependencies — uses setTimeout-based scheduling.\n\n/**\n * Append a soft output-length cap to a cron prompt when the job configured\n * `maxOutputTokens`. Claude Code CLI has no hard flag for output length,\n * but a clear instruction at the end of the prompt is reliably honored by\n * the model. Keeps a cheap knob available for operators without us needing\n * to invent our own token counter or hack a post-response truncate.\n */\nfunction withOutputCap(prompt: string, maxOutputTokens?: number): string {\n if (!maxOutputTokens) return prompt\n const approxChars = maxOutputTokens * 4\n return `${prompt}\\n\\n[Response budget]\\nKeep your response under ~${maxOutputTokens} tokens (~${approxChars} chars). Be concise — this is automated batch work, not a conversation.`\n}\n\n/**\n * Parse a cron expression into next-fire timestamp.\n * Supports standard 5-field format: minute hour day-of-month month day-of-week\n */\nfunction parseCronField(field: string, min: number, max: number): number[] {\n const values: number[] = []\n\n for (const part of field.split(\",\")) {\n if (part === \"*\") {\n for (let i = min; i <= max; i++) values.push(i)\n } else if (part.includes(\"/\")) {\n const [range, stepStr] = part.split(\"/\")\n const step = parseInt(stepStr, 10)\n const start = range === \"*\" ? min : parseInt(range, 10)\n for (let i = start; i <= max; i += step) values.push(i)\n } else if (part.includes(\"-\")) {\n const [a, b] = part.split(\"-\").map(Number)\n for (let i = a; i <= b; i++) values.push(i)\n } else {\n values.push(parseInt(part, 10))\n }\n }\n\n return [...new Set(values)].sort((a, b) => a - b)\n}\n\nexport function getNextCronDate(expression: string, after: Date, timezone: string): Date {\n const fields = expression.trim().split(/\\s+/)\n if (fields.length !== 5) throw new Error(`Invalid cron: ${expression}`)\n\n const minutes = parseCronField(fields[0], 0, 59)\n const hours = parseCronField(fields[1], 0, 23)\n const daysOfMonth = parseCronField(fields[2], 1, 31)\n const months = parseCronField(fields[3], 1, 12)\n const daysOfWeek = parseCronField(fields[4], 0, 6)\n\n // Convert to timezone-aware date\n const fmt = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n hour12: false,\n })\n\n // Start searching from next minute\n const candidate = new Date(after.getTime() + 60_000)\n candidate.setSeconds(0, 0)\n\n // Search up to 1 year ahead\n const limit = new Date(candidate.getTime() + 366 * 24 * 60 * 60 * 1000)\n\n while (candidate < limit) {\n const parts = fmt.formatToParts(candidate)\n const get = (type: string) => parseInt(parts.find((p) => p.type === type)?.value || \"0\", 10)\n\n const m = get(\"minute\")\n const h = get(\"hour\")\n const dom = get(\"day\")\n const mon = get(\"month\")\n const dow = candidate.getDay()\n\n if (\n minutes.includes(m) &&\n hours.includes(h) &&\n daysOfMonth.includes(dom) &&\n months.includes(mon) &&\n daysOfWeek.includes(dow)\n ) {\n return candidate\n }\n\n // Advance by 1 minute\n candidate.setTime(candidate.getTime() + 60_000)\n }\n\n throw new Error(`No next run found for cron \"${expression}\" within 1 year`)\n}\n\n// Retry config (inspired by OpenClaw's exponential backoff)\nconst MAX_RETRIES = 5\nconst RETRY_DELAYS = [30_000, 60_000, 300_000, 900_000, 3_600_000] // 30s, 1m, 5m, 15m, 60m\n\n/** Notification callback — injected by daemon to send alerts via channels */\nexport type CronNotifyCallback = (jobId: string, agent: string, error: string, consecutiveErrors: number) => Promise<void>\n\nexport class CronScheduler {\n private jobs: Map<string, CronJobState> = new Map()\n private timers: Map<string, ReturnType<typeof setTimeout>> = new Map()\n private registry: AgentRegistry\n private hooks?: HookRegistry\n private runsDir: string\n private lastRunFile: string\n private running = false\n private notifyCallback?: CronNotifyCallback\n private log: (...args: unknown[]) => void\n\n constructor(\n config: DaemonConfig,\n registry: AgentRegistry,\n hooks?: HookRegistry,\n log: (...args: unknown[]) => void = console.error.bind(console, \"[cron]\"),\n ) {\n this.registry = registry\n this.hooks = hooks\n this.log = log\n this.runsDir = resolve(process.cwd(), \".agentx/cron/runs\")\n this.lastRunFile = resolve(process.cwd(), \".agentx/cron/last-runs.json\")\n\n for (const [id, def] of Object.entries(config.crons)) {\n this.jobs.set(id, {\n id,\n enabled: def.enabled,\n schedule: def.schedule,\n timezone: def.timezone,\n agent: def.agent,\n prompt: def.prompt,\n command: def.command,\n timeout: def.timeout,\n model: def.model,\n maxOutputTokens: def.maxOutputTokens,\n onError: def.onError,\n consecutiveErrors: 0,\n totalRuns: 0,\n totalFailures: 0,\n })\n }\n }\n\n /**\n * Set a notification callback for failed crons.\n * Called when onError is \"notify\" or after multiple consecutive failures.\n */\n setNotifyCallback(cb: CronNotifyCallback): void {\n this.notifyCallback = cb\n }\n\n async start(): Promise<void> {\n this.running = true\n\n if (!existsSync(this.runsDir)) {\n mkdirSync(this.runsDir, { recursive: true })\n }\n\n // Detect missed runs before scheduling\n const missedRuns = this.detectMissedRuns()\n if (missedRuns.length > 0) {\n this.log(`Detected ${missedRuns.length} missed cron run(s) while daemon was down:`)\n for (const { jobId, missedAt } of missedRuns) {\n this.log(` \"${jobId}\" should have run at ${missedAt.toISOString()}`)\n }\n // Execute missed runs (fire-and-forget, don't block startup)\n this.executeMissedRuns(missedRuns).catch((e) => {\n this.log(`Error executing missed runs: ${e.message}`)\n })\n }\n\n for (const [id, job] of this.jobs) {\n if (!job.enabled) {\n this.log(`Job \"${id}\" is disabled, skipping`)\n continue\n }\n this.scheduleNext(id)\n }\n\n this.log(`${this.jobs.size} cron job(s) loaded, ${Array.from(this.jobs.values()).filter((j) => j.enabled).length} enabled`)\n }\n\n async stop(): Promise<void> {\n this.running = false\n for (const timer of this.timers.values()) {\n clearTimeout(timer)\n }\n this.timers.clear()\n\n // Persist last run times for missed run detection on next start\n this.saveLastRuns()\n }\n\n /** Node stores a timer delay in a 32-bit signed int. Anything larger is\n * silently coerced to 1ms — the timer fires IMMEDIATELY and only a\n * TimeoutOverflowWarning on stderr says why. ~24.8 days. */\n private static readonly MAX_TIMEOUT_MS = 2_147_483_647\n\n /**\n * Arm a timer for an absolute moment, however far away.\n *\n * A job scheduled further out than 24.8 days used to fire the instant\n * the daemon started, every restart, forever. A monthly accounting job\n * set for the 20th ran a month early on every deploy — and because the\n * only symptom was a warning about integers, it read as noise.\n *\n * Long waits are split into hops. Each hop recomputes the remaining time\n * from the TARGET rather than subtracting a constant, so the schedule\n * cannot drift across sleeps, clock adjustments or a slow hop.\n */\n private armTimer(jobId: string, targetMs: number, fire: () => void): void {\n const remaining = targetMs - Date.now()\n if (remaining > CronScheduler.MAX_TIMEOUT_MS) {\n const timer = setTimeout(\n () => this.armTimer(jobId, targetMs, fire),\n CronScheduler.MAX_TIMEOUT_MS,\n )\n this.timers.set(jobId, timer)\n return\n }\n // Negative means the moment already passed — fire now rather than\n // never, which is what a 0 delay does.\n const timer = setTimeout(() => {\n // setTimeout is permitted to fire up to a millisecond EARLY, and on\n // this fleet it does so on roughly one run in eight. The run is then\n // stamped 08:59:59.9xx for a slot of 09:00, and getNextCronDate —\n // which truncates its search start to the minute — hands back the\n // occurrence that has just fired. That occurrence is in the past by\n // the next daemon start, so detectMissedRuns reads it as a missed\n // firing and dispatches the agent a second time for the same slot.\n // Re-arming is cheaper than teaching every consumer of lastRun that\n // the timestamp it holds may be a minute short of the real slot.\n if (Date.now() < targetMs) {\n this.armTimer(jobId, targetMs, fire)\n return\n }\n fire()\n }, Math.max(0, remaining))\n this.timers.set(jobId, timer)\n }\n\n private scheduleNext(jobId: string): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n\n // Clear any existing timer\n const existing = this.timers.get(jobId)\n if (existing) clearTimeout(existing)\n\n try {\n const nextRun = getNextCronDate(job.schedule, new Date(), job.timezone)\n job.nextRun = nextRun\n job.retryPending = false\n const delay = nextRun.getTime() - Date.now()\n\n this.log(`Job \"${jobId}\" next run: ${nextRun.toISOString()} (in ${Math.round(delay / 1000)}s)`)\n\n this.armTimer(jobId, nextRun.getTime(), () => this.executeJob(jobId))\n } catch (e: any) {\n this.log(`Failed to schedule \"${jobId}\": ${e.message}`)\n }\n }\n\n private scheduleRetry(jobId: string, attempt: number): void {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled || !this.running) return\n if (attempt >= MAX_RETRIES) {\n this.log(`Job \"${jobId}\" exhausted all ${MAX_RETRIES} retries, scheduling next regular run`)\n this.scheduleNext(jobId)\n return\n }\n\n const delay = RETRY_DELAYS[attempt] || RETRY_DELAYS[RETRY_DELAYS.length - 1]\n job.retryPending = true\n\n this.log(`Job \"${jobId}\" retry ${attempt + 1}/${MAX_RETRIES} in ${Math.round(delay / 1000)}s`)\n\n const timer = setTimeout(() => this.executeJob(jobId, attempt + 1), delay)\n this.timers.set(jobId, timer)\n }\n\n /**\n * Phase 1 commit 6.d — record one cron-fire decision in the ledger\n * when the source is enabled. Wrapped in try/catch so a ledger\n * failure can never break cron dispatch — legacy stays authoritative\n * until the 1c per-source promotion lands.\n */\n private recordCronDecisionInLedger(\n jobId: string,\n agentId: string,\n firedAt: Date,\n legacy: import(\"@/intent/divergence\").LegacyOutcome,\n ): { eventId: string; decidedBy: string } | undefined {\n if (getLedgerMode(\"cron\") === \"off\") return undefined\n try {\n const decision = recordCronDispatch(\n getDefaultLedger(),\n { jobId, agentId, firedAt },\n JSON.stringify({ jobId, agentId, firedAt: firedAt.toISOString() }),\n legacy,\n )\n if (decision.outcome === \"dispatched\") {\n return { eventId: decision.eventId, decidedBy: decision.decidedBy }\n }\n return undefined\n } catch (e: any) {\n this.log(`[ledger] cron \"${jobId}\" record failed: ${e?.message ?? e}`)\n return undefined\n }\n }\n\n /**\n * Run a cron whose work is a shell command, with no model involved.\n *\n * Failure handling deliberately mirrors the agent path — same\n * consecutiveErrors, same notify, same disable-after-three, same retry —\n * so an operator does not have to learn two sets of cron semantics\n * depending on how a job happens to be defined.\n *\n * Only the output TAIL is kept. The agent prompts this replaces all said\n * \"report the exit code plus the last 10 lines\", which was the right\n * instinct: a run record is read by a person after something broke, and\n * the end of the output is where the breakage is.\n */\n private async executeCommandJob(\n job: CronJobState,\n startedAt: Date,\n isRetry: boolean,\n retryAttempt: number,\n ): Promise<void> {\n const command = job.command!.trim()\n this.log(`${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Running command for \"${job.id}\"`)\n\n let success = false\n let output = \"\"\n let error: string | undefined\n\n try {\n const { stdout, stderr, code } = await runShell(command, job.timeout * 1000)\n output = tail(`${stdout}${stderr ? `\\n${stderr}` : \"\"}`, COMMAND_OUTPUT_LINES)\n success = code === 0\n if (!success) error = `exit ${code}${output ? `\\n${output}` : \"\"}`\n } catch (e: any) {\n error = e?.message ?? String(e)\n }\n\n const result: CronRunResult = {\n jobId: job.id,\n startedAt,\n completedAt: new Date(),\n success,\n response: output || undefined,\n error,\n duration: Date.now() - startedAt.getTime(),\n isRetry,\n retryAttempt,\n }\n\n if (!success) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = error\n this.log(`Command job \"${job.id}\" failed (${job.consecutiveErrors} consecutive): ${error}`)\n await this.notifyFailure(job, error ?? \"command failed\")\n if (job.onError.includes(\"disable\") && job.consecutiveErrors >= 3) {\n job.enabled = false\n this.log(`Job \"${job.id}\" disabled after ${job.consecutiveErrors} consecutive errors`)\n try {\n await applyConfigMutation(\n (cfg) => setAtPath(cfg, `crons.${job.id}.enabled`, false),\n { reload: false },\n )\n } catch (e: any) {\n this.log(`Failed to persist disable for \"${job.id}\": ${e.message}`)\n }\n await this.notifyDisabled(job)\n }\n this.logRun(result)\n this.scheduleRetry(job.id, retryAttempt)\n return\n }\n\n if (job.consecutiveErrors > 0) {\n this.log(`Job \"${job.id}\" recovered after ${job.consecutiveErrors} failure(s)`)\n }\n job.consecutiveErrors = 0\n job.lastSuccess = new Date()\n job.lastError = undefined\n job.retryPending = false\n this.log(`Command job \"${job.id}\" completed in ${result.duration}ms`)\n this.logRun(result)\n this.scheduleNext(job.id)\n }\n\n private async executeJob(jobId: string, retryAttempt: number = 0): Promise<void> {\n const job = this.jobs.get(jobId)\n if (!job || !this.running) return\n\n const isRetry = retryAttempt > 0\n // firedAt is captured here (rather than below at the original\n // `startedAt` declaration) so the ledger event has a stable\n // sourceEventId regardless of whether we record at the hook-block\n // path or the dispatch path.\n const firedAt = new Date()\n\n // Pre-hook\n if (this.hooks?.has(\"pre:cron-run\" as any)) {\n const hookResult = await this.hooks.execute(\"pre:cron-run\" as any, {\n event: \"pre:cron-run\" as any,\n jobId,\n agent: job.agent,\n prompt: job.prompt,\n })\n if (hookResult.blocked) {\n this.log(`Job \"${jobId}\" blocked by hook: ${hookResult.message}`)\n this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: null, outcome: \"halted\",\n reason: `pre-hook blocked: ${hookResult.message ?? \"\"}`.trim(),\n })\n this.scheduleNext(jobId)\n return\n }\n }\n\n // Named after what will actually happen. A command job saying\n // `-> agent \"coo-agent\"` sends a reader looking for a dispatch that\n // never occurs.\n this.log(\n job.command?.trim()\n ? `${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> command`\n : `${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> agent \"${job.agent}\"`,\n )\n const startedAt = firedAt\n job.lastRun = startedAt\n job.totalRuns++\n\n // A command job never reaches a model. Branch before the ledger\n // dispatch record, because nothing is being dispatched TO.\n if (job.command?.trim()) {\n await this.executeCommandJob(job, startedAt, isRetry, retryAttempt)\n return\n }\n\n // Phase 1 commit 6.d — record the dispatch decision before the\n // (potentially long-running) registry.execute call. The returned\n // intentRef threads through to registry.execute so it records a\n // resolution on completion.\n const intentRef = this.recordCronDecisionInLedger(jobId, job.agent, firedAt, {\n agentId: job.agent, outcome: \"dispatched\", reason: isRetry ? `retry ${retryAttempt}` : null,\n })\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(job.prompt, job.maxOutputTokens),\n agentId: job.agent,\n model: job.model,\n intentRef,\n // chatId per-job so different cron jobs for the same agent don't\n // collide in one \"default\" session. Without this, the marketing\n // daily-brief and the marketing weekly-report cron share history,\n // and one job's prompt context bleeds into the other.\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt,\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || Date.now() - startedAt.getTime(),\n isRetry,\n retryAttempt,\n }\n\n if (response.error) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = response.error\n this.log(`Job \"${jobId}\" failed (${job.consecutiveErrors} consecutive): ${response.error}`)\n\n // Notify on failure\n await this.notifyFailure(job, response.error)\n\n if (job.onError.includes(\"disable\") && job.consecutiveErrors >= 3) {\n job.enabled = false\n this.log(`Job \"${jobId}\" disabled after ${job.consecutiveErrors} consecutive errors`)\n // Persist to agentx.json so a daemon restart doesn't resurrect the\n // broken cron (previously this was in-memory only — a repeatedly\n // failing cron would keep burning money across restarts).\n try {\n const res = await applyConfigMutation(\n (cfg) => setAtPath(cfg, `crons.${jobId}.enabled`, false),\n { reload: false },\n )\n if (!res.success) {\n this.log(`Failed to persist disable for \"${jobId}\": ${res.error}`)\n }\n } catch (e: any) {\n this.log(`Failed to persist disable for \"${jobId}\": ${e.message}`)\n }\n await this.notifyDisabled(job)\n }\n\n // Retry\n this.logRun(result)\n this.scheduleRetry(jobId, retryAttempt)\n return\n } else {\n // Success — reset error state\n if (job.consecutiveErrors > 0) {\n this.log(`Job \"${jobId}\" recovered after ${job.consecutiveErrors} failure(s)`)\n }\n job.consecutiveErrors = 0\n job.lastSuccess = new Date()\n job.lastError = undefined\n job.retryPending = false\n this.log(`Job \"${jobId}\" completed in ${result.duration}ms`)\n }\n\n // Log run\n this.logRun(result)\n\n // Post-hook\n if (this.hooks?.has(\"post:cron-run\" as any)) {\n await this.hooks.execute(\"post:cron-run\" as any, {\n event: \"post:cron-run\" as any,\n jobId,\n success: result.success,\n duration: result.duration,\n error: result.error ? new Error(result.error) : undefined,\n })\n }\n } catch (e: any) {\n job.consecutiveErrors++\n job.totalFailures++\n job.lastError = e.message\n this.log(`Job \"${jobId}\" threw: ${e.message}`)\n\n await this.notifyFailure(job, e.message)\n this.scheduleRetry(jobId, retryAttempt)\n return\n }\n\n // Persist last run time\n this.saveLastRuns()\n\n // Schedule next regular run\n this.scheduleNext(jobId)\n }\n\n // --- Missed run detection ---\n\n /**\n * Detect cron jobs that should have fired while the daemon was down.\n * Compares saved last-run times against the cron schedule.\n */\n private detectMissedRuns(): Array<{ jobId: string; missedAt: Date }> {\n const missed: Array<{ jobId: string; missedAt: Date }> = []\n\n const lastRuns = this.loadLastRuns()\n if (!lastRuns) return missed // First boot — no history\n\n for (const [jobId, job] of this.jobs) {\n if (!job.enabled) continue\n\n const lastRunStr = lastRuns[jobId]\n if (!lastRunStr) continue // Never ran before\n\n const lastRun = new Date(lastRunStr)\n try {\n // What SHOULD the next run have been after the last recorded run?\n const shouldHaveRun = getNextCronDate(job.schedule, lastRun, job.timezone)\n if (shouldHaveRun.getTime() < Date.now()) {\n missed.push({ jobId, missedAt: shouldHaveRun })\n }\n } catch {\n // Invalid schedule — skip\n }\n }\n\n return missed\n }\n\n /**\n * Execute missed runs (catch-up). Runs sequentially to avoid overwhelming agents.\n */\n private async executeMissedRuns(missed: Array<{ jobId: string; missedAt: Date }>): Promise<void> {\n for (const { jobId, missedAt } of missed) {\n const job = this.jobs.get(jobId)\n if (!job || !job.enabled) continue\n\n this.log(`Running missed job \"${jobId}\" (was due at ${missedAt.toISOString()})`)\n\n try {\n const response = await this.registry.execute({\n message: withOutputCap(\n `[MISSED RUN — was scheduled for ${missedAt.toISOString()}]\\n\\n${job.prompt}`,\n job.maxOutputTokens,\n ),\n agentId: job.agent,\n context: { channel: \"cron\", chatId: `cron:${jobId}` },\n })\n\n const result: CronRunResult = {\n jobId,\n startedAt: new Date(),\n completedAt: new Date(),\n success: !response.error,\n response: response.content,\n error: response.error,\n duration: response.duration || 0,\n isRetry: false,\n }\n\n this.logRun(result)\n\n if (response.error) {\n this.log(`Missed job \"${jobId}\" failed: ${response.error}`)\n } else {\n this.log(`Missed job \"${jobId}\" completed`)\n job.lastSuccess = new Date()\n }\n job.lastRun = new Date()\n job.totalRuns++\n } catch (e: any) {\n this.log(`Missed job \"${jobId}\" threw: ${e.message}`)\n }\n }\n\n this.saveLastRuns()\n }\n\n // --- Notification ---\n\n private async notifyFailure(job: CronJobState, error: string): Promise<void> {\n if (!job.onError.includes(\"notify\") && job.consecutiveErrors < 2) return\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" failed (${job.consecutiveErrors}x): ${error.slice(0, 200)}`)\n return\n }\n\n try {\n await this.notifyCallback(job.id, job.agent, error, job.consecutiveErrors)\n } catch {\n // Don't fail on notification errors\n }\n }\n\n private async notifyDisabled(job: CronJobState): Promise<void> {\n if (!this.notifyCallback) {\n this.log(`[ALERT] Cron \"${job.id}\" has been DISABLED after ${job.consecutiveErrors} consecutive failures`)\n return\n }\n\n try {\n await this.notifyCallback(\n job.id,\n job.agent,\n `AUTO-DISABLED after ${job.consecutiveErrors} consecutive failures. Last error: ${job.lastError || \"unknown\"}`,\n job.consecutiveErrors,\n )\n } catch {\n // Don't fail on notification errors\n }\n }\n\n // --- Persistence ---\n\n private saveLastRuns(): void {\n try {\n const data: Record<string, string> = {}\n for (const [id, job] of this.jobs) {\n if (job.lastRun) data[id] = job.lastRun.toISOString()\n }\n const dir = resolve(process.cwd(), \".agentx/cron\")\n if (!existsSync(dir)) mkdirSync(dir, { recursive: true })\n writeFileSync(this.lastRunFile, JSON.stringify(data, null, 2))\n } catch {\n // Best-effort\n }\n }\n\n private loadLastRuns(): Record<string, string> | null {\n try {\n if (!existsSync(this.lastRunFile)) return null\n return JSON.parse(readFileSync(this.lastRunFile, \"utf-8\"))\n } catch {\n return null\n }\n }\n\n private logRun(result: CronRunResult): void {\n try {\n const runDir = resolve(this.runsDir, result.jobId)\n if (!existsSync(runDir)) {\n mkdirSync(runDir, { recursive: true })\n }\n\n const filename = `${result.startedAt.toISOString().replace(/[:.]/g, \"-\")}.json`\n writeFileSync(\n resolve(runDir, filename),\n JSON.stringify(result, null, 2),\n )\n } catch {\n // Don't fail on logging errors\n }\n }\n\n /**\n * List all jobs and their status (including failure info).\n */\n list(): CronJobState[] {\n return Array.from(this.jobs.values())\n }\n\n /**\n * Get a health summary of cron jobs.\n */\n health(): { healthy: number; failing: number; disabled: number; missed: number; jobs: Array<{ id: string; status: string; consecutiveErrors: number; lastError?: string }> } {\n const jobs = Array.from(this.jobs.values())\n const missed = this.detectMissedRuns()\n\n return {\n healthy: jobs.filter(j => j.enabled && j.consecutiveErrors === 0).length,\n failing: jobs.filter(j => j.enabled && j.consecutiveErrors > 0).length,\n disabled: jobs.filter(j => !j.enabled).length,\n missed: missed.length,\n jobs: jobs.map(j => ({\n id: j.id,\n status: !j.enabled ? \"disabled\" : j.retryPending ? \"retrying\" : j.consecutiveErrors > 0 ? \"failing\" : \"healthy\",\n consecutiveErrors: j.consecutiveErrors,\n lastError: j.lastError,\n })),\n }\n }\n}\n\n\n/** Lines of command output kept in a run record. */\nconst COMMAND_OUTPUT_LINES = 20\n\nfunction tail(text: string, lines: number): string {\n const all = text.replace(/\\s+$/, \"\").split(\"\\n\")\n return all.length <= lines ? all.join(\"\\n\") : all.slice(-lines).join(\"\\n\")\n}\n\n/**\n * Run a shell command with a hard timeout.\n *\n * Resolves with the exit code rather than rejecting on non-zero: a failing\n * command is an ANSWER here, not an exception, and the caller wants the\n * output either way.\n */\nfunction runShell(\n command: string,\n timeoutMs: number,\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve, reject) => {\n execFile(\n \"/bin/sh\",\n [\"-c\", command],\n { timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024 },\n (err: any, stdout, stderr) => {\n if (err && err.killed) {\n reject(new Error(`command timed out after ${Math.round(timeoutMs / 1000)}s`))\n return\n }\n resolve({\n stdout: String(stdout ?? \"\"),\n stderr: String(stderr ?? \"\"),\n code: err ? (typeof err.code === \"number\" ? err.code : 1) : 0,\n })\n },\n )\n })\n}\n","import type { IntentSource } from \"./types\"\n\n// Mode-flag plumbing — Phase 1 commit 4 of the architectural rescue.\n//\n// The staged rollout in research-rescue-plan.md §7 needs three states:\n//\n// off ledger code is unreachable; legacy paths are authoritative.\n// This is the default and stays the default through 1a.\n// shadow decideAndCommit runs alongside the legacy paths on every\n// dispatch and records what *would* have happened. Legacy\n// remains authoritative; a divergence reporter (commit 5)\n// compares the two. The ≥7-day soak in 1b lives here.\n// authoritative ledger decision is the dispatch decision. Legacy paths\n// remain only as fallback gated by INTENT_LEDGER_FALLBACK\n// (commit 1c → 1d removes the legacy paths entirely).\n//\n// Mode is resolved per-source so 1c can flip sources one at a time\n// (gitlab → workflow → telegram → cron → mesh, ≥48h soak between each).\n//\n// This commit is plumbing only. No call site reads the mode yet —\n// commit 6 wires the readers behind the flag, defaulting to \"off\" so\n// production behaviour is unchanged at deploy time.\n\nexport type LedgerMode = \"off\" | \"shadow\" | \"authoritative\"\n\nconst VALID_MODES = [\"off\", \"shadow\", \"authoritative\"] as const satisfies readonly LedgerMode[]\n\n/** Per-source env-var names. Lifted to a constant so the call site (commit 6)\n * doesn't need to construct strings, and so the test matrix can drive them\n * by table rather than guessing the naming convention. */\nconst PER_SOURCE_ENV_VAR: Record<IntentSource, string> = {\n telegram: \"INTENT_LEDGER_MODE_TELEGRAM\",\n slack: \"INTENT_LEDGER_MODE_SLACK\",\n whatsapp: \"INTENT_LEDGER_MODE_WHATSAPP\",\n discord: \"INTENT_LEDGER_MODE_DISCORD\",\n gitlab: \"INTENT_LEDGER_MODE_GITLAB\",\n github: \"INTENT_LEDGER_MODE_GITHUB\",\n workflow: \"INTENT_LEDGER_MODE_WORKFLOW\",\n cron: \"INTENT_LEDGER_MODE_CRON\",\n mesh: \"INTENT_LEDGER_MODE_MESH\",\n}\n\nconst GLOBAL_ENV_VAR = \"INTENT_LEDGER_MODE\"\n\n/**\n * Resolve the ledger mode for one source. Resolution order:\n *\n * 1. Per-source env var (e.g. INTENT_LEDGER_MODE_GITLAB)\n * 2. Global env var (INTENT_LEDGER_MODE)\n * 3. Default — \"off\"\n *\n * Invalid values at any level (typos, foreign strings) are ignored — that\n * level falls through to the next. Defaulting to \"off\" on garbage means an\n * operator typo never accidentally promotes a source to authoritative; the\n * cost is silence on misconfig, but the cost of the alternative\n * (mis-promoted source) is much higher in production.\n *\n * The accepted values are case-insensitive (\"Shadow\", \"SHADOW\", \"shadow\"\n * all parse) so config copied from a doc or shell history doesn't surprise.\n *\n * Read every call rather than cached. Per-dispatch overhead is one or two\n * `process.env` lookups — negligible — and runtime flips (operator SIGHUPs\n * the daemon and changes `EnvironmentFile=` on systemd) take effect on the\n * next event without a restart.\n */\nexport function getLedgerMode(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): LedgerMode {\n const perSource = parseLedgerMode(env[PER_SOURCE_ENV_VAR[source]])\n if (perSource) return perSource\n const global = parseLedgerMode(env[GLOBAL_ENV_VAR])\n if (global) return global\n return \"off\"\n}\n\n/** Parse a value into a LedgerMode, or return null for invalid / unset. */\nexport function parseLedgerMode(value: unknown): LedgerMode | null {\n if (typeof value !== \"string\") return null\n const normalized = value.trim().toLowerCase()\n return (VALID_MODES as readonly string[]).includes(normalized)\n ? (normalized as LedgerMode)\n : null\n}\n\n/** Convenience: is this source consulting the ledger at all? Equivalent to\n * `getLedgerMode(source) !== \"off\"`, named for callsite readability. */\nexport function isLedgerActive(\n source: IntentSource,\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n return getLedgerMode(source, env) !== \"off\"\n}\n","import Database from \"better-sqlite3\"\nimport { existsSync, mkdirSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentEvent,\n IntentEventInput,\n IntentResolution,\n IntentSource,\n} from \"./types\"\n\n// Intent ledger — Phase 1 of the architectural rescue.\n//\n// Append-only SQLite store that becomes the single source of truth for\n// dispatch decisions across all sources (channel router, workflow\n// dispatcher, gitlab handler, cron, mesh). This commit only opens the db\n// and runs the schema migrations. The read/write API arrives in commit 2;\n// the `decideAndCommit` skeleton in commit 3.\n//\n// Lives in its own database file (`.agentx/intent/ledger.sqlite`) rather\n// than sharing the existing observability db at `.agentx/db.sqlite`:\n// - Different lifecycle: dispatch is hotter than observability, no point\n// making fsync compete.\n// - Different durability story: the ledger is canonical state; the\n// observability tables are derived. Different backup/retention policies.\n// - Cleaner schema separation — ledger migrations don't entangle with the\n// observability ones.\n//\n// WAL mode + synchronous=NORMAL — same balance the observability db uses.\n\nexport interface OpenLedgerOptions {\n /** Resolved relative to cwd. Default: .agentx/intent/ledger.sqlite */\n path?: string\n}\n\n/**\n * IntentLedger handle. One instance per database file. Tests open per-test\n * tmp instances; the daemon opens one process-global instance (added in a\n * later commit when daemon wiring lands).\n */\nexport class IntentLedger {\n readonly db: Database.Database\n readonly path: string\n\n constructor(opts: OpenLedgerOptions = {}) {\n this.path = resolve(process.cwd(), opts.path ?? \".agentx/intent/ledger.sqlite\")\n mkdirSync(dirname(this.path), { recursive: true })\n this.db = new Database(this.path)\n this.db.pragma(\"journal_mode = WAL\")\n this.db.pragma(\"synchronous = NORMAL\")\n this.db.pragma(\"foreign_keys = ON\")\n runMigrations(this.db)\n }\n\n /** Test-only — production never closes. */\n close(): void {\n this.db.close()\n }\n\n /** Current schema version. New migrations append to the runMigrations\n * list and bump the version. Useful for tests + diagnostics. */\n schemaVersion(): number {\n const row = this.db.prepare(\"SELECT MAX(v) AS v FROM schema_version\").get() as { v: number | null }\n return row.v ?? 0\n }\n\n // -------------------------------------------------------------------------\n // Events\n // -------------------------------------------------------------------------\n\n /**\n * Append an event. Idempotent on `(source, sourceEventId)` — a re-delivery\n * with the same external id returns the previously-stored row without\n * inserting a duplicate. Events with `sourceEventId === null` (cron tics,\n * ad-hoc internal events) are NOT deduplicated; each call writes a new row.\n *\n * Returns the canonical (existing or new) event row including its id.\n */\n recordEvent(input: IntentEventInput): IntentEvent {\n if (input.sourceEventId !== null) {\n const existing = this.findEventBySourceId(input.source, input.sourceEventId)\n if (existing) return existing\n }\n const event: IntentEvent = {\n id: input.id ?? newEventId(input.ts),\n ts: input.ts,\n source: input.source,\n sourceEventId: input.sourceEventId,\n project: input.project,\n subject: input.subject,\n intent: input.intent,\n rawJson: input.rawJson,\n }\n this.db\n .prepare(\n `INSERT INTO intent_events (id, ts, source, source_event_id, project, subject, intent, raw_json)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n event.id,\n event.ts,\n event.source,\n event.sourceEventId,\n event.project,\n event.subject,\n event.intent,\n event.rawJson,\n )\n return event\n }\n\n /** Idempotency probe — used by `recordEvent` and by external callers that\n * want to check existence before constructing a full event payload. */\n findEventBySourceId(source: IntentSource, sourceEventId: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE source = ? AND source_event_id = ?`,\n )\n .get(source, sourceEventId) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n /** Lookup by primary key. Returns null when not found. */\n getEventById(id: string): IntentEvent | null {\n const row = this.db\n .prepare(\n `SELECT id, ts, source, source_event_id, project, subject, intent, raw_json\n FROM intent_events WHERE id = ?`,\n )\n .get(id) as EventRow | undefined\n return row ? rowToEvent(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Decisions\n // -------------------------------------------------------------------------\n\n /**\n * Append a decision. Throws on `(eventId, decidedBy)` conflict — decisions\n * are once-and-only-once per decider. Idempotency for the *event* is the\n * caller's responsibility (use `recordEvent` for that); decisions\n * intentionally do not retry-coalesce so a buggy caller surfaces loudly\n * instead of silently overwriting prior judgement.\n */\n recordDecision(decision: IntentDecision): void {\n this.db\n .prepare(\n `INSERT INTO intent_decisions (event_id, decided_at, decided_by, agent_id, outcome, reason)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n decision.eventId,\n decision.decidedAt,\n decision.decidedBy,\n decision.agentId,\n decision.outcome,\n decision.reason,\n )\n }\n\n /** All decisions for one event, oldest first. The chain (channel-router →\n * pm-gate → workflow) reads naturally in insertion order. */\n getDecisionsForEvent(eventId: string): IntentDecision[] {\n const rows = this.db\n .prepare(\n `SELECT event_id, decided_at, decided_by, agent_id, outcome, reason\n FROM intent_decisions WHERE event_id = ? ORDER BY decided_at ASC`,\n )\n .all(eventId) as DecisionRow[]\n return rows.map(rowToDecision)\n }\n\n /**\n * The active-task-safety check. Returns the most recent `dispatched`\n * decision for `(project, subject)` that has not yet been resolved\n * (no row in `intent_resolutions`). `decideAndCommit` (commit 3) consults\n * this to enforce the at-most-one-in-flight invariant.\n *\n * Returns null when project or subject is null — the active-task concept\n * is meaningless without both axes pinned.\n */\n getActiveDecisionForSubject(project: string | null, subject: string | null): IntentDecision | null {\n if (project === null || subject === null) return null\n const row = this.db\n .prepare(\n `SELECT d.event_id, d.decided_at, d.decided_by, d.agent_id, d.outcome, d.reason\n FROM intent_decisions d\n JOIN intent_events e ON e.id = d.event_id\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE e.project = ? AND e.subject = ?\n AND d.outcome = 'dispatched'\n AND r.decision_event_id IS NULL\n ORDER BY d.decided_at DESC\n LIMIT 1`,\n )\n .get(project, subject) as DecisionRow | undefined\n return row ? rowToDecision(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Resolutions\n // -------------------------------------------------------------------------\n\n /**\n * Append a resolution. Throws if a resolution already exists for the\n * decision — the ledger is append-only, so revising an outcome is a new\n * event, not an overwrite. The FK to `intent_decisions` ensures the\n * decision exists.\n */\n recordResolution(resolution: IntentResolution): void {\n this.db\n .prepare(\n `INSERT INTO intent_resolutions (decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary)\n VALUES (?, ?, ?, ?, ?, ?)`,\n )\n .run(\n resolution.decisionEventId,\n resolution.decisionDecidedBy,\n resolution.resolvedAt,\n resolution.status,\n resolution.durationMs,\n resolution.resultSummary,\n )\n }\n\n /**\n * Close every dispatched-and-unresolved decision by writing a\n * resolution with status \"canceled\" and the given reason. Used at\n * daemon startup to clean up dispatches whose agent execution died\n * with the previous process — without this, those decisions sit\n * in-flight forever and Inv-ActiveTaskSafety blocks legitimate\n * re-dispatches on the same slot.\n *\n * Returns the count of resolutions written. Idempotent — repeated\n * calls write 0 the second time because nothing remains in-flight.\n */\n cleanupOrphanedDispatches(reason: string = \"daemon-restart\", now: () => number = Date.now): number {\n const rows = this.db\n .prepare(`\n SELECT d.event_id, d.decided_by FROM intent_decisions d\n LEFT JOIN intent_resolutions r\n ON r.decision_event_id = d.event_id AND r.decision_decided_by = d.decided_by\n WHERE d.outcome = 'dispatched' AND r.decision_event_id IS NULL\n `)\n .all() as Array<{ event_id: string; decided_by: string }>\n const ts = now()\n let count = 0\n for (const row of rows) {\n try {\n this.recordResolution({\n decisionEventId: row.event_id,\n decisionDecidedBy: row.decided_by,\n resolvedAt: ts,\n status: \"canceled\",\n durationMs: null,\n resultSummary: reason,\n })\n count++\n } catch {\n // Skip — resolution already exists (race with normal completion).\n }\n }\n return count\n }\n\n /** Returns the resolution for a decision, or null if still in-flight. */\n getResolution(eventId: string, decidedBy: string): IntentResolution | null {\n const row = this.db\n .prepare(\n `SELECT decision_event_id, decision_decided_by, resolved_at, status, duration_ms, result_summary\n FROM intent_resolutions WHERE decision_event_id = ? AND decision_decided_by = ?`,\n )\n .get(eventId, decidedBy) as ResolutionRow | undefined\n return row ? rowToResolution(row) : null\n }\n\n // -------------------------------------------------------------------------\n // Divergences (shadow-mode soak surface)\n // -------------------------------------------------------------------------\n\n /**\n * Append a divergence record. Throws on duplicate `id`. The composite FK\n * to `intent_decisions` (`event_id`, `decided_by`) enforces that a\n * divergence cannot exist without its ledger-side decision — so callers\n * must record the decision before reporting the divergence.\n */\n recordDivergence(divergence: IntentDivergence): void {\n this.db\n .prepare(\n `INSERT INTO intent_divergences (\n id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n )\n .run(\n divergence.id,\n divergence.ts,\n divergence.source,\n divergence.eventId,\n divergence.decidedBy,\n divergence.ledgerAgentId,\n divergence.ledgerOutcome,\n divergence.ledgerReason,\n divergence.legacyAgentId,\n divergence.legacyOutcome,\n divergence.legacyReason,\n )\n }\n\n /**\n * Recent divergences, newest first. Filters compose: `source` narrows to\n * one dispatch source, `since` to a recency window, `limit` to top-N.\n * The intended consumer is the soak dashboard (commit 8) and `agentx\n * audit --divergence` queries; per-record introspection is rare so we\n * don't expose a single-id getter.\n */\n getDivergences(opts: {\n source?: IntentSource\n since?: number\n limit?: number\n } = {}): IntentDivergence[] {\n const wheres: string[] = []\n const params: Array<string | number> = []\n if (opts.source !== undefined) {\n wheres.push(\"source = ?\")\n params.push(opts.source)\n }\n if (opts.since !== undefined) {\n wheres.push(\"ts >= ?\")\n params.push(opts.since)\n }\n const whereSql = wheres.length ? `WHERE ${wheres.join(\" AND \")}` : \"\"\n const limitSql = opts.limit !== undefined ? \"LIMIT ?\" : \"\"\n if (opts.limit !== undefined) params.push(opts.limit)\n\n const rows = this.db\n .prepare(\n `SELECT id, ts, source, event_id, decided_by,\n ledger_agent_id, ledger_outcome, ledger_reason,\n legacy_agent_id, legacy_outcome, legacy_reason\n FROM intent_divergences\n ${whereSql}\n ORDER BY ts DESC\n ${limitSql}`,\n )\n .all(...params) as DivergenceRow[]\n return rows.map(rowToDivergence)\n }\n}\n\n// --- Row → typed-object adapters --------------------------------------------\n//\n// SQLite returns snake_case rows; the typed surface uses camelCase. Mapping\n// once here keeps every consumer in TS-ergonomic shape and makes column\n// renames a single-file refactor.\n\ninterface EventRow {\n id: string\n ts: number\n source: string\n source_event_id: string | null\n project: string | null\n subject: string | null\n intent: string | null\n raw_json: string\n}\n\ninterface DecisionRow {\n event_id: string\n decided_at: number\n decided_by: string\n agent_id: string | null\n outcome: string\n reason: string | null\n}\n\ninterface ResolutionRow {\n decision_event_id: string\n decision_decided_by: string\n resolved_at: number\n status: string\n duration_ms: number | null\n result_summary: string | null\n}\n\ninterface DivergenceRow {\n id: string\n ts: number\n source: string\n event_id: string\n decided_by: string\n ledger_agent_id: string | null\n ledger_outcome: string\n ledger_reason: string | null\n legacy_agent_id: string | null\n legacy_outcome: string\n legacy_reason: string | null\n}\n\nfunction rowToEvent(row: EventRow): IntentEvent {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n sourceEventId: row.source_event_id,\n project: row.project,\n subject: row.subject,\n intent: row.intent,\n rawJson: row.raw_json,\n }\n}\n\nfunction rowToDecision(row: DecisionRow): IntentDecision {\n return {\n eventId: row.event_id,\n decidedAt: row.decided_at,\n decidedBy: row.decided_by,\n agentId: row.agent_id,\n outcome: row.outcome as IntentDecision[\"outcome\"],\n reason: row.reason,\n }\n}\n\nfunction rowToResolution(row: ResolutionRow): IntentResolution {\n return {\n decisionEventId: row.decision_event_id,\n decisionDecidedBy: row.decision_decided_by,\n resolvedAt: row.resolved_at,\n status: row.status as IntentResolution[\"status\"],\n durationMs: row.duration_ms,\n resultSummary: row.result_summary,\n }\n}\n\nfunction rowToDivergence(row: DivergenceRow): IntentDivergence {\n return {\n id: row.id,\n ts: row.ts,\n source: row.source as IntentSource,\n eventId: row.event_id,\n decidedBy: row.decided_by,\n ledgerAgentId: row.ledger_agent_id,\n ledgerOutcome: row.ledger_outcome as IntentDivergence[\"ledgerOutcome\"],\n ledgerReason: row.ledger_reason,\n legacyAgentId: row.legacy_agent_id,\n legacyOutcome: row.legacy_outcome as IntentDivergence[\"legacyOutcome\"],\n legacyReason: row.legacy_reason,\n }\n}\n\n/**\n * Per-version schema steps. New tables / columns go in a new migration\n * function — never mutate an old one. Each step is idempotent so re-running\n * on an already-current db is safe.\n */\nfunction runMigrations(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS schema_version (\n v INTEGER PRIMARY KEY\n );\n `)\n const current = (db\n .prepare(\"SELECT MAX(v) AS v FROM schema_version\")\n .get() as { v: number | null }).v ?? 0\n\n if (current < 1) migrationV1(db)\n if (current < 2) migrationV2(db)\n}\n\nfunction migrationV1(db: Database.Database): void {\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_events (\n -- TEXT PRIMARY KEY isn't auto-NOT-NULL in SQLite; spell it out so the\n -- ULID invariant is enforced at the schema level rather than relying on\n -- the application layer.\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n source_event_id TEXT,\n project TEXT,\n subject TEXT,\n intent TEXT,\n raw_json TEXT NOT NULL\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_events_subject\n ON intent_events (project, subject);\n CREATE INDEX IF NOT EXISTS idx_intent_events_source_event_id\n ON intent_events (source, source_event_id);\n CREATE INDEX IF NOT EXISTS idx_intent_events_ts\n ON intent_events (ts);\n\n CREATE TABLE IF NOT EXISTS intent_decisions (\n event_id TEXT NOT NULL REFERENCES intent_events(id),\n decided_at INTEGER NOT NULL,\n decided_by TEXT NOT NULL,\n agent_id TEXT,\n outcome TEXT NOT NULL,\n reason TEXT,\n PRIMARY KEY (event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_agent\n ON intent_decisions (agent_id, decided_at);\n CREATE INDEX IF NOT EXISTS idx_intent_decisions_outcome\n ON intent_decisions (outcome, decided_at);\n\n CREATE TABLE IF NOT EXISTS intent_resolutions (\n decision_event_id TEXT NOT NULL,\n decision_decided_by TEXT NOT NULL,\n resolved_at INTEGER NOT NULL,\n status TEXT NOT NULL,\n duration_ms INTEGER,\n result_summary TEXT,\n PRIMARY KEY (decision_event_id, decision_decided_by),\n FOREIGN KEY (decision_event_id, decision_decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n CREATE INDEX IF NOT EXISTS idx_intent_resolutions_status\n ON intent_resolutions (status, resolved_at);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (1)\").run()\n}\n\nfunction migrationV2(db: Database.Database): void {\n // Phase 1 commit 5 — divergence reporter surface. Each row records one\n // observed mismatch between the ledger's decision and the legacy path's\n // outcome during shadow-mode operation. The composite FK to\n // intent_decisions ensures a divergence cannot exist without its\n // ledger-side decision row.\n db.exec(`\n CREATE TABLE IF NOT EXISTS intent_divergences (\n id TEXT NOT NULL PRIMARY KEY,\n ts INTEGER NOT NULL,\n source TEXT NOT NULL,\n event_id TEXT NOT NULL,\n decided_by TEXT NOT NULL,\n ledger_agent_id TEXT,\n ledger_outcome TEXT NOT NULL,\n ledger_reason TEXT,\n legacy_agent_id TEXT,\n legacy_outcome TEXT NOT NULL,\n legacy_reason TEXT,\n FOREIGN KEY (event_id, decided_by)\n REFERENCES intent_decisions(event_id, decided_by)\n );\n\n -- \"show me recent divergences from gitlab\" — the soak's primary query\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_source_ts\n ON intent_divergences (source, ts);\n -- \"are any deciders consistently wrong\" — per-decider analysis\n CREATE INDEX IF NOT EXISTS idx_intent_divergences_decided_by\n ON intent_divergences (decided_by, ts);\n `)\n db.prepare(\"INSERT INTO schema_version (v) VALUES (2)\").run()\n}\n\n// existsSync is imported for symmetry with src/storage/sqlite.ts; the\n// ledger constructor doesn't currently branch on file presence (the\n// migration is idempotent regardless), but keeping the import documents\n// the intent should later code need to distinguish first-open from re-open.\nvoid existsSync\n","import { IntentLedger } from \"./ledger\"\n\n// Daemon-process singleton accessor for the IntentLedger.\n//\n// Phase 1 commit 6.0 — scaffolding for the call-site wiring that lands in\n// 6.a (gitlab), 6.b (router), 6.c (workflow), 6.d (cron + mesh). Each\n// source's wrapper will read this singleton when the mode is non-\"off\".\n//\n// The singleton is lazy because the ledger isn't needed in production\n// until the operator flips INTENT_LEDGER_MODE off the default. Avoiding\n// eager construction means an unflipped agentx process never opens the\n// ledger db, never holds the file, never writes WAL pages — exactly what\n// \"deploy-time default is off\" means in practice.\n//\n// Tests use `setLedgerForTesting` to inject an in-memory or tmp-dir\n// ledger and `resetLedgerForTesting` to release it between cases. Outside\n// of tests, callers go through `getDefaultLedger()`.\n\nlet _ledger: IntentLedger | undefined\n\nexport interface DefaultLedgerOptions {\n /** Path override. Default: `.agentx/intent/ledger.sqlite` (resolved\n * against cwd by the IntentLedger constructor). */\n path?: string\n}\n\n/**\n * Lazy singleton getter. Idempotent — repeated calls return the same\n * handle. Constructs the ledger on first call.\n *\n * Throws on construction failure (file unwritable, native binding broken,\n * etc.). Call sites should gate the call behind `getLedgerMode(...) !== \"off\"`\n * so a bad ledger never reaches construction in normal \"off\" production.\n *\n * The decision to throw rather than fail-soft (return null like\n * src/storage/sqlite.ts does) is deliberate: the ledger is canonical\n * state once `mode !== \"off\"`, so a silent failure would leave the\n * dispatcher in an undefined \"I tried to record but didn't\" state. Loud\n * failure surfaces misconfig at startup rather than days into a soak.\n */\nexport function getDefaultLedger(opts: DefaultLedgerOptions = {}): IntentLedger {\n if (_ledger) return _ledger\n _ledger = new IntentLedger({ path: opts.path })\n return _ledger\n}\n\n/** Test-only: inject a pre-built ledger so per-test tmp dirs work without\n * fighting the singleton. Production code MUST NOT call this. */\nexport function setLedgerForTesting(ledger: IntentLedger): void {\n _ledger = ledger\n}\n\n/** Test-only: drop the singleton reference. Use in `afterEach` so the\n * next test's `setLedgerForTesting` or `getDefaultLedger` starts fresh.\n * Does NOT close the underlying db — the caller (test) owns close(). */\nexport function resetLedgerForTesting(): void {\n _ledger = undefined\n}\n","import type { DispatchGovernance } from \"./decide\"\n\n// Daemon-level governance singleton — Phase 3 of the architectural rescue.\n//\n// `decideAndCommit` reads this when its caller doesn't pass an explicit\n// `governance` argument. The daemon initializes it at startup from the\n// `BusinessLayer.organization` instance, gated by the\n// `INTENT_PM_GATE_ENABLED` env var. When the var is unset (the deploy\n// default), the singleton stays undefined and no PM gate / canHandle\n// check fires — production behaviour is unchanged.\n//\n// This indirection keeps governance an opt-in concern: call sites and\n// helpers (`recordGitLabTargetDispatch`, `recordRouterDispatch`, etc.)\n// don't need to know about Organization. The daemon plumbs Organization\n// → DispatchGovernance once at startup; everything else stays generic.\n//\n// Tests reset between cases via `setDefaultGovernance(undefined)` to\n// avoid leakage from one test's fixture into another's behaviour.\n\nlet _governance: DispatchGovernance | undefined\n\n/** Set the process-wide default governance. Called once at daemon\n * startup (or never, if INTENT_PM_GATE_ENABLED is off). */\nexport function setDefaultGovernance(g: DispatchGovernance | undefined): void {\n _governance = g\n}\n\n/** Read the current default. `decideAndCommit` falls back to this when\n * its caller didn't pass an explicit governance arg. Returns undefined\n * in test contexts that haven't set anything (no governance fires). */\nexport function getDefaultGovernance(): DispatchGovernance | undefined {\n return _governance\n}\n","import type { IntentLedger } from \"./ledger\"\nimport type { IntentDecision, IntentEventInput, IntentEvent } from \"./types\"\nimport { getDefaultGovernance } from \"./governance\"\n\n// decideAndCommit — Phase 1 of the architectural rescue.\n//\n// The single function every dispatch source will route through. Every event\n// entering the system flows: source-adapter → decideAndCommit → (optional\n// agent dispatch). The function's job is to:\n//\n// 1. Record the event idempotently (Inv-Idempotence)\n// 2. Consult the ledger for active-task state (Inv-ActiveTaskSafety)\n// 3. Ask the policy for a tentative decision\n// 4. Commit a single decision row to the ledger (Inv-NoSilentDrops)\n//\n// The four invariants are spelled out below and named so that Phase 2's\n// TLA+ spec can reference them by string. Tests in test/intent-decide.test.ts\n// cite these names in their assertion comments.\n//\n// **Phase 2 status**: three of the four invariants are formally verified\n// by TLC against `docs/architecture/DispatchSpec.tla` (410K distinct\n// states, depth 7, 0 violations as of 2026-04-29). The fourth\n// (Inv-Determinism) is a meta-property over traces, checked by code\n// review + the test in `intent-decide.test.ts`. See\n// `docs/architecture/dispatch-properties.md` for the full mapping\n// between code paths, invariants, and TLC results.\n//\n// Inv-Idempotence calling decideAndCommit twice with the same\n// (source, sourceEventId) and the same policy\n// produces one event row + one decision row;\n// the second call returns the row from the first.\n// Inv-Determinism given a fixed ledger snapshot, a fixed policy,\n// and a fixed clock, the resulting decision is a\n// pure function of the input event.\n// Inv-ActiveTaskSafety at most one decision with outcome=dispatched\n// that has not yet been resolved exists for any\n// (project, subject) at any point in the ledger.\n// Inv-NoSilentDrops every call to decideAndCommit appends exactly\n// one decision row to the ledger (or returns an\n// existing one under Inv-Idempotence). No code\n// path returns without a row visible in the ledger.\n//\n// What this commit does NOT do:\n// - Wire decideAndCommit into any real call site (commit 6).\n// - Add the mode flag (commit 4) — this function is reachable only from\n// tests until commit 6 wires it up behind a flag that defaults off.\n// - Read or expose the divergence reporter (commit 5).\n// - Run async or call out to network. Policies are sync; if a real call\n// site needs an LLM in the loop, that's a refactor for a later phase.\n\n/**\n * A pluggable dispatch policy. Each call site (channel router, workflow\n * dispatcher, gitlab handler, cron firing, mesh receiver) supplies its own\n * policy — the function below is purely the orchestration around the\n * policy's decision.\n *\n * The policy's `decidedBy` is the ledger's attribution string (\"who decided\n * this?\") and is what the ledger uses to scope idempotency: re-delivery of\n * the same event to the same `decidedBy` returns the existing row, while\n * the same event reaching a different `decidedBy` is a separate decision\n * (the chain-of-command case).\n */\nexport interface DispatchPolicy {\n /** Stable attribution string. Examples: `\"channel-router\"`,\n * `\"workflow:gitlab-sdlc-loop\"`, `\"gitlab-handler\"`. Must be stable\n * across calls — the ledger uses it as the per-policy idempotency key. */\n readonly decidedBy: string\n\n /**\n * Inspect the (already-recorded) event and return a tentative decision.\n * Return `null` to mean \"I have no opinion\" — the caller will record a\n * `halted` decision with reason `\"no policy match\"`.\n *\n * The policy MUST NOT write to the ledger directly. It MUST be a pure\n * function of `event` plus any read-only context the caller closed over\n * when constructing the policy. (Determinism — Inv-Determinism — depends\n * on this.)\n */\n decide(event: IntentEvent): PolicyDecision | null\n}\n\n/** What a policy returns. The `outcome` set excludes `\"deduped\"` because\n * dedup is the ledger's call, not the policy's. */\nexport interface PolicyDecision {\n agentId: string | null\n outcome: \"dispatched\" | \"halted\" | \"queued\"\n reason: string | null\n}\n\n/**\n * Phase 3 — Org-chart governance hooks. Optional. When supplied,\n * decideAndCommit consults them AFTER the policy decides:\n *\n * canHandle(agentId, project, intent) returns false → halt the\n * dispatch with reason \"org-chart: agent cannot handle\". Use to\n * enforce per-agent capability constraints (Phase 5 will add\n * typed capabilities; the v0 here is permissive).\n *\n * pmFor(project) returns the agentId of the\n * PM for `project`, or undefined when no PM is configured. When\n * defined AND the policy decided \"dispatched\", the decision's\n * `decidedBy` is rewritten to `pm:<pmId>` so the audit trail\n * attributes the dispatch to the PM gate. Per the kickoff:\n * \"a dispatch decision for (project, ...) where business.projects[].pm\n * is set never resolves to an agent without going through the PM\n * first (PM may rubber-stamp, but the decision row records\n * decided_by='pm:pm-globex')\".\n *\n * The full async-PM gate (synchronously dispatch to the PM agent,\n * wait up to 60s for approval, fall back to escalation on timeout)\n * is a future-phase refactor. The v0 here is the paper-trail gate:\n * the decision row is attributed to the PM, but no real call-out\n * happens. This satisfies the kickoff's property and unblocks the\n * 1c per-source promotions.\n */\nexport interface DispatchGovernance {\n canHandle?(agentId: string, project: string | null, intent: string | null): boolean\n pmFor?(project: string | null): string | undefined\n /** Phase 8 — capability-bounded security. Returns false when\n * dispatching `agentId` on `(project, subject)` would exceed the\n * agent's delegation-depth budget. Blocks cascade loops by\n * walking the ledger's prior decisions on the same slot. */\n withinDelegationBudget?(agentId: string, project: string | null, subject: string | null): boolean\n}\n\n/**\n * Append-only dispatch primitive. Returns the canonical decision row —\n * either freshly written or recovered from a prior call (Inv-Idempotence).\n *\n * The whole call runs inside a single SQLite transaction so the lookup\n * (`getDecisionsForEvent` + `getActiveDecisionForSubject`) and the write\n * (`recordDecision`) are atomic with respect to the same database. This\n * matters under concurrent-call scenarios; in the single-process daemon\n * use case, better-sqlite3 already serialises writes so the transaction\n * is belt-and-braces. Adding it now means the call-site wiring (commit 6)\n * can call decideAndCommit from anywhere without worrying about races.\n */\nexport function decideAndCommit(\n ledger: IntentLedger,\n input: IntentEventInput,\n policy: DispatchPolicy,\n now: () => number = Date.now,\n governance?: DispatchGovernance,\n): IntentDecision {\n const tx = ledger.db.transaction((decidedAt: number): IntentDecision => {\n // Step 1 — record the event. recordEvent is itself idempotent on\n // (source, sourceEventId), so this is safe under re-delivery.\n const event = ledger.recordEvent(input)\n\n // Phase 3 governance: compute the EFFECTIVE decidedBy upfront so\n // it threads through idempotency + recording. When a PM is\n // configured for the project, the decision is attributed to the\n // PM (pm:<id>) regardless of outcome — the PM is the gate, even\n // for halts and queues. canHandle is a veto applied later (forces\n // outcome=halted) but doesn't change decidedBy.\n //\n // Falls back to the daemon-level singleton (`getDefaultGovernance`)\n // when the caller doesn't pass an explicit governance — this is\n // the production path. Tests pass governance directly.\n const gov = governance ?? getDefaultGovernance()\n const pm = gov?.pmFor?.(event.project)\n const effectiveDecidedBy = pm ? `pm:${pm}` : policy.decidedBy\n\n // Step 2 — Inv-Idempotence. If this policy has already decided on this\n // event, return that decision unchanged. Two callers who race the same\n // event-policy pair are reduced to a single decision row.\n const prior = ledger\n .getDecisionsForEvent(event.id)\n .find((d) => d.decidedBy === effectiveDecidedBy)\n if (prior) return prior\n\n // Step 3 — Inv-ActiveTaskSafety. If a dispatched-and-unresolved\n // decision already exists for (project, subject), this event must\n // dedupe. The dedup outcome is ledger-managed; the policy never sees\n // a chance to override it.\n const active = ledger.getActiveDecisionForSubject(event.project, event.subject)\n if (active) {\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId: null,\n outcome: \"deduped\",\n reason: `active dispatch in flight: ${active.decidedBy} → ${active.agentId ?? \"?\"}`,\n }\n ledger.recordDecision(decision)\n return decision\n }\n\n // Step 4 — consult the policy. A null result is a halt with explicit\n // reason rather than a silent drop (Inv-NoSilentDrops). A halted /\n // queued / dispatched policy decision flows through unchanged.\n const policyResult = policy.decide(event)\n let agentId: string | null = policyResult ? policyResult.agentId : null\n let outcome: \"dispatched\" | \"halted\" | \"queued\" = policyResult ? policyResult.outcome : \"halted\"\n let reason: string | null = policyResult ? policyResult.reason : \"no policy match\"\n\n // Step 5 — canHandle veto. Dispatches to agents the org chart says\n // can't handle the event get forced to halted.\n if (gov?.canHandle && outcome === \"dispatched\" && agentId) {\n const allowed = gov.canHandle(agentId, event.project, event.intent)\n if (!allowed) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `org-chart: agent \"${blocked}\" cannot handle (${event.project ?? \"no-project\"}/${event.intent ?? \"no-intent\"})`\n }\n }\n\n // Step 5b — Phase 8 delegation-depth check. Walks the ledger's\n // prior decisions on (project, subject) and refuses dispatches\n // that would push the chain past the agent's\n // `maxDelegationDepth`. Prevents cascade loops where A → B → A → ...\n // blows past sane chain depth.\n if (gov?.withinDelegationBudget && outcome === \"dispatched\" && agentId) {\n if (!gov.withinDelegationBudget(agentId, event.project, event.subject)) {\n const blocked = agentId\n agentId = null\n outcome = \"halted\"\n reason = `delegation-budget: agent \"${blocked}\" depth-limit exceeded on ${event.project ?? \"?\"}/${event.subject ?? \"?\"}`\n }\n }\n\n // Annotate the reason when PM-gate took effect, so the audit trail\n // distinguishes pm-gated dispatches from regular ones.\n if (pm && outcome === \"dispatched\" && agentId) {\n reason = reason\n ? `${reason} (pm-gate: rubber-stamped by ${pm})`\n : `pm-gate: rubber-stamped by ${pm}`\n }\n\n const decision: IntentDecision = {\n eventId: event.id,\n decidedAt,\n decidedBy: effectiveDecidedBy,\n agentId,\n outcome,\n reason,\n }\n ledger.recordDecision(decision)\n return decision\n })\n\n return tx(now())\n}\n","import { logger } from \"../utils/logger\"\nimport type { IntentLedger } from \"./ledger\"\nimport { newEventId } from \"./ulid\"\nimport type {\n IntentDecision,\n IntentDivergence,\n IntentOutcomeKind,\n IntentSource,\n} from \"./types\"\n\n// Divergence reporter — Phase 1 commit 5 of the architectural rescue.\n//\n// During shadow mode (1b in research-rescue-plan.md §7), every dispatch\n// runs through both the legacy path and decideAndCommit. The legacy path\n// remains authoritative; the ledger's decision is recorded but does not\n// drive behaviour. The reporter compares the two and:\n//\n// - on agreement: no-op (the soak's success criterion is \"zero\n// divergences for ≥7 days\" — quiet operation IS the signal).\n// - on mismatch: log a structured warning AND write a row to\n// intent_divergences so the soak dashboard has a queryable surface.\n//\n// The shape of \"the legacy outcome\" is deliberately structural rather\n// than tied to any one source's existing output type — that lets the\n// commit-6 wiring adapt each call site (channel-router's `Routed`, the\n// workflow dispatcher's `DispatchResult`, etc.) into a common\n// LegacyOutcome at the comparison boundary instead of carrying source-\n// specific shapes through the reporter.\n\n/** Minimal projection of a legacy dispatch path's outcome — only the\n * fields we compare against the ledger decision. */\nexport interface LegacyOutcome {\n agentId: string | null\n outcome: IntentOutcomeKind\n /** Optional human-readable reason; recorded for forensics, never\n * compared. (Legacy reasons and ledger reasons phrase the same\n * decision differently — comparing them would produce noise.) */\n reason?: string | null\n}\n\n/**\n * Compare a ledger decision against the legacy path's outcome. On mismatch,\n * append a divergence row and emit a `[ledger-divergence]` log line.\n * Returns `true` when a divergence was recorded, `false` on agreement.\n *\n * Comparison is structural on the load-bearing fields: `outcome` and\n * `agentId`. `reason` strings differ harmlessly between paths and are\n * forensic-only — comparing them would produce noise that drowns out\n * the actual semantic mismatches we care about.\n */\nexport function reportDivergence(\n ledger: IntentLedger,\n source: IntentSource,\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n now: () => number = Date.now,\n): boolean {\n if (decisionsAgree(ledgerDecision, legacy)) return false\n\n const ts = now()\n const record: IntentDivergence = {\n id: newEventId(ts),\n ts,\n source,\n eventId: ledgerDecision.eventId,\n decidedBy: ledgerDecision.decidedBy,\n ledgerAgentId: ledgerDecision.agentId,\n ledgerOutcome: ledgerDecision.outcome,\n ledgerReason: ledgerDecision.reason,\n legacyAgentId: legacy.agentId,\n legacyOutcome: legacy.outcome,\n legacyReason: legacy.reason ?? null,\n }\n ledger.recordDivergence(record)\n\n // Single-line structured log so journalctl + grep are sufficient triage\n // tools during the soak (commit 8 adds a UI; until then, journal is it).\n logger.warn(\n `[ledger-divergence] source=${source} ` +\n `event=${ledgerDecision.eventId} ` +\n `decided_by=${ledgerDecision.decidedBy} ` +\n `ledger=${ledgerDecision.outcome}/${ledgerDecision.agentId ?? \"null\"} ` +\n `legacy=${legacy.outcome}/${legacy.agentId ?? \"null\"}`,\n )\n return true\n}\n\n/** Two outcomes agree iff they pick the same target with the same outcome\n * kind. Reasons (free-form) are not part of agreement.\n *\n * AgentIds that wrap a fresh-per-call instance id (workflow-run:<uuid>,\n * mesh-fwd:<id>) are normalized to the prefix before comparison — both\n * paths legitimately dispatch the same kind of work but with different\n * instance handles, and treating those as divergences buries the real\n * semantic mismatches in noise (Phase 1 soak finding: ~290 false\n * positives across both nodes pre-fix). */\nexport function decisionsAgree(\n ledgerDecision: IntentDecision,\n legacy: LegacyOutcome,\n): boolean {\n return (\n ledgerDecision.outcome === legacy.outcome &&\n normalizeSyntheticAgentId(ledgerDecision.agentId) === normalizeSyntheticAgentId(legacy.agentId)\n )\n}\n\nfunction normalizeSyntheticAgentId(id: string | null): string | null {\n if (!id) return null\n const m = id.match(/^(workflow-run|mesh-fwd):/)\n return m ? `${m[1]}:*` : id\n}\n","import type { IntentLedger } from \"../ledger\"\nimport { decideAndCommit, type DispatchPolicy } from \"../decide\"\nimport { reportDivergence, type LegacyOutcome } from \"../divergence\"\nimport type { IntentDecision, IntentEventInput } from \"../types\"\n\n// Source adapter — cron scheduler. Phase 1 commit 6.d.\n//\n// Cron is the cleanest 1:1 dispatch source: one fire → one agent. The\n// scheduler's `executeJob(jobId)` is the dispatch entry point. We\n// instrument the two decision branches (hook-blocked vs hook-approved)\n// and pass the legacy outcome to a pass-through policy.\n\nexport interface CronJobProjection {\n jobId: string\n agentId: string\n /** When the job fired (used as part of the ULID-friendly sourceEventId). */\n firedAt: Date\n}\n\n/** Build the IntentEventInput for one cron fire. sourceEventId is\n * per-(jobId, firedAt) so concurrent re-fires (shouldn't happen but)\n * collapse via idempotency. Subject scopes active-task safety to one\n * fire-in-flight per job — but project=null disables Inv-ActiveTaskSafety,\n * so successive fires of the same job both dispatch (matches legacy). */\nexport function buildCronEventInput(\n proj: CronJobProjection,\n rawJson: string,\n now: () => number = Date.now,\n): IntentEventInput {\n return {\n ts: now(),\n source: \"cron\",\n sourceEventId: `${proj.jobId}:${proj.firedAt.getTime()}`,\n project: null,\n subject: `cron:${proj.jobId}`,\n intent: \"cron.fired\",\n rawJson,\n }\n}\n\n/** Pass-through policy. Same shape as router/workflow: divergences come\n * from ledger MECHANICS, not policy disagreement. */\nexport function buildCronPolicyFromLegacy(legacy: LegacyOutcome): DispatchPolicy {\n return {\n decidedBy: \"cron-scheduler\",\n decide: () => ({\n agentId: legacy.agentId,\n outcome: legacy.outcome === \"deduped\" ? \"halted\" : legacy.outcome,\n reason:\n legacy.outcome === \"deduped\"\n ? `legacy-dedup: ${legacy.reason ?? \"\"}`.trim()\n : legacy.reason ?? null,\n }),\n }\n}\n\nexport function recordCronDispatch(\n ledger: IntentLedger,\n proj: CronJobProjection,\n rawJson: string,\n legacyOutcome: LegacyOutcome,\n now: () => number = Date.now,\n): IntentDecision {\n const eventInput = buildCronEventInput(proj, rawJson, now)\n const policy = buildCronPolicyFromLegacy(legacyOutcome)\n const ledgerDecision = decideAndCommit(ledger, eventInput, policy, now)\n reportDivergence(ledger, \"cron\", ledgerDecision, legacyOutcome, now)\n return ledgerDecision\n}\n"],"mappings":"qLAIA,OAAS,YAAAA,OAAgB,gBACzB,OAAS,iBAAAC,EAAe,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,OAAoB,KACnE,OAAS,WAAAC,MAAe,OCmBxB,IAAMC,EAAc,CAAC,MAAO,SAAU,eAAe,EAK/CC,EAAmD,CACvD,SAAU,8BACV,MAAO,2BACP,SAAU,8BACV,QAAS,6BACT,OAAQ,4BACR,OAAQ,4BACR,SAAU,8BACV,KAAM,0BACN,KAAM,yBACR,EAEMC,GAAiB,qBAuBhB,SAASC,EACdC,EACAC,EAAyB,QAAQ,IACrB,CACZ,IAAMC,EAAYC,EAAgBF,EAAIJ,EAAmBG,CAAM,CAAC,CAAC,EACjE,GAAIE,EAAW,OAAOA,EACtB,IAAME,EAASD,EAAgBF,EAAIH,EAAc,CAAC,EAClD,OAAIM,GACG,KACT,CAGO,SAASD,EAAgBE,EAAmC,CACjE,GAAI,OAAOA,GAAU,SAAU,OAAO,KACtC,IAAMC,EAAaD,EAAM,KAAK,EAAE,YAAY,EAC5C,OAAQT,EAAkC,SAASU,CAAU,EACxDA,EACD,IACN,CChFAC,IAHA,OAAOC,OAAc,iBACrB,OAAS,cAAAC,GAAY,aAAAC,OA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,EAAQC,EAAI,KAAK;AAAA,CAAI,EAAIA,EAAI,MAAM,CAACD,CAAK,EAAE,KAAK;AAAA,CAAI,CAC3E,CASA,SAAS1B,GACPP,EACAmC,EAC2D,CAC3D,OAAO,IAAI,QAAQ,CAACjE,EAASkE,IAAW,CACtCC,GACE,UACA,CAAC,KAAMrC,CAAO,EACd,CAAE,QAASmC,EAAW,UAAW,EAAI,KAAO,IAAK,EACjD,CAACG,EAAUlC,EAAQC,IAAW,CAC5B,GAAIiC,GAAOA,EAAI,OAAQ,CACrBF,EAAO,IAAI,MAAM,2BAA2B,KAAK,MAAMD,EAAY,GAAI,IAAI,CAAC,EAC5E,OAEFjE,EAAQ,CACN,OAAQ,OAAOkC,GAAU,EAAE,EAC3B,OAAQ,OAAOC,GAAU,EAAE,EAC3B,KAAMiC,EAAO,OAAOA,EAAI,MAAS,SAAWA,EAAI,KAAO,EAAK,CAC9D,CAAC,CACH,CACF,CACF,CAAC,CACH","names":["execFile","writeFileSync","mkdirSync","existsSync","readFileSync","resolve","VALID_MODES","PER_SOURCE_ENV_VAR","GLOBAL_ENV_VAR","getLedgerMode","source","env","perSource","parseLedgerMode","global","value","normalized","init_ulid","Database","existsSync","mkdirSync","dirname","resolve","IntentLedger","opts","runMigrations","input","existing","event","newEventId","source","sourceEventId","row","rowToEvent","id","decision","eventId","rowToDecision","project","subject","resolution","reason","now","rows","ts","count","decidedBy","rowToResolution","divergence","wheres","params","whereSql","limitSql","rowToDivergence","db","current","migrationV1","migrationV2","_ledger","getDefaultLedger","opts","IntentLedger","_governance","setDefaultGovernance","g","getDefaultGovernance","decideAndCommit","ledger","input","policy","now","governance","decidedAt","event","gov","getDefaultGovernance","pm","effectiveDecidedBy","prior","d","active","decision","policyResult","agentId","outcome","reason","blocked","init_logger","init_ulid","reportDivergence","ledger","source","ledgerDecision","legacy","now","decisionsAgree","ts","record","newEventId","logger","normalizeSyntheticAgentId","id","m","buildCronEventInput","proj","rawJson","now","buildCronPolicyFromLegacy","legacy","recordCronDispatch","ledger","legacyOutcome","eventInput","policy","ledgerDecision","decideAndCommit","reportDivergence","withOutputCap","prompt","maxOutputTokens","approxChars","parseCronField","field","min","max","values","part","i","range","stepStr","step","start","a","b","getNextCronDate","expression","after","timezone","fields","minutes","hours","daysOfMonth","months","daysOfWeek","fmt","candidate","limit","parts","get","type","p","m","h","dom","mon","dow","MAX_RETRIES","RETRY_DELAYS","_CronScheduler","config","registry","hooks","log","resolve","id","def","cb","existsSync","mkdirSync","missedRuns","jobId","missedAt","e","job","j","timer","targetMs","fire","remaining","existing","nextRun","delay","attempt","agentId","firedAt","legacy","getLedgerMode","decision","recordCronDispatch","getDefaultLedger","startedAt","isRetry","retryAttempt","command","success","output","error","stdout","stderr","code","runShell","tail","COMMAND_OUTPUT_LINES","result","applyConfigMutation","cfg","setAtPath","hookResult","intentRef","response","res","missed","lastRuns","lastRunStr","lastRun","shouldHaveRun","data","dir","writeFileSync","readFileSync","runDir","filename","jobs","CronScheduler","__publicField","text","lines","all","timeoutMs","reject","execFile","err"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as i}from"./chunk-FIOB3MEX.js";import{randomBytes as c}from"crypto";function f(t){let n="";for(let e=u-1;e>=0;e--)n=r[t&31]+n,t=Math.floor(t/32);return n}function s(){let t=c(o),n="";for(let e=0;e<o;e++)n+=r[t[e]&31];return n}function l(t=Date.now()){return f(t)+s()}var r,u,o,a=i(()=>{"use strict";r="0123456789ABCDEFGHJKMNPQRSTVWXYZ",u=10,o=16});export{l as a,a as b};
|
|
2
|
+
//# sourceMappingURL=chunk-ZTEU5JVQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/intent/ulid.ts"],"sourcesContent":["import { randomBytes } from \"crypto\"\n\n// In-tree ULID generator — Phase 1 of the architectural rescue.\n//\n// The ledger demands monotonically-sortable ids so chronological queries\n// can use ID ranges and the audit trail reads coherently. ULIDs give us\n// that (10-char Crockford-base32 timestamp + 16-char randomness, total\n// 26 chars). The full `ulid` npm package is overkill for the few hundred\n// lines of generation logic we need, and adding a dep means another\n// `pnpm install --prod` step on peer-server. So we inline.\n//\n// This is not a cryptographic primitive — its job is to be a unique,\n// time-sortable identifier. Random bytes come from `crypto.randomBytes`\n// purely because it's the right tool for \"give me bytes\" and there's no\n// reason to use weaker randomness.\n\nconst ENCODING = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\" // Crockford base32\n\nconst TIME_LEN = 10\nconst RAND_LEN = 16\n\nfunction encodeTime(ms: number): string {\n let out = \"\"\n for (let i = TIME_LEN - 1; i >= 0; i--) {\n out = ENCODING[ms & 31] + out\n ms = Math.floor(ms / 32)\n }\n return out\n}\n\nfunction encodeRandom(): string {\n const bytes = randomBytes(RAND_LEN)\n let out = \"\"\n for (let i = 0; i < RAND_LEN; i++) {\n out += ENCODING[bytes[i] & 31]\n }\n return out\n}\n\n/** Generate a new ULID. Pass `now` for deterministic tests. */\nexport function newEventId(now: number = Date.now()): string {\n return encodeTime(now) + encodeRandom()\n}\n\n/** Extract the timestamp portion from a ULID. Inverse of `newEventId`'s\n * time prefix. Useful for sanity checks; not load-bearing. */\nexport function decodeTime(id: string): number {\n let ms = 0\n for (let i = 0; i < TIME_LEN; i++) {\n const v = ENCODING.indexOf(id[i])\n if (v < 0) throw new Error(`invalid ULID character at position ${i}: ${id[i]}`)\n ms = ms * 32 + v\n }\n return ms\n}\n"],"mappings":"wCAAA,OAAS,eAAAA,MAAmB,SAqB5B,SAASC,EAAWC,EAAoB,CACtC,IAAIC,EAAM,GACV,QAASC,EAAIC,EAAW,EAAGD,GAAK,EAAGA,IACjCD,EAAMG,EAASJ,EAAK,EAAE,EAAIC,EAC1BD,EAAK,KAAK,MAAMA,EAAK,EAAE,EAEzB,OAAOC,CACT,CAEA,SAASI,GAAuB,CAC9B,IAAMC,EAAQR,EAAYS,CAAQ,EAC9BN,EAAM,GACV,QAASC,EAAI,EAAGA,EAAIK,EAAUL,IAC5BD,GAAOG,EAASE,EAAMJ,CAAC,EAAI,EAAE,EAE/B,OAAOD,CACT,CAGO,SAASO,EAAWC,EAAc,KAAK,IAAI,EAAW,CAC3D,OAAOV,EAAWU,CAAG,EAAIJ,EAAa,CACxC,CA1CA,IAgBMD,EAEAD,EACAI,EAnBNG,EAAAC,EAAA,kBAgBMP,EAAW,mCAEXD,EAAW,GACXI,EAAW","names":["randomBytes","encodeTime","ms","out","i","TIME_LEN","ENCODING","encodeRandom","bytes","RAND_LEN","newEventId","now","init_ulid","__esmMin"]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{existsSync as u,readdirSync as g,readFileSync as h,statSync as f,watch as d}from"fs";import{extname as b,join as p,resolve as m}from"path";import y from"js-yaml";var c=class{byProject=new Map;dir;log;watcher;debounce;loadErrors=[];constructor(e,t=console.error.bind(console,"[projects]")){this.dir=e,this.log=t}load(){if(this.byProject.clear(),this.loadErrors=[],!u(this.dir))return{count:0,errors:0};for(let e of this.walk(this.dir))try{let t=h(e,"utf-8"),r=y.load(t),s=this.validate(r,e);if(!s)continue;if(s._path=e,this.byProject.has(s.project)){this.log(`duplicate project "${s.project}" \u2014 keeping ${this.byProject.get(s.project)._path}, skipping ${e}`);continue}this.byProject.set(s.project,s)}catch(t){this.loadErrors.push({file:e,error:t?.message??String(t)}),this.log(`failed to load ${e}: ${t?.message??t}`)}return{count:this.byProject.size,errors:this.loadErrors.length}}startWatching(e){if(u(this.dir))try{this.watcher=d(this.dir,{recursive:!0},()=>{this.debounce&&clearTimeout(this.debounce),this.debounce=setTimeout(()=>{let t=this.load();this.log(`rules reloaded: ${t.count} project(s), ${t.errors} error(s)`),e?.()},200)})}catch(t){this.log(`watcher unavailable (${t.message}) \u2014 rules will not hot-reload`)}}stop(){this.watcher?.close(),this.debounce&&clearTimeout(this.debounce)}find(e){return this.byProject.get(e)}list(){return Array.from(this.byProject.values())}static inferKind(e){return e.kind?e.kind:e.gitlab?"gitlab":e.github?"github":"other"}health(){return{count:this.byProject.size,errors:[...this.loadErrors]}}shouldFireGitlabIssue(e,t){let r=this.find(e)?.gitlab?.issue;return r?a(r,t,"gitlab"):{allow:!0}}shouldFireGitlabNote(e,t,r){let s=this.find(e)?.gitlab?.note;return s?w(s,t,r?.knownAgentMentions):{allow:!0}}shouldFireGitlabMR(e,t){let r=this.find(e)?.gitlab?.merge_request;return r?a(r,t,"gitlab"):{allow:!0}}shouldFireGitlabPipeline(e,t){let r=this.find(e)?.gitlab?.pipeline;return r?r.actions&&r.actions.length>0&&t.status&&!r.actions.includes(t.status)?{allow:!1,reason:`pipeline status="${t.status}" not in actions=${JSON.stringify(r.actions)}`}:{allow:!0}:{allow:!0}}shouldFireGithubIssue(e,t){let r=this.find(e)?.github?.issues;return r?a(r,t,"github"):{allow:!0}}shouldFireGithubPR(e,t){let r=this.find(e)?.github?.pull_request;return r?a(r,t,"github"):{allow:!0}}*walk(e){let t;try{t=g(e)}catch{return}for(let r of t){let s=p(e,r),o;try{o=f(s)}catch{continue}if(o.isDirectory()){yield*this.walk(s);continue}let n=b(r).toLowerCase();(n===".yaml"||n===".yml")&&(yield s)}}validate(e,t){if(!e||typeof e!="object")throw new Error(`${t}: top-level must be an object`);let r=e;if(typeof r.project!="string"||!r.project.includes("/"))throw new Error(`${t}: \`project\` must be a string of the form "org/repo"`);if(r.runbook!==void 0&&typeof r.runbook!="string")throw new Error(`${t}: \`runbook\` must be a string path`);return r.runbook&&m(r.runbook),e}};function a(i,e,t){let r=e.labels??[],s=e.authorUsername??"";if(i.actions&&i.actions.length>0&&(!e.action||!i.actions.includes(e.action)))return{allow:!1,reason:`${t} issue action="${e.action}" not in actions=${JSON.stringify(i.actions)}`};if(i.excludeStates&&e.state&&i.excludeStates.includes(e.state))return{allow:!1,reason:`${t} issue state="${e.state}" in excludeStates`};if(i.requireLabels&&i.requireLabels.length>0&&!i.requireLabels.some(n=>r.includes(n)))return{allow:!1,reason:`${t} issue missing requireLabels=${JSON.stringify(i.requireLabels)} (have ${JSON.stringify(r)})`};if(i.excludeLabels&&i.excludeLabels.length>0){let o=i.excludeLabels.find(n=>r.includes(n));if(o)return{allow:!1,reason:`${t} issue carries excluded label "${o}"`}}if(i.excludeAuthors&&i.excludeAuthors.length>0){let o=i.excludeAuthors.find(n=>s.toLowerCase().includes(n.toLowerCase()));if(o)return{allow:!1,reason:`${t} issue authored by "${s}" matched excludeAuthors entry "${o}"`}}return{allow:!0}}function w(i,e,t){let r=(e.text??"").toLowerCase(),s=e.authorUsername??"";if(i.onlyOn&&i.onlyOn.length>0&&(!e.noteableType||!i.onlyOn.includes(e.noteableType)))return{allow:!1,reason:`note noteableType="${e.noteableType}" not in onlyOn=${JSON.stringify(i.onlyOn)}`};if(i.excludeAuthors&&i.excludeAuthors.length>0){let o=i.excludeAuthors.find(n=>s.toLowerCase().includes(n.toLowerCase()));if(o)return{allow:!1,reason:`note authored by "${s}" matched excludeAuthors entry "${o}"`}}return i.triggers&&i.triggers.length>0&&!i.triggers.some(n=>{if(n==="auto")return!t||t.length===0?!1:t.some(l=>r.includes(l.toLowerCase()));if(n.mention){let l=n.mention.toLowerCase();if(r.includes(l))return!0}return!!(n.keyword&&r.includes(n.keyword.toLowerCase()))})?{allow:!1,reason:"note text matched no trigger"}:{allow:!0}}export{c as a};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
2
|
+
//# sourceMappingURL=chunk-ZVP6GB4G.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/projects/rules.ts"],"sourcesContent":["// --- Per-project webhook rules + runbook reference ---\n//\n// Project rules live in `.agentx/projects/<org>/<project>.yaml` (or any\n// nested path; the loader walks the tree). Each file declares which\n// channel events for that project may reach an agent and where the\n// project's runbook (CLAUDE.md / AGENTS.md / DEPLOY.md / RUNBOOK.md)\n// lives so the registry can inject it into the agent's system prefix.\n//\n// The store is loaded at daemon boot and watched for changes — write a\n// file, save, and the next webhook event picks up the new rules without\n// a daemon restart. Validation errors are logged and the offending file\n// is skipped (other rules keep working).\n//\n// Why per-file: agencies grow projects faster than they touch agentx\n// internals; a single project.yaml would force coordination on every\n// edit. One file per project lets each project owner edit their own\n// rules without merge conflicts.\n//\n// Schema is intentionally narrow:\n// - issue.actions / pull_request.actions / issues.actions: action allowlist\n// - requireLabels: at least one must be present (OR-of). Empty/absent = no\n// label requirement.\n// - excludeLabels: any present blocks the event.\n// - excludeStates: states that always block (e.g. \"closed\").\n// - excludeAuthors: handle prefixes that always block (bots).\n// - note.triggers: at least one must match for a comment to fire.\n// - runbook: filesystem path; the registry reads CLAUDE.md / AGENTS.md /\n// DEPLOY.md / RUNBOOK.md from this path (extensible via `runbookFiles`).\n//\n// Anything not listed by a rule passes through with the legacy default\n// (existing adapter behaviour). Rules opt INTO filtering, never opt out\n// of an event the adapter already drops.\n\nimport { existsSync, readdirSync, readFileSync, statSync, watch } from \"fs\"\nimport type { FSWatcher } from \"fs\"\nimport { extname, join, resolve } from \"path\"\nimport yaml from \"js-yaml\"\n\nexport type Channel = \"gitlab\" | \"github\"\n\n/** Declarative source of a project. Drives the Projects-page UI badge\n * and indicates which channel adapters are expected to carry events\n * for it. `gitlab` and `github` have rule clauses + live adapters;\n * `jira` and `linear` are accepted as values for tracking purposes\n * even though no adapter exists yet (events from those sources can't\n * fire workflows today). `other` is the catch-all for projects that\n * exist organisationally but aren't wired to any source. */\nexport type ProjectKind = \"gitlab\" | \"github\" | \"jira\" | \"linear\" | \"other\"\n\n/** Default runbook filenames read into the agent system prefix. Order\n * preserved so CLAUDE.md (claude convention) lands before AGENTS.md\n * (codex convention) — agents see Claude rules first. Operator can\n * override per-project via `runbookFiles`. */\nexport const DEFAULT_RUNBOOK_FILES = [\"CLAUDE.md\", \"AGENTS.md\", \"DEPLOY.md\", \"RUNBOOK.md\"] as const\n\nexport interface IssueRule {\n /** Allowed actions. Empty/absent = no action restriction. */\n actions?: string[]\n /** Issue must carry at least one of these labels. Empty/absent = no req. */\n requireLabels?: string[]\n /** Any of these labels present blocks the event. */\n excludeLabels?: string[]\n /** States that always block (gitlab: opened|closed|reopened, github: open|closed). */\n excludeStates?: string[]\n /** Username substrings/equals that always block — used for bot exclusion. */\n excludeAuthors?: string[]\n}\n\nexport interface NoteTrigger {\n /** Comment must contain this @mention to fire. Case-insensitive. */\n mention?: string\n /** Comment must contain this keyword (case-insensitive substring). */\n keyword?: string\n}\n\n/** Sentinel string that tells the matcher to accept any @-mention that\n * resolves to a configured agent (per `channels.gitlab.agentMappings`).\n * Lets a project rule say \"fire on any agent mention\" without manually\n * enumerating every handle — the canonical list lives in agentMappings.\n * Use it as a string entry in `triggers`:\n * triggers: [auto, { keyword: \"merge and deploy\" }]\n * When the channel adapter doesn't supply `knownAgentMentions`, an\n * `auto` entry is treated as a no-op (it does not block the rule). */\nexport type NoteTriggerEntry = NoteTrigger | \"auto\"\n\nexport interface NoteRule {\n /** Restrict to certain noteable types — gitlab: issue|merge_request|commit|snippet. */\n onlyOn?: string[]\n /** At least one trigger must match the comment text for the event to fire.\n * Mix explicit objects with the `\"auto\"` sentinel to delegate mention\n * enumeration to the channel's agentMappings. */\n triggers?: NoteTriggerEntry[]\n /** Username substrings/equals that always block. */\n excludeAuthors?: string[]\n}\n\nexport interface PipelineRule {\n /** Allowed pipeline statuses (success|failed|canceled|...). */\n actions?: string[]\n}\n\nexport interface ProjectRule {\n /** Project path. GitLab: `org/repo`. GitHub: `owner/repo`. Required. */\n project: string\n channel?: Channel\n /** Declarative source of this project. Optional. When unset, the\n * loader infers from clauses (presence of `gitlab:` → \"gitlab\",\n * `github:` → \"github\", neither → \"other\"). Set explicitly to track\n * jira / linear / other-source projects that don't have rule\n * clauses yet. */\n kind?: ProjectKind\n /** Human-friendly project name shown on the Projects page header. */\n displayName?: string\n /** External URL — opens the project's home (GitLab repo, GitHub repo,\n * Jira board, etc.). Rendered as a link on the project header. */\n homeUrl?: string\n /** Contact ids from `.agentx/contacts.json` associated with this\n * project. The Projects page uses these to populate the Contacts\n * section in addition to contacts that carry their own `project`\n * field. Either side may declare the link — both render. */\n contacts?: string[]\n /** Default agent for this project. Overrides channel-level resolveAgent\n * when set. Optional — leaving unset preserves existing behaviour. */\n agent?: string\n /** Filesystem path to the project root (where CLAUDE.md/AGENTS.md live).\n * When set, the registry injects those files into the agent system\n * prefix for tasks scoped to this project. */\n runbook?: string\n /** Override the default runbook file set (DEFAULT_RUNBOOK_FILES). */\n runbookFiles?: string[]\n gitlab?: {\n issue?: IssueRule\n /** Same matcher shape as issue — actions/requireLabels/excludeLabels/\n * excludeStates/excludeAuthors. GitLab MR `action` values: open,\n * reopen, update, close, approved, unapproved, approval, unapproval,\n * merge. Most W3-style review automations want `[open, reopen, update]`\n * only, with `excludeAuthors: [bot, acme-]` to ignore agent-driven\n * MR updates. */\n merge_request?: IssueRule\n note?: NoteRule\n pipeline?: PipelineRule\n }\n github?: {\n /** GitHub uses `issues` for issue events and `pull_request` for PRs. */\n issues?: IssueRule\n pull_request?: IssueRule\n push?: { branches?: string[] }\n }\n /** Free-form notes for the operator. Ignored by the loader. */\n description?: string\n /** Internal: file path the rule was loaded from, for diagnostics. */\n _path?: string\n}\n\nexport interface FilterDecision {\n allow: boolean\n /** Reason for the decision — surfaced in logs so operators can see why\n * an event was dropped. Always present when allow=false. */\n reason?: string\n}\n\nexport class ProjectRulesStore {\n private byProject = new Map<string, ProjectRule>()\n private dir: string\n private log: (...args: unknown[]) => void\n private watcher?: FSWatcher\n private debounce?: ReturnType<typeof setTimeout>\n private loadErrors: Array<{ file: string; error: string }> = []\n\n constructor(dir: string, log: (...args: unknown[]) => void = console.error.bind(console, \"[projects]\")) {\n this.dir = dir\n this.log = log\n }\n\n load(): { count: number; errors: number } {\n this.byProject.clear()\n this.loadErrors = []\n if (!existsSync(this.dir)) {\n return { count: 0, errors: 0 }\n }\n for (const file of this.walk(this.dir)) {\n try {\n const raw = readFileSync(file, \"utf-8\")\n const parsed = yaml.load(raw) as unknown\n const rule = this.validate(parsed, file)\n if (!rule) continue\n rule._path = file\n if (this.byProject.has(rule.project)) {\n this.log(`duplicate project \"${rule.project}\" — keeping ${this.byProject.get(rule.project)!._path}, skipping ${file}`)\n continue\n }\n this.byProject.set(rule.project, rule)\n } catch (e: any) {\n this.loadErrors.push({ file, error: e?.message ?? String(e) })\n this.log(`failed to load ${file}: ${e?.message ?? e}`)\n }\n }\n return { count: this.byProject.size, errors: this.loadErrors.length }\n }\n\n startWatching(onReload?: () => void): void {\n if (!existsSync(this.dir)) return\n try {\n this.watcher = watch(this.dir, { recursive: true }, () => {\n if (this.debounce) clearTimeout(this.debounce)\n this.debounce = setTimeout(() => {\n const result = this.load()\n this.log(`rules reloaded: ${result.count} project(s), ${result.errors} error(s)`)\n onReload?.()\n }, 200)\n })\n } catch (e: any) {\n this.log(`watcher unavailable (${e.message}) — rules will not hot-reload`)\n }\n }\n\n stop(): void {\n this.watcher?.close()\n if (this.debounce) clearTimeout(this.debounce)\n }\n\n /** Look up a rule by project path. Returns undefined if no rule\n * exists — callers must treat that as \"no filter, legacy behaviour\". */\n find(project: string): ProjectRule | undefined {\n return this.byProject.get(project)\n }\n\n list(): ProjectRule[] {\n return Array.from(this.byProject.values())\n }\n\n /** Resolve a project's `kind` even when not set on the rule file. The\n * loader-side default is intentionally absent — we infer at read time\n * so an operator who flips a `gitlab:` clause to `github:` doesn't\n * also have to remember to update `kind:`. */\n static inferKind(rule: ProjectRule): ProjectKind {\n if (rule.kind) return rule.kind\n if (rule.gitlab) return \"gitlab\"\n if (rule.github) return \"github\"\n return \"other\"\n }\n\n health(): { count: number; errors: Array<{ file: string; error: string }> } {\n return { count: this.byProject.size, errors: [...this.loadErrors] }\n }\n\n // --- Filter decisions ---\n\n /** Should a GitLab issue event reach an agent? */\n shouldFireGitlabIssue(project: string, payload: {\n action?: string\n state?: string\n labels?: string[]\n authorUsername?: string\n }): FilterDecision {\n const rule = this.find(project)?.gitlab?.issue\n if (!rule) return { allow: true }\n return matchIssueRule(rule, payload, \"gitlab\")\n }\n\n /** Should a GitLab MR-or-issue note event reach an agent?\n * `opts.knownAgentMentions` carries the @-handle list resolved by the\n * channel adapter from `agentMappings.gitlabUsernames`. When the rule\n * has an `\"auto\"` trigger entry, the matcher accepts any of these\n * mentions found in the comment text — single source of truth, no\n * manual sync required between rule files and agentMappings. */\n shouldFireGitlabNote(project: string, payload: {\n noteableType?: string\n text?: string\n authorUsername?: string\n }, opts?: { knownAgentMentions?: string[] }): FilterDecision {\n const rule = this.find(project)?.gitlab?.note\n if (!rule) return { allow: true }\n return matchNoteRule(rule, payload, opts?.knownAgentMentions)\n }\n\n /** Should a GitLab MR event reach an agent? Same matcher as issue —\n * filter on action / labels / state / author. */\n shouldFireGitlabMR(project: string, payload: {\n action?: string\n state?: string\n labels?: string[]\n authorUsername?: string\n }): FilterDecision {\n const rule = this.find(project)?.gitlab?.merge_request\n if (!rule) return { allow: true }\n return matchIssueRule(rule, payload, \"gitlab\")\n }\n\n /** Should a GitLab pipeline event reach an agent? */\n shouldFireGitlabPipeline(project: string, payload: { status?: string }): FilterDecision {\n const rule = this.find(project)?.gitlab?.pipeline\n if (!rule) return { allow: true }\n if (rule.actions && rule.actions.length > 0 && payload.status && !rule.actions.includes(payload.status)) {\n return { allow: false, reason: `pipeline status=\"${payload.status}\" not in actions=${JSON.stringify(rule.actions)}` }\n }\n return { allow: true }\n }\n\n /** Should a GitHub issues event reach an agent? */\n shouldFireGithubIssue(project: string, payload: {\n action?: string\n state?: string\n labels?: string[]\n authorUsername?: string\n }): FilterDecision {\n const rule = this.find(project)?.github?.issues\n if (!rule) return { allow: true }\n return matchIssueRule(rule, payload, \"github\")\n }\n\n /** Should a GitHub pull_request event reach an agent? */\n shouldFireGithubPR(project: string, payload: {\n action?: string\n state?: string\n labels?: string[]\n authorUsername?: string\n }): FilterDecision {\n const rule = this.find(project)?.github?.pull_request\n if (!rule) return { allow: true }\n return matchIssueRule(rule, payload, \"github\")\n }\n\n // --- Internals ---\n\n private *walk(dir: string): Generator<string> {\n let entries: string[]\n try { entries = readdirSync(dir) } catch { return }\n for (const name of entries) {\n const full = join(dir, name)\n let stat\n try { stat = statSync(full) } catch { continue }\n if (stat.isDirectory()) {\n yield* this.walk(full)\n continue\n }\n const ext = extname(name).toLowerCase()\n if (ext === \".yaml\" || ext === \".yml\") yield full\n }\n }\n\n private validate(raw: unknown, file: string): ProjectRule | null {\n if (!raw || typeof raw !== \"object\") {\n throw new Error(`${file}: top-level must be an object`)\n }\n const r = raw as Record<string, unknown>\n if (typeof r.project !== \"string\" || !r.project.includes(\"/\")) {\n throw new Error(`${file}: \\`project\\` must be a string of the form \"org/repo\"`)\n }\n if (r.runbook !== undefined && typeof r.runbook !== \"string\") {\n throw new Error(`${file}: \\`runbook\\` must be a string path`)\n }\n if (r.runbook && !resolve(r.runbook as string)) {\n // resolve never returns falsy — kept for symmetry / future expansion.\n }\n return raw as ProjectRule\n }\n}\n\nfunction matchIssueRule(rule: IssueRule, payload: {\n action?: string\n state?: string\n labels?: string[]\n authorUsername?: string\n}, kind: Channel): FilterDecision {\n const labels = payload.labels ?? []\n const author = payload.authorUsername ?? \"\"\n if (rule.actions && rule.actions.length > 0) {\n if (!payload.action || !rule.actions.includes(payload.action)) {\n return { allow: false, reason: `${kind} issue action=\"${payload.action}\" not in actions=${JSON.stringify(rule.actions)}` }\n }\n }\n if (rule.excludeStates && payload.state && rule.excludeStates.includes(payload.state)) {\n return { allow: false, reason: `${kind} issue state=\"${payload.state}\" in excludeStates` }\n }\n if (rule.requireLabels && rule.requireLabels.length > 0) {\n const has = rule.requireLabels.some((req) => labels.includes(req))\n if (!has) {\n return { allow: false, reason: `${kind} issue missing requireLabels=${JSON.stringify(rule.requireLabels)} (have ${JSON.stringify(labels)})` }\n }\n }\n if (rule.excludeLabels && rule.excludeLabels.length > 0) {\n const hit = rule.excludeLabels.find((bad) => labels.includes(bad))\n if (hit) {\n return { allow: false, reason: `${kind} issue carries excluded label \"${hit}\"` }\n }\n }\n if (rule.excludeAuthors && rule.excludeAuthors.length > 0) {\n const hit = rule.excludeAuthors.find((bad) => author.toLowerCase().includes(bad.toLowerCase()))\n if (hit) {\n return { allow: false, reason: `${kind} issue authored by \"${author}\" matched excludeAuthors entry \"${hit}\"` }\n }\n }\n return { allow: true }\n}\n\nfunction matchNoteRule(rule: NoteRule, payload: {\n noteableType?: string\n text?: string\n authorUsername?: string\n}, knownAgentMentions?: string[]): FilterDecision {\n const text = (payload.text ?? \"\").toLowerCase()\n const author = payload.authorUsername ?? \"\"\n if (rule.onlyOn && rule.onlyOn.length > 0) {\n if (!payload.noteableType || !rule.onlyOn.includes(payload.noteableType)) {\n return { allow: false, reason: `note noteableType=\"${payload.noteableType}\" not in onlyOn=${JSON.stringify(rule.onlyOn)}` }\n }\n }\n if (rule.excludeAuthors && rule.excludeAuthors.length > 0) {\n const hit = rule.excludeAuthors.find((bad) => author.toLowerCase().includes(bad.toLowerCase()))\n if (hit) {\n return { allow: false, reason: `note authored by \"${author}\" matched excludeAuthors entry \"${hit}\"` }\n }\n }\n if (rule.triggers && rule.triggers.length > 0) {\n const matched = rule.triggers.some((t) => {\n // \"auto\" sentinel — matches any of the agent mentions resolved by the\n // adapter from agentMappings.gitlabUsernames. When the adapter doesn't\n // supply the list (or it's empty), `auto` neither matches nor blocks\n // — fall through to the next trigger entry.\n if (t === \"auto\") {\n if (!knownAgentMentions || knownAgentMentions.length === 0) return false\n return knownAgentMentions.some((m) => text.includes(m.toLowerCase()))\n }\n if (t.mention) {\n const m = t.mention.toLowerCase()\n if (text.includes(m)) return true\n }\n if (t.keyword) {\n if (text.includes(t.keyword.toLowerCase())) return true\n }\n return false\n })\n if (!matched) {\n return { allow: false, reason: `note text matched no trigger` }\n }\n }\n return { allow: true }\n}\n"],"mappings":"AAiCA,OAAS,cAAAA,EAAY,eAAAC,EAAa,gBAAAC,EAAc,YAAAC,EAAU,SAAAC,MAAa,KAEvE,OAAS,WAAAC,EAAS,QAAAC,EAAM,WAAAC,MAAe,OACvC,OAAOC,MAAU,UA6HV,IAAMC,EAAN,KAAwB,CAC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AAgBM,EAIpCoB,EAA+C,CAChD,IAAMC,GAAQrB,EAAQ,MAAQ,IAAI,YAAY,EACxCgB,EAAShB,EAAQ,gBAAkB,GACzC,GAAIN,EAAK,QAAUA,EAAK,OAAO,OAAS,IAClC,CAACM,EAAQ,cAAgB,CAACN,EAAK,OAAO,SAASM,EAAQ,YAAY,GACrE,MAAO,CAAE,MAAO,GAAO,OAAQ,sBAAsBA,EAAQ,+BAA+B,KAAK,UAAUN,EAAK,MAAM,GAAI,EAG9H,GAAIA,EAAK,gBAAkBA,EAAK,eAAe,OAAS,EAAG,CACzD,IAAMwB,EAAMxB,EAAK,eAAe,KAAMyB,GAAQH,EAAO,YAAY,EAAE,SAASG,EAAI,YAAY,CAAC,CAAC,EAC9F,GAAID,EACF,MAAO,CAAE,MAAO,GAAO,OAAQ,qBAAqBF,oCAAyCE,IAAO,EAGxG,OAAIxB,EAAK,UAAYA,EAAK,SAAS,OAAS,GAmBtC,CAlBYA,EAAK,SAAS,KAAM4B,GAAM,CAKxC,GAAIA,IAAM,OACR,MAAI,CAACF,GAAsBA,EAAmB,SAAW,EAAU,GAC5DA,EAAmB,KAAMG,GAAMF,EAAK,SAASE,EAAE,YAAY,CAAC,CAAC,EAEtE,GAAID,EAAE,QAAS,CACb,IAAMC,EAAID,EAAE,QAAQ,YAAY,EAChC,GAAID,EAAK,SAASE,CAAC,EAAG,MAAO,GAE/B,MAAI,GAAAD,EAAE,SACAD,EAAK,SAASC,EAAE,QAAQ,YAAY,CAAC,EAG7C,CAAC,EAEQ,CAAE,MAAO,GAAO,OAAQ,8BAA+B,EAG3D,CAAE,MAAO,EAAK,CACvB","names":["existsSync","readdirSync","readFileSync","statSync","watch","extname","join","resolve","yaml","ProjectRulesStore","dir","log","existsSync","file","raw","readFileSync","parsed","yaml","rule","e","onReload","watch","result","project","payload","matchIssueRule","opts","matchNoteRule","entries","readdirSync","name","full","join","stat","statSync","ext","extname","resolve","kind","labels","author","req","hit","bad","knownAgentMentions","text","t","m"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as s}from"./chunk-
|
|
2
|
+
import{a as s}from"./chunk-VIH7ARPF.js";import"./chunk-5IA2CYHN.js";import"./chunk-3LYM22IV.js";import"./chunk-UCQ2N3KO.js";import"./chunk-52ZPELD2.js";import"./chunk-G2HMRDUQ.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-SZDACK6O.js";import"./chunk-E3UJHQGN.js";import"./chunk-F6CNF7V3.js";import"./chunk-YLBERT7N.js";import"./chunk-IWMW5432.js";import"./chunk-ZVP6GB4G.js";import"./chunk-ULLAE6LE.js";import"./chunk-64CAIB3C.js";import"./chunk-M4AMWP3H.js";import"./chunk-4BR7D2OU.js";import"./chunk-MHIMGM4G.js";import"./chunk-SFQUP3BP.js";import"./chunk-3SCPRYJB.js";import"./chunk-I3SIXTJO.js";import"./chunk-67Q4DCPS.js";import"./chunk-K33GIBSE.js";import"./chunk-76Z4VHDX.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-ZMYGXHPT.js";import"./chunk-SCTIUFL4.js";import"./chunk-S2MNL5V6.js";import"./chunk-77OV7346.js";import"./chunk-VWTBHLMX.js";import"./chunk-H2QQU2XV.js";import"./chunk-PNWNVOEZ.js";import"./chunk-64P4QHSZ.js";import"./chunk-QHTQPBHU.js";import"./chunk-AJ5RMU7X.js";import"./chunk-EVWEG3VD.js";import"./chunk-YLGIZRHV.js";import"./chunk-AJONZWLT.js";import"./chunk-F4HZTZHW.js";import"./chunk-ZTEU5JVQ.js";import"./chunk-QOYAX2FT.js";import"./chunk-WPMX3VGI.js";import"./chunk-LCIREYTD.js";import"./chunk-L2WSPY6S.js";import"./chunk-VDMYBPYB.js";import"./chunk-DSYKYZMT.js";import"./chunk-P5ZBBEPL.js";import"./chunk-BH3GTCZ6.js";import"./chunk-FIOB3MEX.js";process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function o(){let r=await s();if(process.argv.slice(2).length===0){r.outputHelp();return}r.parse()}o();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\nimport { buildProgram } from \"@/program\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = await buildProgram()\n\n const args = process.argv.slice(2)\n if (args.length === 0) {\n program.outputHelp()\n return\n }\n\n program.parse()\n}\n\nmain()\n"],"mappings":";g6CAGA,QAAQ,GAAG,SAAU,IAAM,QAAQ,KAAK,CAAC,CAAC,EAC1C,QAAQ,GAAG,UAAW,IAAM,QAAQ,KAAK,CAAC,CAAC,EAE3C,eAAeA,GAAO,CACpB,IAAMC,EAAU,MAAMC,EAAa,EAGnC,GADa,QAAQ,KAAK,MAAM,CAAC,EACxB,SAAW,EAAG,CACrBD,EAAQ,WAAW,EACnB,OAGFA,EAAQ,MAAM,CAChB,CAEAD,EAAK","names":["main","program","buildProgram"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as h}from"./chunk-QOYAX2FT.js";import"./chunk-
|
|
1
|
+
import{a as h}from"./chunk-QOYAX2FT.js";import"./chunk-FIOB3MEX.js";import{readFileSync as O,writeFileSync as k,existsSync as S,mkdirSync as E}from"fs";import{resolve as g}from"path";function f(t,o){let n=new Map;for(let r of t){if(r.role!=="agent")continue;let s=h(r.content);for(let a of s)n.set(a,(n.get(a)||0)+1)}let e=[...n.entries()].sort((r,s)=>s[1]-r[1]).slice(0,50).map(([r])=>r);return{lexicon:n,toolCalls:o||[],topKeywords:e,capturedAt:new Date().toISOString(),messageCount:t.length}}function y(t,o){let n=D(t,o),{distance:e,newTools:r,missingTools:s}=T(t,o),a=b(t,o),c=Math.min(1,n*.4+e*.3+a*.3),m=t.topKeywords.filter(l=>!o.lexicon.has(l)||(o.lexicon.get(l)||0)===0).slice(0,10);return{overallScore:Math.round(c*100)/100,lexiconDecay:Math.round(n*100)/100,toolShift:Math.round(e*100)/100,semanticDrift:Math.round(a*100)/100,lostWords:m,newTools:r,missingTools:s}}function D(t,o){if(t.topKeywords.length===0)return 0;let n=0;for(let e of t.topKeywords)o.lexicon.has(e)||n++;return n/t.topKeywords.length}function T(t,o){let n=new Set(t.toolCalls),e=new Set(o.toolCalls);if(n.size===0&&e.size===0)return{distance:0,newTools:[],missingTools:[]};let r=[...n].filter(u=>e.has(u)),s=new Set([...n,...e]),c=1-r.length/s.size,m=[...e].filter(u=>!n.has(u)),l=[...n].filter(u=>!e.has(u));return{distance:c,newTools:m,missingTools:l}}function b(t,o){if(t.topKeywords.length===0)return 0;let n=new Set(o.topKeywords),e=0;for(let r of t.topKeywords)n.has(r)&&e++;return 1-e/t.topKeywords.length}var w=".agentx/drift";function C(t,o,n=process.cwd()){let e=g(n,w);S(e)||E(e,{recursive:!0});let r={...o,lexicon:Object.fromEntries(o.lexicon)};k(g(e,`${t}.json`),JSON.stringify(r,null,2))}function M(t,o=process.cwd()){let n=g(o,w,`${t}.json`);if(!S(n))return null;try{let e=JSON.parse(O(n,"utf-8"));return{...e,lexicon:new Map(Object.entries(e.lexicon))}}catch{return null}}var I="claude-haiku-4-20250514";var R=5e4,A=6,v=8,K=`You are a conversation summarizer. Given a conversation history between a user and an AI agent, produce a concise summary that preserves:
|
|
2
2
|
|
|
3
3
|
1. Key decisions made and their reasoning
|
|
4
4
|
2. Important facts learned (names, IDs, paths, URLs, credentials shared)
|
|
@@ -17,12 +17,12 @@ Format as a structured summary:
|
|
|
17
17
|
Keep it under 500 words. Prioritize actionable information over conversational flow.
|
|
18
18
|
Do NOT include greetings, acknowledgments, or meta-commentary about the conversation.`;function U(t){return t.length<v?!1:t.reduce((n,e)=>n+e.content.length,0)>R}async function G(t,o,n){if(t.length<v)return{summary:"",compactedCount:0,keptCount:t.length,memoryFlushed:!1};let e=Math.max(0,t.length-A),r=t.slice(0,e),s=t.slice(e);if(r.length===0)return{summary:"",compactedCount:0,keptCount:s.length,memoryFlushed:!1};let a=f(r);C(o,a);let c=!1;if(n)try{await _(o,r,n),c=!0}catch{}let m=$(r),l=await j(m),{qualityScore:u,lostEntities:i}=P(m,l),p,F=[{role:"agent",content:l,timestamp:new Date().toISOString()}],x=f(F),d=M(o);return d&&(p=y(d,x)),{summary:l,compactedCount:r.length,keptCount:s.length,memoryFlushed:c,qualityScore:u,lostEntities:i.length>0?i:void 0,drift:p&&p.overallScore>.1?p:void 0}}function P(t,o){let n=B(t);if(n.length===0)return{qualityScore:100,lostEntities:[]};let e=o.toLowerCase(),r=[],s=[];for(let c of n)e.includes(c.toLowerCase())?r.push(c):s.push(c);return{qualityScore:Math.round(r.length/n.length*100),lostEntities:s}}function B(t){let o=[],n=new Set,e=i=>{let p=i.toLowerCase().trim();p.length<3||n.has(p)||(n.add(p),o.push(i.trim()))},r=t.match(/https?:\/\/[^\s<>)"]+/g)||[];for(let i of r)e(i.slice(0,80));let s=t.match(/(?:\/[\w.-]+){2,}/g)||[];for(let i of s)e(i);let a=t.match(/[#!]\d{2,}/g)||[];for(let i of a)e(i);let c=t.match(/[\w.-]+@[\w.-]+\.\w+/g)||[];for(let i of c)e(i);let m=t.match(/"([^"]{3,40})"/g)||[];for(let i of m)e(i.slice(1,-1));let l=t.match(/[A-Z][a-z]+(?:\s+[A-Z][a-z]+)+/g)||[];for(let i of l)e(i);let u=t.match(/[a-f0-9]{8,}/gi)||[];for(let i of u.slice(0,5))e(i);return o.slice(0,30)}function J(t,o){if(o.compactedCount===0)return t;let n=t.slice(-o.keptCount);return[{role:"agent",name:"system",content:`[Compacted conversation summary \u2014 ${o.compactedCount} earlier messages]
|
|
19
19
|
|
|
20
|
-
${o.summary}`,timestamp:new Date().toISOString()},...n]}async function _(t,o,n){let e=[],r=[];for(let a of o)a.role==="user"?e.push(`${a.name||"User"}: ${a.content}`):r.push(a.content);if(e.length===0||r.length===0)return;let{extractMemories:s}=await import("./memory-extract-
|
|
20
|
+
${o.summary}`,timestamp:new Date().toISOString()},...n]}async function _(t,o,n){let e=[],r=[];for(let a of o)a.role==="user"?e.push(`${a.name||"User"}: ${a.content}`):r.push(a.content);if(e.length===0||r.length===0)return;let{extractMemories:s}=await import("./memory-extract-F5ZHWY5E.js");await s(t,e.join(`
|
|
21
21
|
`),r.join(`
|
|
22
22
|
`),{channel:"compaction",chatId:"flush",sender:"compaction"},n)}function $(t){return t.map(o=>{let n=o.timestamp.slice(11,16),e=o.role==="user"?o.name||"User":o.name||"Agent";return`[${n}] ${e}: ${o.content}`}).join(`
|
|
23
23
|
|
|
24
|
-
`)}async function j(t){let n=t.length>2e4?t.slice(-2e4):t;try{let{createProvider:e}=await import("./providers-
|
|
24
|
+
`)}async function j(t){let n=t.length>2e4?t.slice(-2e4):t;try{let{createProvider:e}=await import("./providers-KO2DODIO.js");return(await e("claude").generate([{role:"system",content:K},{role:"user",content:n}],{model:I,maxTokens:1024})).content.trim()}catch{let s=t.split(`
|
|
25
25
|
`).slice(-20);return`[Summary unavailable \u2014 keeping last ${s.length} lines]
|
|
26
26
|
${s.join(`
|
|
27
27
|
`)}`}}export{J as applyCompaction,G as compactSession,U as needsCompaction};
|
|
28
|
-
//# sourceMappingURL=compaction-
|
|
28
|
+
//# sourceMappingURL=compaction-FD4R23HZ.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-
|
|
2
|
-
//# sourceMappingURL=conflict-detector-
|
|
1
|
+
import"./chunk-FIOB3MEX.js";function u(r,g){let n=[];for(let o of r)n.push(...c(o,g));return n}function c(r,g){let n=[],o=g.channels.gitlab;if(!o?.enabled||!o.agentMappings?.length)return n;let l=new Set(["on:gitlab-issue","on:gitlab-mr","on:gitlab-note"]);for(let i of r.nodes){let s,t;if(i.type==="trigger.channel"){let e=i.config;if(e?.source!=="gitlab-issue")continue;t=e.filter?.project,s=`trigger.channel(gitlab-issue, project=${t??"*"})`}else if(i.type==="trigger.hook"){let e=i.config;if(!e?.event||!l.has(e.event))continue;t=void 0,s=`trigger.hook(${e.event})`}else continue;let a=o.agentMappings.filter(e=>!t||t==="*"?!0:o.routes.find(f=>f.project===t)?.agent===e.agentId);a.length!==0&&n.push({kind:"workflow-vs-gitlab-agentmapping",severity:"warn",workflowId:r.id,summary:`workflow "${r.id}" ${s} overlaps with gitlab agentMapping(s) ${a.map(e=>e.agentId).join(", ")}`,details:{triggerNodeId:i.id,triggerType:i.type,project:t??"*",overlappingAgents:a.map(e=>e.agentId)},suggestion:"set `hookBlocked: true` on the gitlab trigger so the channel router's default-target dispatch defers to the workflow",autoFix:!0})}return n}export{u as detectConflicts};
|
|
2
|
+
//# sourceMappingURL=conflict-detector-ZPOT3M2C.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/workflows/conflict-detector.ts"],"sourcesContent":["// Static analyzer for the dispatch graph.\n//\n// A \"conflict\" is two dispatch paths that can fire for the same external\n// event. The classic case (incident 2026-04-29 issue globex/globex-system-v2#709):\n// a workflow `gitlab-sdlc-loop` triggers on `gitlab-issue` for project\n// globex/globex-system-v2 AND the gitlab channel router has an agentMapping for\n// `globex-v2` on the same project. Both fire on issue.create — two parallel\n// agent runs on one issue.\n//\n// This module runs at workflow load and on config reload. It returns a list\n// of detected conflicts. v0 covers only the trigger.channel(gitlab-issue) ↔\n// gitlab.agentMappings case (the one that produced #709). The detector is\n// designed to grow: each conflict kind is a single function, all wired into\n// detectConflicts().\n//\n// The dispatcher and trigger registrar do NOT consult this module directly\n// today — they honor `workflow.state`, which is set by the operator (manual\n// `disabled`) or by an upcoming auto-quarantine layer (`quarantined`). This\n// stub exists so that layer has a stable contract to build on.\n\nimport type { Workflow } from \"./types\"\nimport type { DaemonConfig } from \"@/daemon/config\"\n\nexport type ConflictSeverity = \"warn\" | \"block\"\nexport type ConflictKind = \"workflow-vs-gitlab-agentmapping\"\n\nexport interface Conflict {\n kind: ConflictKind\n severity: ConflictSeverity\n workflowId: string\n /** Brief one-liner suitable for log + admin panel summary. */\n summary: string\n /** What overlaps. Free-form so each conflict kind can carry its own data. */\n details: Record<string, unknown>\n /** Suggested resolution shown to the operator. Auto-applicable fixes set\n * `autoFix: true` so an upcoming auto-fix layer can act without prompt. */\n suggestion: string\n autoFix: boolean\n}\n\n/**\n * Run all conflict checks for the current workflow set against the daemon\n * config. Pure function — does not mutate state, does not log. Callers\n * decide what to do with the result (log, surface, quarantine, auto-fix).\n */\nexport function detectConflicts(workflows: Workflow[], config: DaemonConfig): Conflict[] {\n const out: Conflict[] = []\n for (const wf of workflows) {\n out.push(...detectGitlabAgentMappingOverlap(wf, config))\n }\n return out\n}\n\n// --- Individual conflict checks ---------------------------------------------\n\n/**\n * trigger.channel(source: gitlab-issue, filter.project: P) overlaps with\n * channels.gitlab.agentMappings entries that route the same project. Both\n * paths reach an agent on issue events for project P; the channel router's\n * default-target dispatch (`src/channels/gitlab.ts:712`) will fire alongside\n * the workflow's own dispatch.\n *\n * Auto-fix: set the workflow trigger's `hookBlocked: true` (or the matching\n * channel-router opt-out) so the channel router's default dispatch defers to\n * the workflow. Not applied here — the auto-fix engine consumes this result.\n */\nfunction detectGitlabAgentMappingOverlap(wf: Workflow, config: DaemonConfig): Conflict[] {\n const out: Conflict[] = []\n const gitlab = config.channels.gitlab\n if (!gitlab?.enabled || !gitlab.agentMappings?.length) return out\n\n // Hook events whose source is the gitlab channel router. trigger.hook\n // workflows on these events race against gitlab.agentMappings dispatched\n // from the same webhook (gitlab.ts handleIssue/handleMR/handleNote).\n const GITLAB_HOOK_EVENTS = new Set([\"on:gitlab-issue\", \"on:gitlab-mr\", \"on:gitlab-note\"])\n\n for (const node of wf.nodes) {\n let triggerLabel: string | undefined\n let project: string | undefined\n\n if (node.type === \"trigger.channel\") {\n const cfg = node.config as { source?: string; filter?: { project?: string } } | undefined\n if (cfg?.source !== \"gitlab-issue\") continue\n project = cfg.filter?.project\n triggerLabel = `trigger.channel(gitlab-issue, project=${project ?? \"*\"})`\n } else if (node.type === \"trigger.hook\") {\n // trigger.hook fires on a HookRegistry event; project filter is not\n // part of the hook config (the event IS the filter), so any matching\n // hook races for every project the gitlab adapter dispatches to.\n const cfg = node.config as { event?: string } | undefined\n if (!cfg?.event || !GITLAB_HOOK_EVENTS.has(cfg.event)) continue\n project = undefined // hook fires for all projects\n triggerLabel = `trigger.hook(${cfg.event})`\n } else {\n continue\n }\n\n const overlaps = gitlab.agentMappings.filter((m) => {\n if (!project || project === \"*\") return true\n // The mapping itself doesn't carry a project field — gitlab routing is\n // by username + project routes. We approximate \"this mapping handles\n // this project\" by looking at gitlab.routes too.\n const projectRoute = gitlab.routes.find((r) => r.project === project)\n return projectRoute?.agent === m.agentId\n })\n if (overlaps.length === 0) continue\n\n out.push({\n kind: \"workflow-vs-gitlab-agentmapping\",\n severity: \"warn\",\n workflowId: wf.id,\n summary: `workflow \"${wf.id}\" ${triggerLabel} overlaps with gitlab agentMapping(s) ${overlaps.map((m) => m.agentId).join(\", \")}`,\n details: {\n triggerNodeId: node.id,\n triggerType: node.type,\n project: project ?? \"*\",\n overlappingAgents: overlaps.map((m) => m.agentId),\n },\n suggestion: \"set `hookBlocked: true` on the gitlab trigger so the channel router's default-target dispatch defers to the workflow\",\n autoFix: true,\n })\n }\n return out\n}\n"],"mappings":"4BA6CO,SAASA,EAAgBC,EAAuBC,EAAkC,CACvF,IAAMC,EAAkB,CAAC,EACzB,QAAWC,KAAMH,E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K_EVENTS","node","triggerLabel","project","cfg","overlaps","m","r"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{a as d,b as C}from"./chunk-AJONZWLT.js";import"./chunk-FIOB3MEX.js";C();var S="claude-haiku-4-5-20251001",I=`You are a context planner for an AI agent. Given the user's current message and recent conversation tail, decide what historical context the agent needs.
|
|
2
|
+
|
|
3
|
+
Output ONE JSON object on one line, no prose, no fences:
|
|
4
|
+
{ "recentTurns": number, "memory": { "include": boolean, "query": string }, "crossChat": boolean, "reasoning": string }
|
|
5
|
+
|
|
6
|
+
Rules:
|
|
7
|
+
- "recentTurns" in [0,6]. Short acknowledgments ("ok", "yes", "do it", "continue") need 2-3 turns to know what they refer to. New topics need 0. Technical follow-ups need 3-5.
|
|
8
|
+
- "memory.include" = true only when the message likely references a person, past event, decision, or project the agent should recall. "memory.query" = 3-8 words distilling what to search for (leave "" when include=false).
|
|
9
|
+
- "crossChat" = true only when the message references another chat ("DM", "the group", "earlier conversation", a peer agent's name). Most messages = false.
|
|
10
|
+
- "reasoning" = one short phrase explaining the plan.
|
|
11
|
+
|
|
12
|
+
Be conservative \u2014 unneeded context costs tokens. When in doubt, exclude.`;async function N(e){let c=Date.now(),i=e.timeoutMs??8e3,r=M(e.sessions,e.agentId,e.channel,e.chatId,4),o=[`Agent: ${e.agentId}`,`Channel: ${e.channel}`,r?`Recent conversation:
|
|
13
|
+
${r}`:"Recent conversation: (none \u2014 first message)","",`Current message: ${e.message.slice(0,1500)}`].join(`
|
|
14
|
+
`),n;try{let{createProvider:l}=await import("./providers-KO2DODIO.js"),f=l("claude"),b=new AbortController,p=setTimeout(()=>b.abort(),i);try{let x=await f.generate([{role:"system",content:I},{role:"user",content:o}],{model:S,maxTokens:256});n=d(x.content)}finally{clearTimeout(p)}}catch(l){return process.env.AGENTX_PLANNER_DEBUG&&console.error(`[planner] error: ${l?.message??l}`),null}if(!n||typeof n!="object")return null;let m=T(n.recentTurns,0,6,3),t=!!n.memory?.include,s=typeof n.memory?.query=="string"?n.memory.query:"",a=!!n.crossChat,g=typeof n.reasoning=="string"?n.reasoning:void 0,y=w(e.sessions,e.agentId,e.channel,e.chatId,m),u="";if(t&&s)try{let l=e.memoryStore.findRelevant(s,e.agentId,5);u=e.memoryStore.buildContext(l)}catch{}let h="";return a&&(h=e.sessions.getCrossSessionSummary(e.agentId,e.channel,e.chatId,"")),{sessionHistory:y,memoryContext:u,crossChatContext:h,debug:{recentTurns:m,memoryIncluded:t,memoryQuery:s||void 0,crossChatIncluded:a,reasoning:g,planLatencyMs:Date.now()-c}}}function w(e,c,i,r,o){if(o<=0)return"";let n=e.getSession(c,i,r);if(n.messages.length===0)return"";let m=Math.min(n.messages.length,o*2),t=n.messages.slice(-m),s=[`[Recent exchange \u2014 last ${t.length} messages]`];for(let a of t){let g=a.name||(a.role==="user"?"User":"Agent");s.push(`${g}: ${a.content}`)}return s.push("[End recent exchange \u2014 respond to the latest message above]"),s.push(""),s.join(`
|
|
15
|
+
`)}function M(e,c,i,r,o){let n=e.getSession(c,i,r);return n.messages.length===0?"":n.messages.slice(-o).map(t=>{let s=t.name||(t.role==="user"?"User":"Agent"),a=t.content.length>200?t.content.slice(0,200)+"\u2026":t.content;return` ${s}: ${a}`}).join(`
|
|
16
|
+
`)}function T(e,c,i,r){let o=typeof e=="number"?Math.floor(e):Number.parseInt(String(e??""),10);return Number.isFinite(o)?Math.min(i,Math.max(c,o)):r}export{N as planContext};
|
|
17
|
+
//# sourceMappingURL=context-planner-AQHJMVY2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/agents/context-planner.ts"],"sourcesContent":["// --- Context Planner ---\n//\n// A Haiku pre-call that decides what context to retrieve for the current\n// message, replacing the blind \"stack every layer\" approach of the layered\n// strategy. Drops --resume bloat by avoiding the full session history blob\n// on every turn; instead pulls only the specific facts / memory / cross-chat\n// the current message actually needs.\n//\n// Always-on core (handled by registry, not the planner): channel, scope,\n// landscape, identity, intent, and a small `recentTurns`-sized tail of the\n// session verbatim. The planner decides: how many tail turns to keep, and\n// whether to pull memory or cross-chat on top.\n//\n// Fail-open: any planner error returns null and the registry falls back to\n// the layered strategy. This keeps the feature safe to enable even when\n// the planner model is misbehaving.\n//\n// Cost model: one small Haiku call per message (~300 input / ~80 output\n// tokens, ~$0.0005). Win threshold is when it avoids shipping ≥5K tokens\n// of layered history/memory the agent didn't need — typical for short\n// \"ok / yes / do it\" messages where the layered path still dumps the\n// whole 12K-char session blob.\n\nimport type { SessionStore, SessionMessage } from \"./sessions\"\nimport { extractJson } from \"@/utils/extract-json\"\nimport type { MemoryStore } from \"./memory-store\"\n\n/** Planner output. When `null`, the caller falls back to the layered\n * strategy. Otherwise each field overrides the corresponding context\n * layer — an empty string means \"skip this layer entirely\". */\nexport interface ContextPlan {\n /** Rendered session history (same shape buildHistoryContext returns),\n * truncated to the last N turns the planner picked. */\n sessionHistory: string\n /** Rendered memory context, or \"\" when the planner decided memory\n * isn't relevant to this message. */\n memoryContext: string\n /** Rendered cross-chat summary, or \"\" when not needed. */\n crossChatContext: string\n /** Debug metadata — surfaced in logs + bench output so operators can\n * see what the planner chose. Not sent to the main agent. */\n debug: {\n recentTurns: number\n memoryIncluded: boolean\n memoryQuery?: string\n crossChatIncluded: boolean\n reasoning?: string\n planLatencyMs: number\n }\n}\n\nexport interface PlanContextInput {\n agentId: string\n channel: string\n chatId: string\n message: string\n sessions: SessionStore\n memoryStore: MemoryStore\n /** Caller-controlled timeout for the Haiku planner call. Defaults to\n * 8s — the planner is in the critical path before the main agent\n * runs, so we can't afford a long timeout. Fail-open if exceeded. */\n timeoutMs?: number\n}\n\nconst PLANNER_MODEL = \"claude-haiku-4-5-20251001\"\nconst PLANNER_PROMPT = `You are a context planner for an AI agent. Given the user's current message and recent conversation tail, decide what historical context the agent needs.\n\nOutput ONE JSON object on one line, no prose, no fences:\n { \"recentTurns\": number, \"memory\": { \"include\": boolean, \"query\": string }, \"crossChat\": boolean, \"reasoning\": string }\n\nRules:\n- \"recentTurns\" in [0,6]. Short acknowledgments (\"ok\", \"yes\", \"do it\", \"continue\") need 2-3 turns to know what they refer to. New topics need 0. Technical follow-ups need 3-5.\n- \"memory.include\" = true only when the message likely references a person, past event, decision, or project the agent should recall. \"memory.query\" = 3-8 words distilling what to search for (leave \"\" when include=false).\n- \"crossChat\" = true only when the message references another chat (\"DM\", \"the group\", \"earlier conversation\", a peer agent's name). Most messages = false.\n- \"reasoning\" = one short phrase explaining the plan.\n\nBe conservative — unneeded context costs tokens. When in doubt, exclude.`\n\nexport async function planContext(input: PlanContextInput): Promise<ContextPlan | null> {\n const start = Date.now()\n const timeoutMs = input.timeoutMs ?? 8_000\n\n // Snapshot the session tail for the planner prompt. Don't send the\n // whole session — the planner only needs enough to judge whether the\n // message is a follow-up, and we pay tokens for every line we ship.\n const recentTail = sessionTail(input.sessions, input.agentId, input.channel, input.chatId, 4)\n\n const userPrompt = [\n `Agent: ${input.agentId}`,\n `Channel: ${input.channel}`,\n recentTail ? `Recent conversation:\\n${recentTail}` : \"Recent conversation: (none — first message)\",\n ``,\n `Current message: ${input.message.slice(0, 1500)}`,\n ].join(\"\\n\")\n\n // Use the Anthropic SDK path — warm HTTP client, no subprocess cold-start.\n // resolveToken now recognizes CLAUDE_CODE_OAUTH_TOKEN so this works out\n // of the box for any operator who already has Claude CLI auth set up.\n // Planner timeout is tight (8s default) because plan latency is in the\n // critical path before the main agent runs.\n let planJson: any\n try {\n const { createProvider } = await import(\"@/agent/providers\")\n const provider = createProvider(\"claude\")\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), timeoutMs)\n try {\n const result = await provider.generate(\n [\n { role: \"system\", content: PLANNER_PROMPT },\n { role: \"user\", content: userPrompt },\n ],\n { model: PLANNER_MODEL, maxTokens: 256 },\n )\n planJson = extractJson(result.content)\n } finally {\n clearTimeout(timer)\n }\n } catch (err: any) {\n // Temporary: surface planner errors for debugging. Will silence once\n // we're confident the SDK path is stable.\n if (process.env.AGENTX_PLANNER_DEBUG) {\n // eslint-disable-next-line no-console\n console.error(`[planner] error: ${err?.message ?? err}`)\n }\n return null\n }\n\n if (!planJson || typeof planJson !== \"object\") return null\n\n const recentTurns = clampInt(planJson.recentTurns, 0, 6, 3)\n const memoryInclude = Boolean(planJson.memory?.include)\n const memoryQuery: string = typeof planJson.memory?.query === \"string\" ? planJson.memory.query : \"\"\n const crossChatInclude = Boolean(planJson.crossChat)\n const reasoning = typeof planJson.reasoning === \"string\" ? planJson.reasoning : undefined\n\n // Resolve the plan into actual retrieval strings.\n const sessionHistory = renderSessionTail(\n input.sessions,\n input.agentId,\n input.channel,\n input.chatId,\n recentTurns,\n )\n\n let memoryContext = \"\"\n if (memoryInclude && memoryQuery) {\n try {\n const relevant = input.memoryStore.findRelevant(memoryQuery, input.agentId, 5)\n memoryContext = input.memoryStore.buildContext(relevant)\n } catch {\n // Memory retrieval is best-effort; planner proceeds with empty memory.\n }\n }\n\n let crossChatContext = \"\"\n if (crossChatInclude) {\n // Force-include via empty message arg — the planner already decided.\n crossChatContext = input.sessions.getCrossSessionSummary(\n input.agentId, input.channel, input.chatId, \"\",\n )\n }\n\n return {\n sessionHistory,\n memoryContext,\n crossChatContext,\n debug: {\n recentTurns,\n memoryIncluded: memoryInclude,\n memoryQuery: memoryQuery || undefined,\n crossChatIncluded: crossChatInclude,\n reasoning,\n planLatencyMs: Date.now() - start,\n },\n }\n}\n\n/** Render the last N message pairs as a compact prompt tail. Returns \"\" when\n * there's no session on disk yet (first message). Format mirrors\n * SessionStore.buildHistoryContext but with an N-turn cap — the planner's\n * whole point is to cap this instead of dumping the full 12K-char log. */\nfunction renderSessionTail(\n sessions: SessionStore,\n agentId: string,\n channel: string,\n chatId: string,\n turns: number,\n): string {\n if (turns <= 0) return \"\"\n const session = sessions.getSession(agentId, channel, chatId)\n if (session.messages.length === 0) return \"\"\n // N \"turns\" = N*2 messages (user+agent pairs). Round to nearest message\n // count so a partial trailing user message still gets included.\n const msgCount = Math.min(session.messages.length, turns * 2)\n const tail = session.messages.slice(-msgCount)\n const lines: string[] = [`[Recent exchange — last ${tail.length} messages]`]\n for (const msg of tail) {\n const name = msg.name || (msg.role === \"user\" ? \"User\" : \"Agent\")\n lines.push(`${name}: ${msg.content}`)\n }\n lines.push(\"[End recent exchange — respond to the latest message above]\")\n lines.push(\"\")\n return lines.join(\"\\n\")\n}\n\n/** Very small tail for the planner's own prompt — enough for the planner to\n * decide whether this message is a follow-up, not enough to bloat the\n * planner call itself. Distinct from renderSessionTail (used for the main\n * agent) because we cap more aggressively here. */\nfunction sessionTail(\n sessions: SessionStore,\n agentId: string,\n channel: string,\n chatId: string,\n maxMessages: number,\n): string {\n const session = sessions.getSession(agentId, channel, chatId)\n if (session.messages.length === 0) return \"\"\n const tail = session.messages.slice(-maxMessages)\n return tail\n .map((m: SessionMessage) => {\n const name = m.name || (m.role === \"user\" ? \"User\" : \"Agent\")\n const content = m.content.length > 200 ? m.content.slice(0, 200) + \"…\" : m.content\n return ` ${name}: ${content}`\n })\n .join(\"\\n\")\n}\n\n/** Extract the first JSON object from a text response. Haiku sometimes\n * wraps output in backticks or prose despite the instructions, so we\n * scan for the first `{...}` span. */\n\nfunction clampInt(v: unknown, min: number, max: number, fallback: number): number {\n const n = typeof v === \"number\" ? Math.floor(v) : Number.parseInt(String(v ?? \"\"), 10)\n if (!Number.isFinite(n)) return fallback\n return Math.min(max, Math.max(min, n))\n}\n"],"mappings":"2EAwBAA,IAwCA,IAAMC,EAAgB,4BAChBC,EAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,+EAavB,eAAsBC,EAAYC,EAAsD,CACtF,IAAMC,EAAQ,KAAK,IAAI,EACjBC,EAAYF,EAAM,WAAa,IAK/BG,EAAaC,EAAYJ,EAAM,SAAUA,EAAM,QAASA,EAAM,QAASA,EAAM,OAAQ,CAAC,EAEtFK,EAAa,CACjB,UAAUL,EAAM,UAChB,YAAYA,EAAM,UAClBG,EAAa;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wB,EAAYC,EAAaC,EAAaC,EAA0B,CAChF,IAAMC,EAAI,OAAOJ,GAAM,SAAW,KAAK,MAAMA,CAAC,EAAI,OAAO,SAAS,OAAOA,GAAK,EAAE,EAAG,EAAE,EACrF,OAAK,OAAO,SAASI,CAAC,EACf,KAAK,IAAIF,EAAK,KAAK,IAAID,EAAKG,CAAC,CAAC,EADLD,CAElC","names":["init_extract_json","PLANNER_MODEL","PLANNER_PROMPT","planContext","input","start","timeoutMs","recentTail","sessionTail","userPrompt","planJson","createProvider","provider","ac","timer","result","extractJson","err","recentTurns","clampInt","memoryInclude","memoryQuery","crossChatInclude","reasoning","sessionHistory","renderSessionTail","memoryContext","relevant","crossChatContext","sessions","agentId","channel","chatId","turns","session","msgCount","tail","lines","msg","name","maxMessages","m","content","v","min","max","fallback","n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-FIOB3MEX.js";var $=/\bssh\s+(?:-i\s+(\S+)\s+)?([a-z_][a-z0-9_-]*)@([a-z0-9][a-z0-9.-]+|\d{1,3}(?:\.\d{1,3}){3})/gi,R=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g,y=/\b([a-z0-9][a-z0-9._-]*)@([a-z0-9][a-z0-9.-]+\.[a-z]{2,})\b/gi;var k=/groups\/([a-z0-9][a-z0-9._-]+)[^\n|]*\(?\s*ID:?\s*(\d+)\s*\)?/gi,_=/(\/Users\/[^\s)`'"\]]+|\/home\/[^\s)`'"\]]+|\/var\/www\/[^\s)`'"\]]+|\/etc\/[^\s)`'"\]]+)/g,v=/(\+\d{1,3}[\s.-]?(?:\(\d+\)[\s.-]?)?\d[\s.\d-]{6,}\d)/g,z=/^(?:127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.)/;function x(i,r){let s={byKind:{ssh:[],gitlab:[],path:[],contact:[]},scannedSkills:[],diagnostics:[]},c=new Set;for(let a of i){let e=a.frontmatter,n=a.instructions??"";if(r.filter?.length){let t=[e.name,e.description,...e.tags??[],e.category??"",a.path??"",n.slice(0,500)].join(" ").toLowerCase();if(!r.filter.some(u=>t.includes(u.toLowerCase())))continue}s.scannedSkills.push(e.name);let o=e.name;for(let t of w(n,r.namespace,o))m(s,t,"ssh",c)&&s.diagnostics.push({skill:e.name,kind:"ssh",id:t.id});for(let t of E(n,r.namespace,r.gitlabHost))m(s,t,"gitlab",c)&&s.diagnostics.push({skill:e.name,kind:"gitlab",id:t.id});for(let t of I(n,r.namespace))m(s,t,"path",c)&&s.diagnostics.push({skill:e.name,kind:"path",id:t.id});for(let t of j(n,r.namespace))m(s,t,"contact",c)&&s.diagnostics.push({skill:e.name,kind:"contact",id:t.id})}return s}function m(i,r,s,c){return c.has(r.id)?!1:(c.add(r.id),i.byKind[s].push(r),!0)}function w(i,r,s){let c=[];for(let e of i.matchAll($)){let[,n,o,t]=e;if(!o||!t)continue;let d=g(`${o}-${t.replace(/[^a-z0-9-]/gi,"-")}`);c.push({id:`${r}.ssh.${d}`,kind:"ssh",summary:`SSH ${o}@${t}`,fields:D({user:o,host:t,key:n}),tags:["discovered"],ownerAgent:s})}let a=new Set(c.flatMap(e=>Object.values(e.fields)));for(let e of i.matchAll(R)){let n=e[0];if(a.has(n)||z.test(n))continue;let o=g(`host-${n.replace(/\./g,"-")}`);c.push({id:`${r}.ssh.${o}`,kind:"ssh",summary:`Host ${n} (user not detected \u2014 fill in)`,fields:{host:n},tags:["discovered","needs-review"],ownerAgent:s}),a.add(n)}return c}var C=/\b([a-z0-9][a-z0-9._-]{1,40})\/([a-z0-9][a-z0-9._-]{1,40})\b/i,A=/\b(\d{1,8})\b/g;function E(i,r,s){let c=[];if(s&&!i.includes(s.replace(/^https?:\/\//,"")))return c;for(let e of i.matchAll(k)){let[,n,o]=e;!n||!o||c.push({id:`${r}.gitlab.group.${g(n)}`,kind:"gitlab",summary:`GitLab group ${n}`,fields:{groupId:Number(o),path:n},tags:["discovered"]})}let a=new RegExp(C.source,"gi");for(let e of i.split(/\r?\n/)){if(!/^\s*\|.+\|/.test(e)&&!/\bID[:\s]/i.test(e)&&!/gitlab/i.test(e))continue;let o,t,d=e.match(/https?:\/\/[^\s)]*gitlab[^\s)]*?\/([a-z0-9][a-z0-9._-]+)\/([a-z0-9][a-z0-9._-]+)/i);if(d&&d[1]&&d[2])o=d[1],t=d[2].replace(/[).,;:]+$/,"");else for(let f of e.matchAll(a)){let p=f[1],h=f[2];!p||!h||p==="wp-content"||h==="wp-content"||p.includes(".")||S(h)||(o=p,t=h)}if(!o||!t)continue;let l=[...e.matchAll(A)].map(f=>Number(f[1])).find(f=>f>=10&&f<=9999999);l&&c.push({id:`${r}.gitlab.project.${g(t)}`,kind:"gitlab",summary:`GitLab project ${o}/${t}`,fields:{projectId:l,path:`${o}/${t}`},tags:["discovered"]})}return c}function S(i){return/\.(md|ya?ml|json|ts|tsx|js|jsx|py|sh|conf|env)$/i.test(i)}function I(i,r){let s=[];for(let c of i.matchAll(_)){let a=c[1].replace(/[.,;:)]+$/,"");if(a.length<4)continue;let e=g(a.replace(/^\//,"").replace(/[/.]/g,"-"));s.push({id:`${r}.paths.${e}`,kind:"path",summary:a,fields:{path:a},tags:["discovered"]})}return s}function j(i,r){let s=[];for(let a of i.matchAll(y)){let[,e,n]=a;if(n.endsWith(".png")||n.endsWith(".jpg"))continue;let o=g(e);s.push({id:`${r}.contacts.${o}`,kind:"contact",summary:`${e}@${n}`,fields:{email:`${e}@${n}`},tags:["discovered"]})}let c=[...i.matchAll(v)].map(a=>a[1].trim());for(let a of c){let e=g(`phone-${a.replace(/\D+/g,"")}`);s.push({id:`${r}.contacts.${e}`,kind:"contact",summary:`Phone ${a}`,fields:{mobile:a},tags:["discovered","needs-review"]})}return s}function D(i){let r={};for(let[s,c]of Object.entries(i))c===void 0||c===""||(r[s]=c);return r}function g(i){return i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"x"}function L(i,r){let s={},c={ssh:"ssh.yaml",gitlab:"gitlab.yaml",path:"paths.yaml",contact:"contacts.yaml"};for(let[a,e]of Object.entries(i.byKind)){if(e.length===0)continue;let n=`${r}.${a==="path"?"paths":a==="contact"?"contacts":a}`,o=["# Discovered automatically by 'agentx references discover'.",'# Review every card \u2014 flagged ones (tags include "needs-review") are',"# best-effort guesses. Set lastVerified once you've confirmed.",`namespace: ${n}`,"cards:"];for(let t of e){let d=t.id.startsWith(`${n}.`)?t.id.slice(n.length+1):t.id;o.push(` - id: ${d}`),o.push(` kind: ${t.kind}`),o.push(` summary: ${b(t.summary)}`),o.push(" fields:");for(let[u,l]of Object.entries(t.fields))o.push(` ${u}: ${typeof l=="number"||typeof l=="boolean"?l:b(String(l))}`);o.push(` tags: [${t.tags.join(", ")}]`),t.ownerAgent&&o.push(` ownerAgent: ${t.ownerAgent}`)}s[c[a]]=o.join(`
|
|
2
2
|
`)+`
|
|
3
3
|
`}return s}function b(i){return/^[A-Za-z0-9_./@+:-]+$/.test(i)&&!/^\d/.test(i)?i:`"${i.replace(/"/g,'\\"')}"`}export{x as discoverFromSkills,L as renderDiscovery};
|
|
4
|
-
//# sourceMappingURL=discover-
|
|
4
|
+
//# sourceMappingURL=discover-D4VVRNAI.js.map
|