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
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/crons/scheduler.ts","../src/intent/mode.ts","../src/intent/ledger.ts","../src/intent/ulid.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 { 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 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 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 const timer = setTimeout(() => this.executeJob(jobId), delay)\n this.timers.set(jobId, timer)\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 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 this.log(`${isRetry ? `[retry ${retryAttempt}] ` : \"\"}Executing job \"${jobId}\" -> agent \"${job.agent}\"`)\n const startedAt = firedAt\n job.lastRun = startedAt\n job.totalRuns++\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","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 { 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 clawd-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","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-mtgl')\".\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":"uFAIA,OAAS,iBAAAA,EAAe,aAAAC,EAAW,cAAAC,EAAY,gBAAAC,OAAoB,KACnE,OAAS,WAAAC,MAAe,OCoBxB,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,EAAiB,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,CAAc,CAAC,EAClD,OAAIM,GACG,KACT,CAGO,SAASD,EAAgBE,EAAmC,CACjE,GAAI,OAAOA,GAAU,SAAU,OAAO,KACtC,IAAMC,EAAaD,EAAM,KAAK,EAAE,Y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AAQ,KAAM,CAAC,CAChC,CACF,MAAE,CAEF,CACF,CAKA,MAAuB,CACrB,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,CACtC,CAKA,QAA6K,CAC3K,IAAMiB,EAAO,MAAM,KAAK,KAAK,KAAK,OAAO,CAAC,EACpCZ,EAAS,KAAK,iBAAiB,EAErC,MAAO,CACL,QAASY,EAAK,OAAOpC,GAAKA,EAAE,SAAWA,EAAE,oBAAsB,CAAC,EAAE,OAClE,QAASoC,EAAK,OAAOpC,GAAKA,EAAE,SAAWA,EAAE,kBAAoB,CAAC,EAAE,OAChE,SAAUoC,EAAK,OAAOpC,GAAK,CAACA,EAAE,OAAO,EAAE,OACvC,OAAQwB,EAAO,OACf,KAAMY,EAAK,IAAIpC,IAAM,CACnB,GAAIA,EAAE,GACN,OAASA,EAAE,QAAuBA,EAAE,aAAe,WAAaA,EAAE,kBAAoB,EAAI,UAAY,UAAjF,WACrB,kBAAmBA,EAAE,kBACrB,UAAWA,EAAE,SACf,EAAE,CACJ,CACF,CACF","names":["writeFileSync","mkdirSync","existsSync","readFileSync","resolve","VALID_MODES","PER_SOURCE_ENV_VAR","GLOBAL_ENV_VAR","getLedgerMode","source","env","perSource","parseLedgerMode","global","value","normalized","Database","existsSync","mkdirSync","dirname","resolve","randomBytes","ENCODING","TIME_LEN","RAND_LEN","encodeTime","ms","out","i","encodeRandom","bytes","newEventId","now","IntentLedger","opts","resolve","mkdirSync","dirname","Database","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","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","existing","nextRun","delay","attempt","agentId","firedAt","legacy","getLedgerMode","decision","recordCronDispatch","getDefaultLedger","retryAttempt","isRetry","hookResult","startedAt","intentRef","response","result","res","applyConfigMutation","cfg","setAtPath","missed","lastRuns","lastRunStr","lastRun","shouldHaveRun","error","data","dir","writeFileSync","readFileSync","runDir","filename","jobs"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent/skills/loader.ts","../src/agent/skills/types.ts"],"sourcesContent":["import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport fg from \"fast-glob\"\nimport yaml from \"js-yaml\"\nimport { logger } from \"@/utils/logger\"\nimport type { Skill, SkillFrontmatter, SkillMatch } from \"./types\"\nimport { skillFrontmatterSchema } from \"./types\"\n\n// --- Load skills from local files and remote packages ---\n\nconst SKILL_DIRS = [\".skills\", \".claude/skills\", \"skills\"]\nconst SKILL_FILE = \"SKILL.md\"\n\nexport async function loadLocalSkills(cwd: string): Promise<Skill[]> {\n const skills: Skill[] = []\n\n for (const dir of SKILL_DIRS) {\n const skillDir = path.resolve(cwd, dir)\n if (!existsSync(skillDir)) continue\n\n const skillFiles = await fg.glob(`**/${SKILL_FILE}`, {\n cwd: skillDir,\n deep: 3,\n caseSensitiveMatch: false,\n })\n\n for (const file of skillFiles) {\n const fullPath = path.resolve(skillDir, file)\n const skill = await parseSkillFile(fullPath)\n if (skill) {\n skill.source = \"local\"\n skill.path = fullPath\n skills.push(skill)\n }\n }\n }\n\n // Also check for a single SKILL.md at project root\n const rootSkill = path.resolve(cwd, SKILL_FILE)\n if (existsSync(rootSkill)) {\n const skill = await parseSkillFile(rootSkill)\n if (skill) {\n skill.source = \"local\"\n skill.path = rootSkill\n skills.push(skill)\n }\n }\n\n return skills\n}\n\nexport async function parseSkillFile(filePath: string): Promise<Skill | null> {\n try {\n const content = await fs.readFile(filePath, \"utf8\")\n return parseSkillContent(content)\n } catch {\n return null\n }\n}\n\nexport function parseSkillContent(content: string): Skill | null {\n try {\n // Parse YAML frontmatter\n const frontmatterMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/)\n\n if (!frontmatterMatch) {\n // No frontmatter - treat entire content as instructions with minimal metadata\n return {\n frontmatter: { name: \"unnamed\", description: \"No description\" },\n instructions: content.trim(),\n source: \"local\",\n }\n }\n\n const [, frontmatterRaw, instructions] = frontmatterMatch\n const frontmatter = parseYamlFrontmatter(frontmatterRaw)\n\n const validated = skillFrontmatterSchema.parse(frontmatter)\n\n return {\n frontmatter: validated,\n instructions: instructions.trim(),\n source: \"local\",\n }\n } catch {\n return null\n }\n}\n\nfunction parseYamlFrontmatter(raw: string): Record<string, unknown> {\n // Real YAML — handles arrays (block + flow), nested objects (e.g. `metadata:`\n // sub-block used by some skills), quoted strings, and comma-separated tag\n // strings. The previous primitive parser silently dropped nested keys, which\n // caused valid skills (ksi-pm, hotmail, ksi-v1-coder) to fail Zod validation\n // and load as null.\n const parsed = yaml.load(raw)\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return {}\n }\n const result = parsed as Record<string, unknown>\n // Some skills nest tags under `metadata.tags` as a comma-separated string.\n // Lift it to the top-level shape Zod expects (array of strings) so the\n // schema accepts the skill.\n const meta = result.metadata as Record<string, unknown> | undefined\n if (meta && typeof meta === \"object\") {\n if (!result.tags && meta.tags) {\n if (typeof meta.tags === \"string\") {\n result.tags = meta.tags.split(\",\").map(t => t.trim()).filter(Boolean)\n } else if (Array.isArray(meta.tags)) {\n result.tags = meta.tags\n }\n }\n if (!result.version && meta.version) result.version = meta.version\n }\n return result\n}\n\nexport function matchSkillsToTask(\n skills: Skill[],\n taskDescription: string,\n outputType?: string\n): SkillMatch[] {\n const matches: SkillMatch[] = []\n const taskLower = taskDescription.toLowerCase()\n const taskWords = new Set(taskLower.split(/\\s+/))\n\n for (const skill of skills) {\n let relevance = 0\n let matchReason = \"\"\n\n // Check trigger patterns\n if (skill.frontmatter.triggers) {\n for (const trigger of skill.frontmatter.triggers) {\n try {\n const regex = new RegExp(trigger.pattern, \"i\")\n if (regex.test(taskDescription)) {\n relevance = Math.max(relevance, 0.9)\n matchReason = `Trigger match: ${trigger.description || trigger.pattern}`\n }\n } catch {\n // Invalid regex - try simple string match\n if (taskLower.includes(trigger.pattern.toLowerCase())) {\n relevance = Math.max(relevance, 0.7)\n matchReason = `Keyword match: ${trigger.pattern}`\n }\n }\n }\n }\n\n // Check tags overlap\n if (skill.frontmatter.tags) {\n const tagOverlap = skill.frontmatter.tags.filter(\n (tag) => taskWords.has(tag.toLowerCase()) || taskLower.includes(tag.toLowerCase())\n )\n if (tagOverlap.length) {\n const tagRelevance = Math.min(tagOverlap.length * 0.3, 0.8)\n if (tagRelevance > relevance) {\n relevance = tagRelevance\n matchReason = `Tag match: ${tagOverlap.join(\", \")}`\n }\n }\n }\n\n // Check name/description overlap\n const nameWords = skill.frontmatter.name.toLowerCase().split(/[-_\\s]+/)\n const descWords = skill.frontmatter.description.toLowerCase().split(/\\s+/)\n const allSkillWords = new Set([...nameWords, ...descWords])\n\n const overlap = [...taskWords].filter((w) => allSkillWords.has(w) && w.length > 3)\n if (overlap.length > 0) {\n const wordRelevance = Math.min(overlap.length * 0.2, 0.6)\n if (wordRelevance > relevance) {\n relevance = wordRelevance\n matchReason = `Content match: ${overlap.join(\", \")}`\n }\n }\n\n if (relevance > 0.1) {\n matches.push({ skill, relevance, matchReason })\n }\n }\n\n return matches.sort((a, b) => b.relevance - a.relevance)\n}\n\n/**\n * Find auto-injectable skills that match the current message.\n * Only skills with `autoInject: true` in frontmatter participate.\n * Returns skill content to inject into context, capped at maxTokens.\n */\nexport function getAutoInjectSkills(\n skills: Skill[],\n message: string,\n maxTokens: number = 2000,\n): string {\n const autoSkills = skills.filter(s => s.frontmatter.autoInject)\n if (autoSkills.length === 0) return \"\"\n\n const matches = matchSkillsToTask(autoSkills, message)\n if (matches.length === 0) return \"\"\n\n // Inject matched skills within token budget\n const maxChars = maxTokens * 4\n const sections: string[] = [\"[Auto-Injected Skills — matched to current task]\"]\n let totalChars = sections[0].length\n\n for (const match of matches) {\n const content = `\\n## ${match.skill.frontmatter.name} (${Math.round(match.relevance * 100)}% match)\\n${match.skill.instructions}`\n if (totalChars + content.length > maxChars) break\n sections.push(content)\n totalChars += content.length\n }\n\n if (sections.length === 1) return \"\" // no skills fit in budget\n return sections.join(\"\\n\")\n}\n","import { z } from \"zod\"\n\n// --- Skill types aligned with skills.sh / Agent Skills spec ---\n\nexport const skillFrontmatterSchema = z.object({\n name: z.string(),\n description: z.string(),\n version: z.string().optional(),\n author: z.string().optional(),\n tags: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n // When to automatically apply this skill\n triggers: z\n .array(\n z.object({\n pattern: z.string(), // regex or keyword pattern\n description: z.string().optional(),\n })\n )\n .optional(),\n /** If true, skill is auto-injected into context when triggers match (per-turn) */\n autoInject: z.boolean().optional(),\n /** Reference card ids cited by this skill (e.g. \"ksi.gitlab.project.ksi-v2\").\n * Audit lint flags FAILING when any id does not resolve. */\n references: z.array(z.string()).optional(),\n /** Skills this one delegates to (e.g. ksi-cx-email → [hotmail]). Audit lint\n * flags FAILING when a delegate has no SKILL.md. */\n delegatesTo: z.array(z.string()).optional(),\n /** Free-form category — used by recipes and audit rules. Common values:\n * deploy, ssh, email, gitlab, ops, content, marketing. */\n category: z.string().optional(),\n})\n\nexport type SkillFrontmatter = z.infer<typeof skillFrontmatterSchema>\n\nexport interface Skill {\n frontmatter: SkillFrontmatter\n instructions: string // Markdown body\n source: \"local\" | \"remote\" | \"generated\"\n path?: string // Local file path\n packageId?: string // e.g., \"intellectronica/agent-skills\"\n}\n\nexport interface SkillMatch {\n skill: Skill\n relevance: number // 0-1 how relevant to current task\n matchReason: string\n}\n\nexport interface SkillPackage {\n owner: string\n repo: string\n skills: Skill[]\n}\n"],"mappings":"AAAA,OAAS,cAAAA,EAAY,YAAYC,MAAU,KAC3C,OAAOC,MAAU,OACjB,OAAOC,MAAQ,YACf,OAAOC,MAAU,UCHjB,OAAS,KAAAC,MAAS,MAIX,IAAMC,EAAyBD,EAAE,OAAO,CAC7C,KAAMA,EAAE,OAAO,EACf,YAAaA,EAAE,OAAO,EACtB,QAASA,EAAE,OAAO,EAAE,SAAS,EAC7B,OAAQA,EAAE,OAAO,EAAE,SAAS,EAC5B,KAAMA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EACnC,MAAOA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EAEpC,SAAUA,EACP,MACCA,EAAE,OAAO,CACP,QAASA,EAAE,OAAO,EAClB,YAAaA,EAAE,OAAO,EAAE,SAAS,CACnC,CAAC,CACH,EACC,SAAS,EAEZ,WAAYA,EAAE,QAAQ,EAAE,SAAS,EAGjC,WAAYA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EAGzC,YAAaA,EAAE,MAAMA,EAAE,OAAO,CAAC,EAAE,SAAS,EAG1C,SAAUA,EAAE,OAAO,EAAE,SAAS,CAChC,CAAC,EDrBD,IAAME,EAAa,CAAC,UAAW,iBAAkB,QAAQ,EACnDC,EAAa,WAEnB,eAAsBC,EAAgBC,EAA+B,CACnE,IAAMC,EAAkB,CAAC,EAEzB,QAAWC,KAAOL,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,OAGxB,OAAIyC,EAAS,SAAW,EAAU,GAC3BA,EAAS,KAAK;AAAA,CAAI,CAC3B","names":["existsSync","fs","path","fg","yaml","z","skillFrontmatterSchema","SKILL_DIRS","SKILL_FILE","loadLocalSkills","cwd","skills","dir","skillDir","path","existsSync","skillFiles","fg","file","fullPath","skill","parseSkillFile","rootSkill","filePath","content","fs","parseSkillContent","frontmatterMatch","frontmatterRaw","instructions","frontmatter","parseYamlFrontmatter","skillFrontmatterSchema","raw","parsed","yaml","result","meta","t","matchSkillsToTask","taskDescription","outputType","matches","taskLower","taskWords","relevance","matchReason","trigger","tagOverlap","tag","tagRelevance","nameWords","descWords","allSkillWords","overlap","w","wordRelevance","a","b","getAutoInjectSkills","message","maxTokens","autoSkills","s","maxChars","sections","totalChars","match"]}
|