agentix-cli 0.26.0 → 0.27.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/dist/{App-BPNHIGUX.js → App-U52IPUK2.js} +2 -2
- package/dist/{ChatApp-6XSSZB4U.js → ChatApp-XP4OMHPL.js} +2 -2
- package/dist/agent-V2CA4TXD.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-TTMAYRLG.js} +1407 -447
- package/dist/board-dashboard-TTMAYRLG.js.map +1 -0
- package/dist/{builtin-FRKAQMFS.js → builtin-B67DMJ3M.js} +2 -2
- package/dist/calibration-ILS5OI44.js +2 -0
- package/dist/chunk-2T5W3ETS.js +5 -0
- package/dist/{chunk-K2CAPYES.js.map → chunk-2T5W3ETS.js.map} +1 -1
- 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-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-AX2PWSRT.js +114 -0
- package/dist/chunk-AX2PWSRT.js.map +1 -0
- package/dist/chunk-BH3GTCZ6.js +2 -0
- package/dist/chunk-BH3GTCZ6.js.map +1 -0
- package/dist/chunk-BPIRO4YD.js +126 -0
- package/dist/chunk-BPIRO4YD.js.map +1 -0
- package/dist/chunk-CJQQIRPD.js +13 -0
- package/dist/chunk-CJQQIRPD.js.map +1 -0
- package/dist/chunk-DCDQZR7I.js +24 -0
- package/dist/chunk-DCDQZR7I.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-FIEJDZVC.js +121 -0
- package/dist/chunk-FIEJDZVC.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-GDWJUGB5.js +9 -0
- package/dist/chunk-GDWJUGB5.js.map +1 -0
- package/dist/{chunk-BVGJSPW4.js → chunk-IB3F7VBE.js} +7 -7
- package/dist/{chunk-BVGJSPW4.js.map → chunk-IB3F7VBE.js.map} +1 -1
- package/dist/chunk-IBUSGCLQ.js +109 -0
- package/dist/chunk-IBUSGCLQ.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-L2IZPR6P.js +45 -0
- package/dist/chunk-L2IZPR6P.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-LNRB5MCU.js +530 -0
- package/dist/chunk-LNRB5MCU.js.map +1 -0
- package/dist/chunk-OPHIXXGI.js +157 -0
- package/dist/chunk-OPHIXXGI.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-V3U4OF7L.js → chunk-UFAGYX73.js} +45 -47
- package/dist/chunk-UFAGYX73.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-VTE7L6LO.js +5 -0
- package/dist/{chunk-O6YPEOQF.js.map → chunk-VTE7L6LO.js.map} +1 -1
- 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-WZ72HX5C.js +1182 -0
- package/dist/chunk-WZ72HX5C.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-PX25MD47.js +2 -0
- package/dist/{compaction-NWEMOSHA.js → compaction-FD4R23HZ.js} +4 -4
- package/dist/config-HL5F36V4.js +2 -0
- package/dist/config-mutator-HBX53OMJ.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-PBAH6XL3.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 +1016 -65
- package/dist/index.js +13 -13
- 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-YGXVCV2Y.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-ZKTFJMNE.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-PSZDPFZK.js +2 -0
- package/dist/review-candidates-AEUXRQQC.js +4 -0
- package/dist/review-candidates-AEUXRQQC.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-4PV66BK6.js +2 -0
- package/dist/routing-4PV66BK6.js.map +1 -0
- package/dist/runner-YRBVNYTY.js +2 -0
- package/dist/scheduler-GZZAN6ZG.js +2 -0
- package/dist/seat-VZ7AVO27.js +2 -0
- package/dist/select-F5I5PO2O.js +2 -0
- package/dist/select-F5I5PO2O.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/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-N5SMP3DT.js +2 -0
- package/dist/wiki-N5SMP3DT.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 +1 -1
- 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-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-U52IPUK2.js.map} +0 -0
- /package/dist/{ChatApp-6XSSZB4U.js.map → ChatApp-XP4OMHPL.js.map} +0 -0
- /package/dist/{agent-5QMITZT6.js.map → agent-V2CA4TXD.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-PX25MD47.js.map} +0 -0
- /package/dist/{compaction-NWEMOSHA.js.map → compaction-FD4R23HZ.js.map} +0 -0
- /package/dist/{config-mutator-MNSFUN7D.js.map → config-HL5F36V4.js.map} +0 -0
- /package/dist/{debug-N3B5NVJU.js.map → config-mutator-HBX53OMJ.js.map} +0 -0
- /package/dist/{doctor-3Q36ZFE6.js.map → debug-3MEUO2P2.js.map} +0 -0
- /package/dist/{heal-HZ3EQD52.js.map → doctor-PBAH6XL3.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-YGXVCV2Y.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-ZKTFJMNE.js.map} +0 -0
- /package/dist/{registry-HK3WQ7BS.js.map → recipes-7S4MC5OJ.js.map} +0 -0
- /package/dist/{runner-BFYDWPUO.js.map → registry-PSZDPFZK.js.map} +0 -0
- /package/dist/{rotation-memo-B3EXXSEH.js.map → rotation-memo-7T75BLEX.js.map} +0 -0
- /package/dist/{scheduler-6T2SU5ST.js.map → runner-YRBVNYTY.js.map} +0 -0
- /package/dist/{store-I3HEWVLQ.js.map → scheduler-GZZAN6ZG.js.map} +0 -0
- /package/dist/{surface-usage-PRL6Z4U3.js.map → seat-VZ7AVO27.js.map} +0 -0
- /package/dist/{timers-5LPZN55J.js.map → store-MCOA6N4F.js.map} +0 -0
- /package/dist/{subagent-WV7QKQ3L.js.map → subagent-2SJHSSJS.js.map} +0 -0
- /package/dist/{types-VECTMYTO.js.map → surface-usage-NS74AXSE.js.map} +0 -0
- /package/dist/{types-Y6ZCZ52Z.js.map → timers-PCB4ZIBD.js.map} +0 -0
- /package/dist/{wiki-M6YNRFC4.js.map → types-H5ENIUIT.js.map} +0 -0
- /package/dist/{workspace-setup-TBQAHYHJ.js.map → types-OIFU3KSQ.js.map} +0 -0
- /package/dist/{whatsapp-state-XMTCSRXU.js.map → whatsapp-state-6D6FHHD2.js.map} +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`):
|
|
3
|
-
`)[0]}catch{return null}},o=e("npm");n.push({severity:o?"ok":"fail",group:"Environment",title:o?"npm on PATH":"npm not found",detail:o||void 0});let s=e("claude");if(s){let a;try{a=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${a||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let a;try{a=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${a||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let l=e("opencode");if(l){let a;try{a=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${a||"installed"}`,detail:l})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{
|
|
4
|
-
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function
|
|
5
|
-
`)[0]||null}catch{o=null}if(o){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:o})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let l=m(r.workspace,".codegraph","codegraph.db");y(l)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:l}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function A(n){return{errors:n.filter(i=>i.severity==="fail").length,warnings:n.filter(i=>i.severity==="warn").length,ok:n.filter(i=>i.severity==="ok").length}}function
|
|
6
|
-
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=A(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{
|
|
7
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{g as C,j as S}from"./chunk-CJQQIRPD.js";S();import{Command as R}from"commander";import f from"chalk";import{execFileSync as h}from"child_process";import{existsSync as y,readFileSync as k,readdirSync as j,statSync as N}from"fs";import{resolve as m}from"path";import{createRequire as W}from"module";async function E(n={}){let i=[];await P(i);let e=T(i);return e&&L(i,e),e&&_(i,e),e&&D(i,e),e&&q(i,e),e&&B(i,e),n.running!==!1&&e&&await z(i,e),{checks:i,summary:A(i)}}var K=new R().name("doctor").description("pre-flight health check: Node, config, credentials, daemon").option("--no-running","skip the live daemon probe").option("--json","emit machine-readable JSON (stable shape for CI)").action(async n=>{let{checks:i,summary:e}=await E({running:n.running!==!1});n.json?process.stdout.write(JSON.stringify({checks:i,summary:e},null,2)+`
|
|
2
|
+
`):H(i),process.exit(e.errors>0?1:0)});async function P(n){let i=Number(process.versions.node.split(".")[0]);n.push({severity:i>=20?"ok":"fail",group:"Environment",title:`Node.js ${process.versions.node}`,detail:i>=20?void 0:"AgentX needs Node 20 or newer.",fix:i>=20?void 0:"Install a newer Node (nvm install 20 && nvm use 20)"});let e=a=>{try{return h(process.platform==="win32"?"where":"which",[a],{encoding:"utf-8"}).trim().split(`
|
|
3
|
+
`)[0]}catch{return null}},o=e("npm");n.push({severity:o?"ok":"fail",group:"Environment",title:o?"npm on PATH":"npm not found",detail:o||void 0});let s=e("claude");if(s){let a;try{a=h("claude",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`claude CLI ${a||"installed"}`,detail:s})}else n.push({severity:"warn",group:"Environment",title:"claude CLI not on PATH",detail:"Only required for agents on the claude-code tier.",fix:"See https://docs.anthropic.com/en/docs/claude-code"});let r=e("codex");if(r){let a;try{a=h("codex",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`codex CLI ${a||"installed"}`,detail:r})}else n.push({severity:"warn",group:"Environment",title:"codex CLI not on PATH",detail:"Only required for agents on the codex-cli tier.",fix:"Install with `npm i -g @openai/codex`."});let l=e("opencode");if(l){let a;try{a=h("opencode",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"Environment",title:`opencode CLI ${a||"installed"}`,detail:l})}else n.push({severity:"warn",group:"Environment",title:"opencode CLI not on PATH",detail:"Only required for agents on the opencode tier.",fix:"Install from https://opencode.ai/docs/."});try{W(import.meta.url)("better-sqlite3"),n.push({severity:"ok",group:"Environment",title:`better-sqlite3 loads for Node ${process.version}`,detail:`NODE_MODULE_VERSION ${process.versions.modules}`})}catch(a){n.push({severity:"fail",group:"Environment",title:"better-sqlite3 native binding does not load",detail:a?.message??String(a),fix:`Run "pnpm rebuild better-sqlite3" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`})}}function T(n){let i=m(process.cwd(),"agentx.json");if(!y(i))return n.push({severity:"fail",group:"Config",title:"agentx.json not found",detail:`Looked in ${i}`,fix:"Run `agentx setup` to create one via the web wizard."}),null;let e;try{e=JSON.parse(k(i,"utf-8"))}catch(l){return n.push({severity:"fail",group:"Config",title:"agentx.json is not valid JSON",detail:l.message}),null}try{C(i),n.push({severity:"ok",group:"Config",title:`agentx.json valid (${Object.keys(e.agents||{}).length} agents, ${Object.keys(e.crons||{}).length} schedules)`})}catch(l){n.push({severity:"fail",group:"Config",title:"agentx.json failed schema validation",detail:l.message,fix:"Open /admin \u2192 Advanced tab to edit and re-save."})}let o=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="claude-code");o.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["claude"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${o.length} agent(s) use claude-code tier but claude CLI is missing`,detail:o.map(([a])=>a).join(", "),fix:"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk."}));let s=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="codex-cli");s.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["codex"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${s.length} agent(s) use codex-cli tier but codex CLI is missing`,detail:s.map(([a])=>a).join(", "),fix:"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code."}));let r=Object.entries(e.agents||{}).filter(([,l])=>l.tier==="opencode");return r.length>0&&((()=>{try{return h(process.platform==="win32"?"where":"which",["opencode"],{stdio:"ignore"}),!0}catch{return!1}})()||n.push({severity:"fail",group:"Config",title:`${r.length} agent(s) use opencode tier but OpenCode CLI is missing`,detail:r.map(([a])=>a).join(", "),fix:"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier."})),e}function L(n,i){let e=new Set;if($(i,e),e.size===0){n.push({severity:"ok",group:"Secrets",title:"No ${VAR} references in agentx.json"});return}let o=m(process.cwd(),".env"),s={};if(y(o))for(let a of k(o,"utf-8").split(/\r?\n/)){let g=a.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);g&&(s[g[1]]=g[2])}let r=[],l=[];for(let a of e){let g=process.env[a]??s[a];g===void 0?r.push(a):(!g.trim()||/^["']?\s*["']?$/.test(g))&&l.push(a)}r.length===0&&l.length===0?n.push({severity:"ok",group:"Secrets",title:`${e.size} env reference(s) resolved`}):(r.length>0&&n.push({severity:"fail",group:"Secrets",title:`${r.length} env var(s) referenced in agentx.json but missing`,detail:r.join(", "),fix:`Add to .env \u2014 e.g. ${r[0]}=<value>`}),l.length>0&&n.push({severity:"warn",group:"Secrets",title:`${l.length} env var(s) set but empty`,detail:l.join(", ")}))}function $(n,i){if(typeof n=="string")for(let e of n.matchAll(/\$\{([A-Z_][A-Z0-9_]*)\}/g))i.add(e[1]);else if(Array.isArray(n))for(let e of n)$(e,i);else if(n&&typeof n=="object")for(let e of Object.values(n))$(e,i)}function _(n,i){let e=[];for(let[o,s]of Object.entries(i.agents||{})){if(!s.workspace)continue;let r=s.workspace.startsWith("/")?s.workspace:m(process.cwd(),s.workspace);try{N(r).isDirectory()||e.push(`${o}: ${r} (exists but not a directory)`)}catch{e.push(`${o}: ${r}`)}}e.length===0?n.push({severity:"ok",group:"Workspaces",title:"All agent workspace folders exist"}):n.push({severity:"warn",group:"Workspaces",title:`${e.length} agent workspace(s) missing`,detail:e.join(`
|
|
4
|
+
`),fix:"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them."})}function D(n,i){let e=/\$\{[A-Za-z_][A-Za-z0-9_]*\}/g,o=[];for(let[s,r]of Object.entries(i.agents||{})){if(!r.workspace)continue;let l=r.workspace.startsWith("/")?r.workspace:m(process.cwd(),r.workspace);for(let a of["settings.json","settings.local.json"]){let g=m(l,".claude",a);if(!y(g))continue;let w;try{w=JSON.parse(k(g,"utf-8"))}catch(d){o.push({severity:"fail",agent:s,msg:`${a}: JSON parse error \u2014 ${d.message}`});continue}let b=w.env||{};for(let[d,p]of Object.entries(b)){if(typeof p!="string")continue;let u=p.match(e);u&&o.push({severity:"fail",agent:s,msg:`${a} env.${d} contains unexpanded ${[...new Set(u)].join(",")} \u2014 Claude Code does NOT expand \${VAR} in settings.json (use a fully-literal value)`})}let t=b.PATH;if(typeof t=="string"){let d=t.split(":").filter(Boolean);d.includes("/usr/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /usr/bin \u2014 cat/head/sh/which will fail`}),d.includes("/bin")||o.push({severity:"fail",agent:s,msg:`${a} env.PATH missing /bin \u2014 ls/cp/mv will fail`})}let c=w.permissions;if(c&&typeof c=="object"&&"allow"in c){let d=c.allow,p=c.deny;Array.isArray(d)&&d.length===0&&Array.isArray(p)&&p.length>0&&o.push({severity:"warn",agent:s,msg:`${a} permissions.allow is explicitly [] with ${p.length} deny rules \u2014 agent may be locked out (omit the key to use defaults instead)`})}}}if(o.length===0){n.push({severity:"ok",group:"Workspace settings",title:`All ${Object.keys(i.agents||{}).length} agent .claude/settings.json files clean`});return}for(let s of o)n.push({severity:s.severity,group:"Workspace settings",title:`${s.agent}: ${s.msg}`,fix:s.severity==="fail"?"Edit .claude/settings.json \u2014 replace ${VAR} with the literal value or omit the key to inherit.":"Either remove the empty allow list or populate it."})}function q(n,i){let e=i.webhooks??[],o=[],s=m(process.cwd(),i.workflows?.dir||".agentx/workflows"),r=new Set;try{if(y(s))for(let t of j(s))t.endsWith(".json")&&!t.startsWith("_")&&!t.endsWith(".disabled.json")&&r.add(t.replace(/\.json$/,""))}catch{}let l=new Set(["github","gitlab"]);for(let t of e){if(!t.enabled||!l.has(t.source))continue;!(t.triggers&&Object.keys(t.triggers).length>0)&&!t.defaultWorkflow&&o.push({severity:"warn",title:`webhook "${t.id}" (${t.source} -> ${t.agentId}) has no triggers map; every event-type collapses to the bound agent`,fix:'Add a triggers map: { "issues.opened": "wf-id", "pull_request.synchronize": "wf-id" } \u2014 or set defaultWorkflow.'})}for(let t of e)if(!(!t.enabled||!t.triggers)){for(let[c,d]of Object.entries(t.triggers))r.size>0&&!r.has(d)&&o.push({severity:"fail",title:`webhook "${t.id}".triggers["${c}"] -> "${d}" \u2014 no such workflow under ${i.workflows?.dir||".agentx/workflows"}`,fix:"Create the workflow file or fix the id in agentx.json"});t.defaultWorkflow&&r.size>0&&!r.has(t.defaultWorkflow)&&o.push({severity:"fail",title:`webhook "${t.id}".defaultWorkflow -> "${t.defaultWorkflow}" \u2014 no such workflow`,fix:"Create the workflow file or fix the id in agentx.json"})}try{if(y(s)){for(let t of j(s))if(!(!t.endsWith(".json")||t.startsWith("_")||t.endsWith(".disabled.json")))try{let c=JSON.parse(k(m(s,t),"utf-8"));c?.status==="active"&&c?.state==="quarantined"&&o.push({severity:"warn",title:`workflow "${c.id??t}" is status=active but state=quarantined \u2014 it looks live but will never dispatch`,fix:'Resolve the conflict the detector flagged, then set state back to "active" (or set status to "review" while parked).'})}catch{}}}catch{}let a=new Set((i.mesh?.peers??[]).map(t=>t.name));for(let t of e)!t.enabled||!t.node||a.has(t.node)||o.push({severity:"fail",title:`webhook "${t.id}" routes to mesh peer "${t.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or remove the node field on the webhook."});let g=new Map;for(let t of e){if(!t.enabled)continue;let c=`${t.source}:${t.agentId}`,d=g.get(c);d?o.push({severity:"warn",title:`webhook entries "${d}" and "${t.id}" both enabled for ${t.source} -> ${t.agentId}; only the first is dispatched`,fix:"Disable one entry, or merge their triggers maps into a single entry."}):g.set(c,t.id)}let w=new Set(Object.keys(i.agents??{}));for(let t of i.channels?.gitlab?.agentMappings??[])if(t?.agentId){if(t.node){a.has(t.node)||o.push({severity:"fail",title:`gitlab.agentMappings entry agentId="${t.agentId}" routes to mesh peer "${t.node}" which is not in mesh.peers`,fix:"Add the peer to mesh.peers or drop the node field on the mapping."});continue}w.has(t.agentId)||o.push({severity:"warn",title:`gitlab.agentMappings entry agentId="${t.agentId}" \u2014 no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,fix:'Add the agent to agents.*, set node:"<peer>" if the agent lives remotely, or remove the mapping.'})}for(let[t,c]of Object.entries(i.channels?.telegram?.accounts??{}))c.agentBinding?w.has(c.agentBinding)||o.push({severity:"fail",title:`telegram account "${t}".agentBinding -> "${c.agentBinding}" \u2014 no such agent in agents.*`,fix:"Fix the agentBinding or define the agent in agents.*."}):o.push({severity:"fail",title:`telegram account "${t}" has no agentBinding; every DM to this bot will drop`,fix:"Set agentBinding to a valid agent id."});let b=new Set(["telegram-bot","whatsapp","slack-bot","discord-bot","gitlab-user","github-user","gmail","hotmail","smtp","hubspot","salesforce","pipedrive","odoo","trello","linear","asana","jira","notion","stripe","sentry","vercel","twilio","custom"]);for(let[t,c]of Object.entries(i.agents??{})){let d=c.integrations??[];if(!d.length)continue;let p=new Set;for(let u of d){let x=`${u.kind}::${u.label}`;p.has(x)&&o.push({severity:"warn",title:`agents.${t}.integrations: duplicate (${u.kind}, ${u.label})`,fix:"Remove the duplicate or rename one. (kind, label) must be unique per agent."}),p.add(x),b.has(u.kind)||o.push({severity:"warn",title:`agents.${t}.integrations: unknown kind "${u.kind}" on integration "${u.label}"`,fix:'Use a canonical kind from INTEGRATION_KINDS, or "custom" for ad-hoc services.'});let I=u.credentials||{};for(let[O,v]of Object.entries(I))typeof v=="string"&&/^[A-Z][A-Z0-9_]*$/.test(v)&&!process.env[v]&&o.push({severity:"warn",title:`agents.${t}.integrations[${u.kind}/${u.label}].${O} -> $${v} but env var is unset (in this shell)`,fix:`Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`})}}if(o.length===0){n.push({severity:"ok",group:"Routing",title:`${e.length} webhook(s), ${Object.keys(i.channels?.telegram?.accounts??{}).length} telegram account(s) \u2014 all routing references resolve`});return}for(let t of o)n.push({severity:t.severity,group:"Routing",title:t.title,fix:t.fix})}async function z(n,i){let e=i.dashboard?.daemonUrl?.replace(/\/+$/,"")||"http://127.0.0.1:18800",o={};i.dashboard?.token&&(o.Authorization=`Bearer ${i.dashboard.token}`);try{let s=new AbortController,r=setTimeout(()=>s.abort(),2e3),l=await fetch(e+"/health",{headers:o,signal:s.signal});if(clearTimeout(r),!l.ok){n.push({severity:"warn",group:"Runtime",title:`Daemon responded ${l.status}`,detail:e});return}let a=await l.json();n.push({severity:"ok",group:"Runtime",title:`Daemon healthy \u2014 ${a.agents?.length??0} agents live, uptime ${Math.round((a.uptime??0)/60)}m`,detail:e})}catch{n.push({severity:"warn",group:"Runtime",title:"Daemon not reachable (not running?)",detail:e,fix:"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`."})}}function B(n,i){let e=Object.entries(i.agents||{}).filter(([,s])=>s?.codegraph===!0&&(s.tier==="claude-code"||s.tier==="codex-cli"));if(e.length===0)return;let o=null;try{o=h(process.platform==="win32"?"where":"which",["codegraph"],{encoding:"utf-8"}).trim().split(`
|
|
5
|
+
`)[0]||null}catch{o=null}if(o){let s;try{s=h("codegraph",["--version"],{encoding:"utf-8",timeout:3e3}).trim()}catch{}n.push({severity:"ok",group:"CodeGraph",title:`codegraph CLI ${s||"installed"}`,detail:o})}else n.push({severity:"fail",group:"CodeGraph",title:"codegraph CLI not on PATH",detail:`${e.length} agent(s) have codegraph:true but the binary isn't available.`,fix:"Install with `npm i -g @colbymchenry/codegraph`."});for(let[s,r]of e){if(!r.workspace||!y(r.workspace)){n.push({severity:"warn",group:"CodeGraph",title:`${s}: workspace missing`,detail:`Workspace path ${r.workspace} does not exist \u2014 codegraph will skip this agent.`});continue}let l=m(r.workspace,".codegraph","codegraph.db");y(l)?n.push({severity:"ok",group:"CodeGraph",title:`${s}: index present`,detail:l}):n.push({severity:"warn",group:"CodeGraph",title:`${s}: index not built yet`,detail:".codegraph/ missing \u2014 daemon will background-index this workspace on next boot.",fix:`Run \`codegraph init --index ${r.workspace}\` to build it now.`})}}function A(n){return{errors:n.filter(i=>i.severity==="fail").length,warnings:n.filter(i=>i.severity==="warn").length,ok:n.filter(i=>i.severity==="ok").length}}function H(n){console.log(),console.log(f.bold(" agentx doctor")),console.log();let i=new Map;for(let o of n)i.has(o.group)||i.set(o.group,[]),i.get(o.group).push(o);for(let[o,s]of i){console.log(f.bold(" "+o));for(let r of s){let l=r.severity==="ok"?f.green("\u2713"):r.severity==="warn"?f.yellow("!"):f.red("\u2717");console.log(` ${l} ${r.title}`),r.detail&&console.log(f.dim(" "+r.detail.replace(/\n/g,`
|
|
6
|
+
`))),r.fix&&console.log(f.dim(" \u2192 "+r.fix))}console.log()}let e=A(n);e.errors>0?console.log(f.red.bold(` ${e.errors} error${e.errors===1?"":"s"}`)+(e.warnings?f.yellow(`, ${e.warnings} warning${e.warnings===1?"":"s"}`):"")+`. Fix the error${e.errors===1?"":"s"} and rerun.`):e.warnings>0?console.log(f.yellow.bold(` ${e.warnings} warning${e.warnings===1?"":"s"}.`)+f.dim(" Review but not blocking.")):console.log(f.green.bold(` All checks passed (${e.ok}).`)),console.log()}export{E as a,K as b};
|
|
7
|
+
//# sourceMappingURL=chunk-IB3F7VBE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const nodeMajor = Number(process.versions.node.split(\".\")[0])\n checks.push({\n severity: nodeMajor >= 20 ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: nodeMajor >= 20 ? undefined : \"AgentX needs Node 20 or newer.\",\n fix: nodeMajor >= 20 ? undefined : \"Install a newer Node (nvm install 20 && nvm use 20)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n"],"mappings":"wCAAA,OAAS,WAAAA,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KAChE,OAAS,WAAAC,MAAe,OACxB,OAAS,iBAAAC,MAAqB,SA8B9B,eAAsBC,EACpBC,EAA8B,CAAC,EAC0D,CACzF,IAAMC,EAAkB,CAAC,EACzB,MAAMC,EAAaD,CAAM,EACzB,IAAME,EAAMC,EAAgBH,CAAM,EAClC,OAAIE,GAAKE,EAAmBJ,EAAQE,CAAG,EACnCA,GAAKG,EAAmBL,EAAQE,CAAG,EACnCA,GAAKI,EAA2BN,EAAQE,CAAG,EAC3CA,GAAKK,EAAiBP,EAAQE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GAAGE,EAAO,IAAIF,EAAE,MAAO,CAAC,CAAC,EAChDE,EAAO,IAAIF,EAAE,KAAK,EAAG,KAAKA,CAAC,EAE7B,OAAW,CAACG,EAAOC,CAAK,IAAKF,EAAQ,CACnC,QAAQ,IAAID,EAAM,KAAK,KAAOE,CAAK,CAAC,EACpC,QAAWH,KAAKI,EAAO,CACrB,IAAMC,EAASL,EAAE,WAAa,KAAOC,EAAM,MAAM,QAAG,EAChDD,EAAE,WAAa,OAASC,EAAM,OAAO,GAAG,EACxCA,EAAM,IAAI,QAAG,EACjB,QAAQ,IAAI,OAAOI,KAAUL,EAAE,OAAO,EAClCA,EAAE,QAAQ,QAAQ,IAAIC,EAAM,IAAI,SAAWD,EAAE,OAAO,QAAQ,MAAO;AAAA,OAAU,CAAC,CAAC,EAC/EA,EAAE,KAAK,QAAQ,IAAIC,EAAM,IAAI,gBAAaD,EAAE,GAAG,CAAC,EAEtD,QAAQ,IAAI,EAGd,IAAMM,EAAI9F,EAAUV,CAAM,EACtBwG,EAAE,OAAS,EACb,QAAQ,IAAIL,EAAM,IAAI,KAAK,KAAKK,EAAE,eAAeA,EAAE,SAAW,EAAI,GAAK,KAAK,GACzEA,EAAE,SAAWL,EAAM,OAAO,KAAKK,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,KAAK,EAAI,IACtF,kBAAkBA,EAAE,SAAW,EAAI,GAAK,gBAAgB,EACjDA,EAAE,SAAW,EACtB,QAAQ,IAAIL,EAAM,OAAO,KAAK,KAAKK,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,MAAM,EAAIL,EAAM,IAAI,2BAA2B,CAAC,EAEhI,QAAQ,IAAIA,EAAM,MAAM,KAAK,wBAAwBK,EAAE,MAAM,CAAC,EAEhE,QAAQ,IAAI,CACd","names":["Command","chalk","execFileSync","existsSync","readFileSync","readdirSync","statSync","resolve","createRequire","runDoctorChecks","opts","checks","runEnvChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runRuntimeChecks","summarize","doctor","Command","summary","printHumanReport","nodeMajor","which","bin","execFileSync","npmPath","claudePath","ver","codexPath","openCodePath","createRequire","e","cfgPath","resolve","existsSync","readFileSync","loadDaemonConfig","claudeCodeAgents","a","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","name","raw","node","into","item","v","abs","statSync","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","readdirSync","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","url","headers","ac","timer","r","body","optedIn","cgPath","def","dbPath","c","chalk","groups","group","items","marker","s"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/doctor.ts"],"sourcesContent":["import { Command } from \"commander\"\nimport chalk from \"chalk\"\nimport { execFileSync } from \"child_process\"\nimport { existsSync, readFileSync, readdirSync, statSync } from \"fs\"\nimport { resolve } from \"path\"\nimport { createRequire } from \"module\"\nimport { loadDaemonConfig } from \"@/daemon/config\"\n\n// --- agentx doctor ---\n//\n// Pre-flight health check. Catches the common \"why isn't it working\" reasons\n// before the operator hits them at runtime:\n// - wrong Node version\n// - invalid / missing agentx.json\n// - agents with claude-code tier but no claude CLI installed\n// - ${FOO} references in agentx.json that have no matching env var\n// - agent workspace dirs that don't exist\n// - daemon reachable? (when --check-running, default true)\n//\n// Exit code: 0 if clean, 1 if any error, 0 if only warnings (so CI won't block\n// on advisory checks).\n\nexport type Severity = \"ok\" | \"warn\" | \"fail\"\n\nexport interface Check {\n severity: Severity\n group: string\n title: string\n detail?: string\n fix?: string\n}\n\n/** Run every preflight check and return the result as data. Exposed so\n * the dashboard's /admin/doctor route can render the same checks the\n * `agentx doctor` CLI prints — without spawning a child process. */\nexport async function runDoctorChecks(\n opts: { running?: boolean } = {},\n): Promise<{ checks: Check[]; summary: { errors: number; warnings: number; ok: number } }> {\n const checks: Check[] = []\n await runEnvChecks(checks)\n const cfg = runConfigChecks(checks)\n if (cfg) runReferenceChecks(checks, cfg)\n if (cfg) runWorkspaceChecks(checks, cfg)\n if (cfg) runWorkspaceSettingsChecks(checks, cfg)\n if (cfg) runRoutingChecks(checks, cfg)\n if (cfg) runCodegraphChecks(checks, cfg)\n if (opts.running !== false && cfg) await runRuntimeChecks(checks, cfg)\n return { checks, summary: summarize(checks) }\n}\n\nexport const doctor = new Command()\n .name(\"doctor\")\n .description(\"pre-flight health check: Node, config, credentials, daemon\")\n .option(\"--no-running\", \"skip the live daemon probe\")\n .option(\"--json\", \"emit machine-readable JSON (stable shape for CI)\")\n .action(async (opts) => {\n const { checks, summary } = await runDoctorChecks({ running: opts.running !== false })\n if (opts.json) {\n process.stdout.write(JSON.stringify({ checks, summary }, null, 2) + \"\\n\")\n } else {\n printHumanReport(checks)\n }\n process.exit(summary.errors > 0 ? 1 : 0)\n })\n\n// ---------------------------------------------------------------------------\n// Checks\n// ---------------------------------------------------------------------------\n\nasync function runEnvChecks(checks: Check[]): Promise<void> {\n const nodeMajor = Number(process.versions.node.split(\".\")[0])\n checks.push({\n severity: nodeMajor >= 20 ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: `Node.js ${process.versions.node}`,\n detail: nodeMajor >= 20 ? undefined : \"AgentX needs Node 20 or newer.\",\n fix: nodeMajor >= 20 ? undefined : \"Install a newer Node (nvm install 20 && nvm use 20)\",\n })\n\n const which = (bin: string): string | null => {\n try { return execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [bin], { encoding: \"utf-8\" }).trim().split(\"\\n\")[0] }\n catch { return null }\n }\n const npmPath = which(\"npm\")\n checks.push({\n severity: npmPath ? \"ok\" : \"fail\",\n group: \"Environment\",\n title: npmPath ? \"npm on PATH\" : \"npm not found\",\n detail: npmPath || undefined,\n })\n\n // Claude CLI is only required if the config references claude-code agents;\n // we report it advisory here and promote to fail in the config step below.\n const claudePath = which(\"claude\")\n if (claudePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"claude\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `claude CLI ${ver || \"installed\"}`, detail: claudePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"claude CLI not on PATH\",\n detail: \"Only required for agents on the claude-code tier.\",\n fix: \"See https://docs.anthropic.com/en/docs/claude-code\",\n })\n }\n\n const codexPath = which(\"codex\")\n if (codexPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codex\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `codex CLI ${ver || \"installed\"}`, detail: codexPath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"codex CLI not on PATH\",\n detail: \"Only required for agents on the codex-cli tier.\",\n fix: \"Install with `npm i -g @openai/codex`.\",\n })\n }\n\n const openCodePath = which(\"opencode\")\n if (openCodePath) {\n let ver: string | undefined\n try { ver = execFileSync(\"opencode\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({ severity: \"ok\", group: \"Environment\", title: `opencode CLI ${ver || \"installed\"}`, detail: openCodePath })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Environment\",\n title: \"opencode CLI not on PATH\",\n detail: \"Only required for agents on the opencode tier.\",\n fix: \"Install from https://opencode.ai/docs/.\",\n })\n }\n\n try {\n createRequire(import.meta.url)(\"better-sqlite3\")\n checks.push({\n severity: \"ok\",\n group: \"Environment\",\n title: `better-sqlite3 loads for Node ${process.version}`,\n detail: `NODE_MODULE_VERSION ${process.versions.modules}`,\n })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Environment\",\n title: \"better-sqlite3 native binding does not load\",\n detail: e?.message ?? String(e),\n fix: `Run \"pnpm rebuild better-sqlite3\" with the same Node used by the daemon (${process.version}, modules ${process.versions.modules}).`,\n })\n }\n}\n\nfunction runConfigChecks(checks: Check[]): any {\n const cfgPath = resolve(process.cwd(), \"agentx.json\")\n if (!existsSync(cfgPath)) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json not found\",\n detail: `Looked in ${cfgPath}`,\n fix: \"Run `agentx setup` to create one via the web wizard.\",\n })\n return null\n }\n let cfg: any\n try { cfg = JSON.parse(readFileSync(cfgPath, \"utf-8\")) }\n catch (e: any) {\n checks.push({ severity: \"fail\", group: \"Config\", title: \"agentx.json is not valid JSON\", detail: e.message })\n return null\n }\n try {\n // Full schema validation — catches missing required fields.\n loadDaemonConfig(cfgPath)\n checks.push({ severity: \"ok\", group: \"Config\", title: `agentx.json valid (${Object.keys(cfg.agents || {}).length} agents, ${Object.keys(cfg.crons || {}).length} schedules)` })\n } catch (e: any) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: \"agentx.json failed schema validation\",\n detail: e.message,\n fix: \"Open /admin → Advanced tab to edit and re-save.\",\n })\n }\n const claudeCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"claude-code\")\n if (claudeCodeAgents.length > 0) {\n const hasClaude = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"claude\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasClaude) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${claudeCodeAgents.length} agent(s) use claude-code tier but claude CLI is missing`,\n detail: claudeCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Claude Code (https://docs.anthropic.com/en/docs/claude-code) or switch these agents to tier=sdk.\",\n })\n }\n }\n const codexCliAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"codex-cli\")\n if (codexCliAgents.length > 0) {\n const hasCodex = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codex\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasCodex) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${codexCliAgents.length} agent(s) use codex-cli tier but codex CLI is missing`,\n detail: codexCliAgents.map(([id]) => id).join(\", \"),\n fix: \"Install Codex CLI with `npm i -g @openai/codex` or switch these agents to tier=claude-code.\",\n })\n }\n }\n const openCodeAgents = Object.entries(cfg.agents || {}).filter(([, a]: [string, any]) => a.tier === \"opencode\")\n if (openCodeAgents.length > 0) {\n const hasOpenCode = (() => {\n try { execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"opencode\"], { stdio: \"ignore\" }); return true } catch { return false }\n })()\n if (!hasOpenCode) {\n checks.push({\n severity: \"fail\",\n group: \"Config\",\n title: `${openCodeAgents.length} agent(s) use opencode tier but OpenCode CLI is missing`,\n detail: openCodeAgents.map(([id]) => id).join(\", \"),\n fix: \"Install OpenCode from https://opencode.ai/docs/ or switch these agents to another tier.\",\n })\n }\n }\n return cfg\n}\n\nfunction runReferenceChecks(checks: Check[], cfg: any): void {\n // Parse ${VAR} references out of the config (recursively) and verify each\n // one has a matching value in .env or process.env.\n const refs = new Set<string>()\n collectEnvRefs(cfg, refs)\n if (refs.size === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: \"No ${VAR} references in agentx.json\" })\n return\n }\n const envFile = resolve(process.cwd(), \".env\")\n const envFromFile: Record<string, string> = {}\n if (existsSync(envFile)) {\n for (const line of readFileSync(envFile, \"utf-8\").split(/\\r?\\n/)) {\n const m = line.match(/^\\s*([A-Z_][A-Z0-9_]*)\\s*=\\s*(.*)$/i)\n if (m) envFromFile[m[1]] = m[2]\n }\n }\n const missing: string[] = []\n const empty: string[] = []\n for (const name of refs) {\n const raw = process.env[name] ?? envFromFile[name]\n if (raw === undefined) missing.push(name)\n else if (!raw.trim() || /^[\"']?\\s*[\"']?$/.test(raw)) empty.push(name)\n }\n if (missing.length === 0 && empty.length === 0) {\n checks.push({ severity: \"ok\", group: \"Secrets\", title: `${refs.size} env reference(s) resolved` })\n } else {\n if (missing.length > 0) {\n checks.push({\n severity: \"fail\",\n group: \"Secrets\",\n title: `${missing.length} env var(s) referenced in agentx.json but missing`,\n detail: missing.join(\", \"),\n fix: `Add to .env — e.g. ${missing[0]}=<value>`,\n })\n }\n if (empty.length > 0) {\n checks.push({\n severity: \"warn\",\n group: \"Secrets\",\n title: `${empty.length} env var(s) set but empty`,\n detail: empty.join(\", \"),\n })\n }\n }\n}\n\nfunction collectEnvRefs(node: unknown, into: Set<string>): void {\n if (typeof node === \"string\") {\n for (const m of node.matchAll(/\\$\\{([A-Z_][A-Z0-9_]*)\\}/g)) into.add(m[1])\n } else if (Array.isArray(node)) {\n for (const item of node) collectEnvRefs(item, into)\n } else if (node && typeof node === \"object\") {\n for (const v of Object.values(node)) collectEnvRefs(v, into)\n }\n}\n\nfunction runWorkspaceChecks(checks: Check[], cfg: any): void {\n const missing: string[] = []\n for (const [id, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const abs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n try {\n const st = statSync(abs)\n if (!st.isDirectory()) missing.push(`${id}: ${abs} (exists but not a directory)`)\n } catch { missing.push(`${id}: ${abs}`) }\n }\n if (missing.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspaces\", title: \"All agent workspace folders exist\" })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"Workspaces\",\n title: `${missing.length} agent workspace(s) missing`,\n detail: missing.join(\"\\n \"),\n fix: \"The daemon will create missing folders on first task, but you won't see CLAUDE.md / skills until you populate them.\",\n })\n }\n}\n\n// Audit each agent's .claude/settings.json for known traps:\n// - unexpanded ${VAR} literals in env values (Claude Code does NOT expand them)\n// - env.PATH missing /usr/bin or /bin (basic utils unreachable)\n// - JSON syntax errors\n// - permissions.allow: [] explicitly empty alongside non-empty deny\n// Each finding is FAIL severity for the ${VAR} / PATH cases (these break the\n// agent's Bash tool entirely), WARN for the lockdown case.\nfunction runWorkspaceSettingsChecks(checks: Check[], cfg: any): void {\n const VAR_RE = /\\$\\{[A-Za-z_][A-Za-z0-9_]*\\}/g\n const findings: Array<{ severity: Severity; agent: string; msg: string }> = []\n\n for (const [agentId, a] of Object.entries(cfg.agents || {}) as [string, any][]) {\n if (!a.workspace) continue\n const wsAbs = a.workspace.startsWith(\"/\") ? a.workspace : resolve(process.cwd(), a.workspace)\n for (const fname of [\"settings.json\", \"settings.local.json\"]) {\n const p = resolve(wsAbs, \".claude\", fname)\n if (!existsSync(p)) continue\n let data: any\n try {\n data = JSON.parse(readFileSync(p, \"utf-8\"))\n } catch (e: any) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname}: JSON parse error — ${e.message}` })\n continue\n }\n const env = (data.env || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(env)) {\n if (typeof v !== \"string\") continue\n const unexpanded = v.match(VAR_RE)\n if (unexpanded) {\n findings.push({\n severity: \"fail\",\n agent: agentId,\n msg: `${fname} env.${k} contains unexpanded ${[...new Set(unexpanded)].join(\",\")} — Claude Code does NOT expand \\${VAR} in settings.json (use a fully-literal value)`,\n })\n }\n }\n const pathVal = env.PATH\n if (typeof pathVal === \"string\") {\n const parts = pathVal.split(\":\").filter(Boolean)\n if (!parts.includes(\"/usr/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /usr/bin — cat/head/sh/which will fail` })\n }\n if (!parts.includes(\"/bin\")) {\n findings.push({ severity: \"fail\", agent: agentId, msg: `${fname} env.PATH missing /bin — ls/cp/mv will fail` })\n }\n }\n const perms = data.permissions\n if (perms && typeof perms === \"object\" && \"allow\" in perms) {\n const allow = perms.allow\n const deny = perms.deny\n if (Array.isArray(allow) && allow.length === 0 && Array.isArray(deny) && deny.length > 0) {\n findings.push({\n severity: \"warn\",\n agent: agentId,\n msg: `${fname} permissions.allow is explicitly [] with ${deny.length} deny rules — agent may be locked out (omit the key to use defaults instead)`,\n })\n }\n }\n }\n }\n\n if (findings.length === 0) {\n checks.push({ severity: \"ok\", group: \"Workspace settings\", title: `All ${Object.keys(cfg.agents || {}).length} agent .claude/settings.json files clean` })\n return\n }\n for (const f of findings) {\n checks.push({\n severity: f.severity,\n group: \"Workspace settings\",\n title: `${f.agent}: ${f.msg}`,\n fix: f.severity === \"fail\" ? \"Edit .claude/settings.json — replace ${VAR} with the literal value or omit the key to inherit.\" : \"Either remove the empty allow list or populate it.\",\n })\n }\n}\n\n// Surface routing / dispatch fragilities the recurring-patches plan\n// cataloged: webhook entries that route many event-types to a single\n// handler (github, gitlab), trigger maps pointing at workflow ids that\n// don't exist, mesh `node` fields naming peers that aren't configured,\n// gitlab agentMappings referencing unknown agents, and the very common\n// \"I edited agentx.json but didn't reload\" pitfall.\nfunction runRoutingChecks(checks: Check[], cfg: any): void {\n const webhooks = (cfg.webhooks ?? []) as Array<{\n id: string\n source: string\n agentId: string\n enabled: boolean\n node?: string\n secretEnv?: string\n triggers?: Record<string, string>\n defaultWorkflow?: string\n }>\n const findings: Array<{ severity: Severity; title: string; fix?: string }> = []\n\n // Build the set of known workflow ids. Workflows live as JSON files under\n // `workflows.dir` (default .agentx/workflows/). The id is the filename\n // sans extension; we don't need to parse the contents for this check.\n const workflowDir = resolve(process.cwd(), cfg.workflows?.dir || \".agentx/workflows\")\n const knownWorkflows = new Set<string>()\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (f.endsWith(\".json\") && !f.startsWith(\"_\") && !f.endsWith(\".disabled.json\")) {\n knownWorkflows.add(f.replace(/\\.json$/, \"\"))\n }\n }\n }\n } catch { /* directory not yet populated; checks below tolerate empty set */ }\n\n // 1. Multi-event-type sources (github, gitlab) without a triggers map.\n // Without it, every inbound event hits the same agent and the\n // duplicate-firing class of bug returns. Surface as REVIEW (warn) —\n // operators may genuinely want a single-handler setup, but they\n // should opt in by setting `defaultWorkflow` explicitly.\n const multiEventSources = new Set([\"github\", \"gitlab\"])\n for (const w of webhooks) {\n if (!w.enabled) continue\n if (!multiEventSources.has(w.source)) continue\n const hasTriggers = w.triggers && Object.keys(w.triggers).length > 0\n if (!hasTriggers && !w.defaultWorkflow) {\n findings.push({\n severity: \"warn\",\n title: `webhook \"${w.id}\" (${w.source} -> ${w.agentId}) has no triggers map; every event-type collapses to the bound agent`,\n fix: `Add a triggers map: { \"issues.opened\": \"wf-id\", \"pull_request.synchronize\": \"wf-id\" } — or set defaultWorkflow.`,\n })\n }\n }\n\n // 2. Trigger map references workflow ids that don't exist on disk.\n // Hard-fails the dispatch at runtime (and silently — dispatcher just\n // logs \"workflow not found\" and bails). Surface here as FAIL.\n for (const w of webhooks) {\n if (!w.enabled || !w.triggers) continue\n for (const [eventType, workflowId] of Object.entries(w.triggers)) {\n if (knownWorkflows.size > 0 && !knownWorkflows.has(workflowId)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".triggers[\"${eventType}\"] -> \"${workflowId}\" — no such workflow under ${cfg.workflows?.dir || \".agentx/workflows\"}`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n if (w.defaultWorkflow && knownWorkflows.size > 0 && !knownWorkflows.has(w.defaultWorkflow)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\".defaultWorkflow -> \"${w.defaultWorkflow}\" — no such workflow`,\n fix: `Create the workflow file or fix the id in agentx.json`,\n })\n }\n }\n\n // 2b. Incoherent workflow lifecycle: status=active says \"reviewed, ship\n // it\" while state=quarantined means the runtime refuses to dispatch\n // it (conflict detector parked it). The two axes are independent\n // (state is the only dispatch gate — see workflowSchema), so this\n // combo silently looks live while never firing.\n try {\n if (existsSync(workflowDir)) {\n for (const f of readdirSync(workflowDir)) {\n if (!f.endsWith(\".json\") || f.startsWith(\"_\") || f.endsWith(\".disabled.json\")) continue\n try {\n const wf = JSON.parse(readFileSync(resolve(workflowDir, f), \"utf-8\"))\n if (wf?.status === \"active\" && wf?.state === \"quarantined\") {\n findings.push({\n severity: \"warn\",\n title: `workflow \"${wf.id ?? f}\" is status=active but state=quarantined — it looks live but will never dispatch`,\n fix: `Resolve the conflict the detector flagged, then set state back to \"active\" (or set status to \"review\" while parked).`,\n })\n }\n } catch { /* unparseable file is caught by workflow validate */ }\n }\n }\n } catch { /* directory races are non-fatal for doctor */ }\n\n // 3. Mesh-routed webhooks naming peers that don't exist.\n const peers = new Set<string>(((cfg.mesh?.peers ?? []) as Array<{ name: string }>).map(p => p.name))\n for (const w of webhooks) {\n if (!w.enabled || !w.node) continue\n if (!peers.has(w.node)) {\n findings.push({\n severity: \"fail\",\n title: `webhook \"${w.id}\" routes to mesh peer \"${w.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or remove the node field on the webhook.`,\n })\n }\n }\n\n // 4. Two enabled webhook entries collide on (source, agentId): the\n // Phase 3 dispatcher takes the first match, the second is silently\n // ignored — operators rarely realize.\n const seen = new Map<string, string>()\n for (const w of webhooks) {\n if (!w.enabled) continue\n const key = `${w.source}:${w.agentId}`\n const prior = seen.get(key)\n if (prior) {\n findings.push({\n severity: \"warn\",\n title: `webhook entries \"${prior}\" and \"${w.id}\" both enabled for ${w.source} -> ${w.agentId}; only the first is dispatched`,\n fix: `Disable one entry, or merge their triggers maps into a single entry.`,\n })\n } else {\n seen.set(key, w.id)\n }\n }\n\n // 5. GitLab agentMappings referencing agent ids that aren't in agents.\n // A mapping with `node:` set is a cross-mesh route — the agent lives\n // on a remote peer, not locally — so missing-from-agents is correct\n // and not a finding. We still warn when `node` names a peer that\n // isn't configured (caught by check #3 above for webhooks; same\n // invariant should hold for agentMappings).\n const agentIds = new Set(Object.keys(cfg.agents ?? {}))\n for (const m of (cfg.channels?.gitlab?.agentMappings ?? [])) {\n if (!m?.agentId) continue\n if (m.node) {\n // Cross-mesh route — verify the named peer exists.\n if (!peers.has(m.node)) {\n findings.push({\n severity: \"fail\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" routes to mesh peer \"${m.node}\" which is not in mesh.peers`,\n fix: `Add the peer to mesh.peers or drop the node field on the mapping.`,\n })\n }\n continue\n }\n if (!agentIds.has(m.agentId)) {\n findings.push({\n severity: \"warn\",\n title: `gitlab.agentMappings entry agentId=\"${m.agentId}\" — no such agent in agents.* (and no node field, so it's not a cross-mesh route)`,\n fix: `Add the agent to agents.*, set node:\"<peer>\" if the agent lives remotely, or remove the mapping.`,\n })\n }\n }\n\n // 6. Telegram accounts without an agentBinding silently drop every DM.\n for (const [acctId, acct] of Object.entries((cfg.channels?.telegram?.accounts ?? {}) as Record<string, { agentBinding?: string }>)) {\n if (!acct.agentBinding) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\" has no agentBinding; every DM to this bot will drop`,\n fix: `Set agentBinding to a valid agent id.`,\n })\n } else if (!agentIds.has(acct.agentBinding)) {\n findings.push({\n severity: \"fail\",\n title: `telegram account \"${acctId}\".agentBinding -> \"${acct.agentBinding}\" — no such agent in agents.*`,\n fix: `Fix the agentBinding or define the agent in agents.*.`,\n })\n }\n }\n\n // 7. Per-agent integrations: missing env vars + unknown kinds + duplicates.\n // The new agents[].integrations[] block declares third-party credentials\n // (telegram-bot, hubspot, gitlab-user, gmail, ...). Doctor scans for:\n // - duplicate (kind, label) on the same agent (config integrity)\n // - tokenEnv refs that don't exist in process.env (latent failure)\n // - kinds outside the canonical INTEGRATION_KINDS set (typos)\n // Failures are warnings, not blocking — credentials may be set on the\n // daemon process and absent from the doctor's local shell.\n const KNOWN_KINDS = new Set([\n \"telegram-bot\", \"whatsapp\", \"slack-bot\", \"discord-bot\",\n \"gitlab-user\", \"github-user\",\n \"gmail\", \"hotmail\", \"smtp\",\n \"hubspot\", \"salesforce\", \"pipedrive\", \"odoo\",\n \"trello\", \"linear\", \"asana\", \"jira\", \"notion\",\n \"stripe\", \"sentry\", \"vercel\", \"twilio\", \"custom\",\n ])\n for (const [agentId, a] of Object.entries((cfg.agents ?? {}) as Record<string, any>)) {\n const list = (a.integrations as any[] | undefined) ?? []\n if (!list.length) continue\n const seen = new Set<string>()\n for (const i of list) {\n const key = `${i.kind}::${i.label}`\n if (seen.has(key)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: duplicate (${i.kind}, ${i.label})`,\n fix: `Remove the duplicate or rename one. (kind, label) must be unique per agent.`,\n })\n }\n seen.add(key)\n if (!KNOWN_KINDS.has(i.kind)) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations: unknown kind \"${i.kind}\" on integration \"${i.label}\"`,\n fix: `Use a canonical kind from INTEGRATION_KINDS, or \"custom\" for ad-hoc services.`,\n })\n }\n const creds = (i.credentials || {}) as Record<string, unknown>\n for (const [k, v] of Object.entries(creds)) {\n if (typeof v === \"string\" && /^[A-Z][A-Z0-9_]*$/.test(v) && !process.env[v]) {\n findings.push({\n severity: \"warn\",\n title: `agents.${agentId}.integrations[${i.kind}/${i.label}].${k} -> $${v} but env var is unset (in this shell)`,\n fix: `Set ${v} on the daemon environment. The daemon's process.env is what matters; this warning fires from your local shell.`,\n })\n }\n }\n }\n }\n\n // (Removed: the \"agentx.json newer than daemon pid\" check produced\n // false positives because the pid file is only rewritten on start,\n // not on hot-reload. The signal-to-noise was too low. A future check\n // can query /reload's `lastReload` timestamp via the daemon API\n // instead of using filesystem mtimes.)\n\n if (findings.length === 0) {\n checks.push({\n severity: \"ok\",\n group: \"Routing\",\n title: `${webhooks.length} webhook(s), ${Object.keys(cfg.channels?.telegram?.accounts ?? {}).length} telegram account(s) — all routing references resolve`,\n })\n return\n }\n for (const f of findings) {\n checks.push({ severity: f.severity, group: \"Routing\", title: f.title, fix: f.fix })\n }\n}\n\nasync function runRuntimeChecks(checks: Check[], cfg: any): Promise<void> {\n const url = cfg.dashboard?.daemonUrl?.replace(/\\/+$/, \"\") || \"http://127.0.0.1:18800\"\n const headers: Record<string, string> = {}\n if (cfg.dashboard?.token) headers[\"Authorization\"] = `Bearer ${cfg.dashboard.token}`\n try {\n const ac = new AbortController()\n const timer = setTimeout(() => ac.abort(), 2000)\n const r = await fetch(url + \"/health\", { headers, signal: ac.signal })\n clearTimeout(timer)\n if (!r.ok) {\n checks.push({ severity: \"warn\", group: \"Runtime\", title: `Daemon responded ${r.status}`, detail: url })\n return\n }\n const body: any = await r.json()\n checks.push({\n severity: \"ok\",\n group: \"Runtime\",\n title: `Daemon healthy — ${body.agents?.length ?? 0} agents live, uptime ${Math.round((body.uptime ?? 0) / 60)}m`,\n detail: url,\n })\n } catch {\n checks.push({\n severity: \"warn\",\n group: \"Runtime\",\n title: \"Daemon not reachable (not running?)\",\n detail: url,\n fix: \"Run `agentx daemon start`. Skip this check with `agentx doctor --no-running`.\",\n })\n }\n}\n\nfunction runCodegraphChecks(checks: Check[], cfg: any): void {\n const optedIn = Object.entries(cfg.agents || {})\n .filter(([, a]: [string, any]) =>\n a?.codegraph === true && (a.tier === \"claude-code\" || a.tier === \"codex-cli\"),\n ) as Array<[string, any]>\n\n if (optedIn.length === 0) return // No agent uses codegraph — skip silently.\n\n // Binary on PATH.\n let cgPath: string | null = null\n try {\n cgPath = execFileSync(process.platform === \"win32\" ? \"where\" : \"which\", [\"codegraph\"], { encoding: \"utf-8\" })\n .trim().split(\"\\n\")[0] || null\n } catch { cgPath = null }\n\n if (cgPath) {\n let ver: string | undefined\n try { ver = execFileSync(\"codegraph\", [\"--version\"], { encoding: \"utf-8\", timeout: 3000 }).trim() } catch { /* */ }\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `codegraph CLI ${ver || \"installed\"}`,\n detail: cgPath,\n })\n } else {\n checks.push({\n severity: \"fail\",\n group: \"CodeGraph\",\n title: \"codegraph CLI not on PATH\",\n detail: `${optedIn.length} agent(s) have codegraph:true but the binary isn't available.`,\n fix: \"Install with `npm i -g @colbymchenry/codegraph`.\",\n })\n }\n\n // Per-workspace index presence.\n for (const [agentId, def] of optedIn) {\n if (!def.workspace || !existsSync(def.workspace)) {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: workspace missing`,\n detail: `Workspace path ${def.workspace} does not exist — codegraph will skip this agent.`,\n })\n continue\n }\n const dbPath = resolve(def.workspace, \".codegraph\", \"codegraph.db\")\n if (existsSync(dbPath)) {\n checks.push({\n severity: \"ok\",\n group: \"CodeGraph\",\n title: `${agentId}: index present`,\n detail: dbPath,\n })\n } else {\n checks.push({\n severity: \"warn\",\n group: \"CodeGraph\",\n title: `${agentId}: index not built yet`,\n detail: \".codegraph/ missing — daemon will background-index this workspace on next boot.\",\n fix: `Run \\`codegraph init --index ${def.workspace}\\` to build it now.`,\n })\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Output\n// ---------------------------------------------------------------------------\n\nfunction summarize(checks: Check[]): { errors: number; warnings: number; ok: number } {\n return {\n errors: checks.filter((c) => c.severity === \"fail\").length,\n warnings: checks.filter((c) => c.severity === \"warn\").length,\n ok: checks.filter((c) => c.severity === \"ok\").length,\n }\n}\n\nfunction printHumanReport(checks: Check[]): void {\n console.log()\n console.log(chalk.bold(\" agentx doctor\"))\n console.log()\n\n const groups = new Map<string, Check[]>()\n for (const c of checks) {\n if (!groups.has(c.group)) groups.set(c.group, [])\n groups.get(c.group)!.push(c)\n }\n for (const [group, items] of groups) {\n console.log(chalk.bold(\" \" + group))\n for (const c of items) {\n const marker = c.severity === \"ok\" ? chalk.green(\"✓\")\n : c.severity === \"warn\" ? chalk.yellow(\"!\")\n : chalk.red(\"✗\")\n console.log(` ${marker} ${c.title}`)\n if (c.detail) console.log(chalk.dim(\" \" + c.detail.replace(/\\n/g, \"\\n \")))\n if (c.fix) console.log(chalk.dim(\" → \" + c.fix))\n }\n console.log()\n }\n\n const s = summarize(checks)\n if (s.errors > 0) {\n console.log(chalk.red.bold(` ${s.errors} error${s.errors === 1 ? \"\" : \"s\"}`) +\n (s.warnings ? chalk.yellow(`, ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}`) : \"\") +\n `. Fix the error${s.errors === 1 ? \"\" : \"s\"} and rerun.`)\n } else if (s.warnings > 0) {\n console.log(chalk.yellow.bold(` ${s.warnings} warning${s.warnings === 1 ? \"\" : \"s\"}.`) + chalk.dim(\" Review but not blocking.\"))\n } else {\n console.log(chalk.green.bold(` All checks passed (${s.ok}).`))\n }\n console.log()\n}\n"],"mappings":"+CAMAA,IANA,OAAS,WAAAC,MAAe,YACxB,OAAOC,MAAW,QAClB,OAAS,gBAAAC,MAAoB,gBAC7B,OAAS,cAAAC,EAAY,gBAAAC,EAAc,eAAAC,EAAa,YAAAC,MAAgB,KAChE,OAAS,WAAAC,MAAe,OACxB,OAAS,iBAAAC,MAAqB,SA8B9B,eAAsBC,EACpBC,EAA8B,CAAC,EAC0D,CACzF,IAAMC,EAAkB,CAAC,EACzB,MAAMC,EAAaD,CAAM,EACzB,IAAME,EAAMC,EAAgBH,CAAM,EAClC,OAAIE,GAAKE,EAAmBJ,EAAQE,CAAG,EACnCA,GAAKG,EAAmBL,EAAQE,CAAG,EACnCA,GAAKI,EAA2BN,EAAQE,CAAG,EAC3CA,GAAKK,EAAiBP,EAAQE,CAAG,EACjCA,GAAKM,EAAmBR,EAAQE,CAAG,EACnCH,EAAK,UAAY,IAASG,GAAK,MAAMO,EAAiBT,EAAQE,CAAG,EAC9D,CAAE,OAAAF,EAAQ,QAASU,EAAUV,CAAM,CAAE,CAC9C,CAEO,IAAMW,EAAS,IAAItB,EAAQ,EAC/B,KAAK,QAAQ,EACb,YAAY,4DAA4D,EACxE,OAAO,eAAgB,4BAA4B,EACnD,OAAO,SAAU,kDAAkD,EACnE,OAAO,MAAOU,GAAS,CACtB,GAAM,CAAE,OAAAC,EAAQ,QAAAY,CAAQ,EAAI,MAAMd,EAAgB,CAAE,QAASC,EAAK,UAAY,EAAM,CAAC,EACjFA,EAAK,KACP,QAAQ,OAAO,MAAM,KAAK,UAAU,CAAE,OAAAC,EAAQ,QAAAY,CAAQ,EAAG,KAAM,CAAC,EAAI;AAAA,CAAI,EAExEC,EAAiBb,CAAM,EAEzB,QAA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,GAAG,CAAC,EAEtD,QAAQ,IAAI,EAGd,IAAMK,EAAIrF,EAAUV,CAAM,EACtB+F,EAAE,OAAS,EACb,QAAQ,IAAIzG,EAAM,IAAI,KAAK,KAAKyG,EAAE,eAAeA,EAAE,SAAW,EAAI,GAAK,KAAK,GACzEA,EAAE,SAAWzG,EAAM,OAAO,KAAKyG,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,KAAK,EAAI,IACtF,kBAAkBA,EAAE,SAAW,EAAI,GAAK,gBAAgB,EACjDA,EAAE,SAAW,EACtB,QAAQ,IAAIzG,EAAM,OAAO,KAAK,KAAKyG,EAAE,mBAAmBA,EAAE,WAAa,EAAI,GAAK,MAAM,EAAIzG,EAAM,IAAI,2BAA2B,CAAC,EAEhI,QAAQ,IAAIA,EAAM,MAAM,KAAK,wBAAwByG,EAAE,MAAM,CAAC,EAEhE,QAAQ,IAAI,CACd","names":["init_config","Command","chalk","execFileSync","existsSync","readFileSync","readdirSync","statSync","resolve","createRequire","runDoctorChecks","opts","checks","runEnvChecks","cfg","runConfigChecks","runReferenceChecks","runWorkspaceChecks","runWorkspaceSettingsChecks","runRoutingChecks","runCodegraphChecks","runRuntimeChecks","summarize","doctor","summary","printHumanReport","nodeMajor","which","bin","npmPath","claudePath","ver","codexPath","openCodePath","e","cfgPath","loadDaemonConfig","claudeCodeAgents","a","id","codexCliAgents","openCodeAgents","refs","collectEnvRefs","envFile","envFromFile","line","m","missing","empty","name","raw","node","into","item","v","abs","VAR_RE","findings","agentId","wsAbs","fname","p","data","env","k","unexpanded","pathVal","parts","perms","allow","deny","f","webhooks","workflowDir","knownWorkflows","multiEventSources","w","eventType","workflowId","wf","peers","seen","key","prior","agentIds","acctId","acct","KNOWN_KINDS","list","i","creds","url","headers","ac","timer","r","body","optedIn","cgPath","def","dbPath","c","groups","group","items","marker","s"]}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import{a as T,b as P,c as _,d as G}from"./chunk-PNWNVOEZ.js";import{b as ee}from"./chunk-64P4QHSZ.js";import{a as te,b as se,c as re,d as ie,e as ne}from"./chunk-AJ5RMU7X.js";import{v as Z,w as he}from"./chunk-AX2PWSRT.js";import{a as Q,b as pe}from"./chunk-AJONZWLT.js";import{c as M,d as L}from"./chunk-QOYAX2FT.js";import{o as X,p as de}from"./chunk-LCIREYTD.js";var A={version:2,levels:[{id:"category",description:"Top-level kind of work. Closed set \u2014 pick the closest fit.",axes:[{name:"kind",type:"enum",values:["code","ops","support","admin","knowledge","social","system"],description:"Which category this work belongs in."}]},{id:"verb",description:"Specific intent \u2014 verb-level only, NOT client/project-bound.",axes:[{name:"name",type:"free",description:"Lower-kebab dot-namespaced verb. Examples: review.merge-request, fix.bug, investigate.error, deploy.staging, deploy.production, rollback.release, spec.feature, triage.issue, document.feature, chat.greeting, chat.support-request, schedule.add, config.change, ingest.contact, transcribe.audio, brief.daily, summarize.thread, plan.work."}]}],leafInput:{name:"input",type:"enum",values:["telegram","whatsapp","slack","discord","gitlab-mr","gitlab-issue","github-issue","github-pr","cron","webhook","mesh","http"],description:"Where the message entered the system."},leafOutput:{name:"output",type:"free",description:"One short sentence describing what the agent is expected to produce. Generic \u2014 refers to the verb's outcome, not the specific client/project (those are on the event metadata already)."}},F=[{category:"code",verb:"review.merge-request",description:"Review a GitLab MR or GitHub PR"},{category:"code",verb:"review.code-change",description:"General code review (snippet, diff)"},{category:"code",verb:"fix.bug",description:"Fix a reported bug"},{category:"code",verb:"implement.feature",description:"Build a new feature"},{category:"code",verb:"investigate.error",description:"Investigate a failing test, exception, pipeline"},{category:"code",verb:"refactor.code",description:"Restructure existing code without behaviour change"},{category:"code",verb:"spec.feature",description:"Write or update a feature spec / RFC"},{category:"code",verb:"triage.issue",description:"Classify, label, or assign an issue"},{category:"code",verb:"answer.code-question",description:"Answer a code-related question"},{category:"ops",verb:"deploy.staging",description:"Deploy to a staging/preview environment"},{category:"ops",verb:"deploy.production",description:"Deploy to production"},{category:"ops",verb:"rollback.release",description:"Roll back a release"},{category:"ops",verb:"investigate.incident",description:"Investigate a production incident"},{category:"ops",verb:"monitor.system",description:"Check system status / metrics"},{category:"ops",verb:"rotate.credential",description:"Rotate a token, key, certificate"},{category:"ops",verb:"audit.security",description:"Review for security issues"},{category:"support",verb:"chat.greeting",description:"A casual hello, no actionable request"},{category:"support",verb:"chat.support-request",description:"End-user / customer asking for help"},{category:"support",verb:"chat.casual",description:"Informal back-and-forth chat"},{category:"support",verb:"answer.question",description:"Answer an open-ended question"},{category:"support",verb:"route.request",description:"Forward a request to the right agent"},{category:"admin",verb:"config.change",description:"Change agentx.json / environment / config"},{category:"admin",verb:"schedule.add",description:"Add a new cron / scheduled task"},{category:"admin",verb:"schedule.remove",description:"Remove or disable a schedule"},{category:"admin",verb:"token.create",description:"Mint a scoped API token"},{category:"admin",verb:"agent.add",description:"Configure a new agent"},{category:"admin",verb:"channel.add",description:"Wire up a new channel"},{category:"knowledge",verb:"document.feature",description:"Write or update documentation"},{category:"knowledge",verb:"summarize.thread",description:"Summarize a long conversation/thread"},{category:"knowledge",verb:"research.topic",description:"Investigate / gather info on a topic"},{category:"knowledge",verb:"wiki.absorb",description:"Roll raw entries into typed wiki articles"},{category:"social",verb:"brief.daily",description:"Compose a daily brief / digest"},{category:"social",verb:"draft.post",description:"Draft a marketing post / announcement"},{category:"social",verb:"report.weekly",description:"Compose a weekly status report"},{category:"system",verb:"classify.intent",description:"Internal: graph-classifier sub-call"}];import{readFileSync as D,writeFileSync as J,appendFileSync as ge,existsSync as I,mkdirSync as U,renameSync as ue}from"fs";import{resolve as R,dirname as ae}from"path";import{createHash as fe}from"crypto";var H=class{baseDir;log;constructor(e={}){this.baseDir=e.baseDir??R(process.cwd(),".agentx/graph"),this.log=e.log??console.error.bind(console,"[graph]"),U(this.baseDir,{recursive:!0})}schemaPath(){return R(this.baseDir,"schema.json")}nodesPath(){return R(this.baseDir,"nodes.json")}indexPath(){return R(this.baseDir,"index.json")}classificationsPath(){return R(this.baseDir,"classifications.jsonl")}loadSchema(){let e=this.schemaPath();if(!I(e))return this.saveSchema(A),this.log("seeded starter schema at",e),A;let t=D(e,"utf-8"),s=T.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);if((s.data.version??1)<(A.version??2)){let r=e.replace(/\.json$/,`.v${s.data.version??1}.bak.json`);try{J(r,t),this.log(`migrated graph schema v${s.data.version??1} -> v${A.version}; old saved at ${r}`)}catch(n){this.log(`could not back up old schema: ${n?.message??n}`)}this.saveSchema(A);let o=this.nodesPath();if(I(o)){let n=o.replace(/\.json$/,".v1.bak.json");try{J(n,D(o,"utf-8")),this.log(`archived v1 nodes.json -> ${n}`)}catch(i){this.log(`could not back up old nodes: ${i?.message??i}`)}try{let i=oe();this.saveNodes(i)}catch(i){this.log(`could not seed v2 nodes: ${i?.message??i}`)}}return A}return s.data}saveSchema(e){let t=T.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid schema: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.schemaPath(),t.data)}loadNodes(){let e=this.nodesPath();if(!I(e)){let r=oe();return this.saveNodes(r),r}let t=D(e,"utf-8"),s=_.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveNodes(e){let t=_.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid nodes file: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.nodesPath(),t.data)}validateNode(e,t,s){let r=t.levels.find(i=>i.id===e.level);if(!r)throw new Error(`Unknown level: "${e.level}"`);let o=r.axes.filter(i=>!i.optional).filter(i=>!(i.name in e.axes));if(o.length)throw new Error(`Node ${e.id} (${e.level}) missing required axes: ${o.map(i=>i.name).join(", ")}`);for(let i of r.axes){let a=e.axes[i.name];if(a!=null){if(i.type==="enum"&&i.values&&!i.values.includes(a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" not in enum ${JSON.stringify(i.values)}`);if(i.type==="ref"){if(!s.some(c=>c.id===a))throw new Error(`Node ${e.id}: axis ${i.name}="${a}" refers to unknown node`);if(i.refLevel){let c=s.find(l=>l.id===a);if(c.level!==i.refLevel)throw new Error(`Node ${e.id}: axis ${i.name} expected level "${i.refLevel}" but got "${c.level}"`)}}}}let n=t.levels.findIndex(i=>i.id===e.level);if(n===0){if(e.parentId!==null)throw new Error(`Root-level node ${e.id} must have parentId: null`)}else{if(!e.parentId)throw new Error(`Non-root node ${e.id} must have a parentId`);let i=s.find(c=>c.id===e.parentId);if(!i)throw new Error(`Node ${e.id}: parent "${e.parentId}" not found`);let a=t.levels.findIndex(c=>c.id===i.level);if(a<0||a>=n)throw new Error(`Node ${e.id} at level "${e.level}" has parent at level "${i.level}" \u2014 parent must be at a higher level`)}}commitNodesAlongPath(e,t,s,r){let o=[],n=[],i=new Date().toISOString();for(let a=0;a<e.length;a++){let c=e[a],l=this.loadNodes().nodes;if(l.find(m=>m.id===c)){n.push(c);continue}let p=0;for(let m=a-1;m>=0;m--){let w=e[m],N=l.find(k=>k.id===w)||o.find(k=>k.id===w);if(N){p=s.levels.findIndex(k=>k.id===N.level)+1;break}}let g=t[c]??{},d=null;for(let m=p;m<s.levels.length;m++){let w=s.levels[m];if(w.axes.filter(k=>!k.optional).filter(k=>!(k.name in g)).length===0){d=w.id,p=m+1;break}}if(!d&&p<s.levels.length&&(d=s.levels[p].id,p++),!d)throw new Error(`Can't place node ${c} \u2014 no schema level left (cursor=${p}, levels=${s.levels.length})`);let h=null,f=s.levels.findIndex(m=>m.id===d);for(let m=a-1;m>=0;m--){let w=e[m],N=l.find(C=>C.id===w)||o.find(C=>C.id===w);if(!N)continue;let k=s.levels.findIndex(C=>C.id===N.level);if(k>=0&&k<f){h=w;break}}let u={id:c,level:d,parentId:h,axes:g,createdAt:i,createdBy:r};this.addNode(u),o.push(u)}return{added:o,skipped:n}}addNode(e){let t=this.loadSchema(),s=this.loadNodes();if(s.nodes.some(r=>r.id===e.id))throw new Error(`Node id already exists: ${e.id}`);return this.validateNode(e,t,[...s.nodes,e]),s.nodes.push(e),this.saveNodes(s),e}appendClassification(e){let t=P.safeParse(e);if(!t.success){let o=t.error.issues.map(n=>`${n.path.join(".")}: ${n.message}`).join(" \xB7 ");return this.log(`skipped invalid classification \u2014 ${o} \xB7`,`path=${JSON.stringify(e.path)}`,`axes-keys=${JSON.stringify(Object.keys(e.proposedAxes||{}))}`),!1}let s=JSON.stringify(t.data)+`
|
|
2
|
+
`,r=this.classificationsPath();return I(r)||U(ae(r),{recursive:!0}),ge(r,s),!0}listPendingClassifications(e=200){return this.listByStatus("pending",e)}listAllClassifications(){return this.readAllCollapsed()}listByStatus(e,t=200){return this.readAllCollapsed().filter(r=>r.status===e).slice(0,t)}readAllCollapsed(){let e=this.classificationsPath();if(!I(e))return[];let s=D(e,"utf-8").split(`
|
|
3
|
+
`).filter(Boolean),r=new Map;for(let o of s)try{let n=P.safeParse(JSON.parse(o));if(!n.success)continue;r.set(n.data.msgHash,n.data)}catch{}return Array.from(r.values()).sort((o,n)=>o.ts<n.ts?1:-1)}updateClassificationStatus(e,t){let r=this.readAllCollapsed().find(n=>n.msgHash===e);if(!r)return null;let o={...r,status:t.status,ts:new Date().toISOString()};if(t.reviewer||t.reviewReason){let n=` \xB7 ${t.reviewer?`reviewer=${t.reviewer}`:""}${t.reviewReason?` \xB7 ${t.reviewReason}`:""}`;o.preview=((r.preview||"")+n).slice(0,500)}return this.appendClassification(o),o}readRecentClassifications(e=50){let t=this.classificationsPath();if(!I(t))return[];let r=D(t,"utf-8").split(`
|
|
4
|
+
`).filter(Boolean),o=[];for(let n=r.length-1;n>=0&&o.length<e;n--)try{let i=P.safeParse(JSON.parse(r[n]));i.success&&o.push(i.data)}catch{}return o}fingerprint(e){let s=[e.text.toLowerCase().replace(/\s+/g," ").trim(),e.channel??"",e.sender??""].join("");return fe("sha256").update(s).digest("hex").slice(0,32)}loadIndex(){let e=this.indexPath();if(!I(e))return{version:1,entries:{}};let t=D(e,"utf-8"),s=G.safeParse(JSON.parse(t));if(!s.success)throw new Error(`Invalid ${e}: ${s.error.issues.map(r=>r.message).join("; ")}`);return s.data}saveIndex(e){let t=G.safeParse(e);if(!t.success)throw new Error(`Refusing to save invalid index: ${t.error.issues.map(s=>s.message).join("; ")}`);B(this.indexPath(),t.data)}getFingerprint(e){return this.loadIndex().entries[e]}setFingerprint(e,t){let s=this.loadIndex();s.entries[e]={...t,fingerprint:e,updatedAt:new Date().toISOString()},this.saveIndex(s)}updateNodeAxes(e,t){let s=this.loadSchema(),r=this.loadNodes(),o=r.nodes.find(i=>i.id===e);if(!o)throw new Error(`Node not found: ${e}`);let n={...o,axes:t};return this.validateNode(n,s,r.nodes.map(i=>i.id===e?n:i)),r.nodes=r.nodes.map(i=>i.id===e?n:i),this.saveNodes(r),n}deleteNode(e){let t=this.loadNodes(),s=t.nodes.find(o=>o.parentId===e);if(s)throw new Error(`Cannot delete "${e}" \u2014 child node "${s.id}" still points to it`);let r=t.nodes.find(o=>Object.values(o.axes).some(n=>n===e));if(r)throw new Error(`Cannot delete "${e}" \u2014 node "${r.id}" references it via an axis`);t.nodes=t.nodes.filter(o=>o.id!==e),this.saveNodes(t)}approveClassification(e){if(this.getFingerprint(e.msgHash))return;let t=this.loadSchema(),s=new Set(this.loadNodes().nodes.map(r=>r.id));for(let r=0;r<e.path.length;r++){let o=e.path[r];if(s.has(o))continue;let n=t.levels[r]?.id;if(!n)break;let i=e.proposedAxes?.[o]??{},a=r===0?null:e.path[r-1];this.addNode({id:o,level:n,parentId:a,axes:i,createdAt:new Date().toISOString(),createdBy:e.agentId}),s.add(o)}this.setFingerprint(e.msgHash,{path:e.path,leaf:e.leaf}),this.appendClassification({...e,status:"approved",ts:new Date().toISOString()})}rejectClassification(e){this.appendClassification({...e,status:"rejected",ts:new Date().toISOString()})}};function B(b,e){U(ae(b),{recursive:!0});let t=`${b}.tmp-${process.pid}`;J(t,JSON.stringify(e,null,2)),ue(t,b)}function oe(){let b=new Date().toISOString(),e=[],t=new Set;for(let s of F)t.has(s.category)||(e.push({id:s.category,level:"category",parentId:null,axes:{kind:s.category},createdAt:b,createdBy:"starter"}),t.add(s.category));for(let s of F)e.push({id:s.verb,level:"verb",parentId:s.category,axes:{name:s.verb,...s.description?{description:s.description}:{}},createdAt:b,createdBy:"starter"});return{version:1,nodes:e}}pe();de();import{createHash as me}from"crypto";var q=class{store;daemonUrl;token;draftAgent;autoApprove;autoApproveStructure;classifierModel;classifierProviderName;providerInstance;log;constructor(e){this.store=e.store,this.daemonUrl=e.daemonUrl.replace(/\/+$/,""),this.token=e.token,this.draftAgent=e.draftAgent,this.autoApprove=e.autoApproveConfidence??1,this.autoApproveStructure=e.autoApproveStructure??"extend-leaves",this.classifierModel=e.classifierModel??"claude-haiku-4-5-20251001",this.classifierProviderName=e.classifierProvider??"claude-code",this.log=e.log??console.error.bind(console,"[classifier]")}getProvider(){return this.providerInstance||(this.providerInstance=X(this.classifierProviderName)),this.providerInstance}async classify(e){let t=this.store.fingerprint({text:e.text,channel:e.channel,sender:e.sender}),s=this.store.getFingerprint(t);if(s)return this.store.appendClassification({ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:s.path,proposedAxes:{},leaf:s.leaf,source:"cache",status:"approved",preview:e.text.slice(0,200)}),{path:s.path,pathId:z(s.path),pathLabel:K(s.path,this.store.loadNodes().nodes),axes:{},leaf:s.leaf,source:"cache",status:"approved"};let r=this.store.loadSchema(),o=this.store.loadNodes().nodes,n=await this.proposePath(e,r,o).catch(u=>(this.log("LLM proposal failed:",u?.message||u),null));if(!n)return null;let{path:i,proposedAxes:a,confidence:c,leaf:l}=n;if(i.length===0)return null;let v={ts:new Date().toISOString(),msgHash:t,agentId:e.agentId,channel:e.channel,sender:e.sender,path:i,proposedAxes:a,leaf:l,source:"llm",status:"pending",confidence:c,preview:e.text.slice(0,200)},p=new Set(o.map(u=>u.id)),g=i.map((u,m)=>p.has(u)?-1:m).filter(u=>u>=0),d=!1;if(this.autoApproveStructure==="any")d=!0;else if(this.autoApproveStructure==="extend-leaves"){let u=g.length===0,m=g.length===1&&g[0]===i.length-1;d=u||m}let h=c!==void 0&&c>=this.autoApprove,f="pending";if(d||h)try{this.commitNewNodes(i,a,r,o,e.sender),this.store.setFingerprint(t,{path:i,leaf:l}),f="approved"}catch(u){this.log("auto-approve failed \u2014 staying pending \xB7",`path=${JSON.stringify(i)}`,`reason=${(u?.message||u).toString().slice(0,200)}`)}return v.status=f,this.store.appendClassification(v),{path:i,pathId:z(i),pathLabel:K(i,this.store.loadNodes().nodes),axes:a,leaf:l,source:"llm",status:f,confidence:c}}async proposePath(e,t,s){let r=s.map(d=>({id:d.id,level:d.level,parentId:d.parentId,axes:d.axes})),o=["You are the intent classifier for AgentX. You answer ONE question:",'"what kind of work does this message describe?" \u2014 verb-level only.',"","IMPORTANT \u2014 what NOT to encode in the path:","- Client / company / project / team names. Those are already on the event"," metadata (project, channel, agentId). Embedding them in the path causes"," duplicate nodes (one per client) for the same verb.","- The specific subject (issue number, file name, person name). Same reason.","- The agent's name or role. Pick the verb the *requester* intended.","","SCHEMA (fixed levels \u2014 pick one node per level):","```json",JSON.stringify(t,null,2),"```","","EXISTING NODES (prefer reusing these; only invent a new node when no","existing one fits):","```json",JSON.stringify(r,null,2),"```","","MESSAGE:","```",e.text.slice(0,2e3),"```",`channel: ${e.channel??"?"}`,`sender: ${e.sender??"?"}`,"","TASK:","1. Classify into 'category' (closed enum): code, ops, support, admin,"," knowledge, social, system. Pick the closest fit.","2. Pick or propose a 'verb' node. Verb ids are dot-namespaced lower-kebab,",' e.g. "review.merge-request", "deploy.staging", "investigate.error",',' "chat.greeting", "fix.bug". Reuse an existing verb when the message is'," the same kind of work as something already classified, even when the"," client / project / subject differs.","","Examples (right vs wrong):",'- "Please review MR #957 on globex/system" \u2192 ["code", "review.merge-request"]',' NOT ["business", "acme", "globex-v2", "review-mr-957-system"]','- "Deploy initech-v2 to staging please" \u2192 ["ops", "deploy.staging"]',' NOT ["business", "acme", "initech-v2", "deploy-initech-v2-to-staging"]','- "Hello Atlas" \u2192 ["support", "chat.greeting"]',"","NODE ID RULES (strict \u2014 invalid ids get dropped):","- lowercase-kebab + dots only: [a-z0-9][a-z0-9._-]*","- no spaces, no uppercase, no Arabic/other non-Latin",'- verb ids should use a "category.specific" or "verb.modifier" shape',"","Return ONE JSON object on one line, no prose, no fences:",' { "path": string[], "proposedAxes": { [nodeId]: { [axisName]: string } }, "leaf": { "input"?: string, "output"?: string }, "confidence": number }',"confidence in [0,1]. Prefer low confidence over guessing."].join(`
|
|
5
|
+
`),n=await this.callProvider(o),i=Q(n);if(!i||!Array.isArray(i.path))return null;let a=/^[a-z0-9][a-z0-9._-]*$/,c=new Map,l=i.path.filter(d=>typeof d=="string"&&d.length>0).map(d=>{let h=d.trim(),f=ce(h);return h!==f&&c.set(h,f),f}).filter(d=>a.test(d));if(l.length===0)return null;let v={};if(i.proposedAxes&&typeof i.proposedAxes=="object")for(let[d,h]of Object.entries(i.proposedAxes)){if(!h||typeof h!="object")continue;let f=c.get(d)??ce(d);if(!f)continue;let u={};for(let[m,w]of Object.entries(h))typeof w=="string"&&(u[m]=w);!u.name&&d!==f&&(u.name=d.trim()),v[f]=u}let p={};i.leaf&&typeof i.leaf=="object"&&(typeof i.leaf.input=="string"&&(p.input=i.leaf.input),typeof i.leaf.output=="string"&&(p.output=i.leaf.output));let g=typeof i.confidence=="number"?Math.max(0,Math.min(1,i.confidence)):void 0;return{path:l,proposedAxes:v,confidence:g,leaf:p}}commitNewNodes(e,t,s,r,o){this.store.commitNodesAlongPath(e,t,s,o)}async callProvider(e){let t=this.getProvider(),s=new AbortController,r=setTimeout(()=>s.abort(),3e4);try{return(await t.generate([{role:"system",content:"You are a taxonomy classifier. Respond with a single JSON object on one line. No prose, no code fences."},{role:"user",content:e}],{model:this.classifierModel,maxTokens:800})).content||""}finally{clearTimeout(r)}}};function ce(b){let e=b.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").replace(/-{2,}/g,"-");return e?/^[a-z0-9]/.test(e)?e:`n-${e}`.replace(/[-_]+$/,""):""}function z(b){return me("sha1").update(b.join("")).digest("hex").slice(0,16)}function K(b,e){return b.map(t=>{let s=e.find(o=>o.id===t);return s&&(s.axes?.name||s.axes?.what)||t}).join(" \u203A ")}function V(b,e){if(b.length===0||e.length===0)return 0;let t=0;for(let r=0;r<Math.min(b.length,e.length)&&b[r]===e[r];r++)t++;if(t===0)return 0;let s=Math.max(b.length,e.length);return t/s}import{readFileSync as W,writeFileSync as S,appendFileSync as ve,existsSync as x,mkdirSync as j,readdirSync as O,statSync as ye}from"fs";import{resolve as y,join as be,relative as $,dirname as we}from"path";he();var E=class{baseDir;rawDir;log;constructor(e=y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki]")){this.baseDir=e,this.rawDir=y(e,"raw/entries"),this.log=t,j(this.rawDir,{recursive:!0}),j(y(e,"raw"),{recursive:!0}),this.ensureSchema()}canRead(e,t){return e.access==="public"?!0:t?!!(e.owner===t||e.access==="shared"&&e.sharedWith?.includes(t)):!1}canWrite(e,t){return e.owner===t}addEntry(e){let t=`${e.date}_${e.id}.md`,s=y(this.rawDir,t),r=["---",`id: ${e.id}`,`date: ${e.date}`,`agent: ${e.agentId}`,`source: ${e.source}`];if(e.sourceContext&&r.push(`context: ${e.sourceContext}`),e.meta)for(let[o,n]of Object.entries(e.meta))r.push(`${o}: ${JSON.stringify(n)}`);return r.push("---","",e.content),S(s,r.join(`
|
|
6
|
+
`)),this.appendLog("ingest",`${e.id} from ${e.agentId} via ${e.source}`),t}listEntries(e){if(!x(this.rawDir))return[];let t=O(this.rawDir).filter(r=>r.endsWith(".md")).sort(),s=[];for(let r of t){let o=W(y(this.rawDir,r),"utf-8"),n=this.parseEntry(o,r);n&&(e?.agentId&&n.agentId!==e.agentId||e?.after&&n.date<e.after||e?.before&&n.date>e.before||s.push(n))}return s}parseEntry(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],o=s[2].trim(),n=c=>r.match(new RegExp(`^${c}:\\s*(.+)$`,"m"))?.[1]?.trim()||"",i=new Set(["id","date","agent","source","context"]),a={};for(let c of r.split(`
|
|
7
|
+
`)){let l=c.match(/^(\w+):\s*(.+)$/);if(!(!l||i.has(l[1])))try{a[l[1]]=JSON.parse(l[2])}catch{a[l[1]]=l[2].trim()}}return{id:n("id")||t.replace(".md",""),date:n("date"),agentId:n("agent"),source:n("source"),sourceContext:n("context")||void 0,content:o,meta:Object.keys(a).length>0?a:void 0}}writeArticle(e,t,s,r){let o=this.readArticle(e);if(o&&!this.canWrite(o.meta,r))return this.log(`Permission denied: "${r}" cannot write "${e}" (owner: ${o.meta.owner})`),!1;t.type&&!ee(t.type)&&(this.log(`Dropping invalid article type "${t.type}" for "${e}" \u2014 enum is [person, project, place, concept, event, decision, pattern]`),t={...t,type:void 0});let n=y(this.baseDir,e);o&&this.saveVersion(e,n),j(we(n),{recursive:!0});let i=["---",`title: "${t.title}"`];t.type&&i.push(`type: ${t.type}`),t.related?.length&&i.push(`related: [${t.related.map(c=>`"${c}"`).join(", ")}]`),i.push(`tags: [${(t.tags||[]).map(c=>`"${c}"`).join(", ")}]`,`owner: ${t.owner}`,`access: ${t.access}`),t.sharedWith?.length&&i.push(`shared_with: [${t.sharedWith.map(c=>`"${c}"`).join(", ")}]`),i.push(`created: ${t.created}`,`last_updated: ${t.lastUpdated}`,`sources: [${t.sources.map(c=>`"${c}"`).join(", ")}]`),t.graphPath?.length&&i.push(`graph_path: [${t.graphPath.map(c=>`"${c}"`).join(", ")}]`),i.push("---","",s),S(n,i.join(`
|
|
8
|
+
`));let a=o?"update":"create";return this.appendLog(a,`${t.title} [${(t.tags||[]).slice(0,5).join(", ")}] by ${r} at ${e}`),!0}saveVersion(e,t){try{if(!x(t))return;let s=W(t,"utf-8"),r=new Date().toISOString().replace(/[:.]/g,"-"),o=y(this.baseDir,"_versions",e.replace(/\.md$/,""));j(o,{recursive:!0}),S(y(o,`${r}.md`),s)}catch{}}getVersions(e){let t=y(this.baseDir,"_versions",e.replace(/\.md$/,""));if(!x(t))return[];try{return O(t).filter(s=>s.endsWith(".md")).sort().reverse().map(s=>({timestamp:s.replace(/\.md$/,"").replace(/-/g,(r,o)=>o<19?o===10?"T":o===13||o===16?":":"-":r),path:y(t,s)}))}catch{return[]}}restoreVersion(e,t){let r=this.getVersions(e).find(o=>o.timestamp.startsWith(t));if(!r)return!1;try{let o=W(r.path,"utf-8"),n=y(this.baseDir,e);return this.saveVersion(e,n),S(n,o),this.appendLog("restore",`${e} restored to ${t}`),!0}catch{return!1}}readArticle(e){let t=y(this.baseDir,e);if(!x(t))return null;let s=W(t,"utf-8");return this.parseArticle(s,e)}readArticleAs(e,t){let s=this.readArticle(e);return!s||!this.canRead(s.meta,t)?null:s}parseArticle(e,t){let s=e.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);if(!s)return null;let r=s[1],o=s[2].trim(),n=d=>r.match(new RegExp(`^${d}:\\s*(.+)$`,"m"))?.[1]?.trim().replace(/^"(.*)"$/,"$1")||"",i=d=>{let h=r.match(new RegExp(`^${d}:\\s*\\[(.*)\\]$`,"m"));return h?h[1].split(",").map(f=>f.trim().replace(/^"(.*)"$/,"$1")).filter(Boolean):[]},a=n("type")||n("kind"),l=new Set(["person","project","place","concept","event","decision","pattern"]).has(a)?a:void 0,v=i("tags").filter((d,h,f)=>d&&f.indexOf(d)===h),p=i("related"),g=i("graph_path");return{meta:{title:n("title"),type:l,related:p.length?p:void 0,tags:v,owner:n("owner"),access:n("access")||"public",sharedWith:i("shared_with"),created:n("created"),lastUpdated:n("last_updated"),sources:i("sources"),graphPath:g.length?g:void 0},content:o,path:t}}listArticles(e){let t=[];return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=$(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let o=this.readArticle(r);o&&this.canRead(o.meta,e)&&t.push(o)}),t}search(e,t,s=10){let r=e.toLowerCase(),o=[];if(this.walkDir(this.baseDir,p=>{if(!p.endsWith(".md"))return;let g=$(this.baseDir,p);if(g.startsWith("raw/")||g.startsWith("_"))return;let d=this.readArticle(g);!d||!this.canRead(d.meta,t)||o.push(d)}),o.length===0)return[];let n=o.map(p=>p.content),i=y(this.baseDir,"_bm25_cache.json"),a=L(n,i),c=M(e,a),l=new Map(c.map(p=>[p.docIndex,p.score]));return o.map((p,g)=>{let d=l.get(g)??0;return p.meta.title.toLowerCase().includes(r)&&(d+=10),p.meta.tags?.some(h=>h.toLowerCase().includes(r))&&(d+=5),{article:p,score:d}}).filter(p=>p.score>0).sort((p,g)=>g.score-p.score).slice(0,s).map(p=>p.article)}async findRelevantReranked(e,t,s=10,r={}){let o=Math.max(s,r.shortlist??se),n=this.findRelevant(e,t,o);if(n.length<2)return n.slice(0,s);let i=n.map((l,v)=>({id:`c${v}`,title:l.meta.title||`(untitled ${v})`,tags:l.meta.tags,excerpt:l.content})),a=await Z(te,re({query:e,candidates:i,excerptChars:r.excerptChars}),ie(i),{incumbent:{best:i[0].id},features:{agent:t??"unknown"}});return!a||a.mode!=="active"?n.slice(0,s):ne(a.answers,i).ranked.map(l=>n[Number(l.slice(1))]).filter(l=>!!l).slice(0,s)}findRelevant(e,t,s=3,r,o={graph:.6,bm25:.4}){let n=[];if(this.walkDir(this.baseDir,h=>{if(!h.endsWith(".md"))return;let f=$(this.baseDir,h);if(f.startsWith("raw/")||f.startsWith("_"))return;let u=this.readArticle(f);!u||!this.canRead(u.meta,t)||n.push(u)}),n.length===0)return[];let i=n.map(h=>`${h.meta.title} ${(h.meta.tags||[]).join(" ")} ${h.content}`),a=y(this.baseDir,"_bm25_relevance_cache.json"),c=L(i,a),l=M(e,c),v=l.reduce((h,f)=>Math.max(h,f.score),0)||1,p=new Map(l.map(h=>[h.docIndex,h.score/v])),g=!!(r&&r.length>0);return n.map((h,f)=>{let u=p.get(f)??0,m=0;g&&h.meta.graphPath?.length&&(m=V(r,h.meta.graphPath));let w=g?o.graph*m+o.bm25*u:u;return{article:h,score:w}}).filter(h=>h.score>0).sort((h,f)=>f.score-h.score).slice(0,s).map(h=>h.article)}buildContext(e,t=4e3){if(e.length===0)return"";let s=["[Wiki Knowledge]"],r=0;for(let o of e){let n=`
|
|
9
|
+
## ${o.meta.title} [${(o.meta.tags||[]).slice(0,3).join(", ")}]`,i=o.content.length>600?o.content.slice(0,600)+"...":o.content,a=n+`
|
|
10
|
+
`+i;if(r+a.length>t)break;s.push(a),r+=a.length}return s.push(`
|
|
11
|
+
[End Wiki Knowledge]`),s.join(`
|
|
12
|
+
`)}rebuildIndex(){let e=[],t=new Map;this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let i=$(this.baseDir,n);if(i.startsWith("raw/")||i.startsWith("_"))return;let a=this.readArticle(i);if(!a)return;let c=a.content.match(/\[\[([^\]]+)\]\]/g)||[];for(let v of c){let p=v.replace(/\[\[|\]\]/g,"");t.set(p,(t.get(p)||0)+1)}let l=[a.meta.title.toLowerCase()];a.meta.tags&&l.push(...a.meta.tags.map(v=>v.toLowerCase())),e.push({path:i,title:a.meta.title,type:a.meta.type,related:a.meta.related,tags:a.meta.tags||[],owner:a.meta.owner,access:a.meta.access,sharedWith:a.meta.sharedWith,aliases:l,backlinks:t.get(a.meta.title)||0,sources:a.meta.sources,lastUpdated:a.meta.lastUpdated})});let s={articles:e,lastRebuilt:new Date().toISOString()};S(y(this.baseDir,"_index.json"),JSON.stringify(s,null,2)),this.writeCatalog(e,s.lastRebuilt);let r=["# Wiki Index","",`Last rebuilt: ${s.lastRebuilt}`,""],o=new Map;for(let n of e){let i=n.access||"public",a=o.get(i)||[];a.push(n),o.set(i,a)}for(let[n,i]of Array.from(o.entries()).sort()){r.push(`## ${n}`,"");for(let a of i.sort((c,l)=>c.title.localeCompare(l.title))){let c=a.type?` [${a.type}]`:"";r.push(`- [${a.title}](${a.path})${c} \u2014 owner: ${a.owner}`)}r.push("")}return S(y(this.baseDir,"WIKI.md"),r.join(`
|
|
13
|
+
`)),this.log(`Index rebuilt: ${e.length} articles`),this.appendLog("rebuild-index",`${e.length} articles indexed`),s}writeCatalog(e,t){let s=["person","project","place","concept","event","decision","pattern","untyped"],r={person:"## People",project:"## Projects",place:"## Places",concept:"## Concepts",event:"## Events",decision:"## Decisions",pattern:"## Patterns",untyped:"## Untyped (needs migration)"},o=new Map;for(let i of e){let a=i.type||"untyped",c=o.get(a)||[];c.push(i),o.set(a,c)}let n=["# Wiki Content Catalog","",`_Last rebuilt: ${t}_`,"","Articles grouped by type. Agentic query walks this file first to pick candidates.",""];for(let i of s){let a=o.get(i);if(!(!a||a.length===0)){n.push(r[i]||`## ${i}`,"");for(let c of a.sort((l,v)=>l.title.localeCompare(v.title))){let l=c.access==="private"?" (private)":c.access==="shared"?" (shared)":"",v=c.related?.length?` \u2192 [[${c.related.slice(0,3).join("]], [[")}]]${c.related.length>3?", \u2026":""}`:"";n.push(`- [${c.title}](${c.path})${l}${v}`)}n.push("")}}S(y(this.baseDir,"_index.md"),n.join(`
|
|
14
|
+
`))}stats(){let e=0,t={},s={},r={};this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let i=$(this.baseDir,n);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md")return;let a=this.readArticle(i);if(a){e++;for(let c of a.meta.tags||[])t[c]=(t[c]||0)+1;s[a.meta.access]=(s[a.meta.access]||0)+1,r[a.meta.owner]=(r[a.meta.owner]||0)+1}});let o=x(this.rawDir)?O(this.rawDir).filter(n=>n.endsWith(".md")).length:0;return{totalArticles:e,totalEntries:o,articlesByType:t,articlesByAccess:s,articlesByOwner:r}}appendLog(e,t){let s=y(this.baseDir,"log.md"),o=`## [${new Date().toISOString().replace("T"," ").slice(0,16)}] ${e} | ${t}
|
|
15
|
+
|
|
16
|
+
`;x(s)||S(s,`# Wiki Log
|
|
17
|
+
|
|
18
|
+
Chronological record of all wiki operations.
|
|
19
|
+
|
|
20
|
+
`),ve(s,o)}getLog(e=20){let t=y(this.baseDir,"log.md");return x(t)?W(t,"utf-8").split(/^## /m).filter(o=>o.startsWith("[")).slice(-e).map(o=>o.trim()):[]}ensureSchema(){let e=y(this.baseDir,"_schema.md");if(x(e))return;S(e,`# Wiki Schema
|
|
21
|
+
|
|
22
|
+
A personal wiki maintained by LLMs. Karpathy pattern: plain files, aggressive tagging,
|
|
23
|
+
structure emerges from data. The wiki is a compounding artifact.
|
|
24
|
+
|
|
25
|
+
## Structure
|
|
26
|
+
|
|
27
|
+
\`\`\`
|
|
28
|
+
wiki/
|
|
29
|
+
_schema.md # This file
|
|
30
|
+
worldview.md # YOUR mental model \u2014 the LLM reads this during absorb
|
|
31
|
+
raw/entries/ # Immutable raw sources (conversations, imports, anything)
|
|
32
|
+
[LLM-chosen dirs] # Structure emerges from data \u2014 the LLM picks paths
|
|
33
|
+
\`\`\`
|
|
34
|
+
|
|
35
|
+
The LLM decides how to organize articles. You describe YOUR world in worldview.md.
|
|
36
|
+
|
|
37
|
+
## Article Format
|
|
38
|
+
|
|
39
|
+
\`\`\`yaml
|
|
40
|
+
---
|
|
41
|
+
title: "Staging Deployment Process"
|
|
42
|
+
tags: ["deploy", "staging", "devops", "process", "2026-04-06"]
|
|
43
|
+
owner: devops-agent
|
|
44
|
+
access: public
|
|
45
|
+
created: 2026-04-06
|
|
46
|
+
last_updated: 2026-04-06
|
|
47
|
+
sources: ["entry-id-1", "entry-id-2"]
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
Article content with [[wikilinks]] and section tags.
|
|
51
|
+
|
|
52
|
+
## Deploy Steps
|
|
53
|
+
<!-- tags: process, runbook, staging -->
|
|
54
|
+
Content specific to this section...
|
|
55
|
+
\`\`\`
|
|
56
|
+
|
|
57
|
+
## Tags
|
|
58
|
+
|
|
59
|
+
Tags are the primary context-narrowing mechanism. The more tags, the better.
|
|
60
|
+
|
|
61
|
+
Tag aggressively:
|
|
62
|
+
- **Who**: people, agents, teams involved
|
|
63
|
+
- **What**: project, client, topic, technology
|
|
64
|
+
- **When**: dates, periods, milestones
|
|
65
|
+
- **Where**: server, environment, channel
|
|
66
|
+
- **How**: process, decision, pattern
|
|
67
|
+
- **Your terms**: whatever vocabulary makes sense in YOUR world
|
|
68
|
+
|
|
69
|
+
Section tags (\`<!-- tags: ... -->\`) let different parts of an article
|
|
70
|
+
match different queries. A deploy article might have sections tagged
|
|
71
|
+
"runbook" and "incident" separately.
|
|
72
|
+
|
|
73
|
+
## Operations
|
|
74
|
+
|
|
75
|
+
### Absorb
|
|
76
|
+
Read raw entries \u2192 read worldview.md \u2192 tag aggressively \u2192 create/update articles.
|
|
77
|
+
Also identify GAPS: "We mention X but have no article for it."
|
|
78
|
+
|
|
79
|
+
### Query
|
|
80
|
+
Match by tags first \u2192 then keyword within matched articles \u2192 synthesize.
|
|
81
|
+
If agent is working on a specific project, only send content tagged for that project.
|
|
82
|
+
|
|
83
|
+
### Lint
|
|
84
|
+
Check for: orphan articles, broken [[wikilinks]], untagged articles,
|
|
85
|
+
articles over 100 lines that should split, mentioned-but-missing topics.
|
|
86
|
+
|
|
87
|
+
## Worldview
|
|
88
|
+
|
|
89
|
+
Edit \`worldview.md\` to describe YOUR world. This is not a schema \u2014 it's your
|
|
90
|
+
mental model. The LLM reads it during absorb to understand where things go.
|
|
91
|
+
|
|
92
|
+
Example worldview.md:
|
|
93
|
+
\`\`\`
|
|
94
|
+
I'm the founder of Acme Corp.
|
|
95
|
+
We build software products.
|
|
96
|
+
Our agents: Marketing Bot, DevOps Bot, Coordinator.
|
|
97
|
+
Clients: ClientA (enterprise), ClientB (startup).
|
|
98
|
+
Infrastructure: local dev machine, cloud server.
|
|
99
|
+
We use GitLab for version control.
|
|
100
|
+
\`\`\`
|
|
101
|
+
`),this.log("Created _schema.md")}extractWikilinks(e){return(e.match(/\[\[([^\]]+)\]\]/g)||[]).map(s=>s.replace(/\[\[|\]\]/g,""))}buildBacklinks(){let e={};return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=$(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_")||s==="WIKI.md"||s==="log.md")return;let r=W(t,"utf-8"),o=this.extractWikilinks(r);for(let n of o)e[n]||(e[n]=[]),e[n].push(s)}),S(y(this.baseDir,"_backlinks.json"),JSON.stringify(e,null,2)),e}getBacklinks(e){let t=y(this.baseDir,"_backlinks.json");if(!x(t))return[];try{return JSON.parse(W(t,"utf-8"))[e]||[]}catch{return[]}}findByTags(e,t,s=10){let r=e.map(n=>n.toLowerCase()),o=[];return this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let i=$(this.baseDir,n);if(i.startsWith("raw/")||i.startsWith("_"))return;let a=this.readArticle(i);if(!a||t&&!this.canRead(a.meta,t))return;let c=(a.meta.tags||[]).map(g=>g.toLowerCase()),l=(a.content.match(/<!--\s*tags?:\s*([^>]+)\s*-->/gi)||[]).flatMap(g=>g.replace(/<!--\s*tags?:\s*|\s*-->/gi,"").split(",").map(d=>d.trim().toLowerCase())),v=[...c,...l],p=r.filter(g=>v.includes(g)).length;p>0&&o.push({article:a,score:p})}),o.sort((n,i)=>i.score-n.score).slice(0,s).map(n=>n.article)}getAllTags(){let e=new Map;return this.walkDir(this.baseDir,t=>{if(!t.endsWith(".md"))return;let s=$(this.baseDir,t);if(s.startsWith("raw/")||s.startsWith("_"))return;let r=this.readArticle(s);if(r?.meta.tags)for(let o of r.meta.tags)e.set(o,(e.get(o)||0)+1)}),e}getWorldview(){let e=y(this.baseDir,"worldview.md");return x(e)?W(e,"utf-8"):null}setWorldview(e){S(y(this.baseDir,"worldview.md"),e),this.appendLog("worldview","Updated worldview")}lint(){let e=[],t=new Set,s=new Map,r=new Map;this.walkDir(this.baseDir,n=>{if(!n.endsWith(".md"))return;let i=$(this.baseDir,n);if(i.startsWith("raw/")||i.startsWith("_")||i==="WIKI.md"||i==="log.md")return;let a=this.readArticle(i);if(!a)return;t.add(a.meta.title),r.set(a.meta.title,i);let c=this.extractWikilinks(a.content);s.set(i,c);let l=a.content.split(`
|
|
102
|
+
`).length;l>100&&e.push({type:"bloated",article:i,message:`${l} lines \u2014 consider splitting`}),a.meta.sources?.length||e.push({type:"unsourced",article:i,message:"No sources listed in frontmatter"}),l<10&&a.content.trim().length<100&&e.push({type:"stub",article:i,message:"Very short article \u2014 needs enrichment"})});for(let[n,i]of s)for(let a of i)t.has(a)||e.push({type:"broken-link",article:n,message:`[[${a}]] \u2014 target article not found`});let o=this.buildBacklinks();for(let[n,i]of r)(!o[n]||o[n].length===0)&&e.push({type:"orphan",article:i,message:`No other articles link to "${n}"`});return this.appendLog("lint",`Found ${e.length} issues`),e}getUnabsorbedEntries(){let e=new Set;return this.walkDir(this.baseDir,s=>{if(!s.endsWith(".md"))return;let r=$(this.baseDir,s);if(r.startsWith("raw/")||r.startsWith("_"))return;let o=this.readArticle(r);if(o?.meta.sources)for(let n of o.meta.sources)e.add(n)}),this.listEntries().filter(s=>!e.has(s.id))}buildAbsorbPrompt(e=20){let t=this.getUnabsorbedEntries().slice(0,e);if(t.length===0)return null;let s=t.map(r=>`[${r.date} ${r.agentId} via ${r.source}] ${r.content.slice(0,200)}`).join(`
|
|
103
|
+
|
|
104
|
+
`);return`/wiki absorb
|
|
105
|
+
|
|
106
|
+
There are ${t.length} unprocessed entries. Read each, understand what it means, and create or update wiki articles.
|
|
107
|
+
|
|
108
|
+
${s}`}walkDir(e,t){if(x(e))for(let s of O(e)){let r=be(e,s);ye(r).isDirectory()?this.walkDir(r,t):t(r)}}};import{resolve as Y}from"path";import{existsSync as ke,readdirSync as Se,mkdirSync as xe}from"fs";var le=class{baseDir;agentsDir;mode;sharedStore;agentStores=new Map;log;constructor(e=Y(process.cwd(),".agentx/wiki"),t=console.error.bind(console,"[wiki-hub]"),s="graph"){this.baseDir=e,this.agentsDir=Y(e,"agents"),this.mode=s,this.log=t,xe(this.agentsDir,{recursive:!0}),this.sharedStore=new E(e,t)}getMode(){return this.mode}getAgentWiki(e){let t=`${e}:${this.mode}`;if(this.agentStores.has(t))return this.agentStores.get(t);let s=Y(this.agentsDir,e,this.mode),r=new E(s,this.log);return this.agentStores.set(t,r),r}getSharedStore(){return this.sharedStore}listAgents(){let e=new Set,t=this.sharedStore.listEntries();for(let s of t)e.add(s.agentId);if(ke(this.agentsDir))for(let s of Se(this.agentsDir))!s.startsWith("_")&&!s.startsWith(".")&&e.add(s);return[...e].sort()}getAgentEntries(e){return this.sharedStore.listEntries({agentId:e})}getUnabsorbedEntries(e){let t=this.getAgentWiki(e),s=this.getAgentEntries(e),r=new Set,o=t.rebuildIndex();for(let n of o.articles)if(n.sources)for(let i of n.sources)r.add(i);return s.filter(n=>!r.has(n.id))}summary(){return this.listAgents().map(t=>{let s=this.getAgentEntries(t),o=this.getAgentWiki(t).rebuildIndex(),n=this.getUnabsorbedEntries(t);return{agentId:t,totalEntries:s.length,totalArticles:o.articles.length,unabsorbed:n.length,articles:o.articles}})}};export{A as a,H as b,q as c,K as d,E as e,le as f};
|
|
109
|
+
//# sourceMappingURL=chunk-IBUSGCLQ.js.map
|