@unbrained/pm-cli 2026.7.7 → 2026.7.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +1 -0
- package/dist/cli/commands/close.js +5 -2
- package/dist/cli/commands/close.js.map +1 -1
- package/dist/cli/commands/completion.js +16 -2
- package/dist/cli/commands/completion.js.map +1 -1
- package/dist/cli/commands/context.d.ts +1 -0
- package/dist/cli/commands/context.js +4 -4
- package/dist/cli/commands/context.js.map +1 -1
- package/dist/cli/commands/contracts.d.ts +11 -0
- package/dist/cli/commands/contracts.js +112 -15
- package/dist/cli/commands/contracts.js.map +1 -1
- package/dist/cli/commands/create.js +4 -2
- package/dist/cli/commands/create.js.map +1 -1
- package/dist/cli/commands/extension.d.ts +23 -19
- package/dist/cli/commands/extension.js +167 -57
- package/dist/cli/commands/extension.js.map +1 -1
- package/dist/cli/commands/list.d.ts +4 -0
- package/dist/cli/commands/list.js +32 -3
- package/dist/cli/commands/list.js.map +1 -1
- package/dist/cli/commands/search.js +3 -3
- package/dist/cli/commands/search.js.map +1 -1
- package/dist/cli/commands/update.d.ts +32 -1
- package/dist/cli/commands/update.js +19 -2
- package/dist/cli/commands/update.js.map +1 -1
- package/dist/cli/help-content.js +28 -2
- package/dist/cli/help-content.js.map +1 -1
- package/dist/cli/register-list-query.js +5 -2
- package/dist/cli/register-list-query.js.map +1 -1
- package/dist/cli/register-operations.js +4 -2
- package/dist/cli/register-operations.js.map +1 -1
- package/dist/cli/register-setup.js +8 -2
- package/dist/cli/register-setup.js.map +1 -1
- package/dist/cli/registration-helpers.js +4 -2
- package/dist/cli/registration-helpers.js.map +1 -1
- package/dist/cli-bundle/chunks/append-CDPAYYSB.js +11 -0
- package/dist/cli-bundle/chunks/{append-PVCTBVJG.js → append-RSPHC423.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-6G6O3OPQ.js → chunk-26MFLA7K.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-LCFJ7XAM.js → chunk-2BVD4ZD2.js} +267 -232
- package/dist/cli-bundle/chunks/chunk-2BVD4ZD2.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-7ML7JONU.js → chunk-2FKIIQMJ.js} +14 -14
- package/dist/cli-bundle/chunks/chunk-2FKIIQMJ.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-H2SMKL2N.js → chunk-3FUXM574.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-DR2V5OIV.js → chunk-3SHDAKMF.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-MRFWUSVA.js → chunk-3UXIMY62.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-WCWVEXGA.js → chunk-3V5C7PUH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-43YSKY75.js → chunk-3YJDIJIE.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-HX6QXV5P.js → chunk-4I7KS5ES.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XHCVAZGM.js → chunk-4OCWJ2AP.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-C5ACVMOI.js → chunk-5RJ4LFD3.js} +34 -7
- package/dist/cli-bundle/chunks/chunk-5RJ4LFD3.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-3TYOW6RR.js → chunk-5STY7NVM.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-7VQ3JJN5.js → chunk-5VAZHYVQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4IQKDKGE.js → chunk-5ZMZF53A.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-6LCJRGPD.js → chunk-63PZJCKO.js} +10 -7
- package/dist/cli-bundle/chunks/chunk-63PZJCKO.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-MCEUKJKW.js → chunk-6FU5BVRB.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-AJUON7E6.js → chunk-6RR4XM5H.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-TEISGNSH.js → chunk-6TD5QGIB.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-565WYS5W.js → chunk-6WCXSC5V.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-NWWL22C7.js → chunk-6ZKDMEVT.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-VLEA2UTQ.js → chunk-7QKSLAHB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-S6VC2A2K.js → chunk-7TBUV7XS.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-YPMZMKN7.js → chunk-7UCBLJDF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4MZOKTI2.js → chunk-AEOFBBWO.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-QFBSP3NI.js → chunk-ASSVI7FP.js} +12 -10
- package/dist/cli-bundle/chunks/{chunk-QFBSP3NI.js.map → chunk-ASSVI7FP.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-ZO7CLOY2.js → chunk-BFNFTHWQ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-YNCFP5AR.js → chunk-BPJ5NYSJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J2VGADNG.js → chunk-BPYVKTZE.js} +122 -27
- package/dist/cli-bundle/chunks/chunk-BPYVKTZE.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-P3MJJW7P.js → chunk-C3YU3TXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SY75LYXR.js → chunk-C6XSTACC.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-S547WBYG.js → chunk-CEX2DQXZ.js} +600 -96
- package/dist/cli-bundle/chunks/chunk-CEX2DQXZ.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-2TILG6F2.js → chunk-CGDUIPJL.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-LZQU6XJG.js → chunk-CHSXGTWF.js} +23 -9
- package/dist/cli-bundle/chunks/{chunk-LZQU6XJG.js.map → chunk-CHSXGTWF.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J7BOLHAV.js → chunk-CXH7EMSB.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-W5HXHC7C.js → chunk-D6J5673C.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-XZWL7VNE.js → chunk-DBV5A7FT.js} +9 -7
- package/dist/cli-bundle/chunks/chunk-DBV5A7FT.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-ARKHKYYS.js → chunk-DQLP22K2.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-YPD7SQ5P.js → chunk-EEJKHF7M.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-EDO7VXSO.js → chunk-EP2CKDS7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SIM5JDON.js → chunk-F5DDGY6R.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-I74FMIWA.js → chunk-FFB3WITE.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-43UQN754.js → chunk-FJR2S7S4.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-CJQM7O7R.js → chunk-FOJEBRDD.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-E3YQFSFE.js → chunk-GLMJLBLR.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-KTGJ2CBU.js → chunk-GO2X6ZRB.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-DDDWVPID.js → chunk-GSQVQINP.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-EVEPHNXJ.js → chunk-GZ365M6E.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-VGO73OCK.js → chunk-HZZ3AC27.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-7Y5N34HX.js → chunk-IINCZYM3.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-GLS6VMWI.js → chunk-INOWVPUD.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-PDXJXEZJ.js → chunk-J6AD3GWC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-52NS7JDP.js → chunk-JH5XDDYS.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-GPIDUMMN.js → chunk-JYVPLGOW.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-XC3X7BQR.js → chunk-K2OKKYSO.js} +11 -9
- package/dist/cli-bundle/chunks/{chunk-XC3X7BQR.js.map → chunk-K2OKKYSO.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YCVWWIKY.js → chunk-K4NMHZR3.js} +111 -24
- package/dist/cli-bundle/chunks/chunk-K4NMHZR3.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-EIUBK2LT.js → chunk-K52C6YPA.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-IDIBF4E2.js → chunk-KAJNWMBE.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-2LEJGRQ7.js → chunk-KFL3XHMA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XS2TMNXR.js → chunk-LD2NBQ5T.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-II7R6KD4.js → chunk-LG4N6YOK.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-M62RO3XK.js → chunk-LHDHS4Z6.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-YTD5GICJ.js → chunk-MBLHA6LR.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-F6MT7KKE.js → chunk-MCH6IKK7.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-7PNQA24K.js → chunk-MCZK7LY6.js} +24 -10
- package/dist/cli-bundle/chunks/{chunk-7PNQA24K.js.map → chunk-MCZK7LY6.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-UO7XAZK6.js → chunk-MFLLULHU.js} +267 -232
- package/dist/cli-bundle/chunks/chunk-MFLLULHU.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-FILL6BB2.js → chunk-N4S7BV43.js} +14 -14
- package/dist/cli-bundle/chunks/chunk-N4S7BV43.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-2APXX4TZ.js → chunk-NBJCIAVV.js} +108 -21
- package/dist/cli-bundle/chunks/chunk-NBJCIAVV.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-Y7KYVCZM.js → chunk-NGBWEYNY.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-RB3KLPAH.js → chunk-NRMDT4OV.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-TZLYO4PP.js → chunk-NRYZ4QLH.js} +121 -26
- package/dist/cli-bundle/chunks/chunk-NRYZ4QLH.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-F6YC2A6X.js → chunk-NSPSJWGL.js} +9 -6
- package/dist/cli-bundle/chunks/chunk-NSPSJWGL.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-GH73UOSJ.js → chunk-NTOOEVJ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6XTSYPPO.js → chunk-ONADVBMD.js} +8 -6
- package/dist/cli-bundle/chunks/chunk-ONADVBMD.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-Y5IKRUEM.js → chunk-P5SUMCU5.js} +167 -65
- package/dist/cli-bundle/chunks/chunk-P5SUMCU5.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-EMXPI36L.js → chunk-PAWPLIWW.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-AGAVEDIE.js → chunk-PCBZ2VJD.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-MHNMCDWR.js → chunk-PPY3GXFK.js} +600 -96
- package/dist/cli-bundle/chunks/chunk-PPY3GXFK.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-3X542TEY.js → chunk-Q3CFSOQZ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-4BKDAEDF.js → chunk-QJZM5WO5.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-HHEWQXPD.js → chunk-QLEH6FTQ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-D2DCTFTL.js → chunk-QYZMZD4L.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-6UQCNWFV.js → chunk-RFHLRMLQ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-Q64AYQYW.js → chunk-RL24NAUX.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-QDABF2RB.js → chunk-S7J3GEHL.js} +10 -10
- package/dist/cli-bundle/chunks/{chunk-5FIQ4EX3.js → chunk-SCJPFQQT.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-42LXP4VO.js → chunk-SIQGG335.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-RY7PTTUB.js → chunk-TI7QSUFK.js} +35 -8
- package/dist/cli-bundle/chunks/chunk-TI7QSUFK.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-43SIHQND.js → chunk-TKWTJGD6.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-EOUVR7JN.js → chunk-U72GF3I2.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-FN6SB4HU.js → chunk-UEATYUZW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V5ZWKJNY.js → chunk-UFNFHCAC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-XBX5CBRQ.js → chunk-UH6VFRV6.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-GTM5HQL4.js → chunk-UIHDZS6X.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-TGUK6XN6.js → chunk-UURYLDDC.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-S5BNGFN5.js → chunk-VCGHRLJU.js} +10 -10
- package/dist/cli-bundle/chunks/{chunk-3G6UMXT3.js → chunk-W2VFNVSJ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-ZNEG2UDO.js → chunk-WDNPNW22.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-DG6BSXZ7.js → chunk-WVEMZZCR.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-TNC6MZUD.js → chunk-XXN2B2MJ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-YH5NBDFA.js → chunk-Y2736PT5.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-X47MKQXU.js → chunk-YHKXNGLA.js} +166 -64
- package/dist/cli-bundle/chunks/chunk-YHKXNGLA.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-XXIYUTLK.js → chunk-YPE5MFPJ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-XPMXPR7K.js → chunk-YSRXFGNV.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-N6ZHDLUY.js → chunk-YUMNZS3X.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-TEKZOS7M.js → chunk-Z2JQH2MG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-E3LWJUGF.js → chunk-Z6RLSNUX.js} +3 -3
- package/dist/cli-bundle/chunks/close-5WY6QO5F.js +12 -0
- package/dist/cli-bundle/chunks/{close-3YYQ5OG2.js → close-TKTFRL7N.js} +5 -5
- package/dist/cli-bundle/chunks/{close-many-D366FTIG.js → close-many-HEPL66EG.js} +13 -13
- package/dist/cli-bundle/chunks/close-many-U2KLQ3NL.js +22 -0
- package/dist/cli-bundle/chunks/{comments-54XDJNFE.js → comments-PLFK5ZKK.js} +7 -7
- package/dist/cli-bundle/chunks/comments-ZNOD5PTV.js +13 -0
- package/dist/cli-bundle/chunks/copy-F7BUFY4J.js +9 -0
- package/dist/cli-bundle/chunks/{copy-44RT5GDW.js → copy-VH3L4MN2.js} +4 -4
- package/dist/cli-bundle/chunks/create-KCQM6UYM.js +25 -0
- package/dist/cli-bundle/chunks/{create-4GWJWPXG.js → create-LD4SEUD6.js} +9 -9
- package/dist/cli-bundle/chunks/delete-6KQHZYIP.js +10 -0
- package/dist/cli-bundle/chunks/{delete-YQ2VPXNF.js → delete-ZNXUNCZR.js} +4 -4
- package/dist/cli-bundle/chunks/{deps-FMANWFRP.js → deps-CVDY7FFK.js} +4 -4
- package/dist/cli-bundle/chunks/{deps-BU5EBJDU.js → deps-SZXQHV73.js} +4 -4
- package/dist/cli-bundle/chunks/{docs-OQBSJNIA.js → docs-DR74ITCD.js} +6 -6
- package/dist/cli-bundle/chunks/docs-WCVYY6I7.js +14 -0
- package/dist/cli-bundle/chunks/{files-72HZEBOE.js → files-H5YCA74Z.js} +6 -6
- package/dist/cli-bundle/chunks/{files-HTSB2KJG.js → files-QEFQ2M3H.js} +6 -6
- package/dist/cli-bundle/chunks/{focus-FOG4ALC2.js → focus-55TRYSNA.js} +5 -5
- package/dist/cli-bundle/chunks/focus-N2QGNS5D.js +10 -0
- package/dist/cli-bundle/chunks/history-compact-GWQ4UOEI.js +21 -0
- package/dist/cli-bundle/chunks/{history-compact-M6IFAMBP.js → history-compact-JJZ4EFL3.js} +9 -9
- package/dist/cli-bundle/chunks/history-redact-4GJOLXCM.js +17 -0
- package/dist/cli-bundle/chunks/{history-redact-NQX3OGZP.js → history-redact-TPPUT3A5.js} +7 -7
- package/dist/cli-bundle/chunks/history-repair-HVCVCGUF.js +19 -0
- package/dist/cli-bundle/chunks/{history-repair-NHOJG7WO.js → history-repair-J7PIZ6ZP.js} +9 -9
- package/dist/cli-bundle/chunks/{learnings-T63JGKKN.js → learnings-KB6BT4NR.js} +7 -7
- package/dist/cli-bundle/chunks/learnings-YYY3U2Y7.js +13 -0
- package/dist/cli-bundle/chunks/notes-BGG7VL72.js +13 -0
- package/dist/cli-bundle/chunks/{notes-U7L6HQQ2.js → notes-ZTHXVOKM.js} +7 -7
- package/dist/cli-bundle/chunks/plan-B42KBMX7.js +24 -0
- package/dist/cli-bundle/chunks/{plan-TN537L24.js → plan-LUR7C24X.js} +10 -10
- package/dist/cli-bundle/chunks/{profile-TIGLAKJ7.js → profile-5F75MO5O.js} +9 -9
- package/dist/cli-bundle/chunks/{profile-MHAMXMHQ.js → profile-JRDMDGT5.js} +9 -9
- package/dist/cli-bundle/chunks/{register-list-query-ZCRABAPN.js → register-list-query-GZYRZLQZ.js} +17 -16
- package/dist/cli-bundle/chunks/register-list-query-GZYRZLQZ.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-list-query-OHXD7G5N.js → register-list-query-W2W7RQJJ.js} +16 -15
- package/dist/cli-bundle/chunks/register-list-query-W2W7RQJJ.js.map +7 -0
- package/dist/cli-bundle/chunks/{register-mutation-XX4H56PE.js → register-mutation-5UDT3WL3.js} +29 -29
- package/dist/cli-bundle/chunks/{register-mutation-P3G4XP6Q.js → register-mutation-7DMOYDPC.js} +29 -29
- package/dist/cli-bundle/chunks/{register-operations-V6VKTG54.js → register-operations-NW43IUPE.js} +29 -28
- package/dist/cli-bundle/chunks/register-operations-NW43IUPE.js.map +7 -0
- package/dist/cli-bundle/chunks/{register-operations-V6PIYEDU.js → register-operations-Y4E32W4D.js} +30 -29
- package/dist/cli-bundle/chunks/register-operations-Y4E32W4D.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-setup-6YVUSQYD.js → register-setup-3GVJ7XPE.js} +21 -19
- package/dist/cli-bundle/chunks/register-setup-3GVJ7XPE.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-setup-6RVAWT6W.js → register-setup-MPTTS52V.js} +20 -18
- package/dist/cli-bundle/chunks/register-setup-MPTTS52V.js.map +7 -0
- package/dist/cli-bundle/chunks/{restore-HC3YSWF7.js → restore-BTBEZ5CK.js} +7 -7
- package/dist/cli-bundle/chunks/restore-EX4UUZL6.js +15 -0
- package/dist/cli-bundle/chunks/{schema-DAGSYO6E.js → schema-DGSTYYQB.js} +6 -6
- package/dist/cli-bundle/chunks/{schema-UBXJCQAC.js → schema-HAIBEE24.js} +6 -6
- package/dist/cli-bundle/chunks/update-76CRUMC7.js +21 -0
- package/dist/cli-bundle/chunks/{update-LKD64AFP.js → update-ZMYVXM77.js} +12 -12
- package/dist/cli-bundle/chunks/update-many-QYQRGNPU.js +31 -0
- package/dist/cli-bundle/chunks/update-many-U4CEQWI4.js +35 -0
- package/dist/cli-bundle/main.js +39 -13
- package/dist/cli-bundle/main.js.map +2 -2
- package/dist/cli-bundle/sdk-runtime.js +149 -53
- package/dist/cli-bundle/sdk-testing.js +6 -6
- package/dist/cli-bundle/sdk.js +153 -57
- package/dist/cli-bundle/sdk.js.map +3 -3
- package/dist/core/extensions/extension-types.d.ts +1 -0
- package/dist/core/extensions/extension-types.js +2 -2
- package/dist/core/extensions/extension-types.js.map +1 -1
- package/dist/core/extensions/loader.js +268 -231
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/sdk/cli-contracts/commander-types.js +3 -3
- package/dist/sdk/cli-contracts/commander-types.js.map +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +10 -3
- package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.js +10 -5
- package/dist/sdk/cli-contracts/tool-option-contracts.js.map +1 -1
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +20 -4
- package/dist/sdk/cli-contracts/tool-parameter-tables.js.map +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +4 -0
- package/dist/sdk/cli-contracts/tool-schema.js +71 -12
- package/dist/sdk/cli-contracts/tool-schema.js.map +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +3 -3
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/runtime.d.ts +471 -25
- package/dist/sdk/runtime.js +611 -25
- package/dist/sdk/runtime.js.map +1 -1
- package/docs/AGENT_GUIDE.md +3 -0
- package/docs/COMMANDS.md +10 -1
- package/docs/EXTENSIONS.md +7 -20
- package/docs/RELEASING.md +6 -0
- package/docs/SDK.md +67 -0
- package/package.json +2 -1
- package/dist/cli-bundle/chunks/append-F7WPGIQL.js +0 -11
- package/dist/cli-bundle/chunks/chunk-2APXX4TZ.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-6LCJRGPD.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-6XTSYPPO.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-7ML7JONU.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-C5ACVMOI.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-F6YC2A6X.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-FILL6BB2.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-J2VGADNG.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-LCFJ7XAM.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-MHNMCDWR.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-RY7PTTUB.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-S547WBYG.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-TZLYO4PP.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-UO7XAZK6.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-X47MKQXU.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-XZWL7VNE.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-Y5IKRUEM.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-YCVWWIKY.js.map +0 -7
- package/dist/cli-bundle/chunks/close-Z3Q4U7TS.js +0 -12
- package/dist/cli-bundle/chunks/close-many-3L2RXH3M.js +0 -22
- package/dist/cli-bundle/chunks/comments-HGHC2PN6.js +0 -13
- package/dist/cli-bundle/chunks/copy-UGMUGHZA.js +0 -9
- package/dist/cli-bundle/chunks/create-AZXCUYKP.js +0 -25
- package/dist/cli-bundle/chunks/delete-Y6SXIQ4X.js +0 -10
- package/dist/cli-bundle/chunks/docs-VNPBZXEL.js +0 -14
- package/dist/cli-bundle/chunks/focus-SUTMKXGX.js +0 -10
- package/dist/cli-bundle/chunks/history-compact-NEXRPP2O.js +0 -21
- package/dist/cli-bundle/chunks/history-redact-WQJBZ3PX.js +0 -17
- package/dist/cli-bundle/chunks/history-repair-CBHMHAJO.js +0 -19
- package/dist/cli-bundle/chunks/learnings-M64NTSOR.js +0 -13
- package/dist/cli-bundle/chunks/notes-73WE2UV2.js +0 -13
- package/dist/cli-bundle/chunks/plan-OSCNYFGC.js +0 -24
- package/dist/cli-bundle/chunks/register-list-query-OHXD7G5N.js.map +0 -7
- package/dist/cli-bundle/chunks/register-list-query-ZCRABAPN.js.map +0 -1
- package/dist/cli-bundle/chunks/register-operations-V6PIYEDU.js.map +0 -1
- package/dist/cli-bundle/chunks/register-operations-V6VKTG54.js.map +0 -7
- package/dist/cli-bundle/chunks/register-setup-6RVAWT6W.js.map +0 -7
- package/dist/cli-bundle/chunks/register-setup-6YVUSQYD.js.map +0 -1
- package/dist/cli-bundle/chunks/restore-LFAMMRYZ.js +0 -15
- package/dist/cli-bundle/chunks/update-CJGG5WMV.js +0 -21
- package/dist/cli-bundle/chunks/update-many-G4SM7BHC.js +0 -31
- package/dist/cli-bundle/chunks/update-many-VLIV3D7R.js +0 -35
- /package/dist/cli-bundle/chunks/{append-F7WPGIQL.js.map → append-CDPAYYSB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{append-PVCTBVJG.js.map → append-RSPHC423.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-6G6O3OPQ.js.map → chunk-26MFLA7K.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-H2SMKL2N.js.map → chunk-3FUXM574.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-DR2V5OIV.js.map → chunk-3SHDAKMF.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-MRFWUSVA.js.map → chunk-3UXIMY62.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-WCWVEXGA.js.map → chunk-3V5C7PUH.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-43YSKY75.js.map → chunk-3YJDIJIE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-HX6QXV5P.js.map → chunk-4I7KS5ES.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-XHCVAZGM.js.map → chunk-4OCWJ2AP.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-3TYOW6RR.js.map → chunk-5STY7NVM.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-7VQ3JJN5.js.map → chunk-5VAZHYVQ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-4IQKDKGE.js.map → chunk-5ZMZF53A.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-MCEUKJKW.js.map → chunk-6FU5BVRB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-AJUON7E6.js.map → chunk-6RR4XM5H.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-TEISGNSH.js.map → chunk-6TD5QGIB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-565WYS5W.js.map → chunk-6WCXSC5V.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-NWWL22C7.js.map → chunk-6ZKDMEVT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-VLEA2UTQ.js.map → chunk-7QKSLAHB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-S6VC2A2K.js.map → chunk-7TBUV7XS.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-YPMZMKN7.js.map → chunk-7UCBLJDF.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-4MZOKTI2.js.map → chunk-AEOFBBWO.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-ZO7CLOY2.js.map → chunk-BFNFTHWQ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-YNCFP5AR.js.map → chunk-BPJ5NYSJ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-P3MJJW7P.js.map → chunk-C3YU3TXX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-SY75LYXR.js.map → chunk-C6XSTACC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-2TILG6F2.js.map → chunk-CGDUIPJL.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-J7BOLHAV.js.map → chunk-CXH7EMSB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-W5HXHC7C.js.map → chunk-D6J5673C.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-ARKHKYYS.js.map → chunk-DQLP22K2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-YPD7SQ5P.js.map → chunk-EEJKHF7M.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EDO7VXSO.js.map → chunk-EP2CKDS7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-SIM5JDON.js.map → chunk-F5DDGY6R.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-I74FMIWA.js.map → chunk-FFB3WITE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-43UQN754.js.map → chunk-FJR2S7S4.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-CJQM7O7R.js.map → chunk-FOJEBRDD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-E3YQFSFE.js.map → chunk-GLMJLBLR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-KTGJ2CBU.js.map → chunk-GO2X6ZRB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-DDDWVPID.js.map → chunk-GSQVQINP.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EVEPHNXJ.js.map → chunk-GZ365M6E.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-VGO73OCK.js.map → chunk-HZZ3AC27.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-7Y5N34HX.js.map → chunk-IINCZYM3.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-GLS6VMWI.js.map → chunk-INOWVPUD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-PDXJXEZJ.js.map → chunk-J6AD3GWC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-52NS7JDP.js.map → chunk-JH5XDDYS.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-GPIDUMMN.js.map → chunk-JYVPLGOW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EIUBK2LT.js.map → chunk-K52C6YPA.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-IDIBF4E2.js.map → chunk-KAJNWMBE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-2LEJGRQ7.js.map → chunk-KFL3XHMA.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-XS2TMNXR.js.map → chunk-LD2NBQ5T.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-II7R6KD4.js.map → chunk-LG4N6YOK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-M62RO3XK.js.map → chunk-LHDHS4Z6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-YTD5GICJ.js.map → chunk-MBLHA6LR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-F6MT7KKE.js.map → chunk-MCH6IKK7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-Y7KYVCZM.js.map → chunk-NGBWEYNY.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-RB3KLPAH.js.map → chunk-NRMDT4OV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-GH73UOSJ.js.map → chunk-NTOOEVJ4.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EMXPI36L.js.map → chunk-PAWPLIWW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-AGAVEDIE.js.map → chunk-PCBZ2VJD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-3X542TEY.js.map → chunk-Q3CFSOQZ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-4BKDAEDF.js.map → chunk-QJZM5WO5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-HHEWQXPD.js.map → chunk-QLEH6FTQ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-D2DCTFTL.js.map → chunk-QYZMZD4L.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-6UQCNWFV.js.map → chunk-RFHLRMLQ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-Q64AYQYW.js.map → chunk-RL24NAUX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-QDABF2RB.js.map → chunk-S7J3GEHL.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-5FIQ4EX3.js.map → chunk-SCJPFQQT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-42LXP4VO.js.map → chunk-SIQGG335.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-43SIHQND.js.map → chunk-TKWTJGD6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EOUVR7JN.js.map → chunk-U72GF3I2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-FN6SB4HU.js.map → chunk-UEATYUZW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-V5ZWKJNY.js.map → chunk-UFNFHCAC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-XBX5CBRQ.js.map → chunk-UH6VFRV6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-GTM5HQL4.js.map → chunk-UIHDZS6X.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-TGUK6XN6.js.map → chunk-UURYLDDC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-S5BNGFN5.js.map → chunk-VCGHRLJU.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-3G6UMXT3.js.map → chunk-W2VFNVSJ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-ZNEG2UDO.js.map → chunk-WDNPNW22.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-DG6BSXZ7.js.map → chunk-WVEMZZCR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-TNC6MZUD.js.map → chunk-XXN2B2MJ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-YH5NBDFA.js.map → chunk-Y2736PT5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-XXIYUTLK.js.map → chunk-YPE5MFPJ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-XPMXPR7K.js.map → chunk-YSRXFGNV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-N6ZHDLUY.js.map → chunk-YUMNZS3X.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-TEKZOS7M.js.map → chunk-Z2JQH2MG.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-E3LWJUGF.js.map → chunk-Z6RLSNUX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-Z3Q4U7TS.js.map → close-5WY6QO5F.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-3YYQ5OG2.js.map → close-TKTFRL7N.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-many-D366FTIG.js.map → close-many-HEPL66EG.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-many-3L2RXH3M.js.map → close-many-U2KLQ3NL.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{comments-54XDJNFE.js.map → comments-PLFK5ZKK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{comments-HGHC2PN6.js.map → comments-ZNOD5PTV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{copy-UGMUGHZA.js.map → copy-F7BUFY4J.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{copy-44RT5GDW.js.map → copy-VH3L4MN2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{create-AZXCUYKP.js.map → create-KCQM6UYM.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{create-4GWJWPXG.js.map → create-LD4SEUD6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{delete-Y6SXIQ4X.js.map → delete-6KQHZYIP.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{delete-YQ2VPXNF.js.map → delete-ZNXUNCZR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{deps-FMANWFRP.js.map → deps-CVDY7FFK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{deps-BU5EBJDU.js.map → deps-SZXQHV73.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{docs-OQBSJNIA.js.map → docs-DR74ITCD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{docs-VNPBZXEL.js.map → docs-WCVYY6I7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{files-72HZEBOE.js.map → files-H5YCA74Z.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{files-HTSB2KJG.js.map → files-QEFQ2M3H.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{focus-FOG4ALC2.js.map → focus-55TRYSNA.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{focus-SUTMKXGX.js.map → focus-N2QGNS5D.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-compact-NEXRPP2O.js.map → history-compact-GWQ4UOEI.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-compact-M6IFAMBP.js.map → history-compact-JJZ4EFL3.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-redact-WQJBZ3PX.js.map → history-redact-4GJOLXCM.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-redact-NQX3OGZP.js.map → history-redact-TPPUT3A5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-repair-CBHMHAJO.js.map → history-repair-HVCVCGUF.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-repair-NHOJG7WO.js.map → history-repair-J7PIZ6ZP.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{learnings-T63JGKKN.js.map → learnings-KB6BT4NR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{learnings-M64NTSOR.js.map → learnings-YYY3U2Y7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{notes-73WE2UV2.js.map → notes-BGG7VL72.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{notes-U7L6HQQ2.js.map → notes-ZTHXVOKM.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{plan-OSCNYFGC.js.map → plan-B42KBMX7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{plan-TN537L24.js.map → plan-LUR7C24X.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{profile-TIGLAKJ7.js.map → profile-5F75MO5O.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{profile-MHAMXMHQ.js.map → profile-JRDMDGT5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{register-mutation-XX4H56PE.js.map → register-mutation-5UDT3WL3.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{register-mutation-P3G4XP6Q.js.map → register-mutation-7DMOYDPC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{restore-HC3YSWF7.js.map → restore-BTBEZ5CK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{restore-LFAMMRYZ.js.map → restore-EX4UUZL6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{schema-DAGSYO6E.js.map → schema-DGSTYYQB.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{schema-UBXJCQAC.js.map → schema-HAIBEE24.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-CJGG5WMV.js.map → update-76CRUMC7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-LKD64AFP.js.map → update-ZMYVXM77.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-many-G4SM7BHC.js.map → update-many-QYQRGNPU.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-many-VLIV3D7R.js.map → update-many-U4CEQWI4.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../../../../../sdk/start-task-status.ts", "../../../../../../../../cli/commands/claim.ts", "../../../../../../../../mcp/tool-definitions.ts", "../../../../../../../../cli/commands/contracts.ts", "../../../../../../../../cli/commands/gc.ts", "../../../../../../../../core/checkpoint/checkpoint-gc.ts", "../../../../../../../../core/lock/lock-gc.ts", "../../../../../../../../cli/commands/health.ts", "../../../../../../../../core/diagnostics/remediation.ts", "../../../../../../../../cli/commands/scheduling-shortcuts.ts", "../../../../../../../../cli/commands/stats.ts", "../../../../../../../../core/history/history-storage-stats.ts", "../../../../../../../../cli/commands/telemetry.ts", "../../../../../../../../cli/commands/test.ts", "../../../../../../../../core/test/item-test-run-tracking.ts", "../../../../../../../../core/test/run-selectors.ts", "../../../../../../../../cli/commands/test/linked-command-detection.ts", "../../../../../../../../cli/commands/test-all.ts", "../../../../../../../../cli/commands/test-runs.ts", "../../../../../../../../core/test/background-runs.ts", "../../../../../../../../cli/commands/validate.ts", "../../../../../../../../core/validate/fix-planning.ts", "../../../../../../../../core/governance/issue-codes.ts", "../../../../../../../../core/validate/missing-by-type.ts", "../../../../../../../../core/validate/stale-file-classification.ts", "../../../../../../../../core/validate/missing-link-owners.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @module sdk/start-task-status\n *\n * Resolves lifecycle alias status transitions shared by CLI registration and the SDK runtime.\n */\nimport {\n normalizeStatusInputWithRegistry,\n type RuntimeStatusRegistry,\n} from \"../core/schema/runtime-schema.js\";\n\n/**\n * Resolve the status the `start-task` lifecycle alias should move an item to.\n * Resolves `in_progress` strictly through the workspace registry so a custom\n * workflow that omits in_progress falls back to its open status instead of\n * setting a status the workflow does not define.\n */\nexport function resolveStartTaskInProgressStatus(statusRegistry: RuntimeStatusRegistry): string {\n return normalizeStatusInputWithRegistry(\"in_progress\", statusRegistry) ?? statusRegistry.open_status;\n}\n", "/**\n * @module cli/commands/claim\n *\n * Implements the pm claim command surface and its agent-facing runtime behavior.\n */\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { resolveRuntimeStatusRegistry, statusIsTerminal } from \"../../core/schema/runtime-schema.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { toItemRecord } from \"../../core/item/item-record.js\";\nimport { mutateItem } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { resolveAuthor } from \"../../core/shared/author.js\";\nimport { wrapOwnershipConflict } from \"./annotation-command.js\";\n\n/**\n * Documents the claim result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ClaimResult {\n item: Record<string, unknown>;\n claimed_by: string;\n previous_assignee: string | null;\n forced: boolean;\n skipped?: boolean;\n warnings?: string[];\n}\n\n/**\n * Documents the release result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ReleaseResult {\n item: Record<string, unknown>;\n released_by: string;\n previous_assignee: string | null;\n audit_release: boolean;\n forced: boolean;\n}\n\n/**\n * Documents the claim mutation options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ClaimMutationOptions {\n author?: string;\n message?: string;\n ifAvailable?: boolean;\n}\n\n/**\n * Documents the release mutation options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ReleaseMutationOptions extends ClaimMutationOptions {\n allowAuditRelease?: boolean;\n}\n\n/**\n * Implements run claim for the public runtime surface of this module.\n */\nexport async function runClaim(\n id: string,\n force: boolean,\n global: GlobalOptions,\n options: ClaimMutationOptions = {},\n): Promise<ClaimResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n const settings = await readSettings(pmRoot);\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const author = resolveAuthor(options.author, settings.author_default);\n let previousAssignee: string | null = null;\n let skipped = false;\n const mutationWarnings: string[] = [];\n\n const result = await mutateItem({\n pmRoot,\n settings,\n id,\n op: \"claim\",\n author,\n message: options.message,\n force,\n skipNoop: true,\n mutate(document) {\n const currentAssignee = document.metadata.assignee;\n const currentAssigneeText = typeof currentAssignee === \"string\" ? currentAssignee : \"\";\n previousAssignee = currentAssigneeText.trim().length > 0 ? currentAssigneeText : null;\n if (statusIsTerminal(document.metadata.status, statusRegistry) && !force) {\n throw new PmCliError(`Cannot claim terminal item ${document.metadata.id} without --force`, EXIT_CODE.CONFLICT);\n }\n const heldByOther = previousAssignee !== null && previousAssignee !== author;\n if (heldByOther && options.ifAvailable === true) {\n skipped = true;\n mutationWarnings.push(`claim_skipped_held_by:${previousAssignee}`);\n return { changedFields: [] };\n }\n if (heldByOther && !force) {\n throw new PmCliError(\n `Item ${document.metadata.id} is already claimed by ${previousAssignee}. Use --force to take over, or --if-available to skip without failing.`,\n EXIT_CODE.CONFLICT,\n {\n code: \"already_claimed_by\",\n why: \"Claim is an atomic test-and-set so parallel agents never proceed believing they own the same item.\",\n nextSteps: [\n \"Run pm next to pick a different unclaimed item.\",\n \"Re-run with --if-available to treat a held item as a no-op skip.\",\n \"Re-run with --force only when taking over the item is coordinated.\",\n ],\n },\n );\n }\n if (heldByOther) {\n mutationWarnings.push(`claim_takeover:${previousAssignee}->${author}`);\n }\n document.metadata.assignee = author;\n return { changedFields: [\"assignee\"], warnings: mutationWarnings };\n },\n });\n\n return {\n item: toItemRecord(result.item),\n claimed_by: skipped && previousAssignee !== null ? previousAssignee : author,\n previous_assignee: previousAssignee,\n forced: force,\n ...(skipped ? { skipped: true } : {}),\n ...(mutationWarnings.length > 0 ? { warnings: mutationWarnings } : {}),\n };\n}\n\n/**\n * Implements run release for the public runtime surface of this module.\n */\nexport async function runRelease(\n id: string,\n force: boolean,\n global: GlobalOptions,\n options: ReleaseMutationOptions = {},\n): Promise<ReleaseResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n const settings = await readSettings(pmRoot);\n const author = resolveAuthor(options.author, settings.author_default);\n let previousAssignee: string | null = null;\n\n let result: Awaited<ReturnType<typeof mutateItem>>;\n try {\n result = await mutateItem({\n pmRoot,\n settings,\n id,\n op: \"release\",\n author,\n message: options.message,\n force,\n bypassAssigneeConflict: Boolean(options.allowAuditRelease),\n mutate(document) {\n previousAssignee = document.metadata.assignee ?? null;\n if (!previousAssignee) {\n return { changedFields: [] };\n }\n delete document.metadata.assignee;\n return { changedFields: [\"assignee\"] };\n },\n });\n } catch (error: unknown) {\n wrapOwnershipConflict(error, {\n required: \"For audited non-owner handoffs, prefer --allow-audit-release before considering --force.\",\n examples: ['pm release pm-a1b2 --author \"reviewer\" --allow-audit-release'],\n nextSteps: [\n \"Use --allow-audit-release for append-only release handoffs that only clear assignee metadata.\",\n \"Use --force only when an explicit override is approved for broader ownership conflicts.\",\n ],\n });\n }\n\n return {\n item: toItemRecord(result.item),\n released_by: author,\n previous_assignee: previousAssignee,\n audit_release: options.allowAuditRelease === true,\n forced: force,\n };\n}\n", "/**\n * @module mcp/tool-definitions\n *\n * Defines the Tool Definitions module for pm CLI source.\n */\nimport { PM_TOOL_ACTIONS } from \"../sdk/cli-contracts/enum-contracts.js\";\nimport { RUNTIME_STATUS_ROLE_VALUES } from \"../types.js\";\n\n/**\n * Static MCP tool surface for the pm MCP server.\n *\n * Kept as a dependency-light data module (only the enum contract import) so the\n * `pm contracts` command can snapshot the tool surface into the contract\n * golden file (pm-4os2) without importing the full MCP server runtime, and so\n * the server itself stays the single consumer of the dispatch handlers.\n */\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nconst TOOL_SCHEMA_BASE = {\n type: \"object\",\n properties: {\n cwd: {\n type: \"string\",\n description: \"Workspace directory to run the native pm operation in. Defaults to the MCP server process cwd.\",\n },\n path: {\n type: \"string\",\n description: \"Optional pm data root, equivalent to PM_PATH/global --path. Leave unset for real repository tracking.\",\n },\n author: {\n type: \"string\",\n description: \"Mutation author. Defaults to PM_AUTHOR or pm settings when supported by the underlying operation.\",\n },\n },\n additionalProperties: true,\n} as const;\n\nconst idSchema = {\n type: \"string\",\n description: \"pm item id, for example pm-abc1.\",\n};\n\n// pm-fd8n: derive the pm_run action enumeration from the canonical\n// PM_TOOL_ACTIONS contract instead of a hand-maintained prose list, so the\n// MCP-facing description can never drift from the actual supported actions.\nconst PM_RUN_ACTION_DESCRIPTION =\n `Operation name (one of): ${PM_TOOL_ACTIONS.join(\", \")}. ` +\n \"Package-owned actions (for example calendar/templates/guide/dedupe-audit/normalize/reindex/comments-audit/completion/test-runs-list/test-runs-status/test-runs-logs/test-runs-stop/test-runs-resume) are available dynamically when installed.\";\n\nconst LIST_TOP_LEVEL_OPTION_PROPERTIES: Record<string, unknown> = {\n status: { type: \"string\", description: \"Alias for options.status.\" },\n type: { type: \"string\", description: \"Alias for options.type.\" },\n tag: { type: \"string\", description: \"Alias for options.tag.\" },\n priority: { type: \"string\", description: \"Alias for options.priority.\" },\n limit: { type: [\"string\", \"number\"], description: \"Alias for options.limit.\" },\n offset: { type: [\"string\", \"number\"], description: \"Alias for options.offset.\" },\n};\n\nconst SEARCH_TOP_LEVEL_OPTION_PROPERTIES: Record<string, unknown> = {\n mode: { type: \"string\", description: \"Alias for options.mode.\" },\n status: { type: \"string\", description: \"Alias for options.status.\" },\n type: { type: \"string\", description: \"Alias for options.type.\" },\n tag: { type: \"string\", description: \"Alias for options.tag.\" },\n priority: { type: \"string\", description: \"Alias for options.priority.\" },\n limit: { type: [\"string\", \"number\"], description: \"Alias for options.limit.\" },\n};\n\nfunction objectSchema(properties: Record<string, unknown>, required: string[] = []): Record<string, unknown> {\n return {\n ...TOOL_SCHEMA_BASE,\n properties: {\n ...TOOL_SCHEMA_BASE.properties,\n ...properties,\n },\n required,\n };\n}\n\nexport const TOOLS: ToolDefinition[] = [\n {\n name: \"pm_run\",\n description:\n \"Run any supported pm operation natively through the pm library. Use this for commands not covered by narrower pm_* tools.\",\n inputSchema: objectSchema(\n {\n action: {\n type: \"string\",\n description: PM_RUN_ACTION_DESCRIPTION,\n },\n id: idSchema,\n query: { type: \"string\", description: \"Search query for action=search.\" },\n reason: { type: \"string\", description: \"Close reason for action=close.\" },\n force: { type: \"boolean\", description: \"Force ownership/terminal-state override when supported.\" },\n // pm-v68d: the schema-specific subcommand enum and add-type/add-status\n // properties migrated to the dedicated pm_schema tool. action=schema\n // still accepts them as passthrough, but agents should prefer pm_schema.\n subcommand: {\n type: \"string\",\n description:\n \"Subcommand selector for actions that take one (for example telemetry, or schema — prefer the dedicated pm_schema tool for schema operations).\",\n },\n options: { type: \"object\", description: \"Underlying pm command options using camelCase keys.\" },\n fullChangedFields: {\n type: \"boolean\",\n description:\n \"For mutation actions, return the full changed_fields array instead of the default changed_field_count.\",\n },\n idOnly: {\n type: \"boolean\",\n description: \"For single-item mutation actions, return only id and status.\",\n },\n },\n [\"action\"],\n ),\n },\n {\n name: \"pm_context\",\n description:\n \"Return the agent-oriented project context snapshot. \" +\n \"Pass options.depth=brief|standard|deep|full (full = every section with no per-section row cap), \" +\n \"options.parent='<id>' to scope the snapshot to one item's subtree (the item plus all descendants), \" +\n \"options.fields='id,title,priority' to project focus rows to a field subset for low-token reads, \" +\n \"or options.section=['hierarchy','progress',...] to pick sections.\",\n inputSchema: objectSchema({ options: { type: \"object\" } }),\n },\n {\n name: \"pm_next\",\n description:\n \"Recommend the next actionable work item: the single highest-priority READY item \" +\n \"(active status, no open blockers, no open children; completed containers surface only when no concrete leaf work is ready) plus the ranked ready and blocked queues. \" +\n \"The recommended item carries a rationale and each blocked item lists the open blockers gating it. \" +\n \"Pass options.parent='<id>' to scope to one subtree, options.limit=N to cap ready rows, \" +\n \"options.readyOnly=true to omit the blocked list, or filters (options.type/tag/priority/assignee/sprint/release). \" +\n \"The most token-efficient 'what should I do now?' read for agents.\",\n inputSchema: objectSchema({ options: { type: \"object\" } }),\n },\n {\n name: \"pm_search\",\n description:\n \"Search pm items with keyword, semantic, or hybrid search. \" +\n \"Defaults to a compact projection for token efficiency. \" +\n \"Pass options.mode=keyword|semantic|hybrid, options.limit=N to cap hits, \" +\n \"options.status='all' for no lifecycle restriction, \" +\n \"options.fields='id,title,score' for a custom projection, or options.full=true for full item bodies (can be large). \" +\n \"The result echoes the applied filters and projection mode in query_summary.\",\n inputSchema: objectSchema({ query: { type: \"string\" }, options: { type: \"object\" }, ...SEARCH_TOP_LEVEL_OPTION_PROPERTIES }, [\"query\"]),\n },\n {\n name: \"pm_list\",\n description:\n \"List pm items with status/type/tag/priority filters. Defaults to compact projection for token efficiency. \" +\n \"options.status accepts CSV (all,open,in_progress). \" +\n \"Pass options.compact=false or options.includeBody=true for full bodies/comments. \" +\n \"Pass options.brief=true for ultra-terse (id/status/type/title only). \" +\n \"Pass options.fields='id,title,priority' for custom projection. \" +\n \"Pass options.limit=N to cap row count. \" +\n \"The result echoes the applied filters and projection mode in query_summary.\",\n inputSchema: objectSchema({ options: { type: \"object\" }, ...LIST_TOP_LEVEL_OPTION_PROPERTIES }),\n },\n {\n name: \"pm_get\",\n description:\n \"Read one pm item. Pass options.depth='brief' or options.fields='id,title,status' for low-token inspection.\",\n inputSchema: objectSchema({\n id: idSchema,\n options: { type: \"object\", description: \"Get options such as depth=brief|standard|deep|full or fields=id,title,status.\" },\n }, [\"id\"]),\n },\n {\n name: \"pm_create\",\n description:\n \"Create a pm item natively and write pm history. \" +\n \"Output is compact by default (changed_fields replaced with changed_field_count for token efficiency); pass fullChangedFields=true for the full changed_fields array.\",\n inputSchema: objectSchema(\n {\n fullChangedFields: { type: \"boolean\", description: \"Return full changed_fields instead of changed_field_count.\" },\n allowMissingParent: { type: \"boolean\", description: \"Allow unresolved parent references and emit a validation warning.\" },\n options: { type: \"object\", description: \"Create options. title and description are required.\" },\n },\n [\"options\"],\n ),\n },\n {\n name: \"pm_copy\",\n description:\n \"Copy an existing pm item into a new id while resetting lifecycle fields. \" +\n \"Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.\",\n inputSchema: objectSchema(\n {\n id: idSchema,\n fullChangedFields: { type: \"boolean\", description: \"Return full changed_fields instead of changed_field_count.\" },\n options: { type: \"object\", description: \"Copy options such as title override, author, and message.\" },\n },\n [\"id\"],\n ),\n },\n {\n name: \"pm_focus\",\n description:\n \"Set, clear, or show the session focused item. When focused, pm_create defaults its parent to the focused item \" +\n \"(an explicit parent still overrides). Pass id to focus an item, options.clear=true to clear, or neither to show current focus.\",\n inputSchema: objectSchema(\n {\n id: idSchema,\n clear: { type: \"boolean\", description: \"Clear the focused item (cannot be combined with id).\" },\n options: { type: \"object\", description: \"Focus options such as clear (boolean).\" },\n },\n [],\n ),\n },\n {\n name: \"pm_update\",\n description:\n \"Update pm item metadata/body/dependencies/log seeds natively. \" +\n \"Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields delta.\",\n inputSchema: objectSchema(\n {\n id: idSchema,\n fullChangedFields: { type: \"boolean\", description: \"Return full changed_fields instead of changed_field_count.\" },\n options: { type: \"object\" },\n },\n [\"id\", \"options\"],\n ),\n },\n {\n name: \"pm_append\",\n description:\n \"Append markdown text to a pm item body and write pm history. Useful for seeding evidence/log entries before close. \" +\n \"Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.\",\n inputSchema: objectSchema(\n {\n id: idSchema,\n body: {\n type: \"string\",\n description: \"Markdown text to append to the item body. Required here or as options.body.\",\n },\n fullChangedFields: { type: \"boolean\", description: \"Return full changed_fields instead of changed_field_count.\" },\n options: { type: \"object\", description: \"Append options such as body, author, and message.\" },\n },\n [\"id\"],\n ),\n },\n {\n name: \"pm_claim\",\n description: \"Claim a pm item.\",\n inputSchema: objectSchema({ id: idSchema, force: { type: \"boolean\" }, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_release\",\n description: \"Release a pm item claim.\",\n inputSchema: objectSchema({ id: idSchema, force: { type: \"boolean\" }, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_close\",\n description:\n \"Close a pm item with optional close reason and optional close validation (reason requirement follows governance settings). \" +\n \"Output is compact by default (changed_fields replaced with changed_field_count); pass fullChangedFields=true for the full changed_fields array.\",\n inputSchema: objectSchema(\n {\n id: idSchema,\n reason: { type: \"string\", description: \"Close reason text when provided or required by governance settings.\" },\n duplicateOf: { type: \"string\", description: \"Canonical item id when closing this item as a duplicate.\" },\n fullChangedFields: { type: \"boolean\", description: \"Return full changed_fields instead of changed_field_count.\" },\n idOnly: { type: \"boolean\", description: \"Return only id and status.\" },\n options: { type: \"object\" },\n },\n [\"id\"],\n ),\n },\n {\n name: \"pm_comments\",\n description:\n \"List, add, edit, or delete comments on a pm item. Use options.add to append, options.edit=<1-based index> with replacement text to fix a comment, or options.delete=<1-based index> to remove one. \" +\n \"List calls default to the most recent 20 comments with total_count/has_more metadata for token efficiency. \" +\n \"Pass options.limit=N to choose a page size, options.limit=0 for summary-only metadata, or options.full=true for full history.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_files\",\n description: \"List, add, remove, audit, or validate linked files for a pm item.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_docs\",\n description: \"List, add, or remove linked docs for a pm item.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_notes\",\n description:\n \"List or add structured notes on a pm item. Use options.add to append a note; omit it to list existing notes.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_learnings\",\n description:\n \"List or add learnings on a pm item. Use options.add to capture a learning/insight; omit it to list existing learnings.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_deps\",\n description:\n \"List, add, or remove dependencies for a pm item. Use options.add to declare a dependency and options.remove to drop one; omit both to list current dependencies.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_test\",\n description: \"List, add, remove, or run linked tests for a pm item.\",\n inputSchema: objectSchema({ id: idSchema, options: { type: \"object\" } }, [\"id\"]),\n },\n {\n name: \"pm_validate\",\n description: \"Run pm validation checks.\",\n inputSchema: objectSchema({ options: { type: \"object\" } }),\n },\n {\n name: \"pm_health\",\n description: \"Run pm health diagnostics. Pass options.brief=true for compact low-token details, options.skipIntegrity=true, options.skipDrift=true, options.skipVectors=true for a fast status-only check, or options.full=true for the complete deep check.\",\n inputSchema: objectSchema({ options: { type: \"object\" } }),\n },\n {\n name: \"pm_contracts\",\n description: \"Inspect pm command, flag, schema, and availability contracts.\",\n inputSchema: objectSchema({ options: { type: \"object\" } }),\n },\n {\n name: \"pm_schema\",\n description:\n \"Inspect or modify the workspace item-type/status/field schema (pm schema). \" +\n \"subcommand selects the operation; name carries the item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or field key (show-field/add-field/remove-field). \" +\n \"apply-preset adopts a domain type preset; add-type with infer=true derives types from title-prefix conventions. \" +\n \"Schema mutations write workspace config files, not item history.\",\n inputSchema: objectSchema(\n {\n subcommand: {\n type: \"string\",\n enum: [\n \"list\",\n \"show\",\n \"show-status\",\n \"add-type\",\n \"remove-type\",\n \"add-status\",\n \"remove-status\",\n \"add-field\",\n \"remove-field\",\n \"list-fields\",\n \"show-field\",\n \"apply-preset\",\n ],\n description: \"Schema subcommand to run.\",\n },\n name: {\n type: \"string\",\n description:\n \"Item type name (show/add-type/remove-type), status id (show-status/add-status/remove-status), or custom field key (show-field/add-field/remove-field). Required for those subcommands.\",\n },\n description: {\n type: \"string\",\n description: \"Custom item type, status, or field description for add-type/add-status/add-field.\",\n },\n defaultStatus: { type: \"string\", description: \"Default status for add-type.\" },\n folder: { type: \"string\", description: \"Storage folder for add-type.\" },\n alias: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Aliases for add-type/add-status, or extra CLI flag aliases for add-field.\",\n },\n role: {\n type: \"array\",\n items: { type: \"string\", enum: [...RUNTIME_STATUS_ROLE_VALUES] },\n description: `Lifecycle roles for add-status: ${RUNTIME_STATUS_ROLE_VALUES.join(\", \")}.`,\n },\n order: { type: \"number\", description: \"Display/sort order for add-status.\" },\n fieldType: {\n type: \"string\",\n enum: [\"string\", \"number\", \"boolean\", \"string_array\"],\n description: \"Value type for a custom field (add-field).\",\n },\n commands: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Commands a custom field is wired onto (add-field): create, update, update_many, list, search, calendar, context.\",\n },\n cliFlag: { type: \"string\", description: \"Override the auto-derived CLI flag for a custom field (add-field).\" },\n required: { type: \"boolean\", description: \"Mark a custom field as always required (add-field).\" },\n requiredOnCreate: { type: \"boolean\", description: \"Mark a custom field as required at create time (add-field).\" },\n allowUnset: { type: \"boolean\", description: \"Whether a custom field may be cleared via --unset (add-field); defaults to true.\" },\n requiredTypes: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Restrict a custom field's requirement to specific item types (add-field).\",\n },\n typePreset: {\n type: \"string\",\n enum: [\"agile\", \"ops\", \"research\"],\n description: \"Domain type preset to adopt (apply-preset).\",\n },\n infer: { type: \"boolean\", description: \"Infer item types from title-prefix conventions (add-type); previews unless apply is true.\" },\n minCount: { type: \"number\", description: \"Minimum items sharing a prefix for add-type inference (default 10).\" },\n apply: { type: \"boolean\", description: \"Register inferred types (add-type infer); without it the call previews only.\" },\n force: { type: \"boolean\", description: \"Override removal guardrails for destructive schema changes when supported.\" },\n options: { type: \"object\", description: \"Additional schema options using camelCase keys.\" },\n },\n [\"subcommand\"],\n ),\n },\n {\n name: \"pm_profile\",\n description:\n \"List, show, apply, or lint project profiles (pm profile) — archetype bundles that stage item types, statuses, fields, per-type workflows, config knobs, create templates, and recommended packages. \" +\n \"subcommand selects the operation; name carries the profile name (agile, ops, research) for show/apply/lint. \" +\n \"apply stages every dimension idempotently; dryRun previews the diff without writing; lint reports author-time consistency findings (graded error/warning) without touching the tracker. Profile staging writes workspace config/schema files, not item history.\",\n inputSchema: objectSchema(\n {\n subcommand: {\n type: \"string\",\n enum: [\"list\", \"show\", \"apply\", \"lint\"],\n description: \"Profile subcommand to run.\",\n },\n name: {\n type: \"string\",\n description:\n \"Profile name for show/apply/lint. Required for those subcommands. Built-ins are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.\",\n },\n dryRun: { type: \"boolean\", description: \"Preview the apply diff without writing any files (apply).\" },\n author: { type: \"string\", description: \"Mutation author for apply.\" },\n force: { type: \"boolean\", description: \"Force ownership/lock override for apply.\" },\n options: { type: \"object\", description: \"Additional profile options using camelCase keys.\" },\n },\n [\"subcommand\"],\n ),\n },\n {\n name: \"pm_config\",\n description:\n \"Read or write pm workspace configuration (pm config). \" +\n \"configAction selects get/set/list/export; key/value address a single setting for get/set. \" +\n \"scope chooses the project (default) or global settings file.\",\n inputSchema: objectSchema(\n {\n configAction: {\n type: \"string\",\n enum: [\"get\", \"set\", \"list\", \"export\"],\n description: \"Config operation to perform. get/set require key; list/export dump the resolved settings surface.\",\n },\n key: {\n type: \"string\",\n description:\n \"Settings key for get/set, for example governance-require-close-reason, telemetry-tracking, or a nested leaf such as search_provider (dash and underscore variants accepted; configAction=get without a key lists supported keys in the error).\",\n },\n value: { type: \"string\", description: \"New value for configAction=set.\" },\n scope: {\n type: \"string\",\n enum: [\"project\", \"global\"],\n description: \"Settings scope to read or write. Defaults to project.\",\n },\n options: {\n type: \"object\",\n description: \"Additional config options such as criterion, clearCriteria, format, or policy.\",\n },\n },\n [\"configAction\"],\n ),\n },\n {\n name: \"pm_plan\",\n description:\n \"Run agent-optimized Plan workflows. options.subcommand selects: create|show|add-step|update-step|complete-step|block-step|reorder-step|remove-step|link|unlink|decision|discovery|validation|resume|approve|materialize. Provide id for all non-create subcommands; provide stepRef for step lifecycle subcommands. Plans store agent-readable steps with dependencies, decisions, discoveries, validation, and resume context.\",\n inputSchema: objectSchema({\n id: { type: \"string\", description: \"Plan id (required for all subcommands except create).\" },\n stepRef: { type: \"string\", description: \"Step id or order for step lifecycle subcommands.\" },\n reorderTo: { type: \"number\", description: \"New order for reorder-step.\" },\n options: { type: \"object\", description: \"Plan options including subcommand, stepRef, stepStatus, link, depth, etc.\" },\n }),\n },\n];\n\n/**\n * Stable projection of one MCP tool definition for the contract golden file\n * (pm-4os2): tool name, description, required top-level fields, and the full\n * inputSchema shape. Any drift (typo'd property, dropped required field,\n * changed TOOL_SCHEMA_BASE) shows up in `pnpm contracts:check`.\n */\nexport interface McpToolContract {\n name: string;\n description: string;\n required: string[];\n input_schema: Record<string, unknown>;\n}\n\n/**\n * Implements build mcp tool contracts for the public runtime surface of this module.\n */\nexport function buildMcpToolContracts(): McpToolContract[] {\n return TOOLS.map((tool) => {\n const schemaRequired = tool.inputSchema[\"required\"];\n const required = Array.isArray(schemaRequired)\n ? schemaRequired.map((entry) => String(entry)).sort((left, right) => left.localeCompare(right))\n : [];\n return {\n name: tool.name,\n description: tool.description,\n required,\n input_schema: tool.inputSchema,\n };\n }).sort((left, right) => left.name.localeCompare(right.name));\n}\n", "/**\n * @module cli/commands/contracts\n *\n * Implements the pm contracts command surface and its agent-facing runtime behavior.\n */\nimport { EXIT_CODE, SETTINGS_DEFAULTS } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport {\n activateExtensions,\n getActiveExtensionRegistrations,\n loadExtensions,\n} from \"../../core/extensions/index.js\";\nimport type {\n ExtensionRegistrationRegistry,\n RegisteredExtensionCommandDefinition,\n RegisteredExtensionFlagDefinitions,\n} from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport {\n commandOptionFlagLabel,\n resolveCommandOptionPolicyState,\n resolveItemTypeRegistry,\n} from \"../../core/item/type-registry.js\";\nimport {\n resolveRuntimeFieldRegistry,\n resolveRuntimeStatusRegistry,\n type RuntimeFieldRegistry,\n} from \"../../core/schema/runtime-schema.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { buildMcpToolContracts, type McpToolContract } from \"../../mcp/tool-definitions.js\";\nimport {\n ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,\n ACTIVITY_FLAG_CONTRACTS,\n AGGREGATE_FLAG_CONTRACTS,\n APPEND_FLAG_CONTRACTS,\n CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,\n CALENDAR_FLAG_CONTRACTS,\n CLAIM_FLAG_CONTRACTS,\n CLOSE_TASK_FLAG_CONTRACTS,\n COMMENTS_FLAG_CONTRACTS,\n COMMENTS_AUDIT_FLAG_CONTRACTS,\n CLOSE_FLAG_CONTRACTS,\n CLOSE_MANY_FLAG_CONTRACTS,\n COMPLETION_FLAG_CONTRACTS,\n CONFIG_FLAG_CONTRACTS,\n CONTRACTS_FLAG_CONTRACTS,\n CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,\n CONTEXT_FLAG_CONTRACTS,\n CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,\n CREATE_COMMANDER_STRING_OPTION_CONTRACTS,\n CREATE_FLAG_CONTRACTS,\n DELETE_FLAG_CONTRACTS,\n DEPS_FLAG_CONTRACTS,\n DEDUPE_AUDIT_FLAG_CONTRACTS,\n DEDUPE_MERGE_FLAG_CONTRACTS,\n DOCS_FLAG_CONTRACTS,\n EXTENSION_ACTIVATE_FLAG_CONTRACTS,\n EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,\n EXTENSION_ADOPT_FLAG_CONTRACTS,\n EXTENSION_CATALOG_FLAG_CONTRACTS,\n EXTENSION_DEACTIVATE_FLAG_CONTRACTS,\n EXTENSION_DESCRIBE_FLAG_CONTRACTS,\n EXTENSION_DOCTOR_FLAG_CONTRACTS,\n EXTENSION_EXPLORE_FLAG_CONTRACTS,\n EXTENSION_FLAG_CONTRACTS,\n EXTENSION_INIT_FLAG_CONTRACTS,\n EXTENSION_INSTALL_FLAG_CONTRACTS,\n EXTENSION_MANAGE_FLAG_CONTRACTS,\n EXTENSION_RELOAD_FLAG_CONTRACTS,\n EXTENSION_UNINSTALL_FLAG_CONTRACTS,\n FILES_FLAG_CONTRACTS,\n GC_FLAG_CONTRACTS,\n GET_FLAG_CONTRACTS,\n GUIDE_FLAG_CONTRACTS,\n GLOBAL_FLAG_CONTRACTS,\n HEALTH_FLAG_CONTRACTS,\n HISTORY_FLAG_CONTRACTS,\n HISTORY_COMPACT_FLAG_CONTRACTS,\n HISTORY_REDACT_FLAG_CONTRACTS,\n HISTORY_REPAIR_FLAG_CONTRACTS,\n INSTALL_FLAG_CONTRACTS,\n INIT_FLAG_CONTRACTS,\n LEARNINGS_FLAG_CONTRACTS,\n LIST_COMMANDER_STRING_OPTION_CONTRACTS,\n LIST_FILTER_FLAG_CONTRACTS,\n NORMALIZE_FLAG_CONTRACTS,\n NOTES_FLAG_CONTRACTS,\n PACKAGE_FLAG_CONTRACTS,\n PACKAGE_INIT_FLAG_CONTRACTS,\n PM_EXTENSION_CAPABILITY_CONTRACTS,\n PM_EXTENSION_POLICY_MODE_CONTRACTS,\n PM_EXTENSION_POLICY_SURFACE_CONTRACTS,\n PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,\n PM_EXTENSION_SERVICE_NAME_CONTRACTS,\n PM_EXTENSION_TRUST_MODE_CONTRACTS,\n PLAN_FLAG_CONTRACTS,\n PM_CORE_COMMAND_NAMES,\n PM_TOOL_ACTIONS,\n PM_TOOL_PARAMETERS_SCHEMA,\n REINDEX_FLAG_CONTRACTS,\n RELEASE_FLAG_CONTRACTS,\n RESTORE_FLAG_CONTRACTS,\n SCHEMA_FLAG_CONTRACTS,\n PROFILE_FLAG_CONTRACTS,\n SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,\n EVAL_FLAG_CONTRACTS,\n NEXT_FLAG_CONTRACTS,\n SEARCH_FLAG_CONTRACTS,\n STATS_FLAG_CONTRACTS,\n START_TASK_FLAG_CONTRACTS,\n PAUSE_TASK_FLAG_CONTRACTS,\n TELEMETRY_FLAG_CONTRACTS,\n TEST_ALL_FLAG_CONTRACTS,\n TEST_FLAG_CONTRACTS,\n TEST_RUNS_FLAG_CONTRACTS,\n UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,\n UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,\n UPDATE_FLAG_CONTRACTS,\n UPDATE_MANY_FLAG_CONTRACTS,\n UPGRADE_FLAG_CONTRACTS,\n VALIDATE_FLAG_CONTRACTS,\n compactFlagAliasContracts,\n withFlagAliasMetadata,\n type CliFlagContract,\n type CommanderOptionAliasContract,\n} from \"../../sdk/cli-contracts.js\";\n\n/**\n * Documents the contracts command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContractsCommandOptions {\n action?: string;\n command?: string;\n schemaOnly?: boolean;\n flagsOnly?: boolean;\n availabilityOnly?: boolean;\n runtimeOnly?: boolean;\n full?: boolean;\n}\n\ninterface CommandFlagSurface {\n command: string;\n flags: CliFlagContract[];\n provider?: \"core\" | \"extension\" | \"mixed\";\n extension_sources?: Array<{\n layer: \"global\" | \"project\";\n name: string;\n }>;\n}\n\ninterface CommandAliasSurface {\n canonical: string;\n aliases: string[];\n}\n\n/**\n * Documents the contracts result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContractsResult {\n schema_version: string | null;\n schema_id: string | null;\n selected: {\n action: string | null;\n command: string | null;\n schema_only: boolean;\n flags_only: boolean;\n availability_only: boolean;\n runtime_only: boolean;\n command_scoped: boolean;\n };\n actions?: string[];\n action_availability?: ContractsActionAvailability[];\n commands: string[];\n schema?: Record<string, unknown>;\n schema_omitted_reason?: string;\n command_flags_omitted_reason?: string;\n commander_aliases_omitted_reason?: string;\n command_flags?: CommandFlagSurface[];\n command_aliases?: CommandAliasSurface[];\n commander_aliases?: Record<string, CommanderOptionAliasContract[]>;\n extension_commands?: ExtensionCommandContract[];\n runtime_schema?: {\n statuses: string[];\n open_status: string;\n close_status: string;\n canceled_status: string;\n types: string[];\n fields_by_command: Record<string, string[]>;\n };\n extension_contracts?: {\n capabilities: string[];\n services: string[];\n policy_modes: string[];\n policy_surfaces: string[];\n trust_modes: string[];\n sandbox_profiles: string[];\n manifest_versions: number[];\n compatibility: {\n current: string;\n previous: string[];\n breaking_strategy: string;\n };\n };\n // pm-4os2: static MCP tool surface (tool names, required fields, inputSchema\n // shapes) so the contract golden file catches unintended MCP schema drift.\n // Emitted with --full only — the snapshot script runs `pm contracts --full`.\n mcp_tools?: McpToolContract[];\n}\n\ntype PmToolAction = (typeof PM_TOOL_ACTIONS)[number];\n\n/**\n * Documents the contracts action availability payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContractsActionAvailability {\n action: string;\n invocable: boolean;\n available: boolean;\n requires_extension: boolean;\n provider: \"core\" | \"extension\";\n disabled_reason: string | null;\n command_path: string | null;\n cli_exposed: boolean;\n policy_state?: {\n mode: string;\n trust_mode: string;\n default_sandbox_profile: string;\n };\n}\n\ninterface RuntimeExtensionActionProbe {\n handlers: Set<string>;\n disabledReason: string | null;\n commandDefinitions: RegisteredExtensionCommandDefinition[];\n flagRegistrations: RegisteredExtensionFlagDefinitions[];\n registrations: ExtensionRegistrationRegistry | null;\n policyState: {\n mode: string;\n trust_mode: string;\n default_sandbox_profile: string;\n };\n}\n\ninterface ExtensionCommandContract {\n command: string;\n action: string;\n source: {\n layer: \"global\" | \"project\";\n name: string;\n } | null;\n description: string | null;\n intent: string | null;\n arguments: Array<{\n name: string;\n required: boolean;\n variadic: boolean;\n description: string | null;\n }>;\n flags: CliFlagContract[];\n examples: string[];\n failure_hints: string[];\n}\n\nconst LIST_COMMAND_NAMES = new Set([\n \"list\",\n \"list-all\",\n \"list-draft\",\n \"list-open\",\n \"list-in-progress\",\n \"list-blocked\",\n \"list-closed\",\n \"list-canceled\",\n]);\n\nconst PACKAGE_OWNED_ACTIONS = new Set<string>([\n \"calendar\",\n \"dedupe-audit\",\n \"dedupe-merge\",\n \"guide\",\n \"reindex\",\n \"normalize\",\n \"comments-audit\",\n \"completion\",\n \"test-runs-list\",\n \"test-runs-status\",\n \"test-runs-logs\",\n \"test-runs-stop\",\n \"test-runs-resume\",\n \"templates-list\",\n \"templates-save\",\n \"templates-show\",\n]);\n\nconst PACKAGE_OWNED_COMMANDS = new Set<string>([\n \"cal\",\n \"calendar\",\n \"comments-audit\",\n \"completion\",\n \"completion-statuses\",\n \"completion-tags\",\n \"completion-types\",\n \"dedupe-audit\",\n \"dedupe-merge\",\n \"guide\",\n \"normalize\",\n \"reindex\",\n \"templates\",\n \"templates list\",\n \"templates save\",\n \"templates show\",\n \"test-runs\",\n \"test-runs list\",\n \"test-runs status\",\n \"test-runs logs\",\n \"test-runs stop\",\n \"test-runs resume\",\n]);\n\nconst PACKAGE_OWNED_COMMAND_INSTALL_HINTS = new Map<string, string>([\n [\"cal\", \"calendar\"],\n [\"calendar\", \"calendar\"],\n [\"comments-audit\", \"governance-audit\"],\n [\"completion\", \"guide-shell\"],\n [\"completion-statuses\", \"guide-shell\"],\n [\"completion-tags\", \"guide-shell\"],\n [\"completion-types\", \"guide-shell\"],\n [\"dedupe-audit\", \"governance-audit\"],\n [\"dedupe-merge\", \"governance-audit\"],\n [\"guide\", \"guide-shell\"],\n [\"normalize\", \"governance-audit\"],\n [\"reindex\", \"search-advanced\"],\n [\"templates\", \"templates\"],\n [\"templates list\", \"templates\"],\n [\"templates save\", \"templates\"],\n [\"templates show\", \"templates\"],\n [\"test-runs\", \"linked-test-adapters\"],\n [\"test-runs list\", \"linked-test-adapters\"],\n [\"test-runs status\", \"linked-test-adapters\"],\n [\"test-runs logs\", \"linked-test-adapters\"],\n [\"test-runs stop\", \"linked-test-adapters\"],\n [\"test-runs resume\", \"linked-test-adapters\"],\n]);\n\nconst PACKAGE_OWNED_ACTION_COMMAND_PATHS = new Map<string, string>([\n [\"calendar\", \"calendar|cal\"],\n [\"dedupe-audit\", \"dedupe-audit\"],\n [\"dedupe-merge\", \"dedupe-merge\"],\n [\"guide\", \"guide\"],\n [\"reindex\", \"reindex\"],\n [\"normalize\", \"normalize\"],\n [\"comments-audit\", \"comments-audit\"],\n [\"completion\", \"completion\"],\n [\"test-runs-list\", \"test-runs|test-runs list\"],\n [\"test-runs-status\", \"test-runs status\"],\n [\"test-runs-logs\", \"test-runs logs\"],\n [\"test-runs-stop\", \"test-runs stop\"],\n [\"test-runs-resume\", \"test-runs resume\"],\n [\"templates-list\", \"templates|templates list\"],\n [\"templates-save\", \"templates save\"],\n [\"templates-show\", \"templates show\"],\n]);\n\nconst PACKAGE_OWNED_COMMAND_ACTIONS = new Map(\n [...PACKAGE_OWNED_ACTION_COMMAND_PATHS.entries()].flatMap(([action, commandPaths]) =>\n splitCommandPathAliases(commandPaths).map((commandPath) => [commandPath, action] as const),\n ),\n);\n\nconst CANONICAL_COMMAND_ALIASES: CommandAliasSurface[] = [\n {\n canonical: \"context\",\n aliases: [\"ctx\"],\n },\n {\n canonical: \"package\",\n aliases: [\"extension\", \"packages\", \"install\"],\n },\n];\n\nconst COMMAND_ALIAS_TO_CANONICAL = new Map(\n CANONICAL_COMMAND_ALIASES.flatMap((entry) =>\n entry.aliases.map((alias) => [alias, entry.canonical] as const),\n ),\n);\n\nconst COMMAND_NAMESPACE_DISPLAY_LIMIT = 10;\nconst COMMAND_NAMESPACE_FALLBACK_LIMIT = 20;\n\n// Lifecycle subcommand flag contracts for `pm extension`. Only `init` differs\n// between extension and package: `pm package init` / `pm packages init`\n// additionally accept the package-only `--declarative` flag, so the package\n// variant swaps in PACKAGE_INIT_FLAG_CONTRACTS while every other subcommand is\n// shared verbatim.\nconst EXTENSION_LIFECYCLE_FLAG_CONTRACTS: Array<readonly [string, CliFlagContract[]]> = [\n [\"init\", EXTENSION_INIT_FLAG_CONTRACTS],\n [\"install\", EXTENSION_INSTALL_FLAG_CONTRACTS],\n [\"uninstall\", EXTENSION_UNINSTALL_FLAG_CONTRACTS],\n [\"explore\", EXTENSION_EXPLORE_FLAG_CONTRACTS],\n [\"manage\", EXTENSION_MANAGE_FLAG_CONTRACTS],\n [\"describe\", EXTENSION_DESCRIBE_FLAG_CONTRACTS],\n [\"reload\", EXTENSION_RELOAD_FLAG_CONTRACTS],\n [\"doctor\", EXTENSION_DOCTOR_FLAG_CONTRACTS],\n [\"catalog\", EXTENSION_CATALOG_FLAG_CONTRACTS],\n [\"adopt\", EXTENSION_ADOPT_FLAG_CONTRACTS],\n [\"adopt-all\", EXTENSION_ADOPT_ALL_FLAG_CONTRACTS],\n [\"activate\", EXTENSION_ACTIVATE_FLAG_CONTRACTS],\n [\"deactivate\", EXTENSION_DEACTIVATE_FLAG_CONTRACTS],\n];\n\nconst PACKAGE_LIFECYCLE_FLAG_CONTRACTS: Array<readonly [string, CliFlagContract[]]> =\n EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand, flags]) =>\n subcommand === \"init\" ? ([subcommand, PACKAGE_INIT_FLAG_CONTRACTS] as const) : ([subcommand, flags] as const),\n );\n\nconst CORE_COMMAND_FLAG_CONTRACT_ENTRIES: Array<readonly [string, CliFlagContract[]]> = [\n ...EXTENSION_LIFECYCLE_FLAG_CONTRACTS.map(([subcommand, flags]) => [`extension ${subcommand}`, flags] as const),\n ...PACKAGE_LIFECYCLE_FLAG_CONTRACTS.flatMap(([subcommand, flags]) => [\n [`package ${subcommand}`, flags] as const,\n [`packages ${subcommand}`, flags] as const,\n ]),\n [\"init\", INIT_FLAG_CONTRACTS],\n [\"config\", CONFIG_FLAG_CONTRACTS],\n [\"extension\", EXTENSION_FLAG_CONTRACTS],\n [\"package\", PACKAGE_FLAG_CONTRACTS],\n [\"packages\", PACKAGE_FLAG_CONTRACTS],\n [\"install\", INSTALL_FLAG_CONTRACTS],\n [\"create\", CREATE_FLAG_CONTRACTS],\n [\"update\", UPDATE_FLAG_CONTRACTS],\n [\"update-many\", UPDATE_MANY_FLAG_CONTRACTS],\n [\"upgrade\", UPGRADE_FLAG_CONTRACTS],\n [\"normalize\", NORMALIZE_FLAG_CONTRACTS],\n [\"calendar\", CALENDAR_FLAG_CONTRACTS],\n [\"cal\", CALENDAR_FLAG_CONTRACTS],\n [\"context\", CONTEXT_FLAG_CONTRACTS],\n [\"ctx\", CONTEXT_FLAG_CONTRACTS],\n [\"get\", GET_FLAG_CONTRACTS],\n [\"search\", SEARCH_FLAG_CONTRACTS],\n [\"eval\", EVAL_FLAG_CONTRACTS],\n [\"next\", NEXT_FLAG_CONTRACTS],\n [\"aggregate\", AGGREGATE_FLAG_CONTRACTS],\n [\"dedupe-audit\", DEDUPE_AUDIT_FLAG_CONTRACTS],\n [\"dedupe-merge\", DEDUPE_MERGE_FLAG_CONTRACTS],\n [\"deps\", DEPS_FLAG_CONTRACTS],\n [\"guide\", GUIDE_FLAG_CONTRACTS],\n [\"reindex\", REINDEX_FLAG_CONTRACTS],\n [\"history\", HISTORY_FLAG_CONTRACTS],\n [\"history-compact\", HISTORY_COMPACT_FLAG_CONTRACTS],\n [\"history-redact\", HISTORY_REDACT_FLAG_CONTRACTS],\n [\"history-repair\", HISTORY_REPAIR_FLAG_CONTRACTS],\n [\"schema\", SCHEMA_FLAG_CONTRACTS],\n [\"profile\", PROFILE_FLAG_CONTRACTS],\n [\"plan\", PLAN_FLAG_CONTRACTS],\n [\"restore\", RESTORE_FLAG_CONTRACTS],\n [\"delete\", DELETE_FLAG_CONTRACTS],\n [\"close\", CLOSE_FLAG_CONTRACTS],\n [\"close-many\", CLOSE_MANY_FLAG_CONTRACTS],\n [\"append\", APPEND_FLAG_CONTRACTS],\n [\"claim\", CLAIM_FLAG_CONTRACTS],\n [\"release\", RELEASE_FLAG_CONTRACTS],\n [\"start-task\", START_TASK_FLAG_CONTRACTS],\n [\"pause-task\", PAUSE_TASK_FLAG_CONTRACTS],\n [\"close-task\", CLOSE_TASK_FLAG_CONTRACTS],\n [\"comments\", COMMENTS_FLAG_CONTRACTS],\n [\"notes\", NOTES_FLAG_CONTRACTS],\n [\"learnings\", LEARNINGS_FLAG_CONTRACTS],\n [\"files\", FILES_FLAG_CONTRACTS],\n [\"docs\", DOCS_FLAG_CONTRACTS],\n [\"test\", TEST_FLAG_CONTRACTS],\n [\"test-all\", TEST_ALL_FLAG_CONTRACTS],\n [\"telemetry\", TELEMETRY_FLAG_CONTRACTS],\n [\"test-runs\", TEST_RUNS_FLAG_CONTRACTS],\n [\"gc\", GC_FLAG_CONTRACTS],\n [\"stats\", STATS_FLAG_CONTRACTS],\n [\"validate\", VALIDATE_FLAG_CONTRACTS],\n [\"comments-audit\", COMMENTS_AUDIT_FLAG_CONTRACTS],\n [\"health\", HEALTH_FLAG_CONTRACTS],\n [\"contracts\", CONTRACTS_FLAG_CONTRACTS],\n [\"completion\", COMPLETION_FLAG_CONTRACTS],\n [\"activity\", ACTIVITY_FLAG_CONTRACTS],\n ...[...LIST_COMMAND_NAMES].map((command) => [command, LIST_FILTER_FLAG_CONTRACTS] as const),\n];\n\nconst CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND = new Map(CORE_COMMAND_FLAG_CONTRACT_ENTRIES);\n\n/* c8 ignore start -- extension contract shaping utilities are exercised by dedicated extension/runtime integration suites. */\nfunction packageOwnedActionForCommand(command: string): string {\n const exactAction = PACKAGE_OWNED_COMMAND_ACTIONS.get(command);\n if (exactAction) {\n return exactAction;\n }\n if (command.startsWith(\"test-runs \")) {\n return `test-runs-${command.slice(\"test-runs \".length)}`;\n }\n if (command.startsWith(\"templates \")) {\n return `templates-${command.slice(\"templates \".length)}`;\n }\n return command;\n}\n\nfunction resolveActionCommandPath(action: PmToolAction): string | null {\n if (\n PM_CORE_COMMAND_NAMES.includes(\n action as (typeof PM_CORE_COMMAND_NAMES)[number],\n )\n ) {\n return normalizeCommandPath(action);\n }\n if (action.startsWith(\"extension-\")) {\n return normalizeCommandPath(\n `extension ${action.slice(\"extension-\".length)}`,\n );\n }\n if (action.startsWith(\"package-\")) {\n return normalizeCommandPath(`package ${action.slice(\"package-\".length)}`);\n }\n if (action.startsWith(\"test-runs-\")) {\n return normalizeCommandPath(\n `test-runs ${action.slice(\"test-runs-\".length)}`,\n );\n }\n if (action.startsWith(\"templates-\")) {\n return normalizeCommandPath(\n `templates ${action.slice(\"templates-\".length)}`,\n );\n }\n if (PACKAGE_OWNED_ACTIONS.has(action)) {\n return PACKAGE_OWNED_ACTION_COMMAND_PATHS.get(action) ?? normalizeCommandPath(action);\n }\n return null;\n}\n\nfunction actionDescriptorMatchesSelectedCommand(\n descriptor: ActionContractDescriptor,\n selectedCommand: string,\n): boolean {\n if (descriptor.command_path === null) {\n return false;\n }\n return splitCommandPathAliases(descriptor.command_path).some((commandPath) => {\n if (commandPath === selectedCommand) {\n return true;\n }\n return commandPath.startsWith(`${selectedCommand} `);\n });\n}\n\nfunction splitCommandPathAliases(commandPath: string): string[] {\n return commandPath\n .split(\"|\")\n .map((entry) => normalizeCommandPath(entry))\n .filter((entry) => entry.length > 0);\n}\n\nfunction resolveScopedCommandsFromActionDescriptors(\n descriptors: ActionContractDescriptor[],\n commandCatalog: string[],\n): string[] {\n const commandSet = new Set(commandCatalog);\n const scoped = new Set<string>();\n for (const descriptor of descriptors) {\n if (!descriptor.command_path) {\n continue;\n }\n for (const commandPath of splitCommandPathAliases(descriptor.command_path)) {\n const tokens = commandPath.split(\" \").filter((entry) => entry.length > 0);\n if (tokens.length === 0) {\n continue;\n }\n for (let end = tokens.length; end > 0; end -= 1) {\n const candidate = tokens.slice(0, end).join(\" \");\n if (!commandSet.has(candidate)) {\n continue;\n }\n scoped.add(candidate);\n break;\n }\n }\n }\n return [...scoped].sort((left, right) => left.localeCompare(right));\n}\n\nfunction normalizeToken(value: string | undefined): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const trimmed = value.trim().toLowerCase();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction extractActionBranches(\n schema: Record<string, unknown>,\n): Record<string, unknown>[] {\n const oneOf = schema.oneOf;\n if (!Array.isArray(oneOf)) {\n return [];\n }\n return oneOf.filter(\n (entry): entry is Record<string, unknown> =>\n typeof entry === \"object\" && entry !== null,\n );\n}\n\nfunction filterSchemaByAction(\n schema: Record<string, unknown>,\n action: string | undefined,\n): Record<string, unknown> {\n if (!action) {\n return { ...schema };\n }\n const branches = extractActionBranches(schema);\n const filtered = branches.filter((entry) => {\n const properties = entry.properties;\n if (typeof properties !== \"object\" || properties === null) {\n return false;\n }\n const actionProperty = (properties as Record<string, unknown>).action;\n if (typeof actionProperty !== \"object\" || actionProperty === null) {\n return false;\n }\n return (actionProperty as { const?: unknown }).const === action;\n });\n return {\n ...schema,\n oneOf: filtered,\n };\n}\n\nfunction filterSchemaByActions(\n schema: Record<string, unknown>,\n actions: ReadonlySet<string>,\n): Record<string, unknown> {\n const branches = extractActionBranches(schema);\n const filtered = branches.filter((entry) => {\n const properties = entry.properties;\n if (typeof properties !== \"object\" || properties === null) {\n return false;\n }\n const actionProperty = (properties as Record<string, unknown>).action;\n if (typeof actionProperty !== \"object\" || actionProperty === null) {\n return false;\n }\n const actionConst = (actionProperty as { const?: unknown }).const;\n return typeof actionConst === \"string\" && actions.has(actionConst);\n });\n return {\n ...schema,\n oneOf: filtered,\n };\n}\n\nfunction normalizeCommandPath(value: string): string {\n return value\n .trim()\n .toLowerCase()\n .split(/\\s+/)\n .filter((entry) => entry.length > 0)\n .join(\" \");\n}\n\nfunction normalizeActionNameFromCommand(commandPath: string): string {\n return commandPath.replace(/\\s+/g, \"-\");\n}\n\nfunction toOptionalTrimmedString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n}\n\nfunction normalizeStringList(values: string[] | undefined): string[] {\n if (!Array.isArray(values)) {\n return [];\n }\n const normalized: string[] = [];\n const seen = new Set<string>();\n for (const value of values) {\n const trimmed = toOptionalTrimmedString(value);\n if (!trimmed || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n normalized.push(trimmed);\n }\n return normalized;\n}\n\nfunction assignExtensionFlagBoolean(\n contract: CliFlagContract,\n key: \"required\" | \"repeatable\" | \"list\",\n enabled: boolean,\n): void {\n if (enabled) {\n contract[key] = true;\n }\n}\n\nfunction toExtensionFlagContract(\n definition: Record<string, unknown>,\n): CliFlagContract | null {\n const longName = toOptionalTrimmedString(definition.long);\n const shortName = toOptionalTrimmedString(definition.short);\n const normalizedLong =\n longName && longName.startsWith(\"--\") && longName.length > 2\n ? longName\n : null;\n const normalizedShort =\n shortName && shortName.startsWith(\"-\") && !shortName.startsWith(\"--\")\n ? shortName\n : null;\n const flag = normalizedLong ?? normalizedShort;\n if (!flag) {\n return null;\n }\n const contract: CliFlagContract = { flag };\n if (normalizedShort && normalizedLong) {\n contract.short = normalizedShort;\n }\n assignExtensionFlagBoolean(contract, \"required\", definition.required === true);\n assignExtensionFlagBoolean(contract, \"repeatable\", definition.repeatable === true);\n assignExtensionFlagBoolean(contract, \"list\", definition.list === true);\n const description = toOptionalTrimmedString(definition.description);\n if (description) {\n contract.description = description;\n }\n const valueName = toOptionalTrimmedString(definition.value_name);\n if (valueName) {\n contract.value_name = valueName;\n }\n const rawValueType = [\n toOptionalTrimmedString(definition.value_type),\n toOptionalTrimmedString(definition.type),\n valueName ? \"string\" : null,\n ].find((candidate): candidate is \"string\" | \"number\" | \"boolean\" =>\n candidate === \"string\" || candidate === \"number\" || candidate === \"boolean\",\n );\n if (rawValueType) {\n contract.value_type = rawValueType;\n }\n return contract;\n}\n\nfunction collectExtensionFlagContractsByCommand(\n registrations: RegisteredExtensionFlagDefinitions[],\n): Map<\n string,\n {\n flags: CliFlagContract[];\n sources: Array<{ layer: \"global\" | \"project\"; name: string }>;\n }\n> {\n const grouped = new Map<\n string,\n {\n flags: CliFlagContract[];\n sources: Array<{ layer: \"global\" | \"project\"; name: string }>;\n dedupe: Set<string>;\n sourceDedupe: Set<string>;\n }\n >();\n for (const registration of registrations) {\n const commandPath = normalizeCommandPath(registration.target_command);\n if (commandPath.length === 0) {\n continue;\n }\n const bucket = grouped.get(commandPath) ?? {\n flags: [],\n sources: [],\n dedupe: new Set<string>(),\n sourceDedupe: new Set<string>(),\n };\n const sourceKey = `${registration.layer}:${registration.name}`;\n if (!bucket.sourceDedupe.has(sourceKey)) {\n bucket.sourceDedupe.add(sourceKey);\n bucket.sources.push({\n layer: registration.layer,\n name: registration.name,\n });\n }\n for (const definition of registration.flags) {\n const contract = toExtensionFlagContract(definition);\n if (!contract) {\n continue;\n }\n const key = `${contract.flag}|${contract.short ?? \"\"}`;\n if (bucket.dedupe.has(key)) {\n continue;\n }\n bucket.dedupe.add(key);\n bucket.flags.push(contract);\n }\n grouped.set(commandPath, bucket);\n }\n const normalized = new Map<\n string,\n {\n flags: CliFlagContract[];\n sources: Array<{ layer: \"global\" | \"project\"; name: string }>;\n }\n >();\n for (const [commandPath, bucket] of grouped.entries()) {\n normalized.set(commandPath, {\n flags: bucket.flags,\n sources: bucket.sources.sort((left, right) => {\n const layerOrder = left.layer.localeCompare(right.layer);\n if (layerOrder !== 0) {\n return layerOrder;\n }\n return (left.name ?? \"\").localeCompare(right.name ?? \"\");\n }),\n });\n }\n return normalized;\n}\n\nfunction collectExtensionCommandContracts(\n runtimeProbe: RuntimeExtensionActionProbe,\n): ExtensionCommandContract[] {\n const flagsByCommand = collectExtensionFlagContractsByCommand(\n runtimeProbe.flagRegistrations,\n );\n const definitionsByCommand = new Map<string, ExtensionCommandContract>();\n for (const definition of runtimeProbe.commandDefinitions) {\n const command = normalizeCommandPath(definition.command);\n if (command.length === 0) {\n continue;\n }\n const action =\n toOptionalTrimmedString(definition.action) ??\n normalizeActionNameFromCommand(command);\n const args = Array.isArray(definition.arguments)\n ? definition.arguments\n .map((argument) => {\n const name = toOptionalTrimmedString(argument.name);\n if (!name) {\n return null;\n }\n return {\n name,\n required: argument.required === true,\n variadic: argument.variadic === true,\n description: toOptionalTrimmedString(argument.description),\n };\n })\n .filter(\n (\n argument,\n ): argument is {\n name: string;\n required: boolean;\n variadic: boolean;\n description: string | null;\n } => argument !== null,\n )\n : [];\n definitionsByCommand.set(command, {\n command,\n action,\n source: {\n layer: definition.layer,\n name: definition.name,\n },\n description: toOptionalTrimmedString(definition.description),\n intent: toOptionalTrimmedString(definition.intent),\n arguments: args,\n flags: flagsByCommand.get(command)?.flags ?? [],\n examples: normalizeStringList(definition.examples),\n failure_hints: normalizeStringList(definition.failure_hints),\n });\n }\n\n const extensionCommands = new Set<string>();\n for (const command of runtimeProbe.handlers) {\n extensionCommands.add(normalizeCommandPath(command));\n }\n for (const command of definitionsByCommand.keys()) {\n extensionCommands.add(command);\n }\n for (const command of flagsByCommand.keys()) {\n extensionCommands.add(command);\n }\n\n const contracts: ExtensionCommandContract[] = [];\n for (const command of [...extensionCommands].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const definition = definitionsByCommand.get(command);\n if (definition) {\n contracts.push({\n ...definition,\n flags:\n definition.flags.length > 0\n ? definition.flags\n : (flagsByCommand.get(command)?.flags ?? []),\n });\n continue;\n }\n contracts.push({\n command,\n action: normalizeActionNameFromCommand(command),\n source: null,\n description: null,\n intent: null,\n arguments: [],\n flags: flagsByCommand.get(command)?.flags ?? [],\n examples: [],\n failure_hints: [],\n });\n }\n return contracts;\n}\n\nfunction extensionSchemaPropertyNameFromFlag(\n flag: CliFlagContract,\n): string | null {\n const normalized = flag.flag.replace(/^-+/, \"\").trim();\n if (normalized.length === 0) {\n return null;\n }\n const camelCased = normalized.replace(\n /-([a-z0-9])/g,\n (_match, char: string) => char.toUpperCase(),\n );\n const cleaned = camelCased.replace(/[^a-zA-Z0-9]/g, \"\");\n return cleaned.length > 0 ? cleaned : null;\n}\n\nfunction buildExtensionArgumentSchema(\n argument: ExtensionCommandContract[\"arguments\"][number],\n action: string,\n): Record<string, unknown> {\n if (argument.variadic) {\n return {\n type: \"array\",\n items: { type: \"string\" },\n description:\n argument.description ??\n `Variadic argument '${argument.name}' for extension action '${action}'.`,\n };\n }\n return {\n type: \"string\",\n description:\n argument.description ??\n `Argument '${argument.name}' for extension action '${action}'.`,\n };\n}\n\nfunction buildExtensionFlagSchema(flag: CliFlagContract, action: string): Record<string, unknown> {\n const valueType = flag.value_type ?? \"boolean\";\n const schemaType = valueType === \"boolean\" ? \"boolean\" : valueType === \"number\" ? [\"number\", \"string\"] : \"string\";\n const acceptsMultipleValues = flag.repeatable === true || flag.list === true;\n return {\n type: acceptsMultipleValues ? \"array\" : schemaType,\n ...(acceptsMultipleValues ? { items: { type: schemaType } } : {}),\n description: flag.description ?? `Extension option '${flag.flag}' for action '${action}'.`,\n };\n}\n\nfunction buildExtensionActionSchemaBranch(\n contract: ExtensionCommandContract,\n): Record<string, unknown> {\n const commands = contract.command\n .split(\"|\")\n .map((command) => command.trim())\n .filter((command) => command.length > 0);\n const properties: Record<string, unknown> = {\n action: {\n type: \"string\",\n const: contract.action,\n description:\n contract.intent ??\n contract.description ??\n `Invoke extension command '${contract.command}'.`,\n },\n };\n const required: string[] = [\"action\"];\n for (const argument of contract.arguments) {\n properties[argument.name] = buildExtensionArgumentSchema(argument, contract.action);\n if (argument.required) {\n required.push(argument.name);\n }\n }\n for (const flag of contract.flags) {\n const propertyName = extensionSchemaPropertyNameFromFlag(flag);\n if (!propertyName || properties[propertyName] !== undefined) {\n continue;\n }\n properties[propertyName] = buildExtensionFlagSchema(flag, contract.action);\n if (flag.required === true) {\n required.push(propertyName);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n additionalProperties: true,\n \"x-extension-source\": contract.source,\n \"x-extension-command\": commands[0] ?? contract.command,\n \"x-extension-commands\": commands,\n };\n}\n\nfunction mergeExtensionFlagContract(existing: CliFlagContract, incoming: CliFlagContract): void {\n existing.description ??= incoming.description;\n existing.value_name ??= incoming.value_name;\n existing.value_type ??= incoming.value_type;\n if (incoming.required === true) {\n existing.required = true;\n }\n if (incoming.repeatable === true) {\n existing.repeatable = true;\n }\n}\n\nfunction mergeExtensionContractsByAction(\n contracts: ExtensionCommandContract[],\n): ExtensionCommandContract[] {\n const byAction = new Map<string, ExtensionCommandContract>();\n for (const contract of contracts) {\n const existing = byAction.get(contract.action);\n if (!existing) {\n byAction.set(contract.action, {\n ...contract,\n flags: [...contract.flags],\n examples: [...contract.examples],\n failure_hints: [...contract.failure_hints],\n });\n continue;\n }\n existing.command = [...new Set([existing.command, contract.command])]\n .sort((left, right) => left.localeCompare(right))\n .join(\"|\");\n existing.arguments = existing.arguments.length >= contract.arguments.length ? existing.arguments : contract.arguments;\n const flagKeys = new Set(existing.flags.map((flag) => `${flag.flag}|${flag.short ?? \"\"}`));\n for (const flag of contract.flags) {\n const key = `${flag.flag}|${flag.short ?? \"\"}`;\n if (!flagKeys.has(key)) {\n flagKeys.add(key);\n existing.flags.push(flag);\n } else {\n const existingFlag = existing.flags.find((candidate) => `${candidate.flag}|${candidate.short ?? \"\"}` === key);\n if (existingFlag) {\n mergeExtensionFlagContract(existingFlag, flag);\n }\n }\n }\n existing.examples = [...new Set([...existing.examples, ...contract.examples])];\n existing.failure_hints = [...new Set([...existing.failure_hints, ...contract.failure_hints])];\n }\n return [...byAction.values()].sort((left, right) => left.action.localeCompare(right.action));\n}\n/* c8 ignore stop */\n\nasync function resolveRuntimeExtensionActionProbe(\n global: GlobalOptions,\n): Promise<RuntimeExtensionActionProbe> {\n const defaultPolicyState = {\n mode: SETTINGS_DEFAULTS.extensions.policy.mode,\n trust_mode: SETTINGS_DEFAULTS.extensions.policy.trust_mode,\n default_sandbox_profile:\n SETTINGS_DEFAULTS.extensions.policy.default_sandbox_profile,\n };\n if (global.noExtensions) {\n return {\n handlers: new Set<string>(),\n disabledReason: \"extensions_disabled\",\n commandDefinitions: [],\n flagRegistrations: [],\n registrations: null,\n policyState: defaultPolicyState,\n };\n }\n\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n return {\n handlers: new Set<string>(),\n disabledReason: null,\n commandDefinitions: [],\n flagRegistrations: [],\n registrations: null,\n policyState: defaultPolicyState,\n };\n }\n\n try {\n const settings = await readSettings(pmRoot);\n const loadResult = await loadExtensions({\n pmRoot,\n settings,\n cwd: process.cwd(),\n noExtensions: false,\n });\n const activationResult = await activateExtensions({\n ...loadResult,\n loaded: loadResult.loaded,\n });\n const handlers = new Set<string>(\n activationResult.commands.handlers.map((entry) =>\n normalizeCommandPath(entry.command),\n ),\n );\n return {\n handlers,\n disabledReason: null,\n commandDefinitions: activationResult.registrations.commands,\n flagRegistrations: activationResult.registrations.flags,\n registrations: activationResult.registrations,\n policyState: {\n mode: loadResult.policy.mode,\n trust_mode: loadResult.policy.trust_mode,\n default_sandbox_profile: loadResult.policy.default_sandbox_profile,\n },\n };\n } catch {\n return {\n handlers: new Set<string>(),\n disabledReason: \"extension_runtime_probe_failed\",\n commandDefinitions: [],\n flagRegistrations: [],\n registrations: null,\n policyState: defaultPolicyState,\n };\n }\n}\n\ninterface ActionContractDescriptor {\n action: string;\n provider: \"core\" | \"extension\";\n requires_extension: boolean;\n command_path: string | null;\n}\n\nfunction collectActionContractDescriptors(\n extensionContracts: ExtensionCommandContract[],\n options: { includePackageOwnedActions?: boolean } = {},\n): ActionContractDescriptor[] {\n /* c8 ignore start -- package-owned action descriptor permutations are covered in package-install integration suites. */\n const descriptors = new Map<string, ActionContractDescriptor>();\n for (const action of PM_TOOL_ACTIONS) {\n const packageOwned = PACKAGE_OWNED_ACTIONS.has(action);\n if (packageOwned && !options.includePackageOwnedActions) {\n continue;\n }\n const commandPath = resolveActionCommandPath(action as PmToolAction);\n descriptors.set(action, {\n action,\n provider: packageOwned ? \"extension\" : \"core\",\n requires_extension: packageOwned,\n command_path: commandPath,\n });\n }\n if (options.includePackageOwnedActions) {\n for (const action of PACKAGE_OWNED_ACTIONS) {\n if (descriptors.has(action)) {\n continue;\n }\n descriptors.set(action, {\n action,\n provider: \"extension\",\n requires_extension: true,\n command_path: resolveActionCommandPath(action as PmToolAction),\n });\n }\n }\n for (const contract of extensionContracts) {\n if (descriptors.has(contract.action)) {\n continue;\n }\n descriptors.set(contract.action, {\n action: contract.action,\n provider: \"extension\",\n requires_extension: true,\n command_path: normalizeCommandPath(contract.command),\n });\n }\n return [...descriptors.values()].sort((left, right) =>\n (left.action ?? \"\").localeCompare(right.action ?? \"\"),\n );\n /* c8 ignore stop */\n}\n\nfunction resolveActionAvailability(\n descriptor: ActionContractDescriptor,\n runtimeProbe: RuntimeExtensionActionProbe,\n): ContractsActionAvailability {\n /* c8 ignore start -- runtime extension availability branches are exercised in extension policy integration tests. */\n if (descriptor.provider === \"core\" && !descriptor.requires_extension) {\n return {\n action: descriptor.action,\n invocable: true,\n available: true,\n requires_extension: false,\n provider: \"core\",\n disabled_reason: null,\n command_path: descriptor.command_path,\n cli_exposed: descriptor.command_path !== null,\n };\n }\n\n const commandPaths = descriptor.command_path\n ? splitCommandPathAliases(descriptor.command_path)\n : [];\n const extensionCommandAvailable = commandPaths.some((commandPath) =>\n runtimeProbe.handlers.has(commandPath),\n );\n const optionalPackageHint = commandPaths\n .map((commandPath) => PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(commandPath))\n .find((hint): hint is string => typeof hint === \"string\");\n const invocable =\n runtimeProbe.disabledReason === null && extensionCommandAvailable;\n return {\n action: descriptor.action,\n invocable,\n available: invocable,\n requires_extension: true,\n provider: \"extension\",\n disabled_reason: invocable\n ? null\n : (runtimeProbe.disabledReason ?? (optionalPackageHint ? `optional_package_not_installed:${optionalPackageHint}` : \"extension_command_not_registered\")),\n command_path: descriptor.command_path,\n cli_exposed: extensionCommandAvailable,\n policy_state: {\n mode: runtimeProbe.policyState.mode,\n trust_mode: runtimeProbe.policyState.trust_mode,\n default_sandbox_profile: runtimeProbe.policyState.default_sandbox_profile,\n },\n };\n /* c8 ignore stop */\n}\n\nfunction resolveCoreCommandFlags(command: string): CliFlagContract[] {\n return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.get(command) ?? GLOBAL_FLAG_CONTRACTS;\n}\n\nfunction isCoreCommandPath(command: string): boolean {\n if (PACKAGE_OWNED_COMMANDS.has(command)) {\n return false;\n }\n return CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.has(command);\n}\n\nfunction normalizeCommandForRuntimeFieldFlags(command: string): string {\n if (LIST_COMMAND_NAMES.has(command)) {\n return \"list\";\n }\n if (command === \"cal\") {\n return \"calendar\";\n }\n if (command === \"ctx\") {\n return \"context\";\n }\n if (command === \"update-many\") {\n return \"update_many\";\n }\n return command;\n}\n\nfunction toRuntimeLongFlagToken(token: string): string | null {\n const trimmed = token.trim();\n if (!trimmed) {\n return null;\n }\n if (trimmed.startsWith(\"--\")) {\n return trimmed;\n }\n if (trimmed.startsWith(\"-\")) {\n return null;\n }\n return `--${trimmed}`;\n}\n\nfunction toRuntimeShortFlagToken(token: string): string | null {\n const trimmed = token.trim();\n if (!trimmed) {\n return null;\n }\n if (trimmed.startsWith(\"--\")) {\n return null;\n }\n if (trimmed.startsWith(\"-\")) {\n return trimmed;\n }\n return null;\n}\n\nfunction buildRuntimeFieldFlagContracts(\n fieldRegistry: RuntimeFieldRegistry,\n): Map<string, CliFlagContract[]> {\n /* c8 ignore start -- runtime-field alias collision branches are validated in schema/runtime flag integration tests. */\n const buckets = new Map<\n string,\n { flags: CliFlagContract[]; seen: Set<string> }\n >();\n for (const definition of fieldRegistry.definitions) {\n const primaryFlag = toRuntimeLongFlagToken(definition.cli_flag);\n if (!primaryFlag) {\n continue;\n }\n const shortAlias = definition.cli_aliases\n .map((alias) => toRuntimeShortFlagToken(alias))\n .find((alias) => alias !== null);\n const longAliases = definition.cli_aliases\n .map((alias) => toRuntimeLongFlagToken(alias))\n .filter(\n (alias): alias is string => alias !== null && alias !== primaryFlag,\n );\n for (const command of definition.commands) {\n const bucket = buckets.get(command) ?? {\n flags: [],\n seen: new Set<string>(),\n };\n const primaryContract: CliFlagContract = shortAlias\n ? { flag: primaryFlag, short: shortAlias }\n : { flag: primaryFlag };\n const primaryKey = `${primaryContract.flag}|${primaryContract.short ?? \"\"}`;\n if (!bucket.seen.has(primaryKey)) {\n bucket.seen.add(primaryKey);\n bucket.flags.push(primaryContract);\n }\n for (const alias of longAliases) {\n const key = `${alias}|`;\n if (bucket.seen.has(key)) {\n continue;\n }\n bucket.seen.add(key);\n bucket.flags.push({ flag: alias });\n }\n buckets.set(command, bucket);\n }\n }\n const result = new Map<string, CliFlagContract[]>();\n for (const [command, bucket] of buckets.entries()) {\n result.set(command, compactFlagAliasContracts(bucket.flags));\n }\n return result;\n /* c8 ignore stop */\n}\n\nfunction mergeFlagContracts(\n primary: CliFlagContract[],\n secondary: CliFlagContract[],\n): CliFlagContract[] {\n /* c8 ignore start -- flag merge dedupe permutations are covered via command-surface integration fixtures. */\n const merged: CliFlagContract[] = [];\n const seen = new Set<string>();\n for (const contract of [...primary, ...secondary]) {\n const key = `${contract.flag}|${contract.short ?? \"\"}`;\n if (seen.has(key)) {\n continue;\n }\n seen.add(key);\n merged.push(contract);\n }\n return compactFlagAliasContracts(merged);\n /* c8 ignore stop */\n}\n\nfunction buildCommandFlagSurface(\n commands: string[],\n extensionFlagMap: ReturnType<typeof collectExtensionFlagContractsByCommand>,\n runtimeFieldFlagMap: Map<string, CliFlagContract[]>,\n): CommandFlagSurface[] {\n return commands\n .map((command) => {\n const isCoreCommand = isCoreCommandPath(command);\n const coreFlags = isCoreCommand ? resolveCoreCommandFlags(command) : [];\n const runtimeFlags =\n runtimeFieldFlagMap.get(\n normalizeCommandForRuntimeFieldFlags(command),\n ) ?? [];\n const extensionFlags = extensionFlagMap.get(command);\n const coreWithRuntime = mergeFlagContracts(coreFlags, runtimeFlags);\n const flags = mergeFlagContracts(\n coreWithRuntime,\n extensionFlags?.flags ?? [],\n );\n const provider: CommandFlagSurface[\"provider\"] =\n coreFlags.length > 0 && (extensionFlags?.flags.length ?? 0) > 0\n ? \"mixed\"\n : isCoreCommand\n ? \"core\"\n : \"extension\";\n return {\n command,\n flags,\n provider,\n extension_sources: extensionFlags?.sources,\n };\n })\n .sort((left, right) => left.command.localeCompare(right.command));\n}\n\nfunction compactCommandAliasSurface(commands: string[]): string[] {\n const commandSet = new Set(commands);\n const result: string[] = [];\n for (const command of commands) {\n const canonical = COMMAND_ALIAS_TO_CANONICAL.get(command);\n if (canonical && commandSet.has(canonical)) {\n continue;\n }\n result.push(command);\n }\n return result;\n}\n\nfunction buildCommandAliasSurface(commands: string[]): CommandAliasSurface[] {\n const commandSet = new Set(commands);\n return CANONICAL_COMMAND_ALIASES.map((entry) => ({\n canonical: entry.canonical,\n aliases: entry.aliases.filter((alias) => commandSet.has(alias)),\n })).filter(\n (entry) => commandSet.has(entry.canonical) && entry.aliases.length > 0,\n );\n}\n\nfunction buildCommanderAliasSurface(): Record<\n string,\n CommanderOptionAliasContract[]\n> {\n return {\n create_string_options: CREATE_COMMANDER_STRING_OPTION_CONTRACTS,\n create_repeatable_options: CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,\n update_string_options: UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,\n update_repeatable_options: UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,\n list_string_options: LIST_COMMANDER_STRING_OPTION_CONTRACTS,\n search_string_options: SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,\n calendar_string_options: CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,\n context_string_options: CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,\n activity_string_options: ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,\n };\n}\n\nfunction resolveCreateRequiredOptionContract(\n typeDefinition: ReturnType<typeof resolveItemTypeRegistry>[\"by_type\"][string],\n createMode: \"strict\" | \"progressive\",\n): {\n required_option_keys: string[];\n required_flags: string[];\n required_type_options: string[];\n policy_errors: string[];\n} {\n /* c8 ignore start -- create-option policy shaping is validated by dedicated create command contract fixtures. */\n const baseRequiredOptions = new Set<string>([\"title\", \"type\"]);\n if (createMode === \"strict\") {\n for (const field of typeDefinition.required_create_fields) {\n baseRequiredOptions.add(field);\n }\n for (const field of typeDefinition.required_create_repeatables) {\n baseRequiredOptions.add(field);\n }\n }\n const policyState = resolveCommandOptionPolicyState(\n typeDefinition,\n \"create\",\n baseRequiredOptions,\n );\n const requiredOptionKeys = [...new Set(policyState.required)].sort(\n (left, right) => left.localeCompare(right),\n );\n const requiredFlags = [\n ...new Set(\n requiredOptionKeys.map((option) =>\n commandOptionFlagLabel(\"create\", option),\n ),\n ),\n ].sort((left, right) => left.localeCompare(right));\n const requiredTypeOptions = [\n ...new Set(\n typeDefinition.options\n .filter((option) => option.required === true)\n .map((option) => option.key),\n ),\n ].sort((left, right) => left.localeCompare(right));\n return {\n required_option_keys: requiredOptionKeys,\n required_flags: requiredFlags,\n required_type_options: requiredTypeOptions,\n policy_errors: [...new Set(policyState.errors)].sort((left, right) =>\n left.localeCompare(right),\n ),\n };\n /* c8 ignore stop */\n}\n\nfunction buildCreateRequiredOptionContracts(\n typeRegistry: ReturnType<typeof resolveItemTypeRegistry>,\n): Record<string, unknown> {\n const byTypeStrict: Record<string, unknown> = {};\n const byTypeProgressive: Record<string, unknown> = {};\n for (const typeName of [...typeRegistry.types].sort((left, right) =>\n left.localeCompare(right),\n )) {\n const typeDefinition = typeRegistry.by_type[typeName];\n byTypeStrict[typeName] = resolveCreateRequiredOptionContract(\n typeDefinition,\n \"strict\",\n );\n byTypeProgressive[typeName] = resolveCreateRequiredOptionContract(\n typeDefinition,\n \"progressive\",\n );\n }\n return {\n default_create_mode: \"strict\",\n by_create_mode: {\n strict: {\n by_type: byTypeStrict,\n },\n progressive: {\n by_type: byTypeProgressive,\n },\n },\n };\n}\n\nfunction attachCreateRequiredOptionContracts(\n schema: Record<string, unknown>,\n metadata: Record<string, unknown>,\n): Record<string, unknown> {\n const branches = extractActionBranches(schema);\n if (branches.length === 0) {\n return schema;\n }\n let touched = false;\n const enrichedBranches = branches.map((branch) => {\n const properties = branch.properties;\n if (typeof properties !== \"object\" || properties === null) {\n return branch;\n }\n const actionProperty = (properties as Record<string, unknown>).action;\n if (typeof actionProperty !== \"object\" || actionProperty === null) {\n return branch;\n }\n if ((actionProperty as { const?: unknown }).const !== \"create\") {\n return branch;\n }\n touched = true;\n return {\n ...branch,\n \"x-create-required-options\": metadata,\n };\n });\n if (!touched) {\n return schema;\n }\n return {\n ...schema,\n oneOf: enrichedBranches,\n };\n}\n\ninterface ContractsSelection {\n selectedAction: string | undefined;\n selectedCommand: string | undefined;\n schemaOnly: boolean;\n flagsOnly: boolean;\n availabilityOnly: boolean;\n runtimeOnly: boolean;\n fullOutput: boolean;\n omitUnfilteredSchema: boolean;\n omitUnfilteredCommandFlags: boolean;\n omitUnfilteredCommanderAliases: boolean;\n}\n\ninterface ContractsRuntimeContext {\n settings: Awaited<ReturnType<typeof readSettings>>;\n runtimeProbe: RuntimeExtensionActionProbe;\n typeRegistry: ReturnType<typeof resolveItemTypeRegistry>;\n statusRegistry: ReturnType<typeof resolveRuntimeStatusRegistry>;\n runtimeFieldRegistry: RuntimeFieldRegistry;\n runtimeFieldFlagMap: Map<string, CliFlagContract[]>;\n createRequiredOptionContracts: Record<string, unknown>;\n extensionContracts: ExtensionCommandContract[];\n mergedExtensionContracts: ExtensionCommandContract[];\n extensionFlagMap: ReturnType<typeof collectExtensionFlagContractsByCommand>;\n}\n\ninterface ContractsActionContext {\n actionDescriptors: ActionContractDescriptor[];\n commandCatalog: string[];\n commandScopedDescriptors: ActionContractDescriptor[];\n scopedActionDescriptors: ActionContractDescriptor[];\n selectedPackageOwnedAction: string | undefined;\n actionAvailability: ContractsActionAvailability[];\n actions: string[];\n}\n\ninterface ContractsSchemaContext {\n mergedSchema: Record<string, unknown>;\n filteredSchema: Record<string, unknown>;\n}\n\nfunction resolveContractsSelection(options: ContractsCommandOptions): ContractsSelection {\n const schemaOnly = options.schemaOnly === true;\n const flagsOnly = options.flagsOnly === true;\n const availabilityOnly = options.availabilityOnly === true;\n const runtimeOnly = options.runtimeOnly === true;\n const fullOutput = options.full === true;\n const selectedAction = normalizeToken(options.action);\n const selectedCommand = normalizeToken(options.command);\n const unfilteredDefaultBriefMode =\n !fullOutput && !schemaOnly && !flagsOnly && !availabilityOnly && !selectedAction && !selectedCommand;\n return {\n selectedAction,\n selectedCommand,\n schemaOnly,\n flagsOnly,\n availabilityOnly,\n runtimeOnly,\n fullOutput,\n omitUnfilteredSchema: unfilteredDefaultBriefMode,\n omitUnfilteredCommandFlags: unfilteredDefaultBriefMode,\n omitUnfilteredCommanderAliases: unfilteredDefaultBriefMode,\n };\n}\n\nfunction assertSingleContractsProjection(selection: ContractsSelection): void {\n const projectionFlagsEnabled = [\n selection.schemaOnly,\n selection.flagsOnly,\n selection.availabilityOnly,\n ].filter((value) => value).length;\n if (projectionFlagsEnabled > 1) {\n throw new PmCliError(\n \"Choose only one projection flag: --schema-only, --flags-only, or --availability-only.\",\n EXIT_CODE.USAGE,\n );\n }\n}\n\nasync function readContractsSettings(pmRoot: string): Promise<Awaited<ReturnType<typeof readSettings>>> {\n try {\n return await readSettings(pmRoot);\n } catch {\n return structuredClone(SETTINGS_DEFAULTS);\n }\n}\n\nasync function resolveContractsRuntimeContext(\n global: GlobalOptions,\n pmRoot: string,\n): Promise<ContractsRuntimeContext> {\n const settings = await readContractsSettings(pmRoot);\n const runtimeProbe = await resolveRuntimeExtensionActionProbe(global);\n const typeRegistry = resolveItemTypeRegistry(\n settings,\n runtimeProbe.registrations ?? getActiveExtensionRegistrations(),\n );\n const runtimeFieldRegistry = resolveRuntimeFieldRegistry(settings.schema);\n const extensionContracts = collectExtensionCommandContracts(runtimeProbe);\n return {\n settings,\n runtimeProbe,\n typeRegistry,\n statusRegistry: resolveRuntimeStatusRegistry(settings.schema),\n runtimeFieldRegistry,\n runtimeFieldFlagMap: buildRuntimeFieldFlagContracts(runtimeFieldRegistry),\n createRequiredOptionContracts: buildCreateRequiredOptionContracts(typeRegistry),\n extensionContracts,\n mergedExtensionContracts: mergeExtensionContractsByAction(extensionContracts),\n extensionFlagMap: collectExtensionFlagContractsByCommand(runtimeProbe.flagRegistrations),\n };\n}\n\nfunction shouldIncludePackageOwnedActions(selection: ContractsSelection): boolean {\n return (\n selection.availabilityOnly &&\n ((selection.selectedAction !== undefined && PACKAGE_OWNED_ACTIONS.has(selection.selectedAction)) ||\n (selection.selectedCommand !== undefined && PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand)))\n );\n}\n\nfunction collectContractsActionDescriptors(\n selection: ContractsSelection,\n mergedExtensionContracts: ExtensionCommandContract[],\n): ActionContractDescriptor[] {\n const actionDescriptors = collectActionContractDescriptors(mergedExtensionContracts, {\n includePackageOwnedActions: shouldIncludePackageOwnedActions(selection),\n });\n if (\n shouldIncludePackageOwnedActions(selection) &&\n selection.selectedCommand !== undefined &&\n PACKAGE_OWNED_COMMANDS.has(selection.selectedCommand) &&\n !actionDescriptors.some((entry) => entry.command_path === selection.selectedCommand)\n ) {\n actionDescriptors.push({\n action: packageOwnedActionForCommand(selection.selectedCommand),\n provider: \"extension\",\n requires_extension: true,\n command_path: selection.selectedCommand,\n });\n }\n return actionDescriptors;\n}\n\nfunction assertKnownContractsAction(selection: ContractsSelection, actionDescriptors: ActionContractDescriptor[]): void {\n const actionNames = new Set(actionDescriptors.map((entry) => entry.action));\n if (selection.selectedAction && !actionNames.has(selection.selectedAction)) {\n throw new PmCliError(`Unknown action: \"${selection.selectedAction}\".`, EXIT_CODE.USAGE);\n }\n}\n\nfunction buildContractsCommandCatalog(\n actionDescriptors: ActionContractDescriptor[],\n mergedExtensionContracts: ExtensionCommandContract[],\n): string[] {\n return [\n ...new Set([\n ...PM_CORE_COMMAND_NAMES.filter((entry) => !PACKAGE_OWNED_COMMANDS.has(entry)),\n ...[...CORE_COMMAND_FLAG_CONTRACTS_BY_COMMAND.keys()].filter((entry) => !PACKAGE_OWNED_COMMANDS.has(entry)),\n /* c8 ignore next -- action descriptors always include concrete command paths in command-scoped test fixtures. */\n ...actionDescriptors.flatMap((entry) => entry.command_path ? splitCommandPathAliases(entry.command_path) : []),\n ...mergedExtensionContracts.flatMap((entry) => entry.command.split(\"|\")),\n ]),\n ]\n .map((entry) => normalizeCommandPath(entry))\n .filter((entry) => entry.length > 0)\n .sort((left, right) => left.localeCompare(right));\n}\n\nfunction buildCommandNamespaceError(command: string, namespaceChildren: string[]): PmCliError {\n const displayedNamespaceChildren = namespaceChildren.slice(0, COMMAND_NAMESPACE_DISPLAY_LIMIT);\n const hiddenNamespaceChildCount = namespaceChildren.length - displayedNamespaceChildren.length;\n const displayedChildCommandList = hiddenNamespaceChildCount > 0\n ? `${displayedNamespaceChildren.join(\", \")}, and ${hiddenNamespaceChildCount} more`\n : displayedNamespaceChildren.join(\", \");\n const fallbackCandidates = namespaceChildren.slice(0, COMMAND_NAMESPACE_FALLBACK_LIMIT);\n const childCommandExamples = namespaceChildren\n .slice(0, 5)\n .map((childCommand) => `pm contracts --command \"${childCommand}\" --flags-only --json`);\n const suggestedChildCommand = namespaceChildren[0];\n return new PmCliError(\n `Command \"${command}\" is a command namespace. Choose a concrete child command: ${displayedChildCommandList}.`,\n EXIT_CODE.USAGE,\n {\n code: \"command_namespace\",\n required: \"Use a concrete child command path listed under this namespace.\",\n why:\n \"Command groups expose help at the namespace root, but command flag contracts belong to executable child commands.\",\n examples: childCommandExamples,\n nextSteps: [`Retry with a child command, for example: ${childCommandExamples[0]}`],\n recovery: {\n suggested_retry: `pm contracts --command \"${suggestedChildCommand}\" --flags-only --json`,\n fallback_candidates: fallbackCandidates.map((childCommand) => ({\n source: \"command_namespace\",\n command: `pm contracts --command \"${childCommand}\" --flags-only --json`,\n reason: `Child command under ${command}`,\n })),\n },\n },\n );\n}\n\nfunction buildPackageOwnedCommandError(command: string, packageHint: string): PmCliError {\n return new PmCliError(\n `Unknown command: \"${command}\". Command \"${command}\" is provided by the optional \"${packageHint}\" package. Run \"pm install ${packageHint} --project\" and retry.`,\n EXIT_CODE.USAGE,\n {\n code: \"unknown_command\",\n required: `Install the optional \"${packageHint}\" package, or choose a command from pm contracts --flags-only --json.`,\n why: \"Command contracts include core commands plus commands registered by active packages and extensions.\",\n examples: [`pm install ${packageHint} --project`, `pm contracts --command ${command} --flags-only --json`],\n nextSteps: [`Install the optional package first: pm install ${packageHint} --project`],\n recovery: {\n suggested_retry: `pm install ${packageHint} --project`,\n },\n },\n );\n}\n\nfunction buildUnknownCommandError(command: string): PmCliError {\n return new PmCliError(\n `Unknown command: \"${command}\".`,\n EXIT_CODE.USAGE,\n {\n code: \"unknown_command\",\n required: \"Use a command path listed by pm contracts --flags-only --json.\",\n why: \"Command contracts are generated from the active core, package, and extension command registry.\",\n examples: [\"pm contracts --flags-only --json\", \"pm --help\"],\n nextSteps: [\"Verify spelling and active packages/extensions, then rerun with a known command path.\"],\n recovery: {\n suggested_retry: \"pm contracts --flags-only --json\",\n },\n },\n );\n}\n\nfunction assertKnownContractsCommand(selection: ContractsSelection, commandCatalog: string[]): void {\n if (!selection.selectedCommand) {\n return;\n }\n const commandNames = new Set(commandCatalog);\n if (commandNames.has(selection.selectedCommand)) {\n return;\n }\n const namespaceChildren = commandCatalog.filter((command) => command.startsWith(`${selection.selectedCommand} `));\n if (namespaceChildren.length > 0) {\n throw buildCommandNamespaceError(selection.selectedCommand, namespaceChildren);\n }\n const packageHint = PACKAGE_OWNED_COMMAND_INSTALL_HINTS.get(selection.selectedCommand);\n if (packageHint) {\n throw buildPackageOwnedCommandError(selection.selectedCommand, packageHint);\n }\n throw buildUnknownCommandError(selection.selectedCommand);\n}\n\nfunction resolveContractsActionContext(\n selection: ContractsSelection,\n runtime: ContractsRuntimeContext,\n): ContractsActionContext {\n const actionDescriptors = collectContractsActionDescriptors(selection, runtime.mergedExtensionContracts);\n assertKnownContractsAction(selection, actionDescriptors);\n const commandCatalog = buildContractsCommandCatalog(actionDescriptors, runtime.mergedExtensionContracts);\n assertKnownContractsCommand(selection, commandCatalog);\n const selectedPackageOwnedAction = selection.selectedCommand\n ? PACKAGE_OWNED_COMMAND_ACTIONS.get(selection.selectedCommand)\n : undefined;\n const commandScopedDescriptors = selection.selectedCommand\n ? actionDescriptors.filter((descriptor) =>\n selectedPackageOwnedAction\n ? descriptor.action === selectedPackageOwnedAction\n : actionDescriptorMatchesSelectedCommand(descriptor, selection.selectedCommand as string),\n )\n : actionDescriptors;\n if (\n selection.selectedCommand &&\n selection.selectedAction &&\n !commandScopedDescriptors.some((descriptor) => descriptor.action === selection.selectedAction)\n ) {\n throw new PmCliError(\n `Action \"${selection.selectedAction}\" is not mapped to command \"${selection.selectedCommand}\" in contracts output.`,\n EXIT_CODE.USAGE,\n );\n }\n const scopedActionDescriptors = selection.selectedAction\n ? commandScopedDescriptors.filter((descriptor) => descriptor.action === selection.selectedAction)\n : commandScopedDescriptors;\n const allActionAvailability = [\n ...new Map(\n scopedActionDescriptors\n .map((descriptor) => resolveActionAvailability(descriptor, runtime.runtimeProbe))\n .map((entry) => [\n /* c8 ignore next -- keyed dedupe by action|path is covered by runtime policy integration tests. */\n selectedPackageOwnedAction ? entry.action : `${entry.action}|${entry.command_path ?? \"\"}`,\n entry,\n ] as const),\n ).values(),\n ];\n const actionAvailability =\n selection.runtimeOnly && !selection.selectedAction && !selection.availabilityOnly\n ? allActionAvailability.filter((entry) => entry.invocable)\n : allActionAvailability;\n return {\n actionDescriptors,\n commandCatalog,\n commandScopedDescriptors,\n scopedActionDescriptors,\n selectedPackageOwnedAction,\n actionAvailability,\n actions: [...new Set(actionAvailability.map((entry) => entry.action))],\n };\n}\n\nfunction buildSchemaActionSet(schema: Record<string, unknown>): Set<string> {\n return new Set(\n extractActionBranches(schema)\n .map((entry) => {\n const properties = entry.properties;\n /* c8 ignore start -- PM_TOOL_PARAMETERS_SCHEMA action branches always carry a properties object; the property-less fallback is validated in schema-level contract tests. */\n if (typeof properties !== \"object\" || properties === null) {\n return null;\n }\n /* c8 ignore stop */\n const actionProperty = (properties as Record<string, unknown>).action;\n /* c8 ignore start -- PM_TOOL_PARAMETERS_SCHEMA action branches always carry an action object; the missing-action fallback is validated in schema-level contract tests. */\n if (typeof actionProperty !== \"object\" || actionProperty === null) {\n return null;\n }\n /* c8 ignore stop */\n const actionConst = (actionProperty as { const?: unknown }).const;\n /* c8 ignore start -- the action.const is always a string in PM_TOOL_PARAMETERS_SCHEMA; the non-string fallback is validated in schema-level contract tests. */\n return typeof actionConst === \"string\" ? actionConst : null;\n /* c8 ignore stop */\n })\n .filter((entry): entry is string => entry !== null),\n );\n}\n\nfunction buildMergedContractsSchema(mergedExtensionContracts: ExtensionCommandContract[]): Record<string, unknown> {\n const schema = PM_TOOL_PARAMETERS_SCHEMA as Record<string, unknown>;\n const schemaBranches = extractActionBranches(schema);\n const schemaActionSet = buildSchemaActionSet(schema);\n const extensionBranches = mergedExtensionContracts\n .filter((contract) => !schemaActionSet.has(contract.action))\n .map((contract) => buildExtensionActionSchemaBranch(contract));\n return extensionBranches.length > 0\n ? {\n ...schema,\n oneOf: [...schemaBranches, ...extensionBranches],\n }\n : schema;\n}\n\nfunction filterContractsSchema(\n selection: ContractsSelection,\n actionContext: ContractsActionContext,\n mergedSchema: Record<string, unknown>,\n): Record<string, unknown> {\n const descriptorActionSet = new Set(actionContext.actionDescriptors.map((descriptor) => descriptor.action));\n const filteredSchema = selection.selectedAction\n ? filterSchemaByAction(mergedSchema, selection.selectedAction)\n : selection.selectedCommand\n ? filterSchemaByActions(\n mergedSchema,\n new Set(actionContext.scopedActionDescriptors.map((descriptor) => descriptor.action)),\n )\n : filterSchemaByActions(mergedSchema, descriptorActionSet);\n return selection.runtimeOnly && !selection.selectedAction\n ? filterSchemaByActions(filteredSchema, new Set(actionContext.actions))\n : filteredSchema;\n}\n\nfunction resolveContractsSchemaContext(\n selection: ContractsSelection,\n runtime: ContractsRuntimeContext,\n actionContext: ContractsActionContext,\n): ContractsSchemaContext {\n const mergedSchema = buildMergedContractsSchema(runtime.mergedExtensionContracts);\n const includeSchemaSurface = !selection.flagsOnly && !selection.availabilityOnly;\n const filteredSchema = includeSchemaSurface\n ? attachCreateRequiredOptionContracts(\n filterContractsSchema(selection, actionContext, mergedSchema),\n runtime.createRequiredOptionContracts,\n )\n : filterContractsSchema(selection, actionContext, mergedSchema);\n return { mergedSchema, filteredSchema };\n}\n\nfunction resolveContractsCommands(selection: ContractsSelection, actionContext: ContractsActionContext): string[] {\n if (selection.selectedCommand !== undefined) {\n return [selection.selectedCommand];\n }\n if (selection.selectedAction) {\n return resolveScopedCommandsFromActionDescriptors(\n actionContext.scopedActionDescriptors,\n actionContext.commandCatalog,\n );\n }\n return actionContext.commandCatalog;\n}\n\nfunction resolveOutputCommands(selection: ContractsSelection, commands: string[]): string[] {\n return selection.flagsOnly && selection.selectedCommand === undefined && selection.selectedAction === undefined\n ? compactCommandAliasSurface(commands)\n : commands;\n}\n\nfunction resolveExtensionCommandContracts(\n selection: ContractsSelection,\n runtime: ContractsRuntimeContext,\n outputCommands: string[],\n): ExtensionCommandContract[] {\n if (selection.selectedCommand) {\n return runtime.extensionContracts.filter((entry) =>\n splitCommandPathAliases(entry.command).includes(selection.selectedCommand as string),\n );\n }\n if (selection.selectedAction) {\n const outputCommandSet = new Set(outputCommands);\n return runtime.extensionContracts.filter((entry) =>\n splitCommandPathAliases(entry.command).some((command) => outputCommandSet.has(command)),\n );\n }\n return runtime.extensionContracts;\n}\n\nfunction createContractsResult(\n selection: ContractsSelection,\n schemaContext: ContractsSchemaContext,\n actionContext: ContractsActionContext,\n outputCommands: string[],\n): ContractsResult {\n return {\n schema_version:\n /* c8 ignore next -- schema version/id fallbacks are exercised by schema snapshot tests. */\n typeof schemaContext.mergedSchema[\"x-schema-version\"] === \"string\"\n ? (schemaContext.mergedSchema[\"x-schema-version\"] as string)\n : null,\n schema_id:\n /* c8 ignore next -- schema version/id fallbacks are exercised by schema snapshot tests. */\n typeof schemaContext.mergedSchema.$id === \"string\"\n ? (schemaContext.mergedSchema.$id as string)\n : null,\n selected: {\n action: selection.selectedAction ?? null,\n command: selection.selectedCommand ?? null,\n schema_only: selection.schemaOnly,\n flags_only: selection.flagsOnly,\n availability_only: selection.availabilityOnly,\n runtime_only: selection.runtimeOnly,\n command_scoped: selection.selectedCommand !== undefined,\n },\n commands: outputCommands,\n ...(!selection.flagsOnly\n ? {\n actions: actionContext.actions,\n action_availability: actionContext.actionAvailability,\n }\n : {}),\n };\n}\n\nfunction attachRuntimeContractsResult(result: ContractsResult, runtime: ContractsRuntimeContext): void {\n result.runtime_schema = {\n statuses: runtime.statusRegistry.definitions.map((definition) => definition.id),\n open_status: runtime.statusRegistry.open_status,\n close_status: runtime.statusRegistry.close_status,\n canceled_status: runtime.statusRegistry.canceled_status,\n types: [...runtime.typeRegistry.types],\n fields_by_command: Object.fromEntries(\n [...runtime.runtimeFieldRegistry.command_to_fields.entries()].map(([command, definitions]) => [\n command,\n [...new Set(definitions.map((definition) => `--${definition.cli_flag}`))].sort((left, right) =>\n left.localeCompare(right),\n ),\n ]),\n ),\n };\n result.extension_contracts = {\n capabilities: [...PM_EXTENSION_CAPABILITY_CONTRACTS],\n services: [...PM_EXTENSION_SERVICE_NAME_CONTRACTS],\n policy_modes: [...PM_EXTENSION_POLICY_MODE_CONTRACTS],\n policy_surfaces: [...PM_EXTENSION_POLICY_SURFACE_CONTRACTS],\n trust_modes: [...PM_EXTENSION_TRUST_MODE_CONTRACTS],\n sandbox_profiles: [...PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS],\n manifest_versions: [1, 2],\n compatibility: {\n current: \"v2\",\n previous: [\"v1\"],\n breaking_strategy: \"versioned_breaking\",\n },\n };\n}\n\nfunction attachSchemaContractsResult(\n result: ContractsResult,\n selection: ContractsSelection,\n schemaContext: ContractsSchemaContext,\n extensionCommandContracts: ExtensionCommandContract[],\n): void {\n if (selection.flagsOnly || selection.availabilityOnly) {\n return;\n }\n if (!selection.omitUnfilteredSchema) {\n result.schema = schemaContext.filteredSchema;\n result.extension_commands = extensionCommandContracts;\n return;\n }\n result.schema_omitted_reason = \"unfiltered_default_brief\";\n result.extension_commands = extensionCommandContracts;\n}\n\nfunction attachFlagContractsResult(\n result: ContractsResult,\n selection: ContractsSelection,\n runtime: ContractsRuntimeContext,\n outputCommands: string[],\n commandAliases: CommandAliasSurface[],\n): void {\n if (selection.schemaOnly || selection.availabilityOnly) {\n return;\n }\n if (!selection.omitUnfilteredCommandFlags) {\n result.command_flags = buildCommandFlagSurface(\n outputCommands,\n runtime.extensionFlagMap,\n runtime.runtimeFieldFlagMap,\n );\n } else {\n result.command_flags_omitted_reason = \"unfiltered_default_brief\";\n }\n if (commandAliases.length > 0) {\n result.command_aliases = commandAliases;\n }\n}\n\nfunction attachCommanderAliasContractsResult(result: ContractsResult, selection: ContractsSelection): void {\n if (selection.schemaOnly || selection.flagsOnly || selection.availabilityOnly) {\n return;\n }\n if (!selection.omitUnfilteredCommanderAliases) {\n result.commander_aliases = buildCommanderAliasSurface();\n return;\n }\n result.commander_aliases_omitted_reason = \"unfiltered_default_brief\";\n}\n\n/**\n * Implements run contracts for the public runtime surface of this module.\n */\nexport async function runContracts(\n options: ContractsCommandOptions,\n global: GlobalOptions,\n): Promise<ContractsResult> {\n const selection = resolveContractsSelection(options);\n assertSingleContractsProjection(selection);\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n const runtime = await resolveContractsRuntimeContext(global, pmRoot);\n const actionContext = resolveContractsActionContext(selection, runtime);\n const schemaContext = resolveContractsSchemaContext(selection, runtime, actionContext);\n const commands = resolveContractsCommands(selection, actionContext);\n const outputCommands = resolveOutputCommands(selection, commands);\n const commandAliases = buildCommandAliasSurface(commands);\n const extensionCommandContracts = resolveExtensionCommandContracts(selection, runtime, outputCommands);\n const result = createContractsResult(selection, schemaContext, actionContext, outputCommands);\n\n if (!(selection.flagsOnly && !selection.fullOutput)) {\n attachRuntimeContractsResult(result, runtime);\n }\n attachSchemaContractsResult(result, selection, schemaContext, extensionCommandContracts);\n attachFlagContractsResult(result, selection, runtime, outputCommands, commandAliases);\n attachCommanderAliasContractsResult(result, selection);\n\n // pm-4os2: snapshot the static MCP tool surface in the full projection so\n // `pnpm contracts:check` (CI static gate) fails on unintended inputSchema\n // drift in src/mcp/tool-definitions.ts.\n if (selection.fullOutput && !selection.schemaOnly && !selection.flagsOnly && !selection.availabilityOnly) {\n result.mcp_tools = buildMcpToolContracts();\n }\n\n return result;\n}\n\nexport const _testOnlyContractsCommand = {\n actionDescriptorMatchesSelectedCommand,\n attachCreateRequiredOptionContracts,\n buildExtensionActionSchemaBranch,\n buildRuntimeFieldFlagContracts,\n collectActionContractDescriptors,\n collectExtensionCommandContracts,\n collectExtensionFlagContractsByCommand,\n extractActionBranches,\n extensionSchemaPropertyNameFromFlag,\n filterSchemaByAction,\n filterSchemaByActions,\n isCoreCommandPath,\n mergeExtensionContractsByAction,\n normalizeActionNameFromCommand,\n normalizeCommandForRuntimeFieldFlags,\n normalizeCommandPath,\n packageOwnedActionForCommand,\n resolveActionCommandPath,\n resolveActionAvailability,\n resolveCoreCommandFlags,\n resolveScopedCommandsFromActionDescriptors,\n splitCommandPathAliases,\n toRuntimeLongFlagToken,\n toRuntimeShortFlagToken,\n};\n", "/**\n * @module cli/commands/gc\n *\n * Implements the pm gc command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { runCheckpointGc } from \"../../core/checkpoint/checkpoint-gc.js\";\nimport { runActiveOnIndexHooks, runActiveOnReadHooks, runActiveOnWriteHooks } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { runLockGc } from \"../../core/lock/lock-gc.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\n\nconst GC_SCOPE_VALUES = [\"index\", \"embeddings\", \"runtime\", \"locks\", \"checkpoints\"] as const;\ntype GcScope = (typeof GC_SCOPE_VALUES)[number];\n\ninterface GcTarget {\n scope: GcScope;\n relativePath: string;\n kind: \"file\" | \"directory\";\n}\n\nconst GC_TARGETS: readonly GcTarget[] = [\n {\n scope: \"index\",\n relativePath: \"index/manifest.json\",\n kind: \"file\",\n },\n {\n scope: \"embeddings\",\n relativePath: \"search/embeddings.jsonl\",\n kind: \"file\",\n },\n {\n scope: \"embeddings\",\n relativePath: \"search/vectorization-status.json\",\n kind: \"file\",\n },\n {\n scope: \"embeddings\",\n relativePath: \"search/lancedb\",\n kind: \"directory\",\n },\n {\n // Removing embeddings invalidates the whole semantic index, so the queued\n // background-refresh work is also meaningless: a worker draining a stale\n // queue against an empty ledger would rebuild a partial, inconsistent index\n // (only the queued items vectorized). Clear the queue and its gate so the\n // next mutation re-seeds from a clean slate. See core/search/background-refresh.ts.\n scope: \"embeddings\",\n relativePath: \"search/pending-refresh.json\",\n kind: \"file\",\n },\n {\n scope: \"embeddings\",\n relativePath: \"search/pending-refresh.gate.lock\",\n kind: \"directory\",\n },\n {\n scope: \"runtime\",\n relativePath: \"runtime/test-runs\",\n kind: \"directory\",\n },\n {\n scope: \"runtime\",\n relativePath: \"runtime/history-drift-cache.json\",\n kind: \"file\",\n },\n] as const;\n\n/**\n * Documents the gc command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface GcCommandOptions {\n dryRun?: boolean;\n scope?: string[];\n}\n\n/**\n * Documents the gc locks summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface GcLocksSummary {\n scanned: number;\n removed: number;\n retained: number;\n}\n\n/**\n * Documents the gc checkpoints summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface GcCheckpointsSummary {\n scanned: number;\n removed: number;\n retained: number;\n retention_days: number;\n}\n\n/**\n * Documents the gc result payload exchanged by command, SDK, and package integrations.\n */\nexport interface GcResult {\n ok: boolean;\n dry_run: boolean;\n scope: GcScope[];\n removed: string[];\n retained: string[];\n warnings: string[];\n guidance: string[];\n /** Present only when the locks scope was selected. Summarizes the stale-lock sweep. */\n locks?: GcLocksSummary;\n /** Present only when the checkpoints scope was selected. Summarizes the rollback-checkpoint sweep. */\n checkpoints?: GcCheckpointsSummary;\n generated_at: string;\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === code;\n}\n\nasync function removeCacheFile(\n pmRoot: string,\n target: GcTarget,\n dryRun: boolean,\n): Promise<{ removed: boolean; warnings: string[] }> {\n const relativePath = target.relativePath;\n const absolutePath = path.join(pmRoot, relativePath);\n const warnings = await runActiveOnReadHooks({\n path: absolutePath,\n scope: \"project\",\n });\n try {\n const stats = await fs.stat(absolutePath);\n if (target.kind === \"file\" && !stats.isFile()) {\n return {\n removed: false,\n warnings: [...warnings, `not_a_file:${relativePath}`],\n };\n }\n if (target.kind === \"directory\" && !stats.isDirectory()) {\n return {\n removed: false,\n warnings: [...warnings, `not_a_directory:${relativePath}`],\n };\n }\n if (dryRun) {\n return {\n removed: true,\n warnings,\n };\n }\n if (target.kind === \"file\") {\n await fs.unlink(absolutePath);\n } else {\n await fs.rm(absolutePath, { recursive: true, force: true });\n }\n const writeWarnings = await runActiveOnWriteHooks({\n path: absolutePath,\n scope: \"project\",\n op: \"gc:remove\",\n });\n return {\n removed: true,\n warnings: [...warnings, ...writeWarnings],\n };\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return {\n removed: false,\n warnings,\n };\n }\n throw error;\n }\n}\n\nfunction parseScopes(raw: string[] | undefined): GcScope[] {\n if (!raw || raw.length === 0) {\n return [...GC_SCOPE_VALUES];\n }\n const tokens = raw\n .flatMap((entry) => entry.split(\",\"))\n .map((entry) => entry.trim().toLowerCase())\n .filter((entry) => entry.length > 0);\n if (tokens.length === 0) {\n throw new PmCliError(`--scope requires at least one value (${GC_SCOPE_VALUES.join(\",\")})`, EXIT_CODE.USAGE);\n }\n const resolved = new Set<GcScope>();\n for (const token of tokens) {\n if (!(GC_SCOPE_VALUES as readonly string[]).includes(token)) {\n throw new PmCliError(\n `Invalid --scope value \"${token}\". Expected one or more of: ${GC_SCOPE_VALUES.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n }\n resolved.add(token as GcScope);\n }\n return GC_SCOPE_VALUES.filter((scope) => resolved.has(scope));\n}\n\nfunction buildGcGuidance(params: {\n dryRun: boolean;\n scopes: GcScope[];\n removed: string[];\n}): string[] {\n const guidance: string[] = [];\n if (params.dryRun) {\n guidance.push(\"Dry-run preview only: no cache artifacts were deleted.\");\n }\n const searchScopeSelected = params.scopes.includes(\"index\") || params.scopes.includes(\"embeddings\");\n const searchArtifactsAffected = params.removed.some(\n (entry) =>\n entry === \"index/manifest.json\" ||\n entry === \"search/embeddings.jsonl\" ||\n entry === \"search/vectorization-status.json\" ||\n entry === \"search/lancedb\" ||\n entry === \"search/pending-refresh.json\" ||\n entry === \"search/pending-refresh.gate.lock\",\n );\n if (searchScopeSelected && searchArtifactsAffected) {\n guidance.push(\n 'Search artifacts were removed; the semantic index (including any queued background refresh) is invalidated. Run \"pm install search-advanced --project\" if reindex is unavailable, then \"pm reindex --mode keyword\" (and \"--mode semantic\" when semantic search is enabled) before search-heavy workflows.',\n );\n }\n if (params.removed.includes(\"runtime/history-drift-cache.json\")) {\n guidance.push('History drift cache was removed; the next \"pm health\" run performs a full history-drift re-scan.');\n }\n if (!params.dryRun && params.removed.some((entry) => entry.startsWith(\"checkpoints/\"))) {\n guidance.push(\n 'Aged rollback checkpoints were removed; their \"pm update-many\"/\"pm close-many --rollback\" windows are no longer recoverable.',\n );\n }\n return guidance;\n}\n\n/**\n * Implements run gc for the public runtime surface of this module.\n */\nexport async function runGc(global: GlobalOptions, options: GcCommandOptions = {}): Promise<GcResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const dryRun = options.dryRun === true;\n const scopes = parseScopes(options.scope);\n const selectedTargets = GC_TARGETS.filter((target) => scopes.includes(target.scope));\n\n const removed: string[] = [];\n const retained: string[] = [];\n const warnings: string[] = [];\n\n for (const target of selectedTargets) {\n const result = await removeCacheFile(pmRoot, target, dryRun);\n if (result.removed) {\n removed.push(target.relativePath);\n } else {\n retained.push(target.relativePath);\n }\n warnings.push(...result.warnings);\n }\n\n // The locks scope is not a path-based GC_TARGET: it sweeps the locks/ directory\n // and removes only locks whose own embedded ttl has expired (crashed-process\n // debris), retaining active and unparseable locks. See core/lock/lock-gc.ts.\n let locksSummary: GcLocksSummary | undefined;\n if (scopes.includes(\"locks\")) {\n const lockResult = await runLockGc(pmRoot, {\n dryRun,\n hooks: {\n onRead: (lockPath) => runActiveOnReadHooks({ path: lockPath, scope: \"project\" }),\n onWrite: (lockPath) => runActiveOnWriteHooks({ path: lockPath, scope: \"project\", op: \"gc:lock_remove\" }),\n },\n });\n removed.push(...lockResult.removed);\n retained.push(...lockResult.retained);\n warnings.push(...lockResult.warnings);\n locksSummary = {\n scanned: lockResult.scanned,\n removed: lockResult.removed.length,\n retained: lockResult.retained.length,\n };\n }\n\n // The checkpoints scope is also not a path-based GC_TARGET: it sweeps\n // checkpoints/ and removes only rollback checkpoints older than the configured\n // checkpoints.retention_days, retaining active and unparseable files. See\n // core/checkpoint/checkpoint-gc.ts.\n let checkpointsSummary: GcCheckpointsSummary | undefined;\n if (scopes.includes(\"checkpoints\")) {\n const retentionDays = settings.checkpoints.retention_days;\n const checkpointResult = await runCheckpointGc(pmRoot, {\n dryRun,\n retentionDays,\n hooks: {\n onRead: (checkpointPath) => runActiveOnReadHooks({ path: checkpointPath, scope: \"project\" }),\n onWrite: (checkpointPath) =>\n runActiveOnWriteHooks({ path: checkpointPath, scope: \"project\", op: \"gc:checkpoint_remove\" }),\n },\n });\n removed.push(...checkpointResult.removed);\n retained.push(...checkpointResult.retained);\n warnings.push(...checkpointResult.warnings);\n checkpointsSummary = {\n scanned: checkpointResult.scanned,\n removed: checkpointResult.removed.length,\n retained: checkpointResult.retained.length,\n retention_days: retentionDays,\n };\n }\n\n warnings.push(\n ...(await runActiveOnIndexHooks({\n mode: dryRun ? \"gc:dry-run\" : \"gc\",\n total_items: selectedTargets.length,\n })),\n );\n const guidance = buildGcGuidance({\n dryRun,\n scopes,\n removed,\n });\n\n return {\n ok: warnings.length === 0,\n dry_run: dryRun,\n scope: scopes,\n removed,\n retained,\n warnings,\n ...(locksSummary ? { locks: locksSummary } : {}),\n ...(checkpointsSummary ? { checkpoints: checkpointsSummary } : {}),\n guidance,\n generated_at: nowIso(),\n };\n}\n", "/**\n * @module core/checkpoint/checkpoint-gc\n *\n * Age-based garbage collector for bulk-mutation rollback checkpoints written by\n * `update-many`/`close-many` under `checkpoints/<subdir>/<id>.json`.\n *\n * Safety-first policy (mirroring the stale-lock sweep in `lock/lock-gc.ts`): a\n * checkpoint whose JSON cannot be read or whose `created_at` cannot be parsed is\n * RETAINED rather than deleted. We only prune checkpoints whose age can be\n * conclusively determined from their own `created_at` field and that exceed the\n * configured `checkpoints.retention_days` policy.\n *\n * Staleness formula: (now_ms - Date.parse(created_at)) > retention_days * 86_400_000.\n * A zero/negative age (a future `created_at`) is always treated as active.\n */\n\nimport type { Dirent } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nconst MILLISECONDS_PER_DAY = 86_400_000;\n\n/**\n * Documents the checkpoint gc scan entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface CheckpointGcEntry {\n /** Relative path like \"checkpoints/update-many/update-many-20260619-abc123.json\". */\n file: string;\n /** Parsed `created_at`, or null when missing/unparseable. */\n created_at: string | null;\n /** floor((now - created_at)/1000), null when unparseable. */\n age_seconds: number | null;\n /** True only when classified as expired (older than the retention window). */\n stale: boolean;\n reason: \"expired\" | \"active\" | \"unparseable\";\n}\n\n/**\n * Documents the checkpoint gc hooks payload exchanged by command, SDK, and package integrations.\n */\nexport interface CheckpointGcHooks {\n onRead?: (checkpointPath: string) => Promise<string[]> | string[];\n onWrite?: (checkpointPath: string) => Promise<string[]> | string[];\n}\n\n/**\n * Documents the checkpoint gc options payload exchanged by command, SDK, and package integrations.\n */\nexport interface CheckpointGcOptions {\n dryRun: boolean;\n /**\n * Prune checkpoints older than this many days. Negative values are clamped to\n * zero (prune everything aged); a non-finite value (NaN/Infinity) disables\n * pruning entirely so bad input never deletes recoverable checkpoints.\n */\n retentionDays: number;\n /** Epoch ms; defaults to Date.now() — injectable for deterministic tests. */\n now?: number;\n hooks?: CheckpointGcHooks;\n}\n\n/**\n * Documents the checkpoint gc result payload exchanged by command, SDK, and package integrations.\n */\nexport interface CheckpointGcResult {\n /** Number of *.json checkpoint files examined. */\n scanned: number;\n /** Relative paths removed (or would-remove under dryRun), sorted by file name asc. */\n removed: string[];\n /** Relative paths retained (active OR unparseable — never delete what we can't reason about). */\n retained: string[];\n warnings: string[];\n /** One per scanned checkpoint file, sorted by file name asc. */\n entries: CheckpointGcEntry[];\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === code\n );\n}\n\n/** Extract a parseable `created_at` from a checkpoint's raw JSON, or null. */\nfunction readCheckpointCreatedAt(raw: string): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return null;\n }\n const createdAt = (parsed as Record<string, unknown>).created_at;\n return typeof createdAt === \"string\" ? createdAt : null;\n}\n\n/**\n * Collect relative `checkpoints/<subdir>/<file>.json` (and top-level `<file>.json`)\n * paths under the checkpoints root. Subdirectory reads are resilient to\n * concurrent races: a subdir that vanishes between the parent `readdir` and its\n * own `readdir` (ENOENT) is skipped quietly, and any other read failure (e.g. a\n * permission error) is surfaced as a `checkpoint_subdir_unreadable:<name>`\n * warning rather than aborting the whole sweep.\n */\nasync function collectCheckpointFiles(checkpointsDir: string, warnings: string[]): Promise<string[]> {\n let dirEntries: Dirent[];\n try {\n dirEntries = await fs.readdir(checkpointsDir, { withFileTypes: true });\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return [];\n }\n throw error;\n }\n const files: string[] = [];\n for (const entry of dirEntries) {\n if (entry.isDirectory()) {\n const subdir = path.join(checkpointsDir, entry.name);\n let nested: string[];\n try {\n nested = await fs.readdir(subdir);\n } catch (error: unknown) {\n if (!isErrno(error, \"ENOENT\")) {\n warnings.push(`checkpoint_subdir_unreadable:${entry.name}`);\n }\n continue;\n }\n for (const file of nested) {\n if (file.endsWith(\".json\")) {\n files.push(`${entry.name}/${file}`);\n }\n }\n } else if (entry.name.endsWith(\".json\")) {\n files.push(entry.name);\n }\n }\n return files.sort();\n}\n\n/**\n * Implements run checkpoint gc for the public runtime surface of this module.\n */\nexport async function runCheckpointGc(pmRoot: string, options: CheckpointGcOptions): Promise<CheckpointGcResult> {\n const { dryRun, hooks } = options;\n const nowMs = options.now ?? Date.now();\n const retentionMs = Math.max(0, options.retentionDays) * MILLISECONDS_PER_DAY;\n const checkpointsDir = path.join(pmRoot, \"checkpoints\");\n // A non-finite retentionMs (NaN/Infinity from a non-finite retentionDays)\n // makes every `ageMs > retentionMs` comparison false, so nothing is pruned —\n // pruning is disabled rather than risking deletion under bad input.\n\n const result: CheckpointGcResult = {\n scanned: 0,\n removed: [],\n retained: [],\n warnings: [],\n entries: [],\n };\n\n const files = await collectCheckpointFiles(checkpointsDir, result.warnings);\n for (const relName of files) {\n const absPath = path.join(checkpointsDir, relName);\n const relPath = `checkpoints/${relName}`;\n result.scanned += 1;\n\n if (hooks?.onRead) {\n result.warnings.push(...(await hooks.onRead(absPath)));\n }\n\n let raw: string;\n try {\n raw = await fs.readFile(absPath, \"utf8\");\n } catch (readError: unknown) {\n if (isErrno(readError, \"ENOENT\")) {\n // Disappeared between readdir and readFile — treat as a ghost; skip quietly.\n result.scanned -= 1;\n continue;\n }\n result.warnings.push(`checkpoint_unreadable:${relName}`);\n result.retained.push(relPath);\n result.entries.push({ file: relPath, created_at: null, age_seconds: null, stale: false, reason: \"unparseable\" });\n continue;\n }\n\n const createdAt = readCheckpointCreatedAt(raw);\n const createdAtMs = createdAt === null ? Number.NaN : Date.parse(createdAt);\n if (!Number.isFinite(createdAtMs)) {\n result.warnings.push(`checkpoint_unparseable:${relName}`);\n result.retained.push(relPath);\n result.entries.push({\n file: relPath,\n created_at: createdAt,\n age_seconds: null,\n stale: false,\n reason: \"unparseable\",\n });\n continue;\n }\n\n const ageMs = nowMs - createdAtMs;\n const entry: CheckpointGcEntry = {\n file: relPath,\n created_at: createdAt,\n age_seconds: Math.floor(ageMs / 1000),\n stale: ageMs > retentionMs,\n reason: ageMs > retentionMs ? \"expired\" : \"active\",\n };\n if (!entry.stale) {\n result.retained.push(relPath);\n result.entries.push(entry);\n continue;\n }\n\n if (!dryRun) {\n try {\n await fs.unlink(absPath);\n } catch (unlinkError: unknown) {\n if (!isErrno(unlinkError, \"ENOENT\")) {\n result.warnings.push(`checkpoint_remove_failed:${relName}`);\n result.retained.push(relPath);\n result.entries.push(entry);\n continue;\n }\n // ENOENT on unlink = already gone (race); treat as removed.\n }\n if (hooks?.onWrite) {\n result.warnings.push(...(await hooks.onWrite(absPath)));\n }\n }\n result.removed.push(relPath);\n result.entries.push(entry);\n }\n\n return result;\n}\n", "/**\n * lock-gc.ts — Stale lock file garbage collector.\n *\n * Safety-first policy: if a lock file cannot be read or parsed, it is RETAINED\n * rather than deleted. We only remove locks whose staleness can be conclusively\n * determined from the lock's own embedded `ttl_seconds` field.\n *\n * Staleness formula: (now_ms - Date.parse(created_at)) > ttl_seconds * 1000\n * Zero ttl means any lock older than 0 ms is stale. Negative ttl means always stale.\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\n/**\n * Documents the stale lock scan entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface StaleLockScanEntry {\n /** e.g. \"pm-abc1.lock\" */\n file: string;\n /** parsed id, or null if unparseable */\n id: string | null;\n owner: string | null;\n created_at: string | null;\n ttl_seconds: number | null;\n /** floor((now - created_at)/1000), null if unparseable */\n age_seconds: number | null;\n /** true only when classified expired */\n stale: boolean;\n reason: \"expired\" | \"active\" | \"unparseable\";\n}\n\n/**\n * Documents the lock gc hooks payload exchanged by command, SDK, and package integrations.\n */\nexport interface LockGcHooks {\n onRead?: (lockPath: string) => Promise<string[]> | string[];\n onWrite?: (lockPath: string) => Promise<string[]> | string[];\n}\n\n/**\n * Documents the lock gc options payload exchanged by command, SDK, and package integrations.\n */\nexport interface LockGcOptions {\n dryRun: boolean;\n /** epoch ms; defaults to Date.now() — injectable for deterministic tests */\n now?: number;\n hooks?: LockGcHooks;\n}\n\n/**\n * Documents the lock gc result payload exchanged by command, SDK, and package integrations.\n */\nexport interface LockGcResult {\n /** number of *.lock files examined */\n scanned: number;\n /** relative paths like \"locks/pm-abc1.lock\" (removed, or would-remove under dryRun) */\n removed: string[];\n /** relative paths retained (active OR unparseable — never delete what we can't reason about) */\n retained: string[];\n warnings: string[];\n /** one per scanned *.lock file, sorted by file name asc */\n entries: StaleLockScanEntry[];\n}\n\ninterface ParsedLock {\n id: string;\n owner: string;\n created_at: string;\n ttl_seconds: number;\n}\n\nfunction parseLock(raw: string): ParsedLock | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return null;\n }\n const candidate = parsed as Record<string, unknown>;\n const { id, owner, created_at, ttl_seconds } = candidate;\n if (\n typeof id !== \"string\" ||\n typeof owner !== \"string\" ||\n typeof created_at !== \"string\" ||\n typeof ttl_seconds !== \"number\" ||\n !Number.isFinite(ttl_seconds)\n ) {\n return null;\n }\n return { id, owner, created_at, ttl_seconds };\n}\n\nfunction isErrno(error: unknown, code: string): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: string }).code === code\n );\n}\n\n/**\n * Fine-grained classification outcome for one readable lock file's content.\n * `unparseable_json` and `invalid_timestamp` both surface as the coarse\n * `reason: \"unparseable\"` on the scan entry (gc retains both), but stay\n * distinct here so callers can emit precise warnings.\n */\nexport type LockClassificationDetail = \"active\" | \"expired\" | \"unparseable_json\" | \"invalid_timestamp\";\n\n/**\n * Documents the lock content classification payload exchanged by command, SDK, and package integrations.\n */\nexport interface LockContentClassification {\n detail: LockClassificationDetail;\n entry: StaleLockScanEntry;\n}\n\n/**\n * Pure classification of one lock file's raw content against `nowMs`. This is\n * the single staleness/parse policy shared by `pm gc --scope locks` (which acts\n * on it) and the `pm health` locks check (which only reports it).\n */\nexport function classifyLockContent(file: string, raw: string, nowMs: number): LockContentClassification {\n const lock = parseLock(raw);\n if (lock === null) {\n return {\n detail: \"unparseable_json\",\n entry: {\n file,\n id: null,\n owner: null,\n created_at: null,\n ttl_seconds: null,\n age_seconds: null,\n stale: false,\n reason: \"unparseable\",\n },\n };\n }\n const createdAtMs = Date.parse(lock.created_at);\n if (!Number.isFinite(createdAtMs)) {\n return {\n detail: \"invalid_timestamp\",\n entry: {\n file,\n id: lock.id,\n owner: lock.owner,\n created_at: lock.created_at,\n ttl_seconds: lock.ttl_seconds,\n age_seconds: null,\n stale: false,\n reason: \"unparseable\",\n },\n };\n }\n const ageMs = nowMs - createdAtMs;\n const age_seconds = Math.floor(ageMs / 1000);\n const stale = ageMs > lock.ttl_seconds * 1000;\n return {\n detail: stale ? \"expired\" : \"active\",\n entry: {\n file,\n id: lock.id,\n owner: lock.owner,\n created_at: lock.created_at,\n ttl_seconds: lock.ttl_seconds,\n age_seconds,\n stale,\n reason: stale ? \"expired\" : \"active\",\n },\n };\n}\n\n/**\n * Documents the lock health scan payload exchanged by command, SDK, and package integrations.\n */\nexport interface LockHealthScan {\n /** number of *.lock files examined (ghost files that vanish mid-scan are skipped) */\n scanned: number;\n active_lock_count: number;\n stale_lock_count: number;\n unreadable_lock_count: number;\n /** invalid JSON, wrong shape, or an unparseable created_at timestamp */\n unparseable_lock_count: number;\n}\n\n/**\n * Read-only locks scan for `pm health`: classifies every lock file with the\n * same policy `pm gc --scope locks` uses but never removes anything.\n */\nexport async function scanLockHealth(pmRoot: string, now?: number): Promise<LockHealthScan> {\n const nowMs = now ?? Date.now();\n const locksDir = path.join(pmRoot, \"locks\");\n const scan: LockHealthScan = {\n scanned: 0,\n active_lock_count: 0,\n stale_lock_count: 0,\n unreadable_lock_count: 0,\n unparseable_lock_count: 0,\n };\n\n let dirEntries: string[];\n try {\n const rawDir = await fs.readdir(locksDir);\n dirEntries = rawDir.filter((f) => f.endsWith(\".lock\")).sort();\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return scan;\n }\n throw error;\n }\n\n for (const file of dirEntries) {\n let raw: string;\n try {\n raw = await fs.readFile(path.join(locksDir, file), \"utf8\");\n } catch (readError: unknown) {\n if (isErrno(readError, \"ENOENT\")) {\n // Disappeared between readdir and readFile — treat as a ghost; skip quietly.\n continue;\n }\n scan.scanned += 1;\n scan.unreadable_lock_count += 1;\n continue;\n }\n scan.scanned += 1;\n const { detail } = classifyLockContent(file, raw, nowMs);\n if (detail === \"active\") {\n scan.active_lock_count += 1;\n } else if (detail === \"expired\") {\n scan.stale_lock_count += 1;\n } else {\n scan.unparseable_lock_count += 1;\n }\n }\n\n return scan;\n}\n\n/**\n * Implements run lock gc for the public runtime surface of this module.\n */\nexport async function runLockGc(pmRoot: string, options: LockGcOptions): Promise<LockGcResult> {\n const { dryRun, hooks } = options;\n const nowMs = options.now ?? Date.now();\n const locksDir = path.join(pmRoot, \"locks\");\n\n const result: LockGcResult = {\n scanned: 0,\n removed: [],\n retained: [],\n warnings: [],\n entries: [],\n };\n\n let dirEntries: string[];\n try {\n const raw = await fs.readdir(locksDir);\n dirEntries = raw.filter((f) => f.endsWith(\".lock\")).sort();\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n return result;\n }\n throw error;\n }\n\n for (const file of dirEntries) {\n result.scanned += 1;\n const absPath = path.join(locksDir, file);\n const relPath = `locks/${file}`;\n\n // --- onRead hook ---\n if (hooks?.onRead) {\n const hookWarnings = await hooks.onRead(absPath);\n result.warnings.push(...hookWarnings);\n }\n\n // --- read file ---\n let raw: string;\n try {\n raw = await fs.readFile(absPath, \"utf8\");\n } catch (readError: unknown) {\n if (isErrno(readError, \"ENOENT\")) {\n // Disappeared between readdir and readFile — treat as a ghost; skip quietly.\n result.scanned -= 1;\n continue;\n }\n result.warnings.push(`lock_unreadable:${file}`);\n result.retained.push(relPath);\n result.entries.push({\n file,\n id: null,\n owner: null,\n created_at: null,\n ttl_seconds: null,\n age_seconds: null,\n stale: false,\n reason: \"unparseable\",\n });\n continue;\n }\n\n // --- classify (shared with the read-only pm health locks scan) ---\n const classified = classifyLockContent(file, raw, nowMs);\n if (classified.detail === \"unparseable_json\") {\n result.warnings.push(`lock_unparseable:${file}`);\n result.retained.push(relPath);\n result.entries.push(classified.entry);\n continue;\n }\n if (classified.detail === \"invalid_timestamp\") {\n result.warnings.push(`lock_invalid_timestamp:${file}`);\n result.retained.push(relPath);\n result.entries.push(classified.entry);\n continue;\n }\n if (classified.detail === \"active\") {\n result.retained.push(relPath);\n result.entries.push(classified.entry);\n continue;\n }\n\n // --- stale: remove or preview ---\n if (!dryRun) {\n try {\n await fs.unlink(absPath);\n } catch (unlinkError: unknown) {\n if (!isErrno(unlinkError, \"ENOENT\")) {\n result.warnings.push(`lock_remove_failed:${file}`);\n result.retained.push(relPath);\n result.entries.push(classified.entry);\n continue;\n }\n // ENOENT on unlink = already gone (race); treat as removed\n }\n // onWrite hook after successful removal\n if (hooks?.onWrite) {\n const hookWarnings = await hooks.onWrite(absPath);\n result.warnings.push(...hookWarnings);\n }\n }\n\n result.removed.push(relPath);\n result.entries.push(classified.entry);\n }\n\n return result;\n}\n", "/**\n * @module cli/commands/health\n *\n * Implements the pm health command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { pathExists, readFileIfExists } from \"../../core/fs/fs-utils.js\";\nimport { activateExtensions, getActiveExtensionRegistrations, loadExtensions, runActiveOnReadHooks } from \"../../core/extensions/index.js\";\nimport { collectRegisteredItemFieldNames } from \"../../core/extensions/item-fields.js\";\nimport {\n KNOWN_EXTENSION_CAPABILITIES,\n type LoadedExtension,\n} from \"../../core/extensions/loader.js\";\nimport { enforceHistoryStreamPolicyForItems } from \"../../core/history/history-stream-policy.js\";\nimport { scanHistoryDrift } from \"../../core/history/drift-scan.js\";\nimport { scanLockHealth } from \"../../core/lock/lock-gc.js\";\nimport {\n readVectorizationStatusLedger,\n refreshSemanticEmbeddingsForMutatedItems,\n} from \"../../core/search/cache.js\";\nimport { resolveEmbeddingProviders, resolveProviderConfigSource } from \"../../core/search/providers.js\";\nimport { resolveSettingsWithSemanticRuntimeDefaults } from \"../../core/search/semantic-defaults.js\";\nimport { collectStaleVectorizationIds } from \"../../core/search/staleness.js\";\nimport {\n buildVectorizationEmbeddingIdentity,\n hasVectorizationEmbeddingIdentityChanged,\n} from \"../../core/search/vectorization-metadata.js\";\nimport { resolveVectorStores } from \"../../core/search/vector-stores.js\";\nimport { EXIT_CODE, PM_CORE_REQUIRED_SUBDIRS, PM_OPTIONAL_TYPE_SUBDIRS } from \"../../core/shared/constants.js\";\nimport { findFirstMergeConflictMarker } from \"../../core/shared/conflict-markers.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { toNonEmptyStringOrUndefined } from \"../../core/shared/primitives.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { parseItemDocument } from \"../../core/item/item-format.js\";\nimport { effectiveItemFormatVersion, scanItemFormatVersions } from \"../../core/item/item-format-version.js\";\nimport { listAllFrontMatter, listAllFrontMatterWithBody } from \"../../core/store/item-store.js\";\nimport {\n PM_TELEMETRY_SOURCE_CONTEXT_VALUES,\n TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS,\n TELEMETRY_SCHEMA_VERSION,\n} from \"../../core/telemetry/runtime.js\";\n\nconst PM_TELEMETRY_SOURCE_CONTEXT_SET = new Set<string>(PM_TELEMETRY_SOURCE_CONTEXT_VALUES);\nimport {\n getItemFormatFromPath,\n getSettingsPath,\n ITEM_FILE_EXTENSIONS,\n resolveGlobalPmRoot,\n resolvePmRoot,\n} from \"../../core/store/paths.js\";\nimport { readSettingsWithMetadata } from \"../../core/store/settings.js\";\nimport { buildRemediationMap } from \"../../core/diagnostics/remediation.js\";\nimport type { HistoryCompactPolicy, ItemFormat, ItemMetadata, PmSettings } from \"../../types/index.js\";\nimport { readManagedExtensionState } from \"./extension.js\";\nimport {\n buildCapabilityContractMetadata,\n buildRegistrationCollisionRemediation,\n collectUnknownCapabilityGuidance,\n} from \"./extension/doctor.js\";\n\ntype HealthStatus = \"ok\" | \"warn\";\ntype MigrationRuntimeStatus = \"pending\" | \"failed\" | \"applied\";\n\n/**\n * Documents the health check payload exchanged by command, SDK, and package integrations.\n */\nexport interface HealthCheck {\n name:\n | \"settings\"\n | \"directories\"\n | \"settings_values\"\n | \"telemetry\"\n | \"extensions\"\n | \"storage\"\n | \"locks\"\n | \"integrity\"\n | \"history_drift\"\n | \"vectorization\";\n status: HealthStatus;\n details: Record<string, unknown>;\n}\n\n/**\n * Documents the health result payload exchanged by command, SDK, and package integrations.\n */\nexport interface HealthResult {\n ok: boolean;\n checks: HealthCheck[];\n warning_count?: number;\n warnings: string[];\n projection?: {\n mode: \"brief\" | \"summary\" | \"full\";\n warning_count: number;\n warnings_truncated: boolean;\n detail_limit: number;\n omitted_checks?: HealthCheck[\"name\"][];\n };\n generated_at: string;\n}\n\n/**\n * Documents the run health options payload exchanged by command, SDK, and package integrations.\n */\nexport interface RunHealthOptions {\n strictDirectories?: boolean;\n checkOnly?: boolean;\n checkTelemetry?: boolean;\n noRefresh?: boolean;\n refreshVectors?: boolean;\n verboseStaleItems?: boolean;\n skipVectors?: boolean;\n skipIntegrity?: boolean;\n skipDrift?: boolean;\n full?: boolean;\n brief?: boolean;\n summary?: boolean;\n}\n\ninterface VectorRefreshPolicy {\n enabled: boolean;\n checkOnly: boolean;\n noRefresh: boolean;\n refreshVectors: boolean;\n}\n\ninterface MigrationStatusEntry {\n layer: \"global\" | \"project\";\n name: string;\n id: string;\n status: MigrationRuntimeStatus;\n reason?: string;\n}\n\ninterface MigrationStatusSummary {\n applied: MigrationStatusEntry[];\n pending: MigrationStatusEntry[];\n failed: MigrationStatusEntry[];\n applied_count: number;\n pending_count: number;\n failed_count: number;\n}\n\ninterface ExtensionHealthTriageSummary {\n status: \"ok\" | \"warn\";\n warning_count: number;\n warning_codes: string[];\n load_failure_count: number;\n activation_failure_count: number;\n migration_failed_count: number;\n migration_pending_count: number;\n managed_state_warning_count: number;\n managed_extension_entries_count: number;\n unmanaged_loaded_extension_count: number;\n unmanaged_loaded_extensions: string[];\n unmanaged_expected_extension_count: number;\n unmanaged_expected_extensions: string[];\n unmanaged_action_required_extension_count: number;\n unmanaged_action_required_extensions: string[];\n update_health_coverage: \"full\" | \"partial\";\n update_health_partial: boolean;\n unknown_capability_count: number;\n top_warnings: string[];\n remediation: string[];\n}\n\ntype ItemWithBody = Awaited<ReturnType<typeof listAllFrontMatterWithBody>>[number];\nconst STALE_VECTORIZATION_SUMMARY_LIMIT = 25;\nconst BRIEF_HEALTH_DETAIL_LIMIT = 8;\nconst TELEMETRY_QUEUE_RELATIVE_PATH = path.join(\"runtime\", \"telemetry\", \"events.jsonl\");\nconst TELEMETRY_STATE_RELATIVE_PATH = path.join(\"runtime\", \"telemetry\", \"state.json\");\nconst TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS = 2_500;\nconst TELEMETRY_QUEUE_HIGH_WATER_MARK = 500;\nconst TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD = TELEMETRY_MAX_QUEUE_ENTRY_ATTEMPTS - 3;\nconst TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS = [\n \"x-pm-telemetry-max-schema-version\",\n \"x-pm-telemetry-max-version\",\n] as const;\n\n/**\n * Advisory warnings are surfaced for visibility but never flip overall health to\n * not-ok. Telemetry is opt-out, non-critical observability: a queued/unreachable\n * telemetry endpoint or corrupt local telemetry state is not a project-health\n * failure and must not block agents that gate on `pm health` `ok`. History\n * over-compaction-threshold warnings are likewise advisory maintenance hints —\n * a deep stream is healthy, just a candidate for `pm history-compact`.\n */\nfunction isAdvisoryHealthWarning(warning: string): boolean {\n return warning.startsWith(\"telemetry_\") || warning.startsWith(\"history_stream_over_compact_threshold:\");\n}\n\nfunction warningCode(value: string): string {\n const normalized = value.trim();\n const separator = normalized.indexOf(\":\");\n if (separator === -1) {\n return normalized;\n }\n return normalized.slice(0, separator);\n}\n\nfunction normalizeExtensionNameForMatch(value: string): string {\n return value.trim().toLowerCase();\n}\n\nfunction isExpectedUnmanagedExtension(name: string, directory: string): boolean {\n const normalizedName = normalizeExtensionNameForMatch(name);\n const normalizedDirectory = normalizeExtensionNameForMatch(directory);\n if (normalizedName.startsWith(\"builtin-\")) {\n return true;\n }\n return normalizedDirectory === \"beads\" || normalizedDirectory === \"todos\";\n}\n\nasync function isDirectory(targetPath: string): Promise<boolean> {\n try {\n const stats = await fs.stat(targetPath);\n return stats.isDirectory();\n } catch {\n return false;\n }\n}\n\n/**\n * Summary of the history-stream directory used by the storage health check.\n * `over_threshold` is populated only when the compaction policy is enabled —\n * counting entries requires reading every stream, so the default (policy-off)\n * path stays a cheap directory listing.\n */\ninterface HistoryStreamSummary {\n count: number;\n warnings: string[];\n over_threshold: string[];\n max_entries: number | null;\n}\n\nasync function countHistoryStreams(\n pmRoot: string,\n compactPolicy: HistoryCompactPolicy,\n): Promise<HistoryStreamSummary> {\n const historyDir = path.join(pmRoot, \"history\");\n if (!(await isDirectory(historyDir))) {\n return { count: 0, warnings: [], over_threshold: [], max_entries: null };\n }\n const historyFiles = (await fs.readdir(historyDir))\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .sort((left, right) => left.localeCompare(right));\n\n const policyActive = compactPolicy.enabled;\n const maxEntries = policyActive ? compactPolicy.max_entries : null;\n const warnings: string[] = [];\n const overThreshold: string[] = [];\n for (const fileName of historyFiles) {\n const streamPath = path.join(historyDir, fileName);\n warnings.push(...(await runActiveOnReadHooks({ path: streamPath, scope: \"project\" })));\n if (!policyActive) {\n continue;\n }\n const raw = await fs.readFile(streamPath, \"utf8\");\n let entries = 0;\n for (const line of raw.split(/\\r?\\n/)) {\n if (line.trim().length > 0) {\n entries += 1;\n }\n }\n if (entries > compactPolicy.max_entries) {\n overThreshold.push(fileName.slice(0, -\".jsonl\".length));\n }\n }\n\n return {\n count: historyFiles.length,\n warnings: [...warnings, ...overThreshold.map((id) => `history_stream_over_compact_threshold:${id}`)],\n over_threshold: overThreshold,\n max_entries: maxEntries,\n };\n}\n\nfunction normalizeRelativePath(pmRoot: string, targetPath: string): string {\n return path.relative(pmRoot, targetPath).replaceAll(\"\\\\\", \"/\");\n}\n\nasync function listItemDocumentPaths(pmRoot: string, typeToFolder: Record<string, string>): Promise<string[]> {\n const folders = [...new Set(Object.values(typeToFolder))].sort((left, right) => left.localeCompare(right));\n const itemPaths: string[] = [];\n for (const folder of folders) {\n const directoryPath = path.join(pmRoot, folder);\n let entries: string[] = [];\n try {\n entries = await fs.readdir(directoryPath);\n } catch (error: unknown) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\") {\n continue;\n }\n continue;\n }\n for (const entry of entries) {\n if (!ITEM_FILE_EXTENSIONS.some((extension) => entry.toLowerCase().endsWith(extension))) {\n continue;\n }\n itemPaths.push(path.join(directoryPath, entry));\n }\n }\n itemPaths.sort((left, right) => normalizeRelativePath(pmRoot, left).localeCompare(normalizeRelativePath(pmRoot, right)));\n return itemPaths;\n}\n\nfunction shouldReportHistoryDirectoryUnreadable(error: unknown): boolean {\n return !(typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\");\n}\n\nasync function buildIntegrityCheck(\n pmRoot: string,\n typeToFolder: Record<string, string>,\n schema: PmSettings[\"schema\"],\n): Promise<{ check: HealthCheck; warnings: string[] }> {\n const itemPaths = await listItemDocumentPaths(pmRoot, typeToFolder);\n const itemUnreadable: string[] = [];\n const itemConflictMarkers: Array<{ path: string; line: number; marker: string }> = [];\n const itemParseFailures: string[] = [];\n const formatVersionEntries: Array<{ ref: string; version: number }> = [];\n const extensionFieldNames = collectRegisteredItemFieldNames(getActiveExtensionRegistrations());\n\n for (const itemPath of itemPaths) {\n const relativePath = normalizeRelativePath(pmRoot, itemPath);\n let raw = \"\";\n try {\n raw = await fs.readFile(itemPath, \"utf8\");\n } catch {\n itemUnreadable.push(relativePath);\n continue;\n }\n const conflictMarker = findFirstMergeConflictMarker(raw);\n if (conflictMarker) {\n itemConflictMarkers.push({\n path: relativePath,\n line: conflictMarker.line,\n marker: conflictMarker.marker,\n });\n continue;\n }\n try {\n const parsed = parseItemDocument(raw, { format: getItemFormatFromPath(itemPath) as ItemFormat, schema, extensionFieldNames });\n formatVersionEntries.push({ ref: relativePath, version: effectiveItemFormatVersion(parsed.metadata) });\n } catch {\n itemParseFailures.push(relativePath);\n }\n }\n const formatVersionScan = scanItemFormatVersions(formatVersionEntries);\n\n const historyDir = path.join(pmRoot, \"history\");\n const historyUnreadable: string[] = [];\n const historyConflictMarkers: Array<{ id: string; line: number; marker: string }> = [];\n const historyInvalidJson: Array<{ id: string; line: number }> = [];\n let historyFiles: string[] = [];\n try {\n historyFiles = (await fs.readdir(historyDir)).filter((entry) => entry.endsWith(\".jsonl\")).sort((left, right) => left.localeCompare(right));\n } catch (error: unknown) {\n /* c8 ignore start -- ENOENT/non-ENOENT differentiation requires filesystem fault injection */\n if (shouldReportHistoryDirectoryUnreadable(error)) {\n historyUnreadable.push(\"history\");\n }\n /* c8 ignore stop */\n }\n for (const fileName of historyFiles) {\n const itemId = fileName.slice(0, -\".jsonl\".length);\n const historyPath = path.join(historyDir, fileName);\n let raw = \"\";\n try {\n raw = await fs.readFile(historyPath, \"utf8\");\n } catch {\n historyUnreadable.push(itemId);\n continue;\n }\n const conflictMarker = findFirstMergeConflictMarker(raw);\n if (conflictMarker) {\n historyConflictMarkers.push({\n id: itemId,\n line: conflictMarker.line,\n marker: conflictMarker.marker,\n });\n continue;\n }\n const lines = raw.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]?.trim();\n if (!line) {\n continue;\n }\n try {\n JSON.parse(line);\n } catch {\n historyInvalidJson.push({\n id: itemId,\n line: index + 1,\n });\n }\n }\n }\n\n const warnings = [\n ...itemUnreadable.map((entry) => `integrity_item_unreadable:${entry}`),\n ...itemConflictMarkers.map((entry) => `integrity_item_conflict_marker:${entry.path}:L${entry.line}`),\n ...itemParseFailures.map((entry) => `integrity_item_parse_failed:${entry}`),\n ...historyUnreadable.map((entry) => `integrity_history_unreadable:${entry}`),\n ...historyConflictMarkers.map((entry) => `integrity_history_conflict_marker:${entry.id}:L${entry.line}`),\n ...historyInvalidJson.map((entry) => `integrity_history_invalid_json:${entry.id}:L${entry.line}`),\n /* c8 ignore start -- outdated-version items are unreachable until CURRENT_ITEM_FORMAT_VERSION advances past the baseline (an effective version below 1 cannot occur); the per-item mapping is covered in item-format-version.spec, and the ahead path below is covered by health-command.spec */\n ...formatVersionScan.outdated.map((entry) => `integrity_item_outdated_format_version:${entry}`),\n /* c8 ignore stop */\n ...formatVersionScan.ahead.map((entry) => `integrity_item_ahead_format_version:${entry}`),\n ];\n const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n\n return {\n check: {\n name: \"integrity\",\n status: normalizedWarnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_item_files: itemPaths.length,\n checked_history_streams: historyFiles.length,\n counts: {\n item_unreadable: itemUnreadable.length,\n item_conflict_markers: itemConflictMarkers.length,\n item_parse_failures: itemParseFailures.length,\n history_unreadable: historyUnreadable.length,\n history_conflict_markers: historyConflictMarkers.length,\n history_invalid_json: historyInvalidJson.length,\n item_outdated_format_version: formatVersionScan.outdated.length,\n item_ahead_format_version: formatVersionScan.ahead.length,\n },\n item_unreadable: itemUnreadable,\n item_conflict_markers: itemConflictMarkers,\n item_parse_failures: itemParseFailures,\n item_outdated_format_version: formatVersionScan.outdated,\n item_ahead_format_version: formatVersionScan.ahead,\n history_unreadable: historyUnreadable,\n history_conflict_markers: historyConflictMarkers,\n history_invalid_json: historyInvalidJson,\n },\n },\n warnings: normalizedWarnings,\n };\n}\n\n/* c8 ignore start -- activate export shape variants are exercised through integration load tests */\nfunction hasActivateExport(moduleRecord: Record<string, unknown>): boolean {\n if (typeof moduleRecord.activate === \"function\") {\n return true;\n }\n const defaultExport = moduleRecord.default;\n if (typeof defaultExport !== \"object\" || defaultExport === null) {\n return false;\n }\n return typeof (defaultExport as Record<string, unknown>).activate === \"function\";\n}\n/* c8 ignore stop */\n\nfunction summarizeLoadedExtension(extension: LoadedExtension): Record<string, unknown> {\n const summary: Record<string, unknown> = {\n layer: extension.layer,\n directory: extension.directory,\n manifest_path: extension.manifest_path,\n name: extension.name,\n version: extension.version,\n entry: extension.entry,\n priority: extension.priority,\n entry_path: extension.entry_path,\n has_activate: hasActivateExport(extension.module as Record<string, unknown>),\n };\n /* c8 ignore start -- capability list optionality is exercised by extension load integration suites */\n if (Array.isArray(extension.capabilities)) {\n summary.capabilities = [...extension.capabilities];\n }\n /* c8 ignore stop */\n return summary;\n}\n\nfunction resolveMigrationId(definition: Record<string, unknown>, fallbackIndex: number): string {\n const explicitId = toNonEmptyStringOrUndefined(definition.id);\n if (explicitId) {\n return explicitId;\n }\n return `migration-${String(fallbackIndex + 1).padStart(3, \"0\")}`;\n}\n\nfunction resolveMigrationStatus(definition: Record<string, unknown>): MigrationRuntimeStatus {\n const rawStatus = toNonEmptyStringOrUndefined(definition.status);\n const normalized = rawStatus?.toLowerCase();\n if (normalized === \"failed\") {\n return \"failed\";\n }\n if (normalized === \"applied\") {\n return \"applied\";\n }\n return \"pending\";\n}\n\nfunction resolveMigrationFailureReason(definition: Record<string, unknown>): string | undefined {\n return toNonEmptyStringOrUndefined(definition.reason) ?? toNonEmptyStringOrUndefined(definition.error) ?? toNonEmptyStringOrUndefined(definition.message);\n}\n\n/* c8 ignore start -- comparator tie-break branches are deterministic ordering glue exercised via migration integration tests */\nfunction compareMigrationEntries(left: MigrationStatusEntry, right: MigrationStatusEntry): number {\n const byLayer = (left.layer ?? \"\").localeCompare(right.layer ?? \"\");\n if (byLayer !== 0) {\n return byLayer;\n }\n const byName = (left.name ?? \"\").localeCompare(right.name ?? \"\");\n if (byName !== 0) {\n return byName;\n }\n return (left.id ?? \"\").localeCompare(right.id ?? \"\");\n}\n/* c8 ignore stop */\n\nfunction summarizeMigrationStatuses(\n migrations: Array<{\n layer: \"global\" | \"project\";\n name: string;\n definition: Record<string, unknown>;\n }>,\n): { summary: MigrationStatusSummary; warnings: string[] } {\n const applied: MigrationStatusEntry[] = [];\n const pending: MigrationStatusEntry[] = [];\n const failed: MigrationStatusEntry[] = [];\n\n migrations.forEach((migration, index) => {\n const id = resolveMigrationId(migration.definition, index);\n const status = resolveMigrationStatus(migration.definition);\n if (status === \"applied\") {\n applied.push({\n layer: migration.layer,\n name: migration.name,\n id,\n status,\n });\n return;\n }\n if (status === \"failed\") {\n failed.push({\n layer: migration.layer,\n name: migration.name,\n id,\n status,\n reason: resolveMigrationFailureReason(migration.definition),\n });\n return;\n }\n pending.push({\n layer: migration.layer,\n name: migration.name,\n id,\n status,\n });\n });\n\n applied.sort(compareMigrationEntries);\n pending.sort(compareMigrationEntries);\n failed.sort(compareMigrationEntries);\n\n const warnings = [\n ...failed.map((entry) => `extension_migration_failed:${entry.layer}:${entry.name}:${entry.id}`),\n ...pending.map((entry) => `extension_migration_pending:${entry.layer}:${entry.name}:${entry.id}`),\n ];\n\n return {\n summary: {\n applied,\n pending,\n failed,\n applied_count: applied.length,\n pending_count: pending.length,\n failed_count: failed.length,\n },\n warnings,\n };\n}\n\nfunction buildExtensionHealthTriageSummary(\n warnings: string[],\n loadFailureCount: number,\n activationFailureCount: number,\n migrationStatus: MigrationStatusSummary,\n managedStateWarningCount: number,\n managedExtensionEntriesCount: number,\n unmanagedLoadedExtensions: string[],\n unmanagedExpectedExtensions: string[],\n unmanagedActionRequiredExtensions: string[],\n): ExtensionHealthTriageSummary {\n const normalizedWarnings = [...new Set(warnings)].sort((left, right) => left.localeCompare(right));\n const warningCodes = [...new Set(normalizedWarnings.map((value) => warningCode(value)))].sort((left, right) =>\n left.localeCompare(right),\n );\n const unknownCapabilityCount = normalizedWarnings.filter((warning) => warning.startsWith(\"extension_capability_unknown:\")).length;\n const updateHealthPartial = unmanagedActionRequiredExtensions.length > 0;\n const updateHealthCoverage = updateHealthPartial ? \"partial\" : \"full\";\n const remediation: string[] = [];\n const registrationCollisionRemediation = buildRegistrationCollisionRemediation(normalizedWarnings, {\n deactivate: \"pm extension --deactivate <name> --project/--global\",\n doctor: \"pm extension --doctor --project/--global --detail deep --trace\",\n });\n if (registrationCollisionRemediation) {\n remediation.push(registrationCollisionRemediation);\n }\n if (loadFailureCount > 0) {\n remediation.push(\"Run pm extension --explore --project and pm extension --explore --global to inspect load failures.\");\n }\n if (activationFailureCount > 0) {\n remediation.push(\"Review checks[name=extensions].details.activation.failed in pm health --json for activation error details.\");\n }\n if (migrationStatus.failed_count > 0 || migrationStatus.pending_count > 0) {\n remediation.push(\"Resolve pending/failed extension migrations before write commands; use --force only when policy allows.\");\n }\n if (managedStateWarningCount > 0) {\n remediation.push(\"Run pm extension --manage --project and pm extension --manage --global to refresh managed-state diagnostics.\");\n }\n if (unknownCapabilityCount > 0) {\n remediation.push(\n `Unknown extension capabilities detected. Allowed capabilities: ${KNOWN_EXTENSION_CAPABILITIES.join(\", \")}. ` +\n \"Review extension_capability_unknown warning details for suggested replacements.\",\n );\n }\n if (normalizedWarnings.some((warning) => warning.startsWith(\"extension_capability_legacy_alias:\"))) {\n remediation.push(\n \"Legacy extension capability aliases were auto-remapped to canonical capabilities. \" +\n \"Update manifests to canonical names (migration/validation -> schema).\",\n );\n }\n if (normalizedWarnings.some((warning) => warning.startsWith(\"extension_command_definition_legacy_handler_alias:\"))) {\n remediation.push(\n \"Extension command definitions using legacy handler were auto-remapped. \" +\n \"Update command definitions to use run: (context) => ... for forward compatibility.\",\n );\n }\n if (updateHealthPartial) {\n remediation.push(\n \"Update-check coverage is partial because unmanaged extensions need adoption. Adopt existing installs via pm extension --manage --project/--global --fix-managed-state, pm extension --adopt-all --project/--global, or pm extension --adopt <name>.\",\n );\n } else if (unmanagedLoadedExtensions.length > 0) {\n remediation.push(\n \"Loaded unmanaged extensions are currently treated as informational. Use pm extension --manage --project/--global --fix-managed-state to adopt them for update checks.\",\n );\n }\n if (remediation.length === 0) {\n remediation.push(\"No immediate action required. Re-run pm health after extension configuration changes.\");\n }\n return {\n status: normalizedWarnings.length === 0 ? \"ok\" : \"warn\",\n warning_count: normalizedWarnings.length,\n warning_codes: warningCodes,\n load_failure_count: loadFailureCount,\n activation_failure_count: activationFailureCount,\n migration_failed_count: migrationStatus.failed_count,\n migration_pending_count: migrationStatus.pending_count,\n managed_state_warning_count: managedStateWarningCount,\n managed_extension_entries_count: managedExtensionEntriesCount,\n unmanaged_loaded_extension_count: unmanagedLoadedExtensions.length,\n unmanaged_loaded_extensions: unmanagedLoadedExtensions,\n unmanaged_expected_extension_count: unmanagedExpectedExtensions.length,\n unmanaged_expected_extensions: unmanagedExpectedExtensions,\n unmanaged_action_required_extension_count: unmanagedActionRequiredExtensions.length,\n unmanaged_action_required_extensions: unmanagedActionRequiredExtensions,\n update_health_coverage: updateHealthCoverage,\n update_health_partial: updateHealthPartial,\n unknown_capability_count: unknownCapabilityCount,\n top_warnings: normalizedWarnings.slice(0, 8),\n remediation,\n };\n}\n\nasync function buildExtensionCheck(\n pmRoot: string,\n settings: PmSettings,\n noExtensionsFlag: boolean,\n): Promise<{ check: HealthCheck; warnings: string[] }> {\n const loadResult = await loadExtensions({\n pmRoot,\n settings,\n cwd: process.cwd(),\n noExtensions: noExtensionsFlag,\n });\n const loadedSummaries = loadResult.loaded.map((extension) => summarizeLoadedExtension(extension));\n const activationResult = await activateExtensions({\n ...loadResult,\n loaded: loadResult.loaded,\n });\n const [projectManagedState, globalManagedState] = await Promise.all([\n readManagedExtensionState(loadResult.roots.project),\n readManagedExtensionState(loadResult.roots.global),\n ]);\n const migrationStatus = summarizeMigrationStatuses(activationResult.registrations.migrations);\n const activationDetails = {\n failed: activationResult.failed,\n warnings: activationResult.warnings,\n hook_counts: activationResult.hook_counts,\n command_override_count: activationResult.command_override_count,\n command_handler_count: activationResult.command_handler_count,\n parser_override_count: activationResult.parser_override_count,\n preflight_override_count: activationResult.preflight_override_count,\n service_override_count: activationResult.service_override_count,\n renderer_override_count: activationResult.renderer_override_count,\n registration_counts: activationResult.registration_counts,\n registrations: activationResult.registrations,\n migration_status: migrationStatus.summary,\n managed_extensions: {\n project: {\n path: projectManagedState.path,\n count: projectManagedState.state.entries.length,\n entries: projectManagedState.state.entries,\n },\n global: {\n path: globalManagedState.path,\n count: globalManagedState.state.entries.length,\n entries: globalManagedState.state.entries,\n },\n },\n };\n /* c8 ignore start -- unmanaged/expected grouping matrices are exercised in doctor + extension integration suites */\n const managedProjectNames = new Set(\n projectManagedState.state.entries.map((entry) => normalizeExtensionNameForMatch(entry.name)),\n );\n const managedGlobalNames = new Set(globalManagedState.state.entries.map((entry) => normalizeExtensionNameForMatch(entry.name)));\n const unmanagedLoadedEntries = [\n ...new Map(\n loadResult.loaded\n .filter((entry) => {\n const managedNames = entry.layer === \"project\" ? managedProjectNames : managedGlobalNames;\n return !managedNames.has(normalizeExtensionNameForMatch(entry.name));\n })\n .map((entry) => [\n `${entry.layer}:${entry.name}`,\n {\n layer: entry.layer,\n name: entry.name,\n directory: entry.directory,\n },\n ]),\n ).values(),\n ].sort((left, right) => {\n const leftKey = `${left.layer}:${left.name}`;\n const rightKey = `${right.layer}:${right.name}`;\n return leftKey.localeCompare(rightKey);\n });\n const unmanagedLoadedExtensions = unmanagedLoadedEntries\n .map((entry) => `${entry.layer}:${entry.name}`)\n .sort((left, right) => left.localeCompare(right));\n const unmanagedExpectedExtensions = unmanagedLoadedEntries\n .filter((entry) => isExpectedUnmanagedExtension(entry.name, entry.directory))\n .map((entry) => `${entry.layer}:${entry.name}`)\n .sort((left, right) => left.localeCompare(right));\n const unmanagedActionRequiredExtensions = unmanagedLoadedEntries\n .filter((entry) => !isExpectedUnmanagedExtension(entry.name, entry.directory))\n .map((entry) => `${entry.layer}:${entry.name}`)\n .sort((left, right) => left.localeCompare(right));\n /* c8 ignore stop */\n const updateCoverageWarnings =\n unmanagedActionRequiredExtensions.length > 0\n ? [`extension_update_health_partial_coverage:skipped_unmanaged:${unmanagedActionRequiredExtensions.length}`]\n : [];\n const extensionWarnings = [\n ...loadResult.warnings,\n ...activationDetails.warnings,\n ...migrationStatus.warnings,\n ...projectManagedState.warnings,\n ...globalManagedState.warnings,\n ...updateCoverageWarnings,\n ];\n const capabilityGuidance = collectUnknownCapabilityGuidance(extensionWarnings);\n const capabilityContract = buildCapabilityContractMetadata();\n const extensionTriage = buildExtensionHealthTriageSummary(\n extensionWarnings,\n loadResult.failed.length,\n activationResult.failed.length,\n migrationStatus.summary,\n projectManagedState.warnings.length + globalManagedState.warnings.length,\n projectManagedState.state.entries.length + globalManagedState.state.entries.length,\n unmanagedLoadedExtensions,\n unmanagedExpectedExtensions,\n unmanagedActionRequiredExtensions,\n );\n\n return {\n check: {\n name: \"extensions\",\n status: extensionWarnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n ...loadResult,\n loaded: loadedSummaries,\n warnings: extensionWarnings,\n activation: activationDetails,\n triage: extensionTriage,\n capability_contract: capabilityContract,\n capability_guidance: capabilityGuidance,\n } as Record<string, unknown>,\n },\n warnings: extensionWarnings,\n };\n}\n\nfunction summarizeList(values: string[], limit: number): { values: string[]; truncated: boolean } {\n if (values.length <= limit) {\n return { values, truncated: false };\n }\n return {\n values: values.slice(0, limit),\n truncated: true,\n };\n}\n\nfunction summarizeRecordList(value: unknown, limit: number): { count: number; sample: unknown[]; truncated: boolean } {\n if (!Array.isArray(value)) {\n return {\n count: 0,\n sample: [],\n truncated: false,\n };\n }\n return {\n count: value.length,\n sample: value.slice(0, limit),\n truncated: value.length > limit,\n };\n}\n\nfunction summarizeExtensionRecord(value: unknown): Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return {};\n }\n const record = value as Record<string, unknown>;\n return {\n layer: record.layer,\n directory: record.directory,\n name: record.name,\n version: record.version,\n enabled: record.enabled,\n status: record.status,\n has_activate: record.has_activate,\n capabilities: record.capabilities,\n };\n}\n\nfunction summarizeExtensionList(value: unknown, limit: number): { count: number; sample: unknown[]; truncated: boolean } {\n const summary = summarizeRecordList(value, limit);\n return {\n ...summary,\n sample: summary.sample.map((entry) => summarizeExtensionRecord(entry)),\n };\n}\n\nfunction summarizeStringList(value: unknown, limit: number): { count: number; sample: string[]; truncated: boolean } {\n if (!Array.isArray(value)) {\n return {\n count: 0,\n sample: [],\n truncated: false,\n };\n }\n const strings = value.filter((entry): entry is string => typeof entry === \"string\");\n return {\n count: strings.length,\n sample: strings.slice(0, limit),\n truncated: strings.length > limit,\n };\n}\n\ntype HealthDetailSummarizer = (details: Record<string, unknown>, limit: number) => Record<string, unknown>;\n\nfunction summarizeActivationMigrationStatus(value: unknown): Record<string, unknown> | null {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n const status = value as Record<string, unknown>;\n return {\n applied_count: status.applied_count,\n pending_count: status.pending_count,\n failed_count: status.failed_count,\n };\n}\n\nconst HEALTH_DETAIL_SUMMARIZERS = {\n settings: (details, limit) => ({\n version: details.version,\n id_prefix: details.id_prefix,\n locks_ttl_seconds: details.locks_ttl_seconds,\n warnings: summarizeStringList(details.warnings, limit),\n }),\n directories: (details, limit) => ({\n required_count: Array.isArray(details.required) ? details.required.length : 0,\n optional_count: Array.isArray(details.optional) ? details.optional.length : 0,\n missing_required: summarizeStringList(details.missing_required, limit),\n missing_optional: summarizeStringList(details.missing_optional, limit),\n missing: summarizeStringList(details.missing, limit),\n strict_directories: details.strict_directories,\n }),\n settings_values: (details, limit) => ({\n warnings: summarizeStringList(details.warnings, limit),\n }),\n telemetry: (details) => ({\n enabled: details.enabled,\n capture_level: details.capture_level,\n endpoint: details.endpoint,\n queue_exists: details.queue_exists,\n queue_entries: details.queue_entries,\n queue_draining: details.queue_draining,\n queue_invalid_rows: details.queue_invalid_rows,\n queue_rows_total: details.queue_rows_total,\n last_successful_flush_at: details.last_successful_flush_at,\n last_failed_flush_at: details.last_failed_flush_at,\n endpoint_probe: details.endpoint_probe,\n env_overrides: details.env_overrides,\n }),\n extensions: (details, limit) => {\n const activation = typeof details.activation === \"object\" && details.activation !== null ? (details.activation as Record<string, unknown>) : {};\n return {\n disabled_by_flag: details.disabled_by_flag,\n discovered: summarizeExtensionList(details.discovered, limit),\n effective: summarizeExtensionList(details.effective, limit),\n loaded: summarizeExtensionList(details.loaded, limit),\n failed: summarizeRecordList(details.failed, limit),\n warnings: summarizeStringList(details.warnings, limit),\n activation: {\n failed: summarizeRecordList(activation.failed, limit),\n warnings: summarizeStringList(activation.warnings, limit),\n hook_counts: activation.hook_counts,\n command_handler_count: activation.command_handler_count,\n service_override_count: activation.service_override_count,\n renderer_override_count: activation.renderer_override_count,\n registration_counts: activation.registration_counts,\n migration_status: summarizeActivationMigrationStatus(activation.migration_status),\n },\n triage: details.triage,\n capability_contract: details.capability_contract,\n capability_guidance: summarizeRecordList(details.capability_guidance, limit),\n };\n },\n // Storage details are already compact counters; keep the pre-refactor pass-through shape.\n storage: (details) => details,\n locks: (details) => ({\n active_lock_count: details.active_lock_count,\n stale_lock_count: details.stale_lock_count,\n unreadable_lock_count: details.unreadable_lock_count,\n unparseable_lock_count: details.unparseable_lock_count,\n }),\n integrity: (details, limit) => ({\n checked_item_files: details.checked_item_files,\n checked_history_streams: details.checked_history_streams,\n counts: details.counts,\n item_unreadable: summarizeStringList(details.item_unreadable, limit),\n item_conflict_markers: summarizeRecordList(details.item_conflict_markers, limit),\n item_parse_failures: summarizeStringList(details.item_parse_failures, limit),\n history_unreadable: summarizeStringList(details.history_unreadable, limit),\n history_conflict_markers: summarizeRecordList(details.history_conflict_markers, limit),\n history_invalid_json: summarizeRecordList(details.history_invalid_json, limit),\n skipped: details.skipped,\n }),\n history_drift: (details, limit) => ({\n checked_items: details.checked_items,\n counts: details.counts,\n drifted_items: summarizeStringList(details.drifted_items, limit),\n missing_streams: summarizeStringList(details.missing_streams, limit),\n unreadable_streams: summarizeStringList(details.unreadable_streams, limit),\n hash_mismatches: summarizeStringList(details.hash_mismatches, limit),\n chain_mismatches: summarizeStringList(details.chain_mismatches, limit),\n skipped: details.skipped,\n }),\n vectorization: (details, limit) => ({\n semantic_runtime_available: details.semantic_runtime_available,\n compatibility_mode_auto_defaults: details.compatibility_mode_auto_defaults,\n auto_ollama_defaults_applied: details.auto_ollama_defaults_applied,\n auto_ollama_defaults_skipped_reason: details.auto_ollama_defaults_skipped_reason,\n auto_ollama_defaults_remediation: details.auto_ollama_defaults_remediation,\n refresh_policy: details.refresh_policy,\n provider_active: details.provider_active,\n vector_store_active: details.vector_store_active,\n items: details.items,\n ledger_entries_before: details.ledger_entries_before,\n stale_items_before_total: details.stale_items_before_total,\n stale_items_before: summarizeStringList(details.stale_items_before, limit),\n refresh_attempted: details.refresh_attempted,\n refresh_skipped_reason: details.refresh_skipped_reason,\n refresh_result: details.refresh_result,\n ledger_entries_after: details.ledger_entries_after,\n stale_items_after_total: details.stale_items_after_total,\n stale_items_after: summarizeStringList(details.stale_items_after, limit),\n skipped: details.skipped,\n }),\n} satisfies Record<HealthCheck[\"name\"], HealthDetailSummarizer>;\n\n/* c8 ignore start -- brief/summary projection matrix branches are validated in projection integration tests */\nfunction summarizeHealthCheckDetails(check: HealthCheck, limit: number): Record<string, unknown> {\n const summarize = HEALTH_DETAIL_SUMMARIZERS[check.name];\n return summarize ? summarize(check.details, limit) : check.details;\n}\n/* c8 ignore stop */\n\nfunction applyBriefHealthProjection(result: HealthResult): HealthResult {\n const warningsSummary = summarizeStringList(result.warnings, BRIEF_HEALTH_DETAIL_LIMIT);\n return {\n ok: result.ok,\n checks: result.checks.map((check) => ({\n name: check.name,\n status: check.status,\n details: summarizeHealthCheckDetails(check, BRIEF_HEALTH_DETAIL_LIMIT),\n })),\n warnings: warningsSummary.sample,\n projection: {\n mode: \"brief\",\n warning_count: warningsSummary.count,\n warnings_truncated: warningsSummary.truncated,\n detail_limit: BRIEF_HEALTH_DETAIL_LIMIT,\n },\n generated_at: result.generated_at,\n };\n}\n\nfunction isSkippedHealthCheck(check: HealthCheck): boolean {\n return check.details.skipped === true;\n}\n\nfunction applySummaryHealthProjection(result: HealthResult): HealthResult {\n const warningsSummary = summarizeStringList(result.warnings, BRIEF_HEALTH_DETAIL_LIMIT);\n const omittedChecks = result.checks.filter(isSkippedHealthCheck).map((check) => check.name);\n return {\n ok: result.ok,\n checks: result.checks\n .filter((check) => !isSkippedHealthCheck(check))\n .map((check) => ({\n name: check.name,\n status: check.status,\n details: {},\n })),\n warning_count: warningsSummary.count,\n warnings: warningsSummary.sample,\n projection: {\n mode: \"summary\",\n warning_count: warningsSummary.count,\n warnings_truncated: warningsSummary.truncated,\n detail_limit: BRIEF_HEALTH_DETAIL_LIMIT,\n omitted_checks: omittedChecks,\n },\n generated_at: result.generated_at,\n };\n}\n\nfunction selectStaleItemDetail(\n values: string[],\n verboseStaleItems: boolean,\n): {\n values: string[];\n truncated: boolean;\n total: number;\n} {\n if (verboseStaleItems) {\n return {\n values,\n truncated: false,\n total: values.length,\n };\n }\n const summary = summarizeList(values, STALE_VECTORIZATION_SUMMARY_LIMIT);\n return {\n values: summary.values,\n truncated: summary.truncated,\n total: values.length,\n };\n}\n\ntype VectorizationRuntimeDefaults = ReturnType<typeof resolveSettingsWithSemanticRuntimeDefaults>;\ntype VectorizationProviderResolution = ReturnType<typeof resolveEmbeddingProviders>;\ntype VectorizationStoreResolution = ReturnType<typeof resolveVectorStores>;\ntype VectorizationLedger = Awaited<ReturnType<typeof readVectorizationStatusLedger>>;\ntype VectorizationRefreshResult = Awaited<ReturnType<typeof refreshSemanticEmbeddingsForMutatedItems>>;\n\ninterface VectorizationRuntimeSnapshot {\n runtimeDefaults: VectorizationRuntimeDefaults;\n providerResolution: VectorizationProviderResolution;\n vectorStoreResolution: VectorizationStoreResolution;\n runtimeEmbeddingIdentity: ReturnType<typeof buildVectorizationEmbeddingIdentity> | null;\n semanticRuntimeAvailable: boolean;\n}\n\ninterface TelemetryRuntimeStateRecord {\n endpoint?: string;\n queue_entries?: number;\n last_attempted_flush_at?: string;\n last_successful_flush_at?: string;\n last_failed_flush_at?: string;\n last_failed_flush_error?: string;\n pending_otel_spans?: number;\n last_otel_attempt_at?: string;\n last_otel_success_at?: string;\n last_otel_failure_at?: string;\n last_otel_failure_error?: string;\n}\n\nfunction telemetryEnvFlagEnabled(\n envKey: \"PM_TELEMETRY_DISABLED\" | \"PM_TELEMETRY_OTEL_DISABLED\" | \"PM_NO_TELEMETRY\" | \"PM_TELEMETRY_INLINE_FLUSH\",\n): boolean {\n const value = (process.env[envKey] ?? \"\").trim().toLowerCase();\n return value === \"1\" || value === \"true\" || value === \"yes\" || value === \"on\";\n}\n\n/* c8 ignore start -- environment override permutations are covered by runtime integration tests */\nfunction telemetrySourceContextOverride(): string | null {\n // Only report an override the runtime actually honours: runtime.ts ignores any\n // value outside the enum and falls back to the inferred context, so health must\n // report null for an unrecognized value rather than implying it took effect.\n const value = (process.env.PM_TELEMETRY_SOURCE_CONTEXT ?? \"\").trim().toLowerCase();\n return PM_TELEMETRY_SOURCE_CONTEXT_SET.has(value) ? value : null;\n}\n/* c8 ignore stop */\n\nfunction normalizeEndpointForDisplay(rawEndpoint: string): string {\n const trimmed = rawEndpoint.trim();\n if (trimmed.length === 0) {\n return \"\";\n }\n try {\n const parsed = new URL(trimmed);\n parsed.username = \"\";\n parsed.password = \"\";\n parsed.search = \"\";\n parsed.hash = \"\";\n return parsed.toString();\n } catch {\n return trimmed;\n }\n}\n\nfunction parseTelemetryQueue(raw: string): {\n validEntries: number;\n invalidRows: number;\n totalRows: number;\n highRetryEntries: number;\n maxAttempts: number;\n} {\n let validEntries = 0;\n let invalidRows = 0;\n let totalRows = 0;\n let highRetryEntries = 0;\n let maxAttempts = 0;\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n totalRows += 1;\n try {\n const parsed = JSON.parse(trimmed) as Record<string, unknown>;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof parsed.attempts === \"number\" &&\n Number.isFinite(parsed.attempts)\n ) {\n const attempts = Math.max(0, Math.trunc(parsed.attempts));\n validEntries += 1;\n maxAttempts = Math.max(maxAttempts, attempts);\n if (attempts >= TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD) {\n highRetryEntries += 1;\n }\n } else {\n /* c8 ignore next -- invalid queue rows are covered by end-to-end telemetry fixtures */\n invalidRows += 1;\n }\n } catch {\n invalidRows += 1;\n }\n }\n return {\n validEntries,\n invalidRows,\n totalRows,\n highRetryEntries,\n maxAttempts,\n };\n}\n\ntype TelemetryQueueSummary = ReturnType<typeof parseTelemetryQueue>;\n\ninterface TelemetryEndpointProbeSummary {\n attempted: boolean;\n probe_url?: string;\n ok?: boolean;\n status?: number;\n max_schema_version?: string;\n error?: string;\n}\n\nfunction emptyTelemetryQueueSummary(): TelemetryQueueSummary {\n return { validEntries: 0, invalidRows: 0, totalRows: 0, highRetryEntries: 0, maxAttempts: 0 };\n}\n\n/* c8 ignore start -- telemetry state corruption and otel-failure branches require runtime-coordinated fixture mutation */\nfunction parseTelemetryRuntimeState(stateRaw: string | null): { runtimeState: TelemetryRuntimeStateRecord; stateParseFailed: boolean } {\n if (!stateRaw || stateRaw.trim().length === 0) {\n return { runtimeState: {}, stateParseFailed: false };\n }\n try {\n const parsed = JSON.parse(stateRaw) as TelemetryRuntimeStateRecord;\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return { runtimeState: parsed, stateParseFailed: false };\n }\n return { runtimeState: {}, stateParseFailed: true };\n } catch {\n return { runtimeState: {}, stateParseFailed: true };\n }\n}\n\nasync function maybeProbeTelemetryEndpoint(\n settings: PmSettings,\n checkTelemetry: boolean,\n): Promise<TelemetryEndpointProbeSummary | undefined> {\n const endpoint = settings.telemetry.endpoint.trim();\n if (!checkTelemetry || !settings.telemetry.enabled || endpoint.length === 0) {\n return undefined;\n }\n const probe = await probeTelemetryEndpointHealth(endpoint);\n return {\n attempted: true,\n ...probe,\n };\n}\n\nfunction collectTelemetryQueueWarnings(\n settings: PmSettings,\n queueSummary: TelemetryQueueSummary,\n runtimeState: TelemetryRuntimeStateRecord,\n): string[] {\n const warnings: string[] = [];\n if (queueSummary.invalidRows > 0) {\n warnings.push(`telemetry_queue_invalid_rows:${queueSummary.invalidRows}`);\n }\n if (!settings.telemetry.enabled || queueSummary.validEntries === 0) {\n return warnings;\n }\n const lastSuccess = runtimeState.last_successful_flush_at;\n const lastFailure = runtimeState.last_failed_flush_at;\n const activeFailure = lastFailure && (!lastSuccess || lastFailure > lastSuccess);\n const neverFlushed = !lastSuccess;\n const highWater = queueSummary.validEntries >= TELEMETRY_QUEUE_HIGH_WATER_MARK;\n if (activeFailure || neverFlushed || highWater) {\n warnings.push(`telemetry_queue_pending:${queueSummary.validEntries}`);\n }\n if (queueSummary.highRetryEntries > 0) {\n warnings.push(`telemetry_queue_high_retries:${queueSummary.highRetryEntries}`);\n }\n return warnings;\n}\n\nfunction collectTelemetryEndpointWarnings(endpointProbe: TelemetryEndpointProbeSummary | undefined): string[] {\n if (!endpointProbe || endpointProbe.ok !== false) {\n return [];\n }\n return typeof endpointProbe.status === \"number\"\n ? [`telemetry_endpoint_probe_http_status:${endpointProbe.status}`]\n : [\"telemetry_endpoint_probe_failed\"];\n}\n\nfunction collectTelemetrySchemaWarnings(endpointProbe: TelemetryEndpointProbeSummary | undefined): string[] {\n const parsedMaxSchemaVersion = Number.parseInt(endpointProbe?.max_schema_version ?? \"\", 10);\n if (endpointProbe?.ok === true && Number.isInteger(parsedMaxSchemaVersion) && parsedMaxSchemaVersion > TELEMETRY_SCHEMA_VERSION) {\n return [`telemetry_schema_version_behind:${parsedMaxSchemaVersion}`];\n }\n return [];\n}\n\nfunction collectTelemetryOtelWarnings(settings: PmSettings, runtimeState: TelemetryRuntimeStateRecord): string[] {\n const pendingOtelSpans = typeof runtimeState.pending_otel_spans === \"number\" ? runtimeState.pending_otel_spans : 0;\n const lastOtelSuccess = runtimeState.last_otel_success_at;\n const lastOtelFailure = runtimeState.last_otel_failure_at;\n const otelExportFailing =\n settings.telemetry.enabled &&\n pendingOtelSpans > 0 &&\n Boolean(lastOtelFailure) &&\n // >= so a mixed-outcome batch (success + failure share the same attempt\n // timestamp) still surfaces the warning rather than being masked by the tie.\n (!lastOtelSuccess || (lastOtelFailure as string) >= lastOtelSuccess);\n return otelExportFailing ? [`telemetry_otel_export_failing:${pendingOtelSpans}`] : [];\n}\n\nfunction buildTelemetryEnvOverrideDetails(): Record<string, unknown> {\n return {\n telemetry_disabled: telemetryEnvFlagEnabled(\"PM_TELEMETRY_DISABLED\") || telemetryEnvFlagEnabled(\"PM_NO_TELEMETRY\"),\n pm_no_telemetry: telemetryEnvFlagEnabled(\"PM_NO_TELEMETRY\"),\n telemetry_otel_disabled: telemetryEnvFlagEnabled(\"PM_TELEMETRY_OTEL_DISABLED\"),\n telemetry_inline_flush: telemetryEnvFlagEnabled(\"PM_TELEMETRY_INLINE_FLUSH\"),\n telemetry_source_context: telemetrySourceContextOverride(),\n };\n}\n/* c8 ignore stop */\n\nfunction telemetryQueueHasEntries(settings: PmSettings, queueSummary: TelemetryQueueSummary): boolean {\n return settings.telemetry.enabled && queueSummary.validEntries > 0;\n}\n\nfunction isTelemetryQueueDraining(queueHasEntries: boolean, warnings: string[]): boolean {\n return (\n queueHasEntries &&\n warnings.every(\n (warning) => !warning.startsWith(\"telemetry_queue_pending:\") && !warning.startsWith(\"telemetry_queue_high_retries:\"),\n )\n );\n}\n\nasync function probeTelemetryEndpointHealth(endpoint: string): Promise<{\n probe_url: string;\n ok: boolean;\n status?: number;\n max_schema_version?: string;\n error?: string;\n}> {\n let probeUrl = endpoint;\n try {\n const parsed = new URL(endpoint);\n parsed.pathname = \"/healthz\";\n parsed.search = \"\";\n parsed.hash = \"\";\n probeUrl = parsed.toString();\n } catch {\n // keep original endpoint when URL parsing fails\n }\n try {\n const response = await fetch(probeUrl, {\n method: \"GET\",\n signal: AbortSignal.timeout(TELEMETRY_ENDPOINT_PROBE_TIMEOUT_MS),\n });\n return {\n probe_url: normalizeEndpointForDisplay(probeUrl),\n ok: response.ok,\n status: response.status,\n max_schema_version: (() => {\n for (const headerName of TELEMETRY_SERVER_MAX_SCHEMA_VERSION_HEADERS) {\n const value = response.headers.get(headerName)?.trim();\n if (value && value.length > 0) {\n return value;\n }\n }\n return undefined;\n })(),\n };\n } catch (error: unknown) {\n return {\n probe_url: normalizeEndpointForDisplay(probeUrl),\n ok: false,\n /* c8 ignore next -- non-Error throwables require transport-layer fault injection */\n error: error instanceof Error ? error.message : \"probe_failed\",\n };\n }\n}\n\nasync function buildTelemetryCheck(\n settings: PmSettings,\n options: { checkTelemetry: boolean },\n): Promise<{ check: HealthCheck; warnings: string[] }> {\n const globalPmRoot = resolveGlobalPmRoot(process.cwd());\n const queuePath = path.join(globalPmRoot, TELEMETRY_QUEUE_RELATIVE_PATH);\n const statePath = path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);\n\n const queueRaw = await readFileIfExists(queuePath);\n const queueExists = queueRaw !== null;\n const queueSizeBytes = queueRaw ? Buffer.byteLength(queueRaw, \"utf8\") : 0;\n const queueSummary = queueRaw ? parseTelemetryQueue(queueRaw) : emptyTelemetryQueueSummary();\n\n const stateRaw = await readFileIfExists(statePath);\n const { runtimeState, stateParseFailed } = parseTelemetryRuntimeState(stateRaw);\n\n const endpoint = settings.telemetry.endpoint.trim();\n const endpointDisplay = normalizeEndpointForDisplay(endpoint);\n const endpointProbe = await maybeProbeTelemetryEndpoint(settings, options.checkTelemetry);\n\n const warnings: string[] = [];\n if (stateParseFailed) {\n warnings.push(\"telemetry_state_invalid_json\");\n }\n warnings.push(\n ...collectTelemetryQueueWarnings(settings, queueSummary, runtimeState),\n ...collectTelemetryEndpointWarnings(endpointProbe),\n ...collectTelemetrySchemaWarnings(endpointProbe),\n ...collectTelemetryOtelWarnings(settings, runtimeState),\n );\n const queueHasEntries = telemetryQueueHasEntries(settings, queueSummary);\n const pendingOtelSpans = typeof runtimeState.pending_otel_spans === \"number\" ? runtimeState.pending_otel_spans : 0;\n\n return {\n check: {\n name: \"telemetry\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n enabled: settings.telemetry.enabled,\n capture_level: settings.telemetry.capture_level,\n endpoint: endpointDisplay,\n global_pm_root: globalPmRoot,\n queue_path: queuePath,\n queue_exists: queueExists,\n queue_entries: queueSummary.validEntries,\n queue_draining: isTelemetryQueueDraining(queueHasEntries, warnings),\n queue_invalid_rows: queueSummary.invalidRows,\n queue_rows_total: queueSummary.totalRows,\n queue_size_bytes: queueSizeBytes,\n queue_high_retry_entries: queueSummary.highRetryEntries,\n queue_high_retry_threshold: TELEMETRY_QUEUE_HIGH_RETRY_THRESHOLD,\n queue_max_attempts: queueSummary.maxAttempts,\n runtime_state_path: statePath,\n last_attempted_flush_at: runtimeState.last_attempted_flush_at ?? null,\n last_successful_flush_at: runtimeState.last_successful_flush_at ?? null,\n last_failed_flush_at: runtimeState.last_failed_flush_at ?? null,\n last_failed_flush_error: runtimeState.last_failed_flush_error ?? null,\n pending_otel_spans: pendingOtelSpans,\n last_otel_attempt_at: runtimeState.last_otel_attempt_at ?? null,\n last_otel_success_at: runtimeState.last_otel_success_at ?? null,\n last_otel_failure_at: runtimeState.last_otel_failure_at ?? null,\n last_otel_failure_error: runtimeState.last_otel_failure_error ?? null,\n endpoint_probe: endpointProbe ?? { attempted: false },\n env_overrides: buildTelemetryEnvOverrideDetails(),\n },\n },\n warnings,\n };\n}\n\n/**\n * Read-only locks check (pm-xo1n): surfaces active/stale/unreadable/unparseable\n * lock counts using the exact classification `pm gc --scope locks` acts on, so\n * agents can gate on stale item-claim locks before running gc speculatively.\n */\nasync function buildLocksCheck(pmRoot: string): Promise<{ check: HealthCheck; warnings: string[] }> {\n /* c8 ignore start -- scan failure branches require filesystem-level fault injection */\n let scan: Awaited<ReturnType<typeof scanLockHealth>>;\n try {\n scan = await scanLockHealth(pmRoot);\n } catch (error: unknown) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n check: {\n name: \"locks\",\n status: \"warn\",\n details: {\n active_lock_count: 0,\n stale_lock_count: 0,\n unreadable_lock_count: 0,\n unparseable_lock_count: 0,\n scan_failed: true,\n error: message,\n pm_root: pmRoot,\n },\n },\n warnings: [`locks_scan_failed:${message}`],\n };\n }\n const warnings: string[] = [];\n if (scan.stale_lock_count > 0) {\n warnings.push(`locks_stale_count:${scan.stale_lock_count}`);\n }\n if (scan.unreadable_lock_count > 0) {\n warnings.push(`locks_unreadable:${scan.unreadable_lock_count}`);\n }\n /* c8 ignore stop */\n return {\n check: {\n name: \"locks\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n active_lock_count: scan.active_lock_count,\n stale_lock_count: scan.stale_lock_count,\n unreadable_lock_count: scan.unreadable_lock_count,\n unparseable_lock_count: scan.unparseable_lock_count,\n },\n },\n warnings,\n };\n}\n\nasync function buildHistoryDriftCheck(\n pmRoot: string,\n items: ItemWithBody[],\n): Promise<{ check: HealthCheck; warnings: string[] }> {\n const cacheHitVerification = \"metadata\" as const;\n const { missingStreams, unreadableStreams, hashMismatches, chainMismatches, driftedItems } = await scanHistoryDrift(\n pmRoot,\n items,\n { cacheHitVerification },\n );\n const warnings = [\n ...missingStreams.map((id) => `history_drift_missing_stream:${id}`),\n ...unreadableStreams.map((id) => `history_drift_unreadable_stream:${id}`),\n ...hashMismatches.map((id) => `history_drift_hash_mismatch:${id}`),\n ...chainMismatches.map((id) => `history_drift_chain_mismatch:${id}`),\n ];\n return {\n check: {\n name: \"history_drift\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_items: items.length,\n cache_hit_verification: cacheHitVerification,\n drifted_items: driftedItems,\n counts: {\n drifted: driftedItems.length,\n missing_streams: missingStreams.length,\n unreadable_streams: unreadableStreams.length,\n hash_mismatches: hashMismatches.length,\n chain_mismatches: chainMismatches.length,\n },\n missing_streams: missingStreams,\n unreadable_streams: unreadableStreams,\n hash_mismatches: hashMismatches,\n chain_mismatches: chainMismatches,\n },\n },\n warnings,\n };\n}\n\nfunction buildVectorizationRuntimeSnapshot(settings: PmSettings, pmRoot: string): VectorizationRuntimeSnapshot {\n const runtimeDefaults = resolveSettingsWithSemanticRuntimeDefaults(settings);\n const providerResolution = resolveEmbeddingProviders(runtimeDefaults.settings);\n const vectorStoreResolution = resolveVectorStores(runtimeDefaults.settings, pmRoot);\n const runtimeEmbeddingIdentity = providerResolution.active\n ? buildVectorizationEmbeddingIdentity(providerResolution.active.name, providerResolution.active.model)\n : null;\n return {\n runtimeDefaults,\n providerResolution,\n vectorStoreResolution,\n runtimeEmbeddingIdentity,\n semanticRuntimeAvailable: Boolean(providerResolution.active && vectorStoreResolution.active),\n };\n}\n\nfunction emptyVectorizationRefreshResult(): VectorizationRefreshResult {\n return {\n refreshed: [],\n skipped: [],\n warnings: [],\n };\n}\n\nasync function refreshStaleVectorizationItems(params: {\n pmRoot: string;\n snapshot: VectorizationRuntimeSnapshot;\n refreshPolicy: VectorRefreshPolicy;\n staleBefore: string[];\n}): Promise<VectorizationRefreshResult> {\n if (!params.refreshPolicy.enabled || !params.snapshot.semanticRuntimeAvailable || params.staleBefore.length === 0) {\n return emptyVectorizationRefreshResult();\n }\n return refreshSemanticEmbeddingsForMutatedItems(params.pmRoot, params.staleBefore, {\n settings: params.snapshot.runtimeDefaults.settings,\n apply_runtime_defaults: false,\n });\n}\n\nfunction vectorizationEmbeddingIdentityChanged(params: {\n strictVectorizationWarnings: boolean;\n semanticRuntimeAvailable: boolean;\n ledgerBefore: VectorizationLedger;\n runtimeEmbeddingIdentity: VectorizationRuntimeSnapshot[\"runtimeEmbeddingIdentity\"];\n}): boolean {\n return (\n params.strictVectorizationWarnings &&\n params.semanticRuntimeAvailable &&\n Boolean(\n params.ledgerBefore.embedding &&\n params.runtimeEmbeddingIdentity &&\n hasVectorizationEmbeddingIdentityChanged(params.ledgerBefore.embedding, params.runtimeEmbeddingIdentity),\n )\n );\n}\n\n/* c8 ignore start -- strict-vectorization warning synthesis branches are integration-only policy permutations */\nfunction collectVectorizationWarnings(params: {\n ledgerBefore: VectorizationLedger;\n ledgerAfter: VectorizationLedger;\n refreshResult: VectorizationRefreshResult;\n strictVectorizationWarnings: boolean;\n semanticRuntimeAvailable: boolean;\n embeddingIdentityChanged: boolean;\n staleAfter: string[];\n}): string[] {\n const warningSet = new Set<string>([...params.ledgerBefore.warnings, ...params.ledgerAfter.warnings]);\n if (params.strictVectorizationWarnings) {\n for (const warning of params.refreshResult.warnings) {\n warningSet.add(warning);\n }\n }\n if (params.embeddingIdentityChanged) {\n warningSet.add(\"vectorization_embedding_identity_changed\");\n }\n if (params.strictVectorizationWarnings && params.semanticRuntimeAvailable && params.staleAfter.length > 0) {\n warningSet.add(`vectorization_stale_items_remaining:${params.staleAfter.length}`);\n }\n return [...warningSet].sort((left, right) => left.localeCompare(right));\n}\n/* c8 ignore stop */\n\nfunction resolveVectorizationRefreshSkippedReason(\n refreshPolicy: VectorRefreshPolicy,\n semanticRuntimeAvailable: boolean,\n staleBefore: string[],\n): string | null {\n if (refreshPolicy.enabled && semanticRuntimeAvailable && staleBefore.length > 0) {\n return null;\n }\n if (!refreshPolicy.enabled) {\n return \"refresh_disabled\";\n }\n return semanticRuntimeAvailable ? \"no_stale_items\" : \"semantic_runtime_unavailable\";\n}\n\nfunction buildVectorizationProviderDetails(settings: PmSettings, snapshot: VectorizationRuntimeSnapshot): Record<string, unknown> {\n const activeProvider = snapshot.providerResolution.active?.name ?? null;\n const activeVectorStore = snapshot.vectorStoreResolution.active?.name ?? null;\n return {\n provider_active: activeProvider,\n // GH-244: surface the persisted (possibly empty) configured value and\n // how the active resolution was sourced, so a config audit can tell\n // \"auto-detected\" apart from a genuine misconfiguration when\n // settings.search.provider / vector_store.adapter are empty strings.\n provider_configured: typeof settings.search?.provider === \"string\" ? settings.search.provider : null,\n provider_source: resolveProviderConfigSource(activeProvider, settings.search?.provider ?? null),\n vector_store_active: activeVectorStore,\n vector_store_configured: typeof settings.vector_store?.adapter === \"string\" ? settings.vector_store.adapter : null,\n vector_store_source: resolveProviderConfigSource(activeVectorStore, settings.vector_store?.adapter ?? null),\n };\n}\n\nfunction buildVectorizationRefreshPolicyDetails(refreshPolicy: VectorRefreshPolicy): Record<string, unknown> {\n return {\n enabled: refreshPolicy.enabled,\n check_only: refreshPolicy.checkOnly,\n no_refresh: refreshPolicy.noRefresh,\n refresh_vectors: refreshPolicy.refreshVectors,\n };\n}\n\nfunction vectorizationRefreshAttempted(\n refreshPolicy: VectorRefreshPolicy,\n semanticRuntimeAvailable: boolean,\n staleBefore: string[],\n): boolean {\n return refreshPolicy.enabled && staleBefore.length > 0 && semanticRuntimeAvailable;\n}\n\nasync function buildVectorizationCheck(\n pmRoot: string,\n settings: PmSettings,\n items: ItemWithBody[],\n refreshPolicy: VectorRefreshPolicy,\n verboseStaleItems: boolean,\n): Promise<{ check: HealthCheck; warnings: string[] }> {\n const snapshot = buildVectorizationRuntimeSnapshot(settings, pmRoot);\n const ledgerBefore = await readVectorizationStatusLedger(pmRoot);\n const staleBefore = snapshot.semanticRuntimeAvailable ? collectStaleVectorizationIds(items, ledgerBefore.entries) : [];\n const refreshResult = await refreshStaleVectorizationItems({ pmRoot, snapshot, refreshPolicy, staleBefore });\n const ledgerAfter = await readVectorizationStatusLedger(pmRoot);\n const staleAfter = snapshot.semanticRuntimeAvailable ? collectStaleVectorizationIds(items, ledgerAfter.entries) : [];\n const strictVectorizationWarnings = !snapshot.runtimeDefaults.auto_ollama_defaults_applied;\n const embeddingIdentityChanged = vectorizationEmbeddingIdentityChanged({\n strictVectorizationWarnings,\n semanticRuntimeAvailable: snapshot.semanticRuntimeAvailable,\n ledgerBefore,\n runtimeEmbeddingIdentity: snapshot.runtimeEmbeddingIdentity,\n });\n const warnings = collectVectorizationWarnings({\n ledgerBefore,\n ledgerAfter,\n refreshResult,\n strictVectorizationWarnings,\n semanticRuntimeAvailable: snapshot.semanticRuntimeAvailable,\n embeddingIdentityChanged,\n staleAfter,\n });\n const staleBeforeDetail = selectStaleItemDetail(staleBefore, verboseStaleItems);\n const staleAfterDetail = selectStaleItemDetail(staleAfter, verboseStaleItems);\n const refreshAttempted = vectorizationRefreshAttempted(refreshPolicy, snapshot.semanticRuntimeAvailable, staleBefore);\n\n return {\n check: {\n name: \"vectorization\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n semantic_runtime_available: snapshot.semanticRuntimeAvailable,\n compatibility_mode_auto_defaults: snapshot.runtimeDefaults.auto_ollama_defaults_applied,\n auto_ollama_defaults_applied: snapshot.runtimeDefaults.auto_ollama_defaults_applied,\n auto_ollama_defaults_skipped_reason: snapshot.runtimeDefaults.auto_ollama_defaults_skipped_reason ?? null,\n auto_ollama_defaults_remediation: snapshot.runtimeDefaults.auto_ollama_defaults_remediation ?? null,\n refresh_policy: buildVectorizationRefreshPolicyDetails(refreshPolicy),\n ...buildVectorizationProviderDetails(settings, snapshot),\n embedding_identity_changed: embeddingIdentityChanged,\n embedding_identity_before: ledgerBefore.embedding ?? null,\n embedding_identity_runtime: snapshot.runtimeEmbeddingIdentity ?? null,\n items: items.length,\n ledger_entries_before: Object.keys(ledgerBefore.entries).length,\n stale_items_detail_mode: verboseStaleItems ? \"full\" : \"summary\",\n stale_items_summary_limit: STALE_VECTORIZATION_SUMMARY_LIMIT,\n stale_items_before_total: staleBeforeDetail.total,\n stale_items_before: staleBeforeDetail.values,\n stale_items_before_truncated: staleBeforeDetail.truncated,\n refresh_attempted: refreshAttempted,\n refresh_skipped_reason: resolveVectorizationRefreshSkippedReason(\n refreshPolicy,\n snapshot.semanticRuntimeAvailable,\n staleBefore,\n ),\n refresh_result: refreshResult,\n ledger_entries_after: Object.keys(ledgerAfter.entries).length,\n stale_items_after_total: staleAfterDetail.total,\n stale_items_after: staleAfterDetail.values,\n stale_items_after_truncated: staleAfterDetail.truncated,\n },\n },\n warnings,\n };\n}\n\nfunction validateSettingsValues(settings: PmSettings): string[] {\n const warnings: string[] = [];\n if (settings.id_prefix.trim().length === 0) {\n warnings.push(\"settings:id_prefix_empty\");\n }\n if (settings.locks.ttl_seconds <= 0) {\n warnings.push(\"settings:locks_ttl_non_positive\");\n }\n return warnings;\n}\n\nfunction resolveVectorRefreshPolicy(options: RunHealthOptions): VectorRefreshPolicy {\n const checkOnly = options.checkOnly === true;\n const noRefresh = options.noRefresh === true || checkOnly;\n const refreshVectors = options.refreshVectors === true;\n if (refreshVectors && checkOnly) {\n throw new PmCliError(\"--check-only cannot be combined with --refresh-vectors\", EXIT_CODE.USAGE);\n }\n if (refreshVectors && options.noRefresh === true) {\n throw new PmCliError(\"--no-refresh cannot be combined with --refresh-vectors\", EXIT_CODE.USAGE);\n }\n return {\n enabled: refreshVectors || !noRefresh,\n checkOnly,\n noRefresh,\n refreshVectors,\n };\n}\n\ntype HealthCheckResult = { check: HealthCheck; warnings: string[] };\ntype HealthTypeRegistry = ReturnType<typeof resolveItemTypeRegistry>;\n\ninterface HealthDirectoryState {\n requiredDirs: string[];\n optionalDirs: string[];\n missingRequiredDirs: string[];\n missingOptionalDirs: string[];\n missingDirs: string[];\n hookWarnings: string[];\n}\n\ninterface HealthSkipPolicy {\n summaryMode: boolean;\n skipIntegrity: boolean;\n skipDrift: boolean;\n skipVectors: boolean;\n}\n\nfunction resolveHealthDirectoryLists(typeRegistry: HealthTypeRegistry): {\n requiredDirs: string[];\n optionalDirs: string[];\n optionalDirSet: Set<string>;\n} {\n const optionalBuiltinDirs = new Set<string>(PM_OPTIONAL_TYPE_SUBDIRS.filter((entry) => entry.length > 0));\n const requiredDirSet = new Set<string>(PM_CORE_REQUIRED_SUBDIRS.filter((entry) => entry.length > 0));\n const optionalDirSet = new Set<string>();\n for (const folder of typeRegistry.folders) {\n if (optionalBuiltinDirs.has(folder)) {\n optionalDirSet.add(folder);\n continue;\n }\n requiredDirSet.add(folder);\n }\n return {\n requiredDirs: [...requiredDirSet].sort((left, right) => left.localeCompare(right)),\n optionalDirs: [...optionalDirSet].sort((left, right) => left.localeCompare(right)),\n optionalDirSet,\n };\n}\n\nasync function scanHealthDirectories(\n pmRoot: string,\n typeRegistry: HealthTypeRegistry,\n strictDirectories: boolean,\n): Promise<HealthDirectoryState> {\n const { requiredDirs, optionalDirs, optionalDirSet } = resolveHealthDirectoryLists(typeRegistry);\n const missingRequiredDirs: string[] = [];\n const missingOptionalDirs: string[] = [];\n const hookWarnings: string[] = [];\n for (const relativeDir of [...requiredDirs, ...optionalDirs]) {\n const directoryPath = path.join(pmRoot, relativeDir);\n hookWarnings.push(...(await runActiveOnReadHooks({ path: directoryPath, scope: \"project\" })));\n if (await isDirectory(directoryPath)) {\n continue;\n }\n if (optionalDirSet.has(relativeDir)) {\n missingOptionalDirs.push(relativeDir);\n } else {\n missingRequiredDirs.push(relativeDir);\n }\n }\n return {\n requiredDirs,\n optionalDirs,\n missingRequiredDirs,\n missingOptionalDirs,\n missingDirs: strictDirectories ? [...missingRequiredDirs, ...missingOptionalDirs] : [...missingRequiredDirs],\n hookWarnings,\n };\n}\n\nfunction resolveHealthSkipPolicy(options: RunHealthOptions): HealthSkipPolicy {\n const summaryMode = options.summary === true && options.full !== true;\n const fastProjectionCheckOnly =\n options.checkOnly === true && (options.brief === true || options.summary === true) && options.full !== true;\n return {\n summaryMode,\n skipIntegrity: (options.skipIntegrity === true || fastProjectionCheckOnly) && options.full !== true,\n skipDrift: (options.skipDrift === true || fastProjectionCheckOnly) && options.full !== true,\n skipVectors: (options.skipVectors === true || fastProjectionCheckOnly) && options.full !== true,\n };\n}\n\nasync function readHealthItems(params: {\n pmRoot: string;\n settings: PmSettings;\n typeRegistry: HealthTypeRegistry;\n skipPolicy: HealthSkipPolicy;\n itemReadWarnings: string[];\n}): Promise<Array<ItemMetadata | ItemWithBody>> {\n if (params.skipPolicy.skipDrift && params.skipPolicy.skipVectors) {\n return listAllFrontMatter(\n params.pmRoot,\n params.settings.item_format,\n params.typeRegistry.type_to_folder,\n params.itemReadWarnings,\n params.settings.schema,\n );\n }\n return listAllFrontMatterWithBody(\n params.pmRoot,\n params.settings.item_format,\n params.typeRegistry.type_to_folder,\n params.itemReadWarnings,\n params.settings.schema,\n );\n}\n\nfunction buildSkippedHealthCheck(name: Extract<HealthCheck[\"name\"], \"integrity\" | \"history_drift\" | \"vectorization\">): HealthCheckResult {\n return { check: { name, status: \"ok\", details: { skipped: true } }, warnings: [] };\n}\n\nfunction buildSettingsHealthCheck(\n settingsPath: string,\n settings: PmSettings,\n normalizedSettingsReadWarnings: string[],\n): HealthCheck {\n return {\n name: \"settings\",\n /* c8 ignore next -- settings read-warning status split is covered in broader read-settings integration tests */\n status: normalizedSettingsReadWarnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n path: settingsPath,\n version: settings.version,\n id_prefix: settings.id_prefix,\n locks_ttl_seconds: settings.locks.ttl_seconds,\n warnings: normalizedSettingsReadWarnings,\n },\n };\n}\n\nfunction buildDirectoriesHealthCheck(directoryState: HealthDirectoryState, strictDirectories: boolean): HealthCheck {\n return {\n name: \"directories\",\n status: directoryState.missingDirs.length === 0 ? \"ok\" : \"warn\",\n details: {\n required: directoryState.requiredDirs,\n optional: directoryState.optionalDirs,\n missing_required: directoryState.missingRequiredDirs,\n missing_optional: directoryState.missingOptionalDirs,\n missing: directoryState.missingDirs,\n strict_directories: strictDirectories,\n },\n };\n}\n\nfunction buildSettingsValuesHealthCheck(settingWarnings: string[]): HealthCheck {\n return {\n name: \"settings_values\",\n status: settingWarnings.length === 0 ? \"ok\" : \"warn\",\n details: { warnings: settingWarnings },\n };\n}\n\nfunction buildStorageHealthCheck(\n items: Array<ItemMetadata | ItemWithBody>,\n settings: PmSettings,\n historySummary: HistoryStreamSummary,\n): HealthCheck {\n return {\n name: \"storage\",\n status: historySummary.over_threshold.length === 0 ? \"ok\" : \"warn\",\n details: {\n items: items.length,\n history_streams: historySummary.count,\n ...(historySummary.max_entries !== null\n ? {\n compact_policy: {\n enabled: settings.history.compact_policy.enabled,\n max_entries: historySummary.max_entries,\n trigger: settings.history.compact_policy.trigger,\n over_threshold_count: historySummary.over_threshold.length,\n over_threshold: historySummary.over_threshold,\n },\n }\n : {}),\n },\n };\n}\n\nfunction collectHealthWarnings(params: {\n directoryState: HealthDirectoryState;\n normalizedSettingsReadWarnings: string[];\n settingWarnings: string[];\n normalizedItemReadWarnings: string[];\n telemetryCheck: HealthCheckResult;\n extensionCheck: HealthCheckResult;\n historyPolicyWarnings: string[];\n historySummary: HistoryStreamSummary;\n locksCheck: HealthCheckResult;\n integrityCheck: HealthCheckResult;\n historyDriftCheck: HealthCheckResult;\n vectorizationCheck: HealthCheckResult;\n}): string[] {\n const warnings = [\n ...params.directoryState.missingDirs.map((dir) => `missing_directory:${dir}`),\n ...params.normalizedSettingsReadWarnings,\n ...params.settingWarnings,\n ...params.normalizedItemReadWarnings,\n ...params.telemetryCheck.warnings,\n ...params.extensionCheck.warnings,\n ...params.historyPolicyWarnings,\n ...params.historySummary.warnings,\n ...params.locksCheck.warnings,\n ...params.integrityCheck.warnings,\n ...params.historyDriftCheck.warnings,\n ...params.vectorizationCheck.warnings,\n ...params.directoryState.hookWarnings,\n ];\n return [...new Set(warnings)];\n}\n\nfunction extractHistoryDriftedCount(historyDriftCheck: HealthCheckResult): number {\n const counts = historyDriftCheck.check.details.counts as { drifted?: unknown } | undefined;\n return typeof counts?.drifted === \"number\" ? counts.drifted : 0;\n}\n\nfunction buildHealthRemediationSources(params: {\n directoryState: HealthDirectoryState;\n normalizedSettingsReadWarnings: string[];\n settingWarnings: string[];\n telemetryCheck: HealthCheckResult;\n extensionCheck: HealthCheckResult;\n historySummary: HistoryStreamSummary;\n locksCheck: HealthCheckResult;\n integrityCheck: HealthCheckResult;\n historyDriftCheck: HealthCheckResult;\n vectorizationCheck: HealthCheckResult;\n}): Record<HealthCheck[\"name\"], string[]> {\n return {\n settings: params.normalizedSettingsReadWarnings,\n directories: params.directoryState.missingDirs.map((dir) => `missing_directory:${dir}`),\n settings_values: params.settingWarnings,\n telemetry: params.telemetryCheck.warnings,\n extensions: params.extensionCheck.warnings,\n storage: params.historySummary.over_threshold.map((id) => `history_stream_over_compact_threshold:${id}`),\n locks: params.locksCheck.warnings,\n integrity: params.integrityCheck.warnings,\n history_drift: params.historyDriftCheck.warnings,\n vectorization: params.vectorizationCheck.warnings,\n };\n}\n\nfunction rewriteBulkHealthRemediation(params: {\n check: HealthCheck;\n remediationMap: Record<string, string>;\n historyDriftedCount: number;\n overThresholdCount: number;\n}): void {\n if (params.check.name === \"history_drift\" && params.historyDriftedCount > 1) {\n for (const code of Object.keys(params.remediationMap)) {\n params.remediationMap[code] = \"pm history-repair --all\";\n }\n }\n if (params.check.name === \"storage\" && params.overThresholdCount > 1) {\n for (const code of Object.keys(params.remediationMap)) {\n params.remediationMap[code] = \"pm history-compact --all-streams\";\n }\n }\n}\n\nfunction attachHealthRemediationMaps(params: {\n checks: HealthCheck[];\n remediationSources: Record<HealthCheck[\"name\"], string[]>;\n historyDriftedCount: number;\n overThresholdCount: number;\n}): void {\n for (const check of params.checks) {\n const remediationMap = buildRemediationMap(params.remediationSources[check.name]);\n rewriteBulkHealthRemediation({\n check,\n remediationMap,\n historyDriftedCount: params.historyDriftedCount,\n overThresholdCount: params.overThresholdCount,\n });\n if (Object.keys(remediationMap).length > 0) {\n check.details = { ...check.details, remediation_map: remediationMap };\n }\n }\n}\n\nfunction projectHealthResult(result: HealthResult, options: RunHealthOptions, summaryMode: boolean): HealthResult {\n if (summaryMode) {\n return applySummaryHealthProjection(result);\n }\n return options.brief === true ? applyBriefHealthProjection(result) : result;\n}\n\n/**\n * Implements run health for the public runtime surface of this module.\n */\nexport async function runHealth(global: GlobalOptions, options: RunHealthOptions = {}): Promise<HealthResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n const settingsPath = getSettingsPath(pmRoot);\n if (!(await pathExists(settingsPath))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const { settings, warnings: settingsReadWarnings } = await readSettingsWithMetadata(pmRoot);\n const normalizedSettingsReadWarnings = [...new Set(settingsReadWarnings)];\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const strictDirectories = options.strictDirectories === true;\n const refreshPolicy = resolveVectorRefreshPolicy(options);\n const directoryState = await scanHealthDirectories(pmRoot, typeRegistry, strictDirectories);\n const settingWarnings = validateSettingsValues(settings);\n const telemetryCheck = await buildTelemetryCheck(settings, {\n checkTelemetry: options.checkTelemetry === true,\n });\n const extensionCheck = await buildExtensionCheck(pmRoot, settings, Boolean(global.noExtensions));\n const skipPolicy = resolveHealthSkipPolicy(options);\n const itemReadWarnings: string[] = [];\n const items = await readHealthItems({ pmRoot, settings, typeRegistry, skipPolicy, itemReadWarnings });\n const itemsWithBody = items as Array<ItemMetadata & { body: string }>;\n const normalizedItemReadWarnings = [...new Set(itemReadWarnings)];\n const historyPolicy = skipPolicy.skipDrift\n ? { warnings: [] }\n : await enforceHistoryStreamPolicyForItems({\n pmRoot,\n settings,\n itemIds: items.map((item) => item.id),\n commandLabel: \"health\",\n });\n const historySummary = await countHistoryStreams(pmRoot, settings.history.compact_policy);\n const locksCheck = await buildLocksCheck(pmRoot);\n const integrityCheck = skipPolicy.skipIntegrity\n ? buildSkippedHealthCheck(\"integrity\")\n : await buildIntegrityCheck(pmRoot, typeRegistry.type_to_folder, settings.schema);\n const historyDriftCheck = skipPolicy.skipDrift\n ? buildSkippedHealthCheck(\"history_drift\")\n : await buildHistoryDriftCheck(pmRoot, itemsWithBody);\n const vectorizationCheck = skipPolicy.skipVectors\n ? buildSkippedHealthCheck(\"vectorization\")\n : await buildVectorizationCheck(pmRoot, settings, itemsWithBody, refreshPolicy, options.verboseStaleItems === true);\n\n const checks: HealthCheck[] = [\n buildSettingsHealthCheck(settingsPath, settings, normalizedSettingsReadWarnings),\n buildDirectoriesHealthCheck(directoryState, strictDirectories),\n buildSettingsValuesHealthCheck(settingWarnings),\n telemetryCheck.check,\n extensionCheck.check,\n buildStorageHealthCheck(items, settings, historySummary),\n locksCheck.check,\n integrityCheck.check,\n historyDriftCheck.check,\n vectorizationCheck.check,\n ];\n\n const normalizedWarnings = collectHealthWarnings({\n directoryState,\n normalizedSettingsReadWarnings,\n settingWarnings,\n normalizedItemReadWarnings,\n telemetryCheck,\n extensionCheck,\n historyPolicyWarnings: historyPolicy.warnings,\n historySummary,\n locksCheck,\n integrityCheck,\n historyDriftCheck,\n vectorizationCheck,\n });\n attachHealthRemediationMaps({\n checks,\n remediationSources: buildHealthRemediationSources({\n directoryState,\n normalizedSettingsReadWarnings,\n settingWarnings,\n telemetryCheck,\n extensionCheck,\n historySummary,\n locksCheck,\n integrityCheck,\n historyDriftCheck,\n vectorizationCheck,\n }),\n historyDriftedCount: extractHistoryDriftedCount(historyDriftCheck),\n overThresholdCount: historySummary.over_threshold.length,\n });\n // Telemetry is an opt-out, non-critical observability feature. Its operational\n // state (queue backlog, unreachable endpoint, corrupt local state) is advisory:\n // it must never flip overall project health to not-ok. Such warnings are still\n // surfaced in `warnings` and the telemetry check's own `warn` status.\n const blockingWarnings = normalizedWarnings.filter((warning) => !isAdvisoryHealthWarning(warning));\n const result: HealthResult = {\n ok: blockingWarnings.length === 0,\n checks,\n warnings: normalizedWarnings,\n generated_at: nowIso(),\n };\n return projectHealthResult(result, options, skipPolicy.summaryMode);\n}\n\nexport const _testOnlyHealthCommand = {\n buildExtensionHealthTriageSummary,\n buildCapabilityContractMetadata,\n buildVectorizationProviderDetails,\n collectUnknownCapabilityGuidance,\n isAdvisoryHealthWarning,\n isDirectory,\n isExpectedUnmanagedExtension,\n listItemDocumentPaths,\n normalizeEndpointForDisplay,\n normalizeExtensionNameForMatch,\n parseTelemetryQueue,\n probeTelemetryEndpointHealth,\n selectStaleItemDetail,\n summarizeHealthCheckDetails,\n summarizeExtensionList,\n summarizeRecordList,\n summarizeStringList,\n telemetryEnvFlagEnabled,\n warningCode,\n};\n", "/**\n * Shared machine-executable remediation registry.\n *\n * `pm health` and `pm validate` both emit stable, colon-delimited warning tokens\n * (for example `history_drift_missing_stream:pm-abcd` or\n * `validate_resolution_missing_fields:3`). Agents that gate on these commands\n * previously had to hardcode the mapping from a warning code to the `pm` command\n * that fixes it. This module is the single source of truth for that mapping so\n * `pm health --json` (per-check `remediation_map`) and `pm validate --fix-hints`\n * (per-check `fix_hints`) can both surface executable remediation without any\n * duplicated, drift-prone lookup tables.\n *\n * Semantics of {@link RemediationEntry.command}: the suggested next `pm` command\n * an operator/agent should run to resolve findings with that code. Per-item\n * findings use an `<id>` placeholder (callers that have the concrete id may\n * substitute it); findings whose only fix is a manual file edit point at the\n * most useful diagnostic/repair command and describe the manual step in\n * {@link RemediationEntry.summary}.\n */\n\n/** Maps a stable diagnostic warning code to the command and summary that resolve it. */\nexport interface RemediationEntry {\n /**\n * Stable warning-code prefix this entry resolves. A warning matches when it\n * equals this code or begins with `<code>:`. Registry codes are mutually\n * exclusive under that colon-boundary rule (no code is a `:`-delimited prefix\n * of another — e.g. `settings:id_prefix_empty` is distinct from a bare\n * `settings`, which is intentionally not registered), so `resolveRemediation`\n * uses first-match with no ordering dependency.\n */\n readonly code: string;\n /** Executable `pm` command (or imperative) that resolves the finding. May contain an `<id>` placeholder. */\n readonly command: string;\n /** One-line description of what the command does / which manual step it covers. */\n readonly summary: string;\n}\n\n/**\n * Registry of every non-extension `pm health` / `pm validate` warning code and\n * its remediation. Extension findings keep their richer, contextual\n * `details.triage.remediation` produced by the extension health triage and are\n * intentionally excluded here (see pm-0hnu: \"all non-extension checks\").\n */\nexport const REMEDIATION_REGISTRY: readonly RemediationEntry[] = Object.freeze([\n // --- pm health: directories ---\n {\n code: \"missing_directory\",\n command: \"pm init\",\n summary: \"Recreate missing tracker directories (pm init is idempotent and restores the scaffold).\",\n },\n // --- pm health: settings (read/parse) ---\n {\n code: \"settings_read_invalid_json\",\n command: \"pm config list --json\",\n summary:\n \"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run.\",\n },\n {\n code: \"settings_read_invalid_schema\",\n command: \"pm config list --json\",\n summary:\n \"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run.\",\n },\n {\n code: \"settings_read_merge_failed\",\n command: \"pm config list --json\",\n summary: \"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files.\",\n },\n // --- pm health: settings_values ---\n {\n code: \"settings:id_prefix_empty\",\n command: \"pm config list --json\",\n summary: 'id_prefix is empty; set a non-empty \"id_prefix\" in settings.json so generated item ids are well-formed.',\n },\n {\n code: \"settings:locks_ttl_non_positive\",\n command: \"pm config list --json\",\n summary: 'locks.ttl_seconds must be positive; set a positive \"locks.ttl_seconds\" in settings.json.',\n },\n // --- pm health: telemetry (advisory) ---\n {\n code: \"telemetry_state_invalid_json\",\n command: \"pm health --check-telemetry\",\n summary: \"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only.\",\n },\n {\n code: \"telemetry_queue_invalid_rows\",\n command: \"pm health --check-telemetry\",\n summary: \"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only.\",\n },\n {\n code: \"telemetry_queue_pending\",\n command: \"pm health --check-telemetry\",\n summary: \"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only.\",\n },\n {\n code: \"telemetry_queue_high_retries\",\n command: \"pm telemetry flush\",\n summary:\n \"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped.\",\n },\n {\n code: \"telemetry_endpoint_probe_failed\",\n command: \"pm health --check-telemetry\",\n summary: \"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only.\",\n },\n {\n code: \"telemetry_endpoint_probe_http_status\",\n command: \"pm health --check-telemetry\",\n summary: \"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only.\",\n },\n {\n code: \"telemetry_schema_version_behind\",\n command: \"pm health --check-telemetry\",\n summary: \"Client schema is behind server; upgrade pm-cli to emit the latest event shape.\",\n },\n {\n code: \"telemetry_otel_export_failing\",\n command: \"pm health --check-telemetry\",\n summary:\n \"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only.\",\n },\n // --- pm health: integrity ---\n {\n code: \"integrity_item_unreadable\",\n command: \"pm validate --check-files --verbose-diagnostics\",\n summary: \"An item file could not be read; restore or repair the file at the reported path.\",\n },\n {\n code: \"integrity_item_parse_failed\",\n command: \"pm validate --check-files --verbose-diagnostics\",\n summary: \"An item file failed to parse; fix the malformed front matter at the reported path.\",\n },\n {\n code: \"integrity_item_conflict_marker\",\n command: \"pm validate --check-files --verbose-diagnostics\",\n summary: \"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line.\",\n },\n {\n code: \"integrity_history_unreadable\",\n command: \"pm history-repair <id>\",\n summary: \"A history stream could not be read; re-anchor the affected item's history chain.\",\n },\n {\n code: \"integrity_history_invalid_json\",\n command: \"pm history-repair <id>\",\n summary: \"A history stream contains invalid JSON; re-anchor the affected item's history chain.\",\n },\n {\n code: \"integrity_history_conflict_marker\",\n command: \"pm history-repair <id>\",\n summary: \"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain.\",\n },\n // --- pm health (integrity) + pm validate (format_version): item format version ---\n {\n code: \"integrity_item_outdated_format_version\",\n command: \"pm validate --verbose-diagnostics\",\n summary: \"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items.\",\n },\n {\n code: \"integrity_item_ahead_format_version\",\n command: \"npm install -g @unbrained/pm-cli@latest\",\n summary: \"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely.\",\n },\n // --- pm health: history_drift ---\n // `pm health` rewrites these commands to `pm history-repair --all` in the\n // per-check remediation_map when more than one stream is drifted.\n {\n code: \"history_drift_missing_stream\",\n command: \"pm history-repair <id>\",\n summary: \"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass).\",\n },\n {\n code: \"history_drift_unreadable_stream\",\n command: \"pm history-repair <id>\",\n summary: \"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass).\",\n },\n {\n code: \"history_drift_hash_mismatch\",\n command: \"pm history-repair <id>\",\n summary: \"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass).\",\n },\n {\n code: \"history_drift_chain_mismatch\",\n command: \"pm history-repair <id>\",\n summary: \"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass).\",\n },\n // --- pm health: storage (history compaction policy) ---\n {\n code: \"history_stream_over_compact_threshold\",\n command: \"pm history-compact <id>\",\n summary: \"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass).\",\n },\n // --- pm health: locks ---\n {\n code: \"locks_stale_count\",\n command: \"pm gc --scope locks\",\n summary:\n \"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them — gc retains active and unparseable locks.\",\n },\n {\n code: \"locks_unreadable\",\n command: \"pm gc --scope locks --dry-run\",\n summary:\n \"Some lock files could not be read; preview the sweep and inspect the unreadable files manually — gc never deletes what it cannot read.\",\n },\n // --- pm health: extensions ---\n // Most extension findings keep their richer, contextual\n // `details.triage.remediation` and are intentionally absent here. The\n // partial-coverage code is the exception: it is not a per-extension triage\n // result but a system-wide adoption gap (unmanaged installs the update-health\n // scan had to skip), so it has a single deterministic fix and belongs in the\n // shared registry like any other health finding (pm-bdvm).\n {\n code: \"extension_update_health_partial_coverage\",\n command: \"pm extension --adopt-all --project\",\n summary:\n \"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages).\",\n },\n // --- pm health: vectorization ---\n {\n code: \"vectorization_stale_items_remaining\",\n command: \"pm health --refresh-vectors\",\n summary: \"Some items have stale embeddings; refresh vectors so semantic search results stay current.\",\n },\n {\n code: \"vectorization_embedding_identity_changed\",\n command: \"pm reindex --mode semantic\",\n summary: \"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors.\",\n },\n // --- pm validate: metadata ---\n // Note: validate_metadata_missing_author has no entry on purpose. `pm update\n // --author` sets the mutation/audit author (history), not the item's\n // `metadata.author` front-matter field, and there is no CLI flag that writes\n // that field — so emitting a command here would record an audit entry without\n // clearing the finding. A missing item author must be restored at the source.\n {\n code: \"validate_metadata_missing_acceptance_criteria\",\n command: 'pm update <id> --acceptance-criteria \"<criteria>\"',\n summary: \"Backfill the missing acceptance criteria on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_estimate\",\n command: 'pm update <id> --estimate \"<estimate>\"',\n summary: \"Backfill the missing estimate on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_close_reason\",\n command: 'pm update <id> --close-reason \"<reason>\"',\n summary: \"Backfill the missing close reason on the reported closed item(s).\",\n },\n {\n code: \"validate_metadata_missing_reviewer\",\n command: 'pm update <id> --reviewer \"<name>\"',\n summary: \"Backfill the missing reviewer on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_risk\",\n command: 'pm update <id> --risk \"<level>\"',\n summary: \"Backfill the missing risk on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_confidence\",\n command: 'pm update <id> --confidence \"<level>\"',\n summary: \"Backfill the missing confidence on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_sprint\",\n command: 'pm update <id> --sprint \"<sprint>\"',\n summary: \"Backfill the missing sprint on the reported item(s).\",\n },\n {\n code: \"validate_metadata_missing_release\",\n command: 'pm update <id> --release \"<release>\"',\n summary: \"Backfill the missing release on the reported item(s).\",\n },\n {\n code: \"validate_metadata_custom_profile_missing_required_fields\",\n command: 'pm config set metadata-required-fields --criterion \"<field>\"',\n summary:\n \"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items.\",\n },\n {\n code: \"validate_metadata_duplicate_issue_codes\",\n command: 'pm update <id> --title \"<distinct title>\"',\n summary:\n \"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check).\",\n },\n // --- pm validate: resolution ---\n {\n code: \"validate_resolution_missing_fields\",\n command: 'pm update <id> --resolution \"<how resolved>\"',\n summary: \"Backfill resolution / expected_result / actual_result on the reported closed item(s).\",\n },\n // --- pm validate: lifecycle ---\n {\n code: \"validate_lifecycle_active_closure_like_metadata\",\n command: \"pm update <id> --unset <closure-like-field>\",\n summary:\n \"Clear the closure-like field the validator flags on this active item — the detail row names it (resolution / actual-result / blocked-reason) — or close the item if it is actually done.\",\n },\n {\n code: \"validate_lifecycle_active_terminal_parent\",\n command: \"pm update <id> --parent <active-parent-id>\",\n summary: \"Reopen the terminal parent or move the active child under a non-terminal parent.\",\n },\n {\n code: \"validate_lifecycle_stale_blockers\",\n command: \"pm update <id> --unset blocked-by --unset blocked-reason\",\n summary:\n \"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status.\",\n },\n {\n code: \"validate_lifecycle_dependency_cycles_error\",\n command: \"pm update <id> --dep-remove <dep-id>\",\n summary: \"Break the dependency cycle by removing one edge from the reported cycle.\",\n },\n {\n code: \"validate_lifecycle_dependency_cycles\",\n command: \"pm update <id> --dep-remove <dep-id>\",\n summary: \"Break the dependency cycle by removing one edge from the reported cycle.\",\n },\n {\n code: \"validate_hierarchy_parent_cycle_error\",\n command: \"pm update <id> --parent <other-id>\",\n summary:\n \"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent).\",\n },\n {\n code: \"validate_hierarchy_parent_cycle\",\n command: \"pm update <id> --parent <other-id>\",\n summary:\n \"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent).\",\n },\n // --- pm validate: files ---\n {\n code: \"validate_files_missing_linked_paths\",\n command: \"pm <files|docs> <id> --remove <path>\",\n summary:\n \"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc).\",\n },\n {\n code: \"validate_files_orphaned_paths\",\n command: \"pm <files|docs> <id> --add <path>\",\n summary:\n \"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace.\",\n },\n {\n code: \"validate_files_tracked_all_strict_forces_pm_internals\",\n command: \"pm validate --check-files --include-pm-internals\",\n summary: \"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode.\",\n },\n // --- pm validate: history_drift ---\n {\n code: \"validate_history_drift_missing_streams\",\n command: \"pm history-repair <id>\",\n summary: \"Re-anchor the history chains of the items missing a history stream.\",\n },\n {\n code: \"validate_history_drift_unreadable_streams\",\n command: \"pm history-repair <id>\",\n summary: \"Re-anchor the history chains of the items with an unreadable history stream.\",\n },\n {\n code: \"validate_history_drift_hash_mismatches\",\n command: \"pm history-repair <id>\",\n summary: \"Re-anchor the history chains of the items whose content hash drifted.\",\n },\n {\n code: \"validate_history_drift_chain_mismatches\",\n command: \"pm history-repair <id>\",\n summary: \"Re-anchor the history chains of the items with a broken history chain.\",\n },\n // --- pm validate: command_references ---\n {\n code: \"validate_command_references_stale_pm_ids\",\n command: 'pm update <id> --replace-tests --test \"command=<corrected-command>\" [--test ...]',\n summary:\n \"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call.\",\n },\n {\n code: \"validate_format_version_outdated_items\",\n command: \"pm validate --verbose-diagnostics\",\n summary: \"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items.\",\n },\n {\n code: \"validate_format_version_ahead_items\",\n command: \"npm install -g @unbrained/pm-cli@latest\",\n summary: \"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely.\",\n },\n]);\n\n/**\n * Resolve the remediation entry for a warning token, or `undefined` when no\n * entry is registered. A warning matches an entry when it equals the entry code\n * or begins with `<code>:` (the colon boundary keeps sibling codes such as\n * `validate_lifecycle_dependency_cycles` and\n * `validate_lifecycle_dependency_cycles_error` disjoint).\n *\n * First match is intentional and correct: registry codes are mutually exclusive\n * under the colon-boundary rule, so at most one entry can ever match a warning\n * and order is irrelevant. That invariant is enforced by a test (see\n * remediation-registry.spec.ts \"keeps every registry code mutually exclusive\"),\n * which is why this stays a simple linear scan rather than a longest-prefix\n * search — a longest-prefix tie-break is unreachable with disjoint codes.\n *\n * Accepts unknown input defensively (this is an exported helper SDK consumers\n * may call from untyped JS): a non-string `warning` resolves to `undefined`.\n */\nexport function resolveRemediation(warning: string): RemediationEntry | undefined {\n if (typeof warning !== \"string\") {\n return undefined;\n }\n const normalized = warning.trim();\n for (const entry of REMEDIATION_REGISTRY) {\n if (normalized === entry.code || normalized.startsWith(`${entry.code}:`)) {\n return entry;\n }\n }\n return undefined;\n}\n\n/**\n * Build a compact `remediation_map` (code -> command) for a set of warning\n * tokens. First match wins per code; unknown codes are skipped. Used by\n * `pm health --json` per-check details and as the source of deduped executable\n * commands for `pm validate --fix-hints`.\n */\nexport function buildRemediationMap(warnings: Iterable<string>): Record<string, string> {\n const map: Record<string, string> = {};\n for (const warning of warnings) {\n const entry = resolveRemediation(warning);\n if (entry !== undefined && !Object.prototype.hasOwnProperty.call(map, entry.code)) {\n map[entry.code] = entry.command;\n }\n }\n return map;\n}\n\n/**\n * Build a deduped, ordered list of executable remediation commands for a set of\n * warning tokens (one command per distinct matched code). Used by\n * `pm validate --fix-hints` for checks that do not already emit per-row\n * remediation commands.\n */\nexport function buildRemediationCommands(warnings: Iterable<string>): string[] {\n return Object.values(buildRemediationMap(warnings));\n}\n", "/**\n * @module cli/commands/scheduling-shortcuts\n *\n * Implements the pm scheduling shortcuts command surface and its agent-facing runtime behavior.\n */\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { runCreate, type CreateCommandOptions, type CreateResult } from \"./create.js\";\n\n/**\n * GH-217: low-friction creation shortcuts for the scheduling item types\n * (Meeting/Event/Reminder), which sit unused because `pm create --type Event`\n * demands structured `--event`/`--reminder` CSV entries. These commands accept\n * friendly time flags (`--start`, `--duration`, `--end`, `--at`) and translate\n * them into the canonical scheduling fields, then delegate to `runCreate` so the\n * full create pipeline (parent/focus inheritance, governance, hooks, validation)\n * applies unchanged. The `lightweight` schedule preset is applied so progressive\n * scheduling fields are not demanded up front.\n */\n\n/** Options shared by every scheduling shortcut, forwarded to `runCreate`. */\nexport interface SchedulingShortcutCommonOptions {\n parent?: string;\n allowMissingParent?: boolean;\n tags?: string;\n priority?: string;\n body?: string;\n description?: string;\n author?: string;\n message?: string;\n}\n\n/** Options for `pm meet` and `pm event` (a start time plus a span). */\nexport interface MeetingEventShortcutOptions extends SchedulingShortcutCommonOptions {\n start?: string;\n duration?: string;\n end?: string;\n location?: string;\n timezone?: string;\n allDay?: boolean;\n}\n\n/** Options for `pm remind` (a single point in time). */\nexport interface ReminderShortcutOptions extends SchedulingShortcutCommonOptions {\n at?: string;\n text?: string;\n}\n\n/** Default span applied when neither `--end` nor `--duration` is given. */\nconst DEFAULT_DURATION = \"1h\";\n/** Default start applied when `--start` is omitted (keeps the item calendar-visible). */\nconst DEFAULT_START = \"now\";\n/** Default reminder time applied when `--at` is omitted. */\nconst DEFAULT_REMINDER_AT = \"+1d\";\n\n/**\n * Wrap a free-text value (reminder text, event location) in double quotes so\n * commas and colons survive the CSV round-trip into `--reminder`/`--event`.\n * Backslashes are escaped first, then embedded quotes — escaping quotes alone\n * would let a trailing backslash escape the closing quote and break out of the\n * quoted field (CSV injection). The parser's `unquoteValue` strips the wrapping\n * quotes and unescapes `\\\"` back to `\"`.\n */\nfunction quoteCsvValue(value: string): string {\n return `\"${value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, \"\\\\\\\"\")}\"`;\n}\n\n/**\n * Append a `key=\"value\"` pair. EVERY value is double-quoted (not just free-text\n * fields) so a comma or `=` in any token — `start`, `duration`, `at`, etc. —\n * cannot inject extra CSV key/value pairs into the `--event`/`--reminder`\n * entry. The parser's `parseCsvKv` unquotes every value before use, so quoting\n * is transparent to ISO/relative/timezone tokens.\n */\nfunction appendPair(pairs: string[], key: string, value: string | undefined): void {\n if (value !== undefined) {\n pairs.push(`${key}=${quoteCsvValue(value)}`);\n }\n}\n\nfunction buildCommonOptions(\n type: string,\n title: string,\n options: SchedulingShortcutCommonOptions,\n): CreateCommandOptions {\n return {\n type,\n title,\n schedulePreset: \"lightweight\",\n parent: options.parent,\n allowMissingParent: options.allowMissingParent,\n tags: options.tags,\n priority: options.priority,\n body: options.body,\n description: options.description,\n author: options.author,\n message: options.message,\n };\n}\n\nfunction buildEventEntry(options: MeetingEventShortcutOptions): string {\n const pairs: string[] = [];\n appendPair(pairs, \"start\", options.start ?? DEFAULT_START);\n if (options.end !== undefined) {\n appendPair(pairs, \"end\", options.end);\n } else {\n appendPair(pairs, \"duration\", options.duration ?? DEFAULT_DURATION);\n }\n appendPair(pairs, \"location\", options.location);\n appendPair(pairs, \"timezone\", options.timezone);\n if (options.allDay === true) {\n appendPair(pairs, \"all_day\", \"true\");\n }\n return pairs.join(\",\");\n}\n\nasync function createScheduled(\n type: string,\n title: string,\n options: MeetingEventShortcutOptions,\n global: GlobalOptions,\n): Promise<CreateResult> {\n const createOptions = buildCommonOptions(type, title, options);\n createOptions.event = [buildEventEntry(options)];\n return runCreate(createOptions, global);\n}\n\n/** `pm meet \"<title>\"` — create a Meeting with sensible scheduling defaults. */\nexport function runMeet(\n title: string,\n options: MeetingEventShortcutOptions,\n global: GlobalOptions,\n): Promise<CreateResult> {\n return createScheduled(\"Meeting\", title, options, global);\n}\n\n/** `pm event \"<title>\"` — create an Event with sensible scheduling defaults. */\nexport function runEvent(\n title: string,\n options: MeetingEventShortcutOptions,\n global: GlobalOptions,\n): Promise<CreateResult> {\n return createScheduled(\"Event\", title, options, global);\n}\n\n/** `pm remind \"<title>\"` — create a Reminder from a single point in time. */\nexport function runRemind(\n title: string,\n options: ReminderShortcutOptions,\n global: GlobalOptions,\n): Promise<CreateResult> {\n const createOptions = buildCommonOptions(\"Reminder\", title, options);\n const pairs: string[] = [];\n appendPair(pairs, \"at\", options.at ?? DEFAULT_REMINDER_AT);\n appendPair(pairs, \"text\", options.text ?? title);\n createOptions.reminder = [pairs.join(\",\")];\n return runCreate(createOptions, global);\n}\n", "/**\n * @module cli/commands/stats\n *\n * Implements the pm stats command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { getActiveExtensionRegistrations, runActiveOnReadHooks } from \"../../core/extensions/index.js\";\nimport {\n computeContentFieldUtilization,\n type ContentFieldUtilizationReport,\n} from \"../../core/governance/content-fields.js\";\nimport {\n computeMetadataCoverage,\n groupItemsByDimension,\n lifecycleClassifierFromStatusRegistry,\n type GroupedBreakdown,\n type MetadataCoverageReport,\n} from \"../../core/governance/metadata-coverage.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { enforceHistoryStreamPolicyForItems } from \"../../core/history/history-stream-policy.js\";\nimport { computeHistoryStorageStats, type HistoryStorageStats } from \"../../core/history/history-storage-stats.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { resolveRuntimeStatusRegistry } from \"../../core/schema/runtime-schema.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { listAllFrontMatterLight, listAllFrontMatterWithBody } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport type { ItemStatus, ItemType } from \"../../types/index.js\";\n\n/**\n * Documents the stats command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface StatsCommandOptions {\n /** Include aggregate per-stream history storage metrics (sizes, depth, oldest/newest). */\n storage?: boolean;\n /** Include metadata coverage percentages (AC, estimates, resolution, tags, parent) overall and by type. */\n metadataCoverage?: boolean;\n /** Include a lifecycle-bucketed breakdown grouped by assignee. */\n byAssignee?: boolean;\n /** Include a lifecycle-bucketed breakdown grouped by tag (optionally filtered by --tag-prefix). */\n byTag?: boolean;\n /** Include a lifecycle-bucketed breakdown grouped by priority. */\n byPriority?: boolean;\n /** With --by-tag: only consider tags starting with this prefix (e.g. \"domain:\"). */\n tagPrefix?: string;\n /** Include a content-field utilization breakdown (notes/learnings/files/docs/tests/comments/deps/body usage rates). */\n fieldUtilization?: boolean;\n}\n\n/**\n * Documents the stats result payload exchanged by command, SDK, and package integrations.\n */\nexport interface StatsResult {\n totals: {\n items: number;\n history_streams: number;\n history_entries: number;\n };\n by_type: Record<ItemType, number>;\n by_status: Record<ItemStatus, number>;\n /** Present only with --metadata-coverage: per-field coverage overall and by type. */\n metadata_coverage?: MetadataCoverageReport;\n /** Present only with --by-assignee/--by-tag/--by-priority: lifecycle-bucketed group breakdowns. */\n breakdowns?: {\n assignee?: GroupedBreakdown;\n tag?: GroupedBreakdown;\n priority?: GroupedBreakdown;\n };\n /** Present only with --storage: aggregate history-stream metrics for compaction/planning. */\n storage?: HistoryStorageStats;\n /** Present only with --field-utilization: content-field utilization rates across all items. */\n field_utilization?: ContentFieldUtilizationReport;\n generated_at: string;\n}\n\nfunction zeroByType(itemTypes: string[]): Record<ItemType, number> {\n return itemTypes.reduce(\n (acc, value) => {\n acc[value] = 0;\n return acc;\n },\n {} as Record<ItemType, number>,\n );\n}\n\nfunction zeroByStatus(statuses: string[]): Record<ItemStatus, number> {\n return statuses.reduce(\n (acc, value) => {\n acc[value] = 0;\n return acc;\n },\n {} as Record<ItemStatus, number>,\n );\n}\n\nfunction countNonEmptyLines(raw: string): number {\n if (raw.trim().length === 0) {\n return 0;\n }\n return raw\n .split(/\\r?\\n/u)\n .filter((line) => line.trim().length > 0)\n .length;\n}\n\nfunction isNotFoundError(error: unknown): boolean {\n return typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: unknown }).code === \"ENOENT\";\n}\n\nasync function readHistoryStreamContents(pmRoot: string): Promise<Array<{ id: string; raw: string }>> {\n const historyDir = path.join(pmRoot, \"history\");\n if (!(await pathExists(historyDir))) {\n return [];\n }\n\n await runActiveOnReadHooks({\n path: historyDir,\n scope: \"project\",\n });\n const historyFiles = (await fs.readdir(historyDir))\n .filter((entry) => entry.endsWith(\".jsonl\"))\n .sort((a, b) => a.localeCompare(b));\n\n const streams: Array<{ id: string; raw: string }> = [];\n for (const file of historyFiles) {\n const historyPath = path.join(historyDir, file);\n let raw: string;\n try {\n raw = await fs.readFile(historyPath, \"utf8\");\n } catch (error) {\n if (isNotFoundError(error)) {\n continue;\n }\n throw error;\n }\n await runActiveOnReadHooks({\n path: historyPath,\n scope: \"project\",\n });\n streams.push({ id: file.slice(0, -\".jsonl\".length), raw });\n }\n\n return streams;\n}\n\nexport const _testOnly = {\n zeroByType,\n zeroByStatus,\n countNonEmptyLines,\n readHistoryStreamContents,\n};\n\n/**\n * Implements run stats for the public runtime surface of this module.\n */\nexport async function runStats(global: GlobalOptions, options: StatsCommandOptions = {}): Promise<StatsResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n // Field utilization needs the heavy collections (notes/learnings/files/docs/\n // tests/comments/deps) AND the body, which the light reader drops — so when it\n // is requested we read the WithBody rows and use them for every section.\n const items = options.fieldUtilization\n ? await listAllFrontMatterWithBody(pmRoot, settings.item_format, typeRegistry.type_to_folder, undefined, settings.schema)\n : await listAllFrontMatterLight(pmRoot, settings.item_format, typeRegistry.type_to_folder, undefined, settings.schema);\n await enforceHistoryStreamPolicyForItems({\n pmRoot,\n settings,\n itemIds: items.map((item) => item.id),\n commandLabel: \"stats\",\n });\n\n const byType = zeroByType(typeRegistry.types);\n const byStatus = zeroByStatus(statusRegistry.definitions.map((definition) => definition.id));\n // zeroByType/zeroByStatus pre-seed a bucket for every registry type/status, and\n // the light front-matter reader drops any item whose type/status falls outside\n // the active registry (parse rejects them) — so every item's bucket is already\n // present here and no on-the-fly initialization is reachable.\n for (const item of items) {\n byType[item.type] += 1;\n byStatus[item.status] += 1;\n }\n\n const streams = await readHistoryStreamContents(pmRoot);\n let historyEntries = 0;\n for (const stream of streams) {\n historyEntries += countNonEmptyLines(stream.raw);\n }\n const storage = options.storage ? computeHistoryStorageStats(streams) : undefined;\n\n const classifier = lifecycleClassifierFromStatusRegistry(statusRegistry);\n const metadataCoverage = options.metadataCoverage ? computeMetadataCoverage(items, classifier) : undefined;\n const breakdowns: NonNullable<StatsResult[\"breakdowns\"]> = {};\n if (options.byAssignee) {\n breakdowns.assignee = groupItemsByDimension(items, \"assignee\", classifier);\n }\n if (options.byTag) {\n breakdowns.tag = groupItemsByDimension(items, \"tag\", classifier, { tagPrefix: options.tagPrefix });\n }\n if (options.byPriority) {\n breakdowns.priority = groupItemsByDimension(items, \"priority\", classifier);\n }\n const hasBreakdowns = Object.keys(breakdowns).length > 0;\n const fieldUtilization = options.fieldUtilization ? computeContentFieldUtilization(items) : undefined;\n\n return {\n totals: {\n items: items.length,\n history_streams: streams.length,\n history_entries: historyEntries,\n },\n by_type: byType,\n by_status: byStatus,\n ...(metadataCoverage ? { metadata_coverage: metadataCoverage } : {}),\n ...(hasBreakdowns ? { breakdowns } : {}),\n ...(storage ? { storage } : {}),\n ...(fieldUtilization ? { field_utilization: fieldUtilization } : {}),\n generated_at: nowIso(),\n };\n}\n", "/**\n * Pure aggregate metrics for history streams (JSONL files).\n * No filesystem access — callers read raw stream contents and pass them in.\n * This module has no Node imports; Buffer is available as a global.\n */\n\n/** Per-history-stream size and timestamp summary used by storage diagnostics. */\nexport interface HistoryStreamStat {\n id: string;\n bytes: number;\n lines: number; // non-empty JSONL entry count\n oldest_ts: string | null; // min parseable ts in this stream, else null\n newest_ts: string | null; // max parseable ts in this stream, else null\n}\n\n/**\n * Documents the history storage entry ref payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryStorageEntryRef {\n id: string;\n ts: string;\n}\n\n/**\n * Documents the history storage stats payload exchanged by command, SDK, and package integrations.\n */\nexport interface HistoryStorageStats {\n total_streams: number;\n total_lines: number;\n total_bytes: number;\n largest_by_bytes: HistoryStreamStat[]; // top-N desc by bytes, tie-break id asc\n deepest_by_lines: HistoryStreamStat[]; // top-N desc by lines, tie-break id asc\n oldest_entry: HistoryStorageEntryRef | null; // global min ts across all streams\n newest_entry: HistoryStorageEntryRef | null; // global max ts across all streams\n}\n\nfunction parseStreamStat(id: string, raw: string): HistoryStreamStat {\n const bytes = Buffer.byteLength(raw, \"utf8\");\n\n let lines = 0;\n let oldestTs: string | null = null;\n let newestTs: string | null = null;\n let oldestMs = Number.POSITIVE_INFINITY;\n let newestMs = Number.NEGATIVE_INFINITY;\n\n for (const rawLine of raw.split(/\\r?\\n/)) {\n const trimmed = rawLine.trim();\n if (trimmed === \"\") {\n continue;\n }\n lines += 1;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(trimmed);\n } catch {\n continue;\n }\n\n if (\n parsed === null ||\n typeof parsed !== \"object\" ||\n !(\"ts\" in (parsed as object)) ||\n typeof (parsed as Record<string, unknown>)[\"ts\"] !== \"string\"\n ) {\n continue;\n }\n\n const ts = (parsed as Record<string, unknown>)[\"ts\"] as string;\n const ms = Date.parse(ts);\n if (Number.isNaN(ms)) {\n continue;\n }\n\n if (ms < oldestMs || (ms === oldestMs && oldestTs !== null && ts < oldestTs)) {\n oldestMs = ms;\n oldestTs = ts;\n }\n if (ms > newestMs || (ms === newestMs && newestTs !== null && ts > newestTs)) {\n newestMs = ms;\n newestTs = ts;\n }\n }\n\n return { id, bytes, lines, oldest_ts: oldestTs, newest_ts: newestTs };\n}\n\n/**\n * Implements compute history storage stats for the public runtime surface of this module.\n */\nexport function computeHistoryStorageStats(\n streams: Array<{ id: string; raw: string }>,\n options?: { topN?: number },\n): HistoryStorageStats {\n const rawTopN = options?.topN ?? 5;\n const topN = Math.max(0, Math.floor(rawTopN));\n\n const stats: HistoryStreamStat[] = streams.map(({ id, raw }) => parseStreamStat(id, raw));\n\n let totalLines = 0;\n let totalBytes = 0;\n let oldestEntry: HistoryStorageEntryRef | null = null;\n let newestEntry: HistoryStorageEntryRef | null = null;\n let globalOldestMs = Number.POSITIVE_INFINITY;\n let globalNewestMs = Number.NEGATIVE_INFINITY;\n\n for (const stat of stats) {\n totalLines += stat.lines;\n totalBytes += stat.bytes;\n\n if (stat.oldest_ts !== null) {\n const ms = Date.parse(stat.oldest_ts);\n if (\n ms < globalOldestMs ||\n (ms === globalOldestMs && oldestEntry !== null && stat.id < oldestEntry.id)\n ) {\n globalOldestMs = ms;\n oldestEntry = { id: stat.id, ts: stat.oldest_ts };\n }\n }\n\n if (stat.newest_ts !== null) {\n const ms = Date.parse(stat.newest_ts);\n if (\n ms > globalNewestMs ||\n (ms === globalNewestMs && newestEntry !== null && stat.id < newestEntry.id)\n ) {\n globalNewestMs = ms;\n newestEntry = { id: stat.id, ts: stat.newest_ts };\n }\n }\n }\n\n const largestByBytes =\n topN === 0\n ? []\n : [...stats]\n .sort((a, b) => b.bytes - a.bytes || a.id.localeCompare(b.id))\n .slice(0, topN);\n\n const deepestByLines =\n topN === 0\n ? []\n : [...stats]\n .sort((a, b) => b.lines - a.lines || a.id.localeCompare(b.id))\n .slice(0, topN);\n\n return {\n total_streams: streams.length,\n total_lines: totalLines,\n total_bytes: totalBytes,\n largest_by_bytes: largestByBytes,\n deepest_by_lines: deepestByLines,\n oldest_entry: oldestEntry,\n newest_entry: newestEntry,\n };\n}\n", "/**\n * @module cli/commands/telemetry\n *\n * Implements the pm telemetry command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { pathExists, readFileIfExists } from \"../../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { resolveGlobalPmRoot } from \"../../core/store/paths.js\";\nimport { readSettings, writeSettings } from \"../../core/store/settings.js\";\nimport { flushTelemetryQueueNow } from \"../../core/telemetry/runtime.js\";\n\nconst TELEMETRY_QUEUE_RELATIVE_PATH = path.join(\"runtime\", \"telemetry\", \"events.jsonl\");\nconst TELEMETRY_STATE_RELATIVE_PATH = path.join(\"runtime\", \"telemetry\", \"state.json\");\nconst TELEMETRY_RUNTIME_RELATIVE_PATH = path.join(\"runtime\", \"telemetry\");\nconst DEFAULT_STATS_LIMIT = 20;\n\nexport const TELEMETRY_SUBCOMMANDS = [\"status\", \"flush\", \"stats\", \"clear\"] as const;\n/**\n * Restricts telemetry subcommand values accepted by command, SDK, and storage contracts.\n */\nexport type TelemetrySubcommand = (typeof TELEMETRY_SUBCOMMANDS)[number];\n\ninterface TelemetryRuntimeStateRecord {\n endpoint?: string;\n queue_entries?: number;\n last_attempted_flush_at?: string;\n last_successful_flush_at?: string;\n last_failed_flush_at?: string;\n last_failed_flush_error?: string;\n}\n\ninterface QueuedTelemetryEventRecord {\n attempts: number;\n client_schema_version?: number;\n event: {\n event_id?: string;\n event_type?: string;\n schema_version?: number;\n command?: string;\n payload?: Record<string, unknown>;\n };\n}\n\ninterface ParsedTelemetryQueue {\n rows_total: number;\n valid_entries: number;\n invalid_rows: number;\n entries: QueuedTelemetryEventRecord[];\n}\n\ninterface TelemetryStatusSummary {\n enabled: boolean;\n endpoint: string;\n queue_path: string;\n state_path: string;\n queue_rows_total: number;\n queue_entries: number;\n queue_invalid_rows: number;\n queue_size_bytes: number;\n last_attempted_flush_at: string | null;\n last_successful_flush_at: string | null;\n last_failed_flush_at: string | null;\n last_failed_flush_error: string | null;\n}\n\n/**\n * Documents the telemetry command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TelemetryCommandOptions {\n subcommand?: string;\n limit?: string | number;\n}\n\ninterface TelemetryStatsBucket {\n command: string;\n count: number;\n event_type_counts: Record<string, number>;\n max_attempts: number;\n event_schema_versions: number[];\n client_schema_versions: number[];\n /**\n * Latency percentiles (nearest-rank) over `duration_ms` from the bucket's\n * `command_finish` events. Present only when at least one finish event carries\n * a finite `duration_ms`; `command_start`/`command_error` events are excluded.\n */\n duration_p50_ms?: number;\n duration_p95_ms?: number;\n duration_max_ms?: number;\n /**\n * Success/failure tally derived from `command_finish` payload `ok`. A finish\n * event whose `ok` is missing or not strictly `true` is counted as an error\n * (conservative). Present only when the bucket has at least one finish event;\n * `ok_count + error_count` equals that finish-event count.\n */\n ok_count?: number;\n error_count?: number;\n error_rate?: number;\n /** Distribution of `command_resolution` over `command_finish` events; present only when non-empty. */\n command_resolution_counts?: Record<string, number>;\n}\n\ninterface TelemetryStatsBucketAccumulator {\n count: number;\n max_attempts: number;\n event_type_counts: Record<string, number>;\n event_schema_versions: Set<number>;\n client_schema_versions: Set<number>;\n finish_durations_ms: number[];\n ok_count: number;\n error_count: number;\n resolution_counts: Record<string, number>;\n}\n\ninterface NormalizedTelemetryQueueEntry {\n command: string;\n eventType: string;\n eventSchemaVersion: number | undefined;\n clientSchemaVersion: number | undefined;\n}\n\n/**\n * Returns the nearest-rank percentile of an ascending-sorted, non-empty array.\n *\n * Uses the nearest-rank method (rank = ceil(fraction × n), 1-based, clamped into\n * range) so the result is always an observed sample value with no interpolation.\n */\nfunction nearestRankPercentile(sortedAscending: number[], fraction: number): number {\n const rank = Math.ceil(fraction * sortedAscending.length);\n const index = Math.min(sortedAscending.length - 1, Math.max(0, rank - 1));\n return sortedAscending[index];\n}\n\nfunction normalizeTelemetryQueueEntry(entry: QueuedTelemetryEventRecord): NormalizedTelemetryQueueEntry {\n const command = typeof entry.event.command === \"string\" && entry.event.command.trim().length > 0\n ? entry.event.command\n : \"<unknown>\";\n const eventType = typeof entry.event.event_type === \"string\" && entry.event.event_type.trim().length > 0\n ? entry.event.event_type\n : \"unknown\";\n const eventSchemaVersion = typeof entry.event.schema_version === \"number\" && Number.isFinite(entry.event.schema_version)\n ? Math.trunc(entry.event.schema_version)\n : undefined;\n const clientSchemaVersion =\n typeof entry.client_schema_version === \"number\" && Number.isFinite(entry.client_schema_version)\n ? Math.trunc(entry.client_schema_version)\n : undefined;\n return { command, eventType, eventSchemaVersion, clientSchemaVersion };\n}\n\nfunction createTelemetryStatsAccumulator(): TelemetryStatsBucketAccumulator {\n return {\n count: 0,\n max_attempts: 0,\n event_type_counts: {},\n event_schema_versions: new Set<number>(),\n client_schema_versions: new Set<number>(),\n finish_durations_ms: [],\n ok_count: 0,\n error_count: 0,\n resolution_counts: {},\n };\n}\n\nfunction recordTelemetryFinishPayload(current: TelemetryStatsBucketAccumulator, payload: Record<string, unknown> | undefined): void {\n const durationMs = typeof payload?.duration_ms === \"number\" && Number.isFinite(payload.duration_ms)\n ? payload.duration_ms\n : undefined;\n if (durationMs !== undefined) {\n current.finish_durations_ms.push(durationMs);\n }\n if (payload?.ok === true) {\n current.ok_count += 1;\n } else {\n current.error_count += 1;\n }\n const resolution = typeof payload?.command_resolution === \"string\" && payload.command_resolution.trim().length > 0\n ? payload.command_resolution\n : undefined;\n if (resolution !== undefined) {\n current.resolution_counts[resolution] = (current.resolution_counts[resolution] ?? 0) + 1;\n }\n}\n\nfunction recordTelemetryQueueEntry(\n grouped: Map<string, TelemetryStatsBucketAccumulator>,\n entry: QueuedTelemetryEventRecord,\n): void {\n const normalized = normalizeTelemetryQueueEntry(entry);\n const current = grouped.get(normalized.command) ?? createTelemetryStatsAccumulator();\n const attempts = Number.isFinite(entry.attempts) ? Math.max(0, Math.trunc(entry.attempts)) : 0;\n current.count += 1;\n current.max_attempts = Math.max(current.max_attempts, attempts);\n current.event_type_counts[normalized.eventType] = (current.event_type_counts[normalized.eventType] ?? 0) + 1;\n if (normalized.eventSchemaVersion !== undefined) {\n current.event_schema_versions.add(normalized.eventSchemaVersion);\n }\n if (normalized.clientSchemaVersion !== undefined) {\n current.client_schema_versions.add(normalized.clientSchemaVersion);\n }\n if (normalized.eventType === \"command_finish\") {\n recordTelemetryFinishPayload(current, entry.event.payload);\n }\n grouped.set(normalized.command, current);\n}\n\nfunction buildTelemetryStatsBucket(command: string, value: TelemetryStatsBucketAccumulator): TelemetryStatsBucket {\n const finishCount = value.ok_count + value.error_count;\n const sortedDurations = [...value.finish_durations_ms].sort((left, right) => left - right);\n const resolutionEntries = Object.entries(value.resolution_counts).sort((left, right) => left[0].localeCompare(right[0]));\n return {\n command,\n count: value.count,\n event_type_counts: Object.fromEntries(\n Object.entries(value.event_type_counts).sort((left, right) => left[0].localeCompare(right[0])),\n ),\n max_attempts: value.max_attempts,\n event_schema_versions: [...value.event_schema_versions].sort((left, right) => left - right),\n client_schema_versions: [...value.client_schema_versions].sort((left, right) => left - right),\n ...(sortedDurations.length > 0\n ? {\n duration_p50_ms: nearestRankPercentile(sortedDurations, 0.5),\n duration_p95_ms: nearestRankPercentile(sortedDurations, 0.95),\n duration_max_ms: sortedDurations[sortedDurations.length - 1],\n }\n : {}),\n ...(finishCount > 0\n ? {\n ok_count: value.ok_count,\n error_count: value.error_count,\n error_rate: value.error_count / finishCount,\n }\n : {}),\n ...(resolutionEntries.length > 0 ? { command_resolution_counts: Object.fromEntries(resolutionEntries) } : {}),\n };\n}\n\nfunction normalizeTelemetrySubcommand(value: string | undefined): TelemetrySubcommand {\n const normalized = (value ?? \"status\").trim().toLowerCase();\n if ((TELEMETRY_SUBCOMMANDS as readonly string[]).includes(normalized)) {\n return normalized as TelemetrySubcommand;\n }\n // `value` is always a defined string here: an undefined subcommand normalizes\n // to \"status\" above (a valid value) and never reaches this throw.\n throw new PmCliError(\n `Unknown pm telemetry subcommand \"${value}\". Allowed: ${TELEMETRY_SUBCOMMANDS.join(\", \")}`,\n EXIT_CODE.USAGE,\n {\n code: \"unknown_subcommand\",\n examples: [\n \"pm telemetry status\",\n \"pm telemetry flush\",\n \"pm telemetry stats --limit 10\",\n \"pm telemetry clear\",\n ],\n },\n );\n}\n\nfunction parseTelemetryStatsLimit(raw: string | number | undefined): number {\n if (raw === undefined) {\n return DEFAULT_STATS_LIMIT;\n }\n if (typeof raw === \"number\") {\n if (!Number.isFinite(raw) || !Number.isInteger(raw) || raw <= 0) {\n throw new PmCliError(\"--limit must be a positive integer\", EXIT_CODE.USAGE);\n }\n return raw;\n }\n const trimmed = raw.trim();\n if (trimmed.length === 0 || !/^\\d+$/.test(trimmed)) {\n throw new PmCliError(\"--limit must be a positive integer\", EXIT_CODE.USAGE);\n }\n const parsed = Number.parseInt(trimmed, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n throw new PmCliError(\"--limit must be a positive integer\", EXIT_CODE.USAGE);\n }\n return parsed;\n}\n\nfunction parseTelemetryQueue(raw: string | null): ParsedTelemetryQueue {\n if (raw === null || raw.trim().length === 0) {\n return {\n rows_total: 0,\n valid_entries: 0,\n invalid_rows: 0,\n entries: [],\n };\n }\n const entries: QueuedTelemetryEventRecord[] = [];\n let rowsTotal = 0;\n let invalidRows = 0;\n for (const line of raw.split(\"\\n\")) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n rowsTotal += 1;\n try {\n const parsed = JSON.parse(trimmed) as QueuedTelemetryEventRecord;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof parsed.attempts === \"number\" &&\n typeof parsed.event === \"object\" &&\n parsed.event !== null\n ) {\n entries.push(parsed);\n } else {\n invalidRows += 1;\n }\n } catch {\n invalidRows += 1;\n }\n }\n return {\n rows_total: rowsTotal,\n valid_entries: entries.length,\n invalid_rows: invalidRows,\n entries,\n };\n}\n\nasync function readTelemetryRuntimeState(statePath: string): Promise<TelemetryRuntimeStateRecord> {\n const stateRaw = await readFileIfExists(statePath);\n if (stateRaw === null || stateRaw.trim().length === 0) {\n return {};\n }\n try {\n const parsed = JSON.parse(stateRaw) as TelemetryRuntimeStateRecord;\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n return parsed;\n }\n } catch {\n // Ignore malformed state files; status command is observational.\n }\n return {};\n}\n\nasync function buildTelemetryStatusSummary(globalPmRoot: string): Promise<TelemetryStatusSummary> {\n const settings = await readSettings(globalPmRoot);\n const queuePath = path.join(globalPmRoot, TELEMETRY_QUEUE_RELATIVE_PATH);\n const statePath = path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);\n const queueRaw = await readFileIfExists(queuePath);\n const queue = parseTelemetryQueue(queueRaw);\n const runtimeState = await readTelemetryRuntimeState(statePath);\n return {\n enabled: settings.telemetry.enabled,\n endpoint: settings.telemetry.endpoint,\n queue_path: queuePath,\n state_path: statePath,\n queue_rows_total: queue.rows_total,\n queue_entries: queue.valid_entries,\n queue_invalid_rows: queue.invalid_rows,\n queue_size_bytes: queueRaw === null ? 0 : Buffer.byteLength(queueRaw, \"utf8\"),\n last_attempted_flush_at: runtimeState.last_attempted_flush_at ?? null,\n last_successful_flush_at: runtimeState.last_successful_flush_at ?? null,\n last_failed_flush_at: runtimeState.last_failed_flush_at ?? null,\n last_failed_flush_error: runtimeState.last_failed_flush_error ?? null,\n };\n}\n\nfunction buildTelemetryStatsBuckets(entries: QueuedTelemetryEventRecord[]): TelemetryStatsBucket[] {\n const grouped = new Map<string, TelemetryStatsBucketAccumulator>();\n for (const entry of entries) {\n // Latency + outcome distribution come from command_finish payloads only:\n // command_finish always carries duration_ms/ok/command_resolution at every\n // capture level, while start/error events do not.\n recordTelemetryQueueEntry(grouped, entry);\n }\n return [...grouped.entries()]\n .map(([command, value]) => buildTelemetryStatsBucket(command, value))\n .sort((left, right) => right.count - left.count || left.command.localeCompare(right.command));\n}\n\n/**\n * Implements run telemetry for the public runtime surface of this module.\n */\nexport async function runTelemetry(options: TelemetryCommandOptions, _global: GlobalOptions): Promise<Record<string, unknown>> {\n void _global;\n const subcommand = normalizeTelemetrySubcommand(options.subcommand);\n const globalPmRoot = resolveGlobalPmRoot(process.cwd());\n const queuePath = path.join(globalPmRoot, TELEMETRY_QUEUE_RELATIVE_PATH);\n const statePath = path.join(globalPmRoot, TELEMETRY_STATE_RELATIVE_PATH);\n if (subcommand === \"status\") {\n return {\n action: \"telemetry\",\n subcommand,\n status: await buildTelemetryStatusSummary(globalPmRoot),\n generated_at: nowIso(),\n };\n }\n\n if (subcommand === \"flush\") {\n const before = await buildTelemetryStatusSummary(globalPmRoot);\n await flushTelemetryQueueNow(globalPmRoot);\n const after = await buildTelemetryStatusSummary(globalPmRoot);\n return {\n action: \"telemetry\",\n subcommand,\n queue_entries_before: before.queue_entries,\n queue_entries_after: after.queue_entries,\n queue_drained: after.queue_entries < before.queue_entries,\n status: after,\n generated_at: nowIso(),\n };\n }\n\n if (subcommand === \"stats\") {\n const limit = parseTelemetryStatsLimit(options.limit);\n const queueRaw = await readFileIfExists(queuePath);\n const queue = parseTelemetryQueue(queueRaw);\n const buckets = buildTelemetryStatsBuckets(queue.entries);\n const selected = buckets.slice(0, limit);\n return {\n action: \"telemetry\",\n subcommand,\n limit,\n total_commands: buckets.length,\n queue_entries: queue.valid_entries,\n queue_invalid_rows: queue.invalid_rows,\n queue_rows_total: queue.rows_total,\n truncated: buckets.length > selected.length,\n stats: selected,\n generated_at: nowIso(),\n };\n }\n\n const settings = await readSettings(globalPmRoot);\n const previousEnabled = settings.telemetry.enabled;\n const previousInstallationId = settings.telemetry.installation_id;\n const previousFirstRunPromptCompleted = settings.telemetry.first_run_prompt_completed;\n settings.telemetry.enabled = false;\n settings.telemetry.first_run_prompt_completed = true;\n settings.telemetry.installation_id = \"\";\n const settingsChanged =\n previousEnabled !== settings.telemetry.enabled ||\n previousInstallationId !== settings.telemetry.installation_id ||\n previousFirstRunPromptCompleted !== settings.telemetry.first_run_prompt_completed;\n if (settingsChanged) {\n await writeSettings(globalPmRoot, settings, \"telemetry:clear\");\n }\n\n const telemetryRuntimePath = path.join(globalPmRoot, TELEMETRY_RUNTIME_RELATIVE_PATH);\n const existed = await pathExists(telemetryRuntimePath);\n await fs.rm(telemetryRuntimePath, { recursive: true, force: true });\n const queueExistsAfter = await pathExists(queuePath);\n const stateExistsAfter = await pathExists(statePath);\n return {\n action: \"telemetry\",\n subcommand,\n settings_changed: settingsChanged,\n runtime_dir_removed: existed && !(await pathExists(telemetryRuntimePath)),\n queue_exists_after: queueExistsAfter,\n state_exists_after: stateExistsAfter,\n status: await buildTelemetryStatusSummary(globalPmRoot),\n generated_at: nowIso(),\n };\n}\n", "/**\n * @module cli/commands/test\n *\n * Implements the pm test command surface and its agent-facing runtime behavior.\n */\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { cp, mkdir, mkdtemp, readdir, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { createStdinTokenResolver, parseCsvKv, parseOptionalNumber } from \"../../core/item/parse.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { stableValueEquals } from \"../../core/shared/serialization.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { locateItem, mutateItem, readLocatedItem } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, ITEM_FILE_EXTENSIONS, resolveGlobalPmRoot, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { appendTrackedTestRunSummary } from \"../../core/test/item-test-run-tracking.js\";\nimport { runInit } from \"./init.js\";\nimport { looksLikeStructuredLinkedTestEntry, normalizeStructuredLinkedTestEntry } from \"./linked-test-entry.js\";\nimport {\n LINKED_TEST_ENV_NAME_PATTERN,\n LINKED_TEST_PM_CONTEXT_MODE_VALUES as PM_CONTEXT_MODE_VALUES,\n LINKED_TEST_PROTECTED_ENV_KEYS,\n parseLinkedTestAssertionEqualsMap,\n parseLinkedTestAssertionGteMap,\n parseLinkedTestBoolean as parseLinkedTestBooleanValue,\n parseLinkedTestContextMode as parseLinkedTestContextModeValue,\n parseLinkedTestEnvClear as parseLinkedTestEnvClearValue,\n parseLinkedTestEnvSet as parseLinkedTestEnvSetValue,\n parseLinkedTestJsonEntries,\n parseLinkedTestMinLines,\n parseLinkedTestRegexList,\n parseLinkedTestStringList,\n type LinkedTestPmContextMode,\n} from \"./linked-test-parsers.js\";\nimport {\n parseOnlyIndexValue,\n resolveLinkedTestRunSelection,\n type LinkedTestRunSelection,\n type LinkedTestSelectorKind,\n} from \"../../core/test/run-selectors.js\";\nimport { SCOPE_VALUES } from \"../../types/index.js\";\nimport type { LinkedTest, LinkScope } from \"../../types/index.js\";\n\nconst TEST_OUTPUT_MAX_BUFFER_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS = 3000;\nconst DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS = 10000;\nconst DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS = 5000;\nconst MAX_LINKED_TEST_COMMAND_LABEL_LENGTH = 120;\ntype ResolvedLinkedTestPmContextMode = Exclude<LinkedTestPmContextMode, \"auto\">;\nconst LINKED_TEST_TRACKER_DIRS_TO_SKIP = new Set([\"locks\", \"extensions\", \"runtime\"]);\nconst LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP = new Set([\"history\", \"index\", \"search\", \"extensions\", \"locks\", \"runtime\"]);\nconst LINKED_TEST_INFRA_COLLISION_PATTERNS = [\n /eaddrinuse/i,\n /address already in use/i,\n /port\\s+\\d+\\s+is already in use/i,\n /web server[^.\\n]*already running/i,\n /failed to listen on/i,\n];\nconst PM_SUBCOMMANDS_WITH_ITEM_REFERENCE = new Set([\n \"get\",\n \"history\",\n \"restore\",\n \"update\",\n \"close\",\n \"delete\",\n \"append\",\n \"claim\",\n \"release\",\n \"comments\",\n \"notes\",\n \"learnings\",\n \"files\",\n \"docs\",\n \"deps\",\n \"test\",\n]);\nconst PM_TRACKER_READ_SUBCOMMANDS = new Set([\n \"activity\",\n \"calendar\",\n \"context\",\n \"ctx\",\n \"deps\",\n \"get\",\n \"health\",\n \"history\",\n \"list\",\n \"list-all\",\n \"list-blocked\",\n \"list-canceled\",\n \"list-closed\",\n \"list-draft\",\n \"list-in-progress\",\n \"list-open\",\n \"search\",\n \"stats\",\n \"test-all\",\n \"validate\",\n]);\n\nfunction readPositiveIntegerEnv(name: string, fallback: number): number {\n const raw = process.env[name];\n if (typeof raw !== \"string\" || raw.trim().length === 0) {\n return fallback;\n }\n const parsed = Number.parseInt(raw, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return fallback;\n }\n return parsed;\n}\n\nfunction linkedTestTimeoutForceKillDelayMs(): number {\n return readPositiveIntegerEnv(\"PM_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS\", DEFAULT_LINKED_TEST_TIMEOUT_FORCE_KILL_DELAY_MS);\n}\n\nfunction linkedTestHeartbeatIntervalMs(): number {\n return readPositiveIntegerEnv(\"PM_LINKED_TEST_HEARTBEAT_INTERVAL_MS\", DEFAULT_LINKED_TEST_HEARTBEAT_INTERVAL_MS);\n}\n\nfunction linkedTestPipeCloseGraceMs(): number {\n return readPositiveIntegerEnv(\"PM_LINKED_TEST_PIPE_CLOSE_GRACE_MS\", DEFAULT_LINKED_TEST_PIPE_CLOSE_GRACE_MS);\n}\n\ninterface LinkedTestExecutionResult {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n signal?: NodeJS.Signals | null;\n timedOut: boolean;\n maxBufferExceeded: boolean;\n spawnError?: string;\n}\n\ninterface LinkedTestProgressContext {\n index: number;\n total: number;\n timeoutMs: number;\n command: string;\n}\n\ntype LinkedTestProgressMode = \"auto\" | \"always\" | \"off\";\n\ninterface LinkedTestSandboxSourceRoots {\n projectPmRoot: string;\n globalPmRoot: string;\n}\n\ninterface LinkedTestRuntimeDirectives {\n env_set: Record<string, string>;\n env_clear: string[];\n shared_host_safe: boolean;\n}\n\n/**\n * Documents the test command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestCommandOptions {\n add?: string[];\n addJson?: string[];\n remove?: string[];\n list?: boolean;\n run?: boolean;\n match?: string;\n onlyIndex?: string | number;\n onlyLast?: boolean;\n timeout?: string;\n progress?: boolean;\n envSet?: string[];\n envClear?: string[];\n sharedHostSafe?: boolean;\n pmContext?: string;\n overrideLinkedPmContext?: boolean;\n failOnContextMismatch?: boolean;\n failOnSkipped?: boolean;\n failOnEmptyTestRun?: boolean;\n requireAssertionsForPm?: boolean;\n checkContext?: boolean;\n autoPmContext?: boolean;\n author?: string;\n message?: string;\n force?: boolean;\n}\n\n/**\n * Restricts linked test failure category values accepted by command, SDK, and storage contracts.\n */\nexport type LinkedTestFailureCategory =\n | \"infra_collision\"\n | \"assertion_failure\"\n | \"empty_run\"\n | \"timeout\"\n | \"max_buffer\"\n | \"spawn_error\"\n | \"signal\";\n\n/**\n * Documents the test run result payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestRunResult {\n command?: string;\n path?: string;\n status: \"passed\" | \"failed\" | \"skipped\";\n exit_code?: number;\n failure_category?: LinkedTestFailureCategory;\n execution_context?: {\n requested_pm_context_mode: LinkedTestPmContextMode;\n pm_context_mode: LinkedTestPmContextMode;\n auto_pm_context_applied: boolean;\n is_pm_command: boolean;\n is_pm_tracker_read_command: boolean;\n source_project_pm_path: string;\n sandbox_project_pm_path: string;\n source_global_pm_path: string;\n sandbox_global_pm_path: string;\n source_project_item_count: number;\n sandbox_project_item_count: number;\n source_global_item_count: number;\n sandbox_global_item_count: number;\n mismatch_detected: boolean;\n project_extensions_seeded: boolean;\n global_extensions_seeded: boolean;\n };\n stdout?: string;\n stderr?: string;\n error?: string;\n}\n\n/**\n * Documents the test result payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestResult {\n ok: boolean;\n id: string;\n tests: LinkedTest[];\n run_results: TestRunResult[];\n failure_categories: Record<LinkedTestFailureCategory, number>;\n selection?: Omit<LinkedTestRunSelection, \"selected\">;\n fail_on_skipped_triggered?: boolean;\n warnings?: string[];\n changed: boolean;\n count: number;\n}\n\nfunction resolveAuthor(candidate: string | undefined, fallback: string): string {\n const resolved = candidate ?? process.env.PM_AUTHOR ?? fallback;\n const trimmed = resolved.trim();\n return trimmed || \"unknown\";\n}\n\nfunction resolveTrackedRunId(kind: \"test\" | \"test-all\"): string {\n const fromEnv = process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return `${kind}-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction summarizeRunResultStatuses(results: TestRunResult[]): { passed: number; failed: number; skipped: number } {\n let passed = 0;\n let failed = 0;\n let skipped = 0;\n for (const entry of results) {\n if (entry.status === \"passed\") {\n passed += 1;\n continue;\n }\n if (entry.status === \"failed\") {\n failed += 1;\n continue;\n }\n skipped += 1;\n }\n return { passed, failed, skipped };\n}\n\n/**\n * Implements summarize context preflight for the public runtime surface of this module.\n */\nexport function summarizeContextPreflight(runResults: TestRunResult[]): {\n checked_pm_commands: number;\n tracker_read_commands: number;\n mismatches: number;\n auto_remediated: number;\n} {\n let checkedPmCommands = 0;\n let trackerReadCommands = 0;\n let mismatches = 0;\n let autoRemediated = 0;\n for (const result of runResults) {\n const context = result.execution_context;\n if (!context || context.is_pm_command !== true) {\n continue;\n }\n checkedPmCommands += 1;\n if (context.is_pm_tracker_read_command === true) {\n trackerReadCommands += 1;\n }\n if (context.mismatch_detected === true) {\n mismatches += 1;\n }\n if (context.auto_pm_context_applied === true) {\n autoRemediated += 1;\n }\n }\n return {\n checked_pm_commands: checkedPmCommands,\n tracker_read_commands: trackerReadCommands,\n mismatches,\n auto_remediated: autoRemediated,\n };\n}\n\nfunction ensureScope(raw: string | undefined): LinkScope {\n const value = (raw ?? \"project\") as LinkScope;\n if (!SCOPE_VALUES.includes(value)) {\n throw new PmCliError(`Invalid scope \"${raw}\"`, EXIT_CODE.USAGE);\n }\n return value;\n}\n\nfunction parsePmContextMode(raw: string | undefined): LinkedTestPmContextMode {\n if (!raw) {\n return \"schema\";\n }\n const normalized = raw.trim().toLowerCase();\n if ((PM_CONTEXT_MODE_VALUES as readonly string[]).includes(normalized)) {\n return normalized as LinkedTestPmContextMode;\n }\n throw new PmCliError(\n `Invalid --pm-context value \"${raw}\". Expected one of: ${PM_CONTEXT_MODE_VALUES.join(\", \")}`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveLinkedTestRequestedContextMode(\n linkedTest: LinkedTest,\n runLevelMode: LinkedTestPmContextMode,\n overrideLinkedPmContext: boolean,\n): LinkedTestPmContextMode {\n if (overrideLinkedPmContext) {\n return runLevelMode;\n }\n if (typeof linkedTest.pm_context_mode !== \"string\" || linkedTest.pm_context_mode.trim().length === 0) {\n return runLevelMode;\n }\n return parsePmContextMode(linkedTest.pm_context_mode);\n}\n\nfunction resolveLinkedTestEffectiveContextMode(\n requestedMode: LinkedTestPmContextMode,\n isPmTrackerReadCommand: boolean,\n): ResolvedLinkedTestPmContextMode {\n if (requestedMode === \"auto\") {\n return isPmTrackerReadCommand ? \"tracker\" : \"schema\";\n }\n return requestedMode;\n}\n\n/* c8 ignore start -- assertion-shape truthiness combinations are covered by linked-test integration suites */\nfunction hasLinkedTestAssertions(linkedTest: LinkedTest): boolean {\n return (\n (linkedTest.assert_stdout_contains?.length ?? 0) > 0 ||\n (linkedTest.assert_stdout_regex?.length ?? 0) > 0 ||\n (linkedTest.assert_stderr_contains?.length ?? 0) > 0 ||\n (linkedTest.assert_stderr_regex?.length ?? 0) > 0 ||\n typeof linkedTest.assert_stdout_min_lines === \"number\" ||\n Object.keys(linkedTest.assert_json_field_equals ?? {}).length > 0 ||\n Object.keys(linkedTest.assert_json_field_gte ?? {}).length > 0\n );\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- pm-context mismatch hint combinations are validated by tracker/schema integration runs */\nfunction buildPmContextMismatchHint(params: {\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n runLevelPmContextMode: LinkedTestPmContextMode;\n linkedOverridePmContextMode: LinkedTestPmContextMode | undefined;\n}): string {\n const { executionContext, runLevelPmContextMode, linkedOverridePmContextMode } = params;\n if (!executionContext.is_pm_tracker_read_command || !executionContext.mismatch_detected) {\n return \"\";\n }\n if (runLevelPmContextMode === \"tracker\" && linkedOverridePmContextMode === \"schema\") {\n return (\n \" Linked test metadata pm_context_mode=schema overrides run-level --pm-context tracker.\" +\n \" Set pm_context_mode=tracker (or auto) on the linked test, or remove the override, to run against seeded tracker data.\"\n );\n }\n if (executionContext.pm_context_mode === \"schema\") {\n return (\n \" Use --auto-pm-context to route PM tracker-read linked commands through seeded tracker data automatically.\" +\n \" Alternatively, use --pm-context tracker for the whole run.\"\n );\n }\n return \"\";\n}\n/* c8 ignore stop */\n\nfunction mergeEnvSetDirectives(entries: string[] | undefined, optionName: string): Record<string, string> {\n const merged: Record<string, string> = {};\n if (!entries) {\n return merged;\n }\n for (const entry of entries) {\n const parsed = parseLinkedTestEnvSetValue(entry, optionName);\n if (!parsed) {\n continue;\n }\n for (const [key, value] of Object.entries(parsed)) {\n merged[key] = value;\n }\n }\n return merged;\n}\n\nfunction mergeEnvClearDirectives(entries: string[] | undefined, optionName: string): string[] {\n if (!entries) {\n return [];\n }\n const values: string[] = [];\n for (const entry of entries) {\n const parsed = parseLinkedTestEnvClearValue(entry, optionName);\n if (parsed) {\n values.push(...parsed);\n }\n }\n return [...new Set(values)];\n}\n\n// Linked-test command detection helpers + constants live in a sibling leaf\n// module to keep this command file under the per-file LOC budget. Re-exported\n// here so no consumer outside this file changes.\nimport {\n BUN_GLOBAL_FLAGS_WITH_VALUE,\n NPM_EXEC_SUBCOMMANDS,\n NPM_GLOBAL_FLAGS_WITH_VALUE,\n NPX_FLAGS_WITH_VALUE,\n PM_GLOBAL_FLAGS_WITH_VALUE,\n PNPM_GLOBAL_FLAGS_WITH_VALUE,\n SCRIPT_RUN_FLAGS_WITH_VALUE,\n SCRIPT_RUN_SUBCOMMANDS,\n YARN_GLOBAL_FLAGS_WITH_VALUE,\n firstPmSubcommand,\n firstPositionalToken,\n isPmCliPackageToken,\n isPmCliScriptToken,\n isPmExecutableToken,\n normalizePackageSpecifier,\n parseLauncherSubcommand,\n parseNpmExecCommand,\n parseNpxCommand,\n parsePnpmDlxCommand,\n resolvePmSubcommandContext,\n splitNormalizedCommandSegments,\n stripLeadingEnvAssignments,\n} from \"./test/linked-command-detection.js\";\n\nfunction looksLikePrefixedItemId(token: string, idPrefix: string): boolean {\n const normalizedPrefix = idPrefix.trim().toLowerCase().replace(/-+$/, \"\");\n if (normalizedPrefix.length === 0) {\n return false;\n }\n const normalized = token.trim().toLowerCase();\n if (!normalized.startsWith(`${normalizedPrefix}-`)) {\n return false;\n }\n return normalized.length > normalizedPrefix.length + 1;\n}\n\nfunction extractPmInvocationArgsFromSegment(segment: string): string[] | null {\n const rawTokens = segment.split(\" \").filter((token) => token.length > 0);\n const tokens = stripLeadingEnvAssignments(rawTokens);\n if (tokens.length === 0) {\n return null;\n }\n const [executable, ...args] = tokens;\n if (isPmExecutableToken(executable) || isPmCliScriptToken(executable)) {\n return args;\n }\n if (executable === \"node\" && args.length > 0 && isPmCliScriptToken(args[0])) {\n return args.slice(1);\n }\n return extractPackageManagerPmInvocationArgs(executable, args);\n}\n\nfunction extractPackageManagerPmInvocationArgs(executable: string, args: string[]): string[] | null {\n const parsed = parsePackageManagerPmInvocation(executable, args);\n if (!parsed || (!isPmExecutableToken(parsed.command) && !isPmCliPackageToken(parsed.command))) {\n return null;\n }\n return parsed.args;\n}\n\nfunction parsePackageManagerPmInvocation(executable: string, args: string[]): { command: string; args: string[] } | null {\n if (executable === \"npx\" || executable === \"bunx\") {\n return parseNpxCommand(args);\n }\n if (executable === \"pnpm\") {\n return parsePnpmDlxCommand(args);\n }\n if (executable === \"npm\") {\n return parseNpmExecCommand(args);\n }\n return null;\n}\n\nfunction commandInvokesPmCli(command: string): boolean {\n const normalizedCommand = normalizeCommandForValidation(command);\n return splitNormalizedCommandSegments(normalizedCommand).some((segment) => extractPmInvocationArgsFromSegment(segment) !== null);\n}\n\nfunction commandInvokesPmTrackerReadCommand(command: string): boolean {\n const normalizedCommand = normalizeCommandForValidation(command);\n return splitNormalizedCommandSegments(normalizedCommand).some((segment) => {\n const invocationArgs = extractPmInvocationArgsFromSegment(segment);\n if (!invocationArgs) {\n return false;\n }\n const context = resolvePmSubcommandContext(invocationArgs);\n if (!context) {\n return false;\n }\n return PM_TRACKER_READ_SUBCOMMANDS.has(context.subcommand);\n });\n}\n\n/* c8 ignore start -- command-token extraction edge permutations are covered by integration command-parser tests */\n/**\n * Implements extract referenced pm item ids from command for the public runtime surface of this module.\n */\nexport function extractReferencedPmItemIdsFromCommand(command: string, idPrefix = \"pm\"): string[] {\n const normalizedCommand = normalizeCommandForValidation(command);\n const ids = new Set<string>();\n for (const segment of splitNormalizedCommandSegments(normalizedCommand)) {\n const invocationArgs = extractPmInvocationArgsFromSegment(segment);\n if (!invocationArgs) {\n continue;\n }\n const context = resolvePmSubcommandContext(invocationArgs);\n if (!context) {\n continue;\n }\n if (!PM_SUBCOMMANDS_WITH_ITEM_REFERENCE.has(context.subcommand)) {\n continue;\n }\n const candidate = firstPositionalToken(context.remaining);\n if (!candidate) {\n continue;\n }\n if (looksLikePrefixedItemId(candidate, idPrefix)) {\n ids.add(candidate);\n }\n }\n return [...ids].sort((left, right) => left.localeCompare(right));\n}\n/* c8 ignore stop */\n\nfunction resolveDirectRunnerSubcommand(parsed: { subcommand: string; args: string[] } | null): string | undefined {\n if (!parsed) {\n return undefined;\n }\n if (!SCRIPT_RUN_SUBCOMMANDS.has(parsed.subcommand)) {\n return parsed.subcommand;\n }\n return parseLauncherSubcommand(parsed.args, SCRIPT_RUN_FLAGS_WITH_VALUE)?.subcommand;\n}\n\nfunction firstDirectTestRunnerSubcommand(executable: string, args: string[]): string | undefined {\n if (executable === \"npx\" || executable === \"bunx\") {\n return parseNpxCommand(args)?.command;\n }\n if (executable === \"pnpm\") {\n return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args, PNPM_GLOBAL_FLAGS_WITH_VALUE));\n }\n if (executable === \"npm\") {\n return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args, NPM_GLOBAL_FLAGS_WITH_VALUE));\n }\n if (executable === \"yarn\") {\n return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args, YARN_GLOBAL_FLAGS_WITH_VALUE));\n }\n if (executable === \"bun\") {\n return resolveDirectRunnerSubcommand(parseLauncherSubcommand(args, BUN_GLOBAL_FLAGS_WITH_VALUE));\n }\n return undefined;\n}\n\nfunction isDirectTestRunnerSubcommand(token: string | undefined): boolean {\n if (!token) {\n return false;\n }\n return token === \"vitest\" || token === \"test\" || token.startsWith(\"test:\");\n}\n\nfunction parsedLauncherInvokesRecursiveTestAll(parsed: { command: string; args: string[] } | null): boolean {\n if (!parsed) {\n return false;\n }\n if (!isPmExecutableToken(parsed.command) && !isPmCliPackageToken(parsed.command)) {\n return false;\n }\n return firstPmSubcommand(parsed.args) === \"test-all\";\n}\n\nfunction segmentInvokesRecursiveTestAll(segment: string): boolean {\n const rawTokens = segment.split(\" \").filter((token) => token.length > 0);\n const tokens = stripLeadingEnvAssignments(rawTokens);\n if (tokens.length === 0) {\n return false;\n }\n\n const [executable, ...args] = tokens;\n if (isPmExecutableToken(executable) || isPmCliScriptToken(executable)) {\n return firstPmSubcommand(args) === \"test-all\";\n }\n\n if (executable === \"node\" && args.length > 0 && isPmCliScriptToken(args[0])) {\n return firstPmSubcommand(args.slice(1)) === \"test-all\";\n }\n\n if (executable === \"npx\" || executable === \"bunx\") {\n return parsedLauncherInvokesRecursiveTestAll(parseNpxCommand(args));\n }\n\n if (executable === \"pnpm\") {\n return parsedLauncherInvokesRecursiveTestAll(parsePnpmDlxCommand(args));\n }\n\n if (executable === \"npm\") {\n return parsedLauncherInvokesRecursiveTestAll(parseNpmExecCommand(args));\n }\n\n return false;\n}\n\nfunction invokesRecursiveTestAllCommand(command: string): boolean {\n const normalized = normalizeCommandForValidation(command);\n return splitNormalizedCommandSegments(normalized).some((segment) => segmentInvokesRecursiveTestAll(segment));\n}\n\nfunction assertNoRecursiveTestAllCommand(command: string): void {\n if (!invokesRecursiveTestAllCommand(command)) return;\n throw new PmCliError(\n 'Linked test commands must not invoke \"pm test-all\"; this creates recursive orchestration.',\n EXIT_CODE.USAGE,\n );\n}\n\nfunction normalizeCommandForValidation(command: string): string {\n return command\n .trim()\n .replaceAll(\"\\\\\", \"/\")\n .replaceAll('\"', \"\")\n .replaceAll(\"'\", \"\")\n .replaceAll(/\\s+/g, \" \")\n .toLowerCase();\n}\n\nfunction commandUsesSandboxRunner(normalizedCommand: string): boolean {\n return (\n normalizedCommand.includes(\"node scripts/run-tests.mjs \") ||\n normalizedCommand.endsWith(\"node scripts/run-tests.mjs\") ||\n normalizedCommand.includes(\"node ./scripts/run-tests.mjs \") ||\n normalizedCommand.endsWith(\"node ./scripts/run-tests.mjs\")\n );\n}\n\nfunction segmentHasExplicitSandboxEnv(normalizedSegment: string): boolean {\n const hasExplicitPmPath = /\\bpm_path\\s*=/.test(normalizedSegment) || /\\$env:pm_path\\s*=/.test(normalizedSegment);\n const hasExplicitPmGlobalPath =\n /\\bpm_global_path\\s*=/.test(normalizedSegment) || /\\$env:pm_global_path\\s*=/.test(normalizedSegment);\n return hasExplicitPmPath && hasExplicitPmGlobalPath;\n}\n\nfunction segmentInvokesUnsafeDirectTestRunner(normalizedSegment: string): boolean {\n const rawTokens = normalizedSegment.split(\" \").filter((token) => token.length > 0);\n const tokens = stripLeadingEnvAssignments(rawTokens);\n if (tokens.length === 0) {\n return false;\n }\n const [executable, ...args] = tokens;\n if (executable === \"vitest\" || executable.endsWith(\"/vitest\") || executable.endsWith(\"/vitest.mjs\")) {\n return true;\n }\n if (executable === \"node\") {\n return nodeArgsInvokeUnsafeDirectTestRunner(args);\n }\n return packageManagerInvokesUnsafeDirectTestRunner(executable, args);\n}\n\nfunction nodeArgsInvokeUnsafeDirectTestRunner(args: string[]): boolean {\n return (\n args.includes(\"--test\") ||\n args.some((arg) => arg === \"vitest\" || arg === \"vitest.mjs\" || arg.endsWith(\"/vitest\") || arg.endsWith(\"/vitest.mjs\"))\n );\n}\n\nfunction packageManagerInvokesUnsafeDirectTestRunner(executable: string, args: string[]): boolean {\n if (executable === \"npx\" || executable === \"bunx\") {\n return isDirectTestRunnerSubcommand(parseNpxCommand(args)?.command);\n }\n if (executable === \"pnpm\" || executable === \"npm\") {\n return (\n isDirectTestRunnerSubcommand(parsePackageManagerPmInvocation(executable, args)?.command) ||\n firstDirectTestRunnerSubcommand(executable, args) === \"vitest\"\n );\n }\n return (executable === \"yarn\" || executable === \"bun\") && firstDirectTestRunnerSubcommand(executable, args) === \"vitest\";\n}\n\nfunction assertSandboxSafeTestRunnerCommand(command: string): void {\n const normalized = normalizeCommandForValidation(command);\n const segments = splitNormalizedCommandSegments(normalized);\n const hasUnsafeDirectRunnerSegment = segments.some(\n (segment) =>\n !commandUsesSandboxRunner(segment) &&\n segmentInvokesUnsafeDirectTestRunner(segment) &&\n !segmentHasExplicitSandboxEnv(segment),\n );\n\n if (!hasUnsafeDirectRunnerSegment) {\n return;\n }\n\n throw new PmCliError(\n 'Linked test runner commands must be sandbox-safe: use \"node scripts/run-tests.mjs <test|coverage>\", use a package-manager script such as \"pnpm test\", or include PM_PATH=... PM_GLOBAL_PATH=... INLINE in the command string (exporting them in your shell environment is not checked). Example: \"PM_PATH=/tmp/pm-x PM_GLOBAL_PATH=/tmp/pm-x-g vitest run\".',\n EXIT_CODE.USAGE,\n );\n}\n\nfunction getRuntimeSafetySkipReason(command: string): string | undefined {\n if (!invokesRecursiveTestAllCommand(command)) return undefined;\n return 'Linked test command skipped: Linked test commands must not invoke \"pm test-all\"; this creates recursive orchestration.';\n}\n\nfunction parseAddEntries(raw: string[] | undefined): LinkedTest[] {\n if (!raw) return [];\n return raw.map(parseAddEntry);\n}\n\nfunction parseAddEntry(entry: string): LinkedTest {\n const trimmed = entry.trim();\n const kv = looksLikeStructuredLinkedTestEntry(trimmed)\n ? normalizeStructuredLinkedTestEntry(parseCsvKv(entry, \"--add\"), \"--add\")\n : { command: trimmed };\n const command = trimLinkedTestEntryField(kv.command);\n if (!command) {\n throw new PmCliError(\"--add requires command=<value> or a bare command (path=<value> is optional metadata)\", EXIT_CODE.USAGE);\n }\n assertNoRecursiveTestAllCommand(command);\n assertSandboxSafeTestRunnerCommand(command);\n return {\n command,\n path: trimLinkedTestEntryField(kv.path),\n scope: ensureScope(kv.scope),\n timeout_seconds: parseLinkedTestTimeoutSeconds(\n trimLinkedTestEntryField(kv.timeout_seconds),\n trimLinkedTestEntryField(kv.timeout),\n ),\n pm_context_mode: parseLinkedTestContextModeValue(trimLinkedTestEntryField(kv.pm_context_mode), \"--add\"),\n env_set: parseLinkedTestEnvSetValue(trimLinkedTestEntryField(kv.env_set), \"--add\"),\n env_clear: parseLinkedTestEnvClearValue(trimLinkedTestEntryField(kv.env_clear), \"--add\"),\n shared_host_safe: parseLinkedTestBooleanValue(trimLinkedTestEntryField(kv.shared_host_safe), \"--add\", \"shared_host_safe\"),\n assert_stdout_contains: parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stdout_contains)),\n assert_stdout_regex: parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stdout_regex), \"--add\", \"assert_stdout_regex\"),\n assert_stderr_contains: parseLinkedTestStringList(trimLinkedTestEntryField(kv.assert_stderr_contains)),\n assert_stderr_regex: parseLinkedTestRegexList(trimLinkedTestEntryField(kv.assert_stderr_regex), \"--add\", \"assert_stderr_regex\"),\n assert_stdout_min_lines: parseLinkedTestMinLines(trimLinkedTestEntryField(kv.assert_stdout_min_lines), \"--add\"),\n assert_json_field_equals: parseLinkedTestAssertionEqualsMap(trimLinkedTestEntryField(kv.assert_json_field_equals), \"--add\"),\n assert_json_field_gte: parseLinkedTestAssertionGteMap(trimLinkedTestEntryField(kv.assert_json_field_gte), \"--add\"),\n note: trimLinkedTestEntryField(kv.note),\n };\n}\n\nfunction trimLinkedTestEntryField(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed && trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction parseLinkedTestTimeoutSeconds(timeoutSecondsRaw: string | undefined, timeoutAliasRaw: string | undefined): number | undefined {\n if (timeoutSecondsRaw && timeoutAliasRaw && timeoutSecondsRaw !== timeoutAliasRaw) {\n throw new PmCliError(\"--add timeout and timeout_seconds must match when both are provided\", EXIT_CODE.USAGE);\n }\n const timeoutRaw = timeoutSecondsRaw ?? timeoutAliasRaw;\n return timeoutRaw === undefined ? undefined : Math.floor(parseOptionalNumber(timeoutRaw, \"timeout_seconds\"));\n}\n\n/* c8 ignore start -- add-json validation matrix is covered by linked-test parser integration suites */\nfunction parseAddJsonEntries(raw: string[] | undefined): LinkedTest[] {\n if (!raw) return [];\n return raw.flatMap((entry) => {\n const parsed = parseLinkedTestJsonEntries(entry, \"--add-json\");\n for (const linkedTest of parsed) {\n const command = linkedTest.command;\n if (!command) {\n throw new PmCliError(\"--add-json requires a non-empty command string\", EXIT_CODE.USAGE);\n }\n assertNoRecursiveTestAllCommand(command);\n assertSandboxSafeTestRunnerCommand(command);\n }\n return parsed;\n });\n}\n/* c8 ignore stop */\n\nfunction parseRemoveEntries(raw: string[] | undefined): string[] {\n if (!raw) return [];\n return raw.map((entry) => {\n const trimmed = entry.trim();\n if (!trimmed) {\n throw new PmCliError(\"--remove requires command or path value\", EXIT_CODE.USAGE);\n }\n if (\n trimmed.includes(\"=\") ||\n /^(?:[-*+]\\s+)?(?:path|command)\\s*[:=]/i.test(trimmed) ||\n trimmed.startsWith(\"```\")\n ) {\n const kv = parseCsvKv(trimmed, \"--remove\");\n const value = kv.path ?? kv.command;\n if (!value?.trim()) {\n throw new PmCliError(\"--remove requires command=<value> and/or path=<value>\", EXIT_CODE.USAGE);\n }\n return value.trim();\n }\n return trimmed;\n });\n}\n\nfunction closeLinkedTestStdin(child: ChildProcess): void {\n // Force EOF on child stdin so non-interactive runs do not wait on input.\n try {\n child.stdin?.end();\n } catch {\n // Child stdin can already be closed depending on command startup timing.\n }\n}\n\nfunction summarizeLinkedTestCommand(command: string): string {\n const normalized = command.trim().replaceAll(/\\s+/g, \" \");\n if (normalized.length <= MAX_LINKED_TEST_COMMAND_LABEL_LENGTH) {\n return normalized;\n }\n return `${normalized.slice(0, MAX_LINKED_TEST_COMMAND_LABEL_LENGTH - 3)}...`;\n}\n\nfunction shouldEmitLinkedTestProgress(mode: LinkedTestProgressMode): boolean {\n /* c8 ignore start -- reserved for future explicit \"off\" mode wiring. */\n if (mode === \"off\") {\n return false;\n }\n /* c8 ignore stop */\n if (mode === \"always\") {\n return true;\n }\n return process.stderr.isTTY === true;\n}\n\nfunction emitLinkedTestProgress(message: string): void {\n try {\n process.stderr.write(`${message}\\n`);\n } catch {\n // Ignore transient stderr write failures.\n }\n}\n\nfunction beginLinkedTestProgress(context: LinkedTestProgressContext, mode: LinkedTestProgressMode): NodeJS.Timeout | null {\n if (!shouldEmitLinkedTestProgress(mode)) {\n return null;\n }\n const commandLabel = summarizeLinkedTestCommand(context.command);\n const startAt = Date.now();\n emitLinkedTestProgress(\n `[pm test] linked-test ${context.index}/${context.total} start timeout_ms=${context.timeoutMs} command=\"${commandLabel}\"`,\n );\n const heartbeat = setInterval(() => {\n const elapsedMs = Date.now() - startAt;\n emitLinkedTestProgress(\n `[pm test] linked-test ${context.index}/${context.total} running elapsed_ms=${elapsedMs} command=\"${commandLabel}\"`,\n );\n }, linkedTestHeartbeatIntervalMs());\n heartbeat.unref?.();\n return heartbeat;\n}\n\nfunction endLinkedTestProgress(\n context: LinkedTestProgressContext,\n executionResult: Pick<LinkedTestExecutionResult, \"timedOut\" | \"maxBufferExceeded\" | \"exitCode\" | \"signal\">,\n startedAt: number,\n mode: LinkedTestProgressMode,\n): void {\n if (!shouldEmitLinkedTestProgress(mode)) {\n return;\n }\n const commandLabel = summarizeLinkedTestCommand(context.command);\n const elapsedMs = Date.now() - startedAt;\n const failed = executionResult.timedOut || executionResult.maxBufferExceeded || executionResult.exitCode !== 0;\n const statusLabel = failed ? \"failed\" : \"passed\";\n const reasonTokens: string[] = [];\n if (executionResult.timedOut) {\n reasonTokens.push(\"reason=timeout\");\n }\n if (executionResult.maxBufferExceeded) {\n reasonTokens.push(\"reason=max_buffer\");\n }\n if (executionResult.signal) {\n reasonTokens.push(`signal=${executionResult.signal}`);\n }\n const exitLabel = executionResult.exitCode === null ? \"null\" : String(executionResult.exitCode);\n const reasonSuffix = reasonTokens.length > 0 ? ` ${reasonTokens.join(\" \")}` : \"\";\n emitLinkedTestProgress(\n `[pm test] linked-test ${context.index}/${context.total} end status=${statusLabel} exit_code=${exitLabel} elapsed_ms=${elapsedMs}${reasonSuffix} command=\"${commandLabel}\"`,\n );\n}\n\n/* c8 ignore start -- process-tree teardown paths are highly platform-dependent. */\nasync function killProcessTree(pid: number): Promise<void> {\n if (!Number.isInteger(pid) || pid <= 0) {\n return;\n }\n if (process.platform === \"win32\") {\n await new Promise<void>((resolve) => {\n const killer = spawn(\"taskkill\", [\"/pid\", String(pid), \"/T\", \"/F\"], {\n stdio: \"ignore\",\n windowsHide: true,\n });\n killer.on(\"error\", () => resolve());\n killer.on(\"close\", () => resolve());\n });\n return;\n }\n try {\n process.kill(-pid, \"SIGKILL\");\n return;\n } catch {\n // Fall back to direct child kill when no process group is available.\n }\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n // The process can already be gone.\n }\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- process lifecycle timing/error race branches are covered by cross-platform integration runners */\ninterface LinkedTestTimerState {\n heartbeat: NodeJS.Timeout | null;\n forceKillTimer: NodeJS.Timeout | null;\n timedOutTimer: NodeJS.Timeout | null;\n}\n\ninterface LinkedTestOutputBufferState {\n stdout: string;\n stderr: string;\n stdoutBytes: number;\n stderrBytes: number;\n maxBufferExceeded: boolean;\n}\n\nfunction clearLinkedTestTimers(timers: LinkedTestTimerState): void {\n if (timers.heartbeat) {\n clearInterval(timers.heartbeat);\n }\n if (timers.timedOutTimer) {\n clearTimeout(timers.timedOutTimer);\n timers.timedOutTimer = null;\n }\n if (timers.forceKillTimer) {\n clearTimeout(timers.forceKillTimer);\n timers.forceKillTimer = null;\n }\n}\n\nfunction createLinkedTestTerminationRequester(\n child: ReturnType<typeof spawn>,\n timers: LinkedTestTimerState,\n): () => Promise<void> {\n let terminationRequested = false;\n return async (): Promise<void> => {\n if (terminationRequested) {\n return;\n }\n terminationRequested = true;\n const pid = child.pid;\n if (!pid || pid <= 0) {\n try {\n child.kill(\"SIGTERM\");\n } catch {\n // Child can already be closed.\n }\n return;\n }\n if (process.platform === \"win32\") {\n await killProcessTree(pid);\n return;\n }\n try {\n process.kill(-pid, \"SIGTERM\");\n } catch {\n /* c8 ignore next 4 -- platform-specific process-group fallback path. */\n try {\n child.kill(\"SIGTERM\");\n } catch {\n // Child can already be closed.\n }\n }\n /* c8 ignore next 3 -- exercised only when timeout escalation triggers force-kill fallback. */\n timers.forceKillTimer = setTimeout(() => {\n void killProcessTree(pid);\n }, linkedTestTimeoutForceKillDelayMs());\n timers.forceKillTimer.unref?.();\n };\n}\n\nfunction readLinkedTestOutputChunkText(chunk: Buffer | string, bytes: number, remainingBytes: number): string {\n if (remainingBytes <= 0) {\n return \"\";\n }\n if (bytes <= remainingBytes) {\n return typeof chunk === \"string\" ? chunk : chunk.toString(\"utf8\");\n }\n const buffer = typeof chunk === \"string\" ? Buffer.from(chunk) : chunk;\n return buffer.subarray(0, remainingBytes).toString(\"utf8\");\n}\n\nfunction appendLinkedTestOutputChunk(\n state: LinkedTestOutputBufferState,\n chunk: Buffer | string,\n target: \"stdout\" | \"stderr\",\n): boolean {\n if (state.maxBufferExceeded) {\n return false;\n }\n const bytes = typeof chunk === \"string\" ? Buffer.byteLength(chunk) : chunk.byteLength;\n if (target === \"stdout\") {\n const remainingBytes = TEST_OUTPUT_MAX_BUFFER_BYTES - state.stdoutBytes;\n state.stdout += readLinkedTestOutputChunkText(chunk, bytes, remainingBytes);\n state.stdoutBytes += bytes;\n } else {\n const remainingBytes = TEST_OUTPUT_MAX_BUFFER_BYTES - state.stderrBytes;\n state.stderr += readLinkedTestOutputChunkText(chunk, bytes, remainingBytes);\n state.stderrBytes += bytes;\n }\n const bufferExceeded =\n state.stdoutBytes > TEST_OUTPUT_MAX_BUFFER_BYTES || state.stderrBytes > TEST_OUTPUT_MAX_BUFFER_BYTES;\n if (!state.maxBufferExceeded && bufferExceeded) {\n state.maxBufferExceeded = true;\n return true;\n }\n return false;\n}\n\nfunction waitForLinkedTestChildClose(\n child: ReturnType<typeof spawn>,\n): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {\n return new Promise((resolve) => {\n let settled = false;\n let pipeCloseGraceTimer: NodeJS.Timeout | null = null;\n const settle = (value: { code: number | null; signal: NodeJS.Signals | null }, destroyPipes = false): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (pipeCloseGraceTimer) {\n clearTimeout(pipeCloseGraceTimer);\n pipeCloseGraceTimer = null;\n }\n if (destroyPipes) {\n child.stdin?.destroy();\n child.stdout?.destroy();\n child.stderr?.destroy();\n }\n resolve(value);\n };\n child.on(\"exit\", (exitCode, exitSignal) => {\n if (settled) {\n return;\n }\n pipeCloseGraceTimer = setTimeout(() => {\n settle({\n code: exitCode,\n signal: exitSignal,\n }, true);\n }, linkedTestPipeCloseGraceMs());\n pipeCloseGraceTimer.unref?.();\n });\n child.on(\"close\", (closeCode, closeSignal) => {\n settle({\n code: closeCode,\n signal: closeSignal,\n });\n });\n });\n}\n\nfunction createLinkedTestChild(command: string, env: NodeJS.ProcessEnv): ReturnType<typeof spawn> {\n return spawn(command, {\n cwd: process.cwd(),\n env,\n shell: true,\n windowsHide: true,\n detached: process.platform !== \"win32\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\nasync function runLinkedTestCommand(\n command: string,\n timeoutMs: number,\n env: NodeJS.ProcessEnv,\n progressContext: LinkedTestProgressContext,\n progressMode: LinkedTestProgressMode,\n): Promise<LinkedTestExecutionResult> {\n const startedAt = Date.now();\n const child = createLinkedTestChild(command, env);\n closeLinkedTestStdin(child);\n const timers: LinkedTestTimerState = {\n heartbeat: beginLinkedTestProgress(progressContext, progressMode),\n forceKillTimer: null,\n timedOutTimer: null,\n };\n const output: LinkedTestOutputBufferState = {\n stdout: \"\",\n stderr: \"\",\n stdoutBytes: 0,\n stderrBytes: 0,\n maxBufferExceeded: false,\n };\n const requestTermination = createLinkedTestTerminationRequester(child, timers);\n let timedOut = false;\n let spawnError: string | undefined;\n\n const appendChunk = (chunk: Buffer | string, target: \"stdout\" | \"stderr\"): void => {\n if (appendLinkedTestOutputChunk(output, chunk, target)) {\n void requestTermination();\n }\n };\n\n child.stdout?.on(\"data\", (chunk) => appendChunk(chunk, \"stdout\"));\n child.stderr?.on(\"data\", (chunk) => appendChunk(chunk, \"stderr\"));\n /* c8 ignore next 5 -- shell spawn error callbacks are non-deterministic across platforms. */\n child.on(\"error\", (error) => {\n spawnError = error.message;\n });\n\n /* c8 ignore next 4 -- callback scheduling timing is non-deterministic under coverage instrumentation. */\n timers.timedOutTimer = setTimeout(() => {\n timedOut = true;\n void requestTermination();\n }, timeoutMs);\n timers.timedOutTimer.unref?.();\n\n const { code, signal } = await waitForLinkedTestChildClose(child);\n clearLinkedTestTimers(timers);\n const executionResult: LinkedTestExecutionResult = {\n stdout: output.stdout,\n stderr: output.stderr,\n exitCode: code,\n signal,\n timedOut,\n maxBufferExceeded: output.maxBufferExceeded,\n spawnError,\n };\n endLinkedTestProgress(progressContext, executionResult, startedAt, progressMode);\n return executionResult;\n}\n/* c8 ignore stop */\n\nfunction formatLinkedTestExecutionError(result: LinkedTestExecutionResult, timeoutMs: number): string {\n const details: string[] = [];\n if (result.maxBufferExceeded) {\n details.push(\n `Linked test output exceeded maxBuffer=${TEST_OUTPUT_MAX_BUFFER_BYTES} bytes. Reduce output volume or split the command.`,\n );\n }\n if (result.timedOut && timeoutMs > 0) {\n details.push(`Linked test timed out after ${timeoutMs}ms.`);\n }\n const signalMessage = result.signal ? `Linked test command terminated by signal ${result.signal}.` : undefined;\n const baseMessage = result.spawnError?.trim() || signalMessage || \"Linked test command failed.\";\n if (details.length === 0) {\n return baseMessage;\n }\n return `${baseMessage} ${details.join(\" \")}`;\n}\n\nfunction hasInfraCollisionSignal(result: Pick<LinkedTestExecutionResult, \"stdout\" | \"stderr\" | \"spawnError\">): boolean {\n const combined = [result.spawnError ?? \"\", result.stderr, result.stdout].join(\"\\n\");\n return LINKED_TEST_INFRA_COLLISION_PATTERNS.some((pattern) => pattern.test(combined));\n}\n\n/**\n * Implements classify linked test failure for the public runtime surface of this module.\n */\nexport function classifyLinkedTestFailure(\n result: Pick<LinkedTestExecutionResult, \"stdout\" | \"stderr\" | \"spawnError\" | \"signal\" | \"timedOut\" | \"maxBufferExceeded\">,\n): LinkedTestFailureCategory {\n if (hasInfraCollisionSignal(result)) {\n return \"infra_collision\";\n }\n if (result.timedOut) {\n return \"timeout\";\n }\n if (result.maxBufferExceeded) {\n return \"max_buffer\";\n }\n if (result.spawnError) {\n return \"spawn_error\";\n }\n if (result.signal) {\n return \"signal\";\n }\n return \"assertion_failure\";\n}\n\nfunction createEmptyFailureCategoryCounts(): Record<LinkedTestFailureCategory, number> {\n return {\n infra_collision: 0,\n assertion_failure: 0,\n empty_run: 0,\n timeout: 0,\n max_buffer: 0,\n spawn_error: 0,\n signal: 0,\n };\n}\n\n/**\n * Implements count failure categories for the public runtime surface of this module.\n */\nexport function countFailureCategories(runResults: TestRunResult[]): Record<LinkedTestFailureCategory, number> {\n const counts = createEmptyFailureCategoryCounts();\n for (const result of runResults) {\n if (result.status !== \"failed\" || !result.failure_category) {\n continue;\n }\n counts[result.failure_category] += 1;\n }\n return counts;\n}\n\nfunction applyEnvDirectiveStage(env: NodeJS.ProcessEnv, directives: Pick<LinkedTestRuntimeDirectives, \"env_set\" | \"env_clear\">): void {\n for (const [key, value] of Object.entries(directives.env_set)) {\n if (LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())) {\n continue;\n }\n env[key] = value;\n }\n for (const key of directives.env_clear) {\n if (LINKED_TEST_PROTECTED_ENV_KEYS.has(key.toUpperCase())) {\n continue;\n }\n delete env[key];\n }\n}\n\nfunction applySharedHostSafeDefaults(env: NodeJS.ProcessEnv): void {\n if (env.PORT === undefined) {\n env.PORT = \"0\";\n }\n if (env.HOST === undefined) {\n env.HOST = \"127.0.0.1\";\n }\n if (env.PM_SHARED_HOST_SAFE === undefined) {\n env.PM_SHARED_HOST_SAFE = \"1\";\n }\n if (env.PLAYWRIGHT_HTML_OPEN === undefined) {\n env.PLAYWRIGHT_HTML_OPEN = \"never\";\n }\n if (env.PW_TEST_HTML_REPORT_OPEN === undefined) {\n env.PW_TEST_HTML_REPORT_OPEN = \"never\";\n }\n}\n\nfunction resolveEffectiveLinkedTestDirectives(\n runtimeDirectives: LinkedTestRuntimeDirectives,\n linkedTest: LinkedTest,\n): LinkedTestRuntimeDirectives {\n const envSet = { ...runtimeDirectives.env_set, ...linkedTest.env_set };\n const envClear = [...new Set([...runtimeDirectives.env_clear, ...(linkedTest.env_clear ?? [])])];\n const sharedHostSafe = linkedTest.shared_host_safe ?? runtimeDirectives.shared_host_safe;\n return {\n env_set: envSet,\n env_clear: envClear,\n shared_host_safe: sharedHostSafe,\n };\n}\n\nfunction resolveRuntimeDirectives(\n envSetEntries: string[] | undefined,\n envClearEntries: string[] | undefined,\n sharedHostSafe: boolean | undefined,\n): LinkedTestRuntimeDirectives {\n return {\n env_set: mergeEnvSetDirectives(envSetEntries, \"--env-set\"),\n env_clear: mergeEnvClearDirectives(envClearEntries, \"--env-clear\"),\n shared_host_safe: sharedHostSafe === true,\n };\n}\n\n/* c8 ignore start -- sandbox copy race/path permutations are covered by filesystem integration suites */\nasync function copyIntoSandboxIfPresent(sourcePath: string, targetPath: string, recursive = false): Promise<void> {\n if (!(await pathExists(sourcePath))) {\n return;\n }\n await mkdir(path.dirname(targetPath), { recursive: true });\n try {\n if (recursive) {\n await cp(sourcePath, targetPath, { recursive: true, force: true });\n return;\n }\n await cp(sourcePath, targetPath, { force: true });\n } catch (error: unknown) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n}\n/* c8 ignore stop */\n\nasync function seedLinkedTestSandbox(\n sandboxPmPath: string,\n sandboxGlobalPath: string,\n sourceRoots: LinkedTestSandboxSourceRoots,\n): Promise<void> {\n await copyIntoSandboxIfPresent(getSettingsPath(sourceRoots.projectPmRoot), getSettingsPath(sandboxPmPath));\n await copyIntoSandboxIfPresent(\n path.join(sourceRoots.projectPmRoot, \"extensions\"),\n path.join(sandboxPmPath, \"extensions\"),\n true,\n );\n await copyIntoSandboxIfPresent(getSettingsPath(sourceRoots.globalPmRoot), getSettingsPath(sandboxGlobalPath));\n await copyIntoSandboxIfPresent(\n path.join(sourceRoots.globalPmRoot, \"extensions\"),\n path.join(sandboxGlobalPath, \"extensions\"),\n true,\n );\n}\n\nasync function seedLinkedTestTrackerData(sourceRoot: string, sandboxRoot: string): Promise<void> {\n if (!(await pathExists(sourceRoot))) {\n return;\n }\n const entries = await readdir(sourceRoot, { withFileTypes: true });\n for (const entry of entries) {\n if (LINKED_TEST_TRACKER_DIRS_TO_SKIP.has(entry.name)) {\n continue;\n }\n const sourcePath = path.join(sourceRoot, entry.name);\n const targetPath = path.join(sandboxRoot, entry.name);\n if (entry.isDirectory()) {\n await copyIntoSandboxIfPresent(sourcePath, targetPath, true);\n continue;\n }\n if (entry.isFile()) {\n await copyIntoSandboxIfPresent(sourcePath, targetPath);\n }\n }\n}\n\nasync function countLinkedTestItemFiles(pmRoot: string): Promise<number> {\n if (!(await pathExists(pmRoot))) {\n return 0;\n }\n let total = 0;\n const entries = await readdir(pmRoot, { withFileTypes: true });\n for (const entry of entries) {\n if (!entry.isDirectory() || LINKED_TEST_ITEM_COUNT_DIRS_TO_SKIP.has(entry.name)) {\n continue;\n }\n const folderPath = path.join(pmRoot, entry.name);\n let files;\n try {\n files = await readdir(folderPath, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const file of files) {\n if (!file.isFile()) {\n continue;\n }\n if (ITEM_FILE_EXTENSIONS.some((extension) => file.name.toLowerCase().endsWith(extension))) {\n total += 1;\n }\n }\n }\n return total;\n}\n\n/**\n * Implements resolve linked test failure exit code for the public runtime surface of this module.\n */\nexport function resolveLinkedTestFailureExitCode(\n execution: Pick<LinkedTestExecutionResult, \"exitCode\" | \"timedOut\" | \"maxBufferExceeded\">,\n): number {\n const rawExitCode = typeof execution.exitCode === \"number\" ? execution.exitCode : 1;\n if ((execution.timedOut || execution.maxBufferExceeded) && rawExitCode === 0) {\n return 1;\n }\n return rawExitCode;\n}\n\nfunction splitJsonPathSegments(fieldPath: string): Array<string | number> {\n const segments: Array<string | number> = [];\n const tokens = fieldPath.match(/[^.[\\]]+|\\[\\d+\\]/g) ?? [];\n for (const token of tokens) {\n if (token.startsWith(\"[\") && token.endsWith(\"]\")) {\n const parsedIndex = Number.parseInt(token.slice(1, -1), 10);\n if (!Number.isInteger(parsedIndex) || parsedIndex < 0) {\n return [];\n }\n segments.push(parsedIndex);\n continue;\n }\n segments.push(token);\n }\n return segments;\n}\n\nfunction readJsonPathValue(root: unknown, fieldPath: string): { found: boolean; value: unknown } {\n const normalizedPath = fieldPath.trim();\n if (normalizedPath.length === 0) {\n return { found: false, value: undefined };\n }\n const segments = splitJsonPathSegments(normalizedPath);\n if (segments.length === 0) {\n return { found: false, value: undefined };\n }\n let current: unknown = root;\n for (const segment of segments) {\n if (typeof segment === \"number\") {\n if (!Array.isArray(current) || segment >= current.length) {\n return { found: false, value: undefined };\n }\n current = current[segment];\n continue;\n }\n if (typeof current !== \"object\" || current === null || !(segment in current)) {\n return { found: false, value: undefined };\n }\n current = (current as Record<string, unknown>)[segment];\n }\n return { found: true, value: current };\n}\n\n/* c8 ignore start -- assertion-literal parsing edge cases are validated by assertion integration suites */\nfunction parseAssertionLiteral(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === \"true\") {\n return true;\n }\n if (trimmed === \"false\") {\n return false;\n }\n if (trimmed === \"null\") {\n return null;\n }\n const numeric = Number(trimmed);\n if (trimmed.length > 0 && Number.isFinite(numeric)) {\n return numeric;\n }\n if ((trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) || (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\"))) {\n try {\n return JSON.parse(trimmed) as unknown;\n } catch {\n // Fall back to string comparison for malformed JSON literals.\n }\n }\n return trimmed;\n}\n/* c8 ignore stop */\n\nfunction compareAssertionValues(actual: unknown, expected: unknown): boolean {\n if (\n typeof actual === \"object\" &&\n actual !== null &&\n typeof expected === \"object\" &&\n expected !== null\n ) {\n return stableValueEquals(actual, expected);\n }\n return Object.is(actual, expected);\n}\n\n/* c8 ignore start -- assertion failure-path permutations are covered by linked-test integration fixtures */\nfunction evaluateLinkedTestAssertions(linkedTest: LinkedTest, stdout: string, stderr: string): string[] {\n const failures: string[] = [];\n failures.push(...evaluateContainsAssertions(\"stdout\", stdout, linkedTest.assert_stdout_contains));\n failures.push(...evaluateRegexAssertions(\"stdout\", stdout, linkedTest.assert_stdout_regex));\n failures.push(...evaluateContainsAssertions(\"stderr\", stderr, linkedTest.assert_stderr_contains));\n failures.push(...evaluateRegexAssertions(\"stderr\", stderr, linkedTest.assert_stderr_regex));\n failures.push(...evaluateStdoutLineCountAssertion(stdout, linkedTest.assert_stdout_min_lines));\n\n const jsonEqualsAssertions = linkedTest.assert_json_field_equals ?? {};\n const jsonGteAssertions = linkedTest.assert_json_field_gte ?? {};\n const needsJsonAssertions = Object.keys(jsonEqualsAssertions).length > 0 || Object.keys(jsonGteAssertions).length > 0;\n if (!needsJsonAssertions) {\n return failures;\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(stdout);\n } catch (error: unknown) {\n failures.push(\n `stdout is not valid JSON for assert_json_field_* checks: ${error instanceof Error ? error.message : String(error)}`,\n );\n return failures;\n }\n\n for (const [fieldPath, expectedRaw] of Object.entries(jsonEqualsAssertions)) {\n const resolved = readJsonPathValue(parsedJson, fieldPath);\n if (!resolved.found) {\n failures.push(`assert_json_field_equals missing path \"${fieldPath}\"`);\n continue;\n }\n const expected = parseAssertionLiteral(expectedRaw);\n if (!compareAssertionValues(resolved.value, expected)) {\n failures.push(\n `assert_json_field_equals mismatch at \"${fieldPath}\" (expected=${JSON.stringify(expected)} actual=${JSON.stringify(resolved.value)})`,\n );\n }\n }\n\n for (const [fieldPath, expectedMinimum] of Object.entries(jsonGteAssertions)) {\n const resolved = readJsonPathValue(parsedJson, fieldPath);\n if (!resolved.found) {\n failures.push(`assert_json_field_gte missing path \"${fieldPath}\"`);\n continue;\n }\n if (typeof resolved.value !== \"number\" || !Number.isFinite(resolved.value)) {\n failures.push(`assert_json_field_gte path \"${fieldPath}\" resolved to non-numeric value`);\n continue;\n }\n if (resolved.value < expectedMinimum) {\n failures.push(`assert_json_field_gte failed at \"${fieldPath}\" (expected >= ${expectedMinimum}, actual ${resolved.value})`);\n }\n }\n\n return failures;\n}\n/* c8 ignore stop */\n\nfunction evaluateContainsAssertions(streamName: \"stdout\" | \"stderr\", output: string, expectedValues: string[] | undefined): string[] {\n const failures: string[] = [];\n for (const expected of expectedValues ?? []) {\n if (!output.includes(expected)) {\n failures.push(`${streamName} missing required text: \"${expected}\"`);\n }\n }\n return failures;\n}\n\nfunction evaluateRegexAssertions(streamName: \"stdout\" | \"stderr\", output: string, patterns: string[] | undefined): string[] {\n const failures: string[] = [];\n for (const pattern of patterns ?? []) {\n try {\n const regex = new RegExp(pattern, \"m\");\n if (!regex.test(output)) {\n failures.push(`${streamName} failed regex assertion: /${pattern}/m`);\n }\n } catch (error: unknown) {\n failures.push(`${streamName} regex assertion is invalid: /${pattern}/ (${error instanceof Error ? error.message : String(error)})`);\n }\n }\n return failures;\n}\n\nfunction evaluateStdoutLineCountAssertion(stdout: string, minimum: number | undefined): string[] {\n if (typeof minimum !== \"number\") {\n return [];\n }\n const lineCount = stdout\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0).length;\n return lineCount < minimum ? [`stdout line count ${lineCount} is below required minimum ${minimum}`] : [];\n}\n\nconst EMPTY_LINKED_TEST_RUN_PATTERNS: Array<{ code: string; regex: RegExp }> = [\n { code: \"no_projects_matched_filters\", regex: /\\bNo projects matched the filters\\b/i },\n { code: \"no_test_files_found\", regex: /\\bNo test files found\\b/i },\n { code: \"no_tests_found\", regex: /\\bNo tests found\\b/i },\n { code: \"no_matching_tests\", regex: /\\bNo matching tests?\\b/i },\n { code: \"collected_zero_items\", regex: /\\bcollected 0 items?\\b/i },\n];\n\nfunction detectEmptyLinkedTestRun(stdout: string, stderr: string): string | null {\n const combined = `${stdout}\\n${stderr}`;\n for (const pattern of EMPTY_LINKED_TEST_RUN_PATTERNS) {\n if (pattern.regex.test(combined)) {\n return pattern.code;\n }\n }\n return null;\n}\n\n/* c8 ignore start -- linked-test orchestration branch matrix is covered by end-to-end command integration runs */\ninterface RunLinkedTestsOptions {\n progress?: boolean;\n sourceRoots?: LinkedTestSandboxSourceRoots;\n envSet?: string[];\n envClear?: string[];\n sharedHostSafe?: boolean;\n pmContext?: string;\n overrideLinkedPmContext?: boolean;\n failOnContextMismatch?: boolean;\n failOnEmptyTestRun?: boolean;\n requireAssertionsForPm?: boolean;\n checkContext?: boolean;\n autoPmContext?: boolean;\n}\n\ninterface LinkedTestSandboxLayout {\n root: string;\n schemaProjectPmPath: string;\n schemaGlobalPmPath: string;\n trackerProjectPmPath: string;\n trackerGlobalPmPath: string;\n}\n\ninterface LinkedTestSandboxCounts {\n sourceProjectItemCount: number;\n sourceGlobalItemCount: number;\n schemaProjectItemCount: number;\n schemaGlobalItemCount: number;\n trackerProjectItemCount: number;\n trackerGlobalItemCount: number;\n}\n\ninterface LinkedTestCommandContext {\n linkedOverridePmContextMode: LinkedTestPmContextMode | undefined;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n}\n\nfunction createLinkedTestSandboxLayout(sandboxRoot: string): LinkedTestSandboxLayout {\n return {\n root: sandboxRoot,\n schemaProjectPmPath: path.join(sandboxRoot, \"schema\", \"project\", \".agents\", \"pm\"),\n schemaGlobalPmPath: path.join(sandboxRoot, \"schema\", \"global\"),\n trackerProjectPmPath: path.join(sandboxRoot, \"tracker\", \"project\", \".agents\", \"pm\"),\n trackerGlobalPmPath: path.join(sandboxRoot, \"tracker\", \"global\"),\n };\n}\n\nasync function initializeLinkedTestSandboxes(layout: LinkedTestSandboxLayout): Promise<void> {\n await runInit(undefined, { path: layout.schemaProjectPmPath });\n await runInit(undefined, { path: layout.schemaGlobalPmPath });\n await runInit(undefined, { path: layout.trackerProjectPmPath });\n await runInit(undefined, { path: layout.trackerGlobalPmPath });\n}\n\nasync function seedLinkedTestSandboxesFromSource(\n layout: LinkedTestSandboxLayout,\n sourceRoots: LinkedTestSandboxSourceRoots | undefined,\n): Promise<void> {\n if (!sourceRoots) {\n return;\n }\n await seedLinkedTestSandbox(layout.schemaProjectPmPath, layout.schemaGlobalPmPath, sourceRoots);\n await seedLinkedTestSandbox(layout.trackerProjectPmPath, layout.trackerGlobalPmPath, sourceRoots);\n await seedLinkedTestTrackerData(sourceRoots.projectPmRoot, layout.trackerProjectPmPath);\n await seedLinkedTestTrackerData(sourceRoots.globalPmRoot, layout.trackerGlobalPmPath);\n}\n\nasync function countLinkedTestSandboxItems(\n layout: LinkedTestSandboxLayout,\n sourceRoots: LinkedTestSandboxSourceRoots | undefined,\n): Promise<LinkedTestSandboxCounts> {\n return {\n sourceProjectItemCount: sourceRoots ? await countLinkedTestItemFiles(sourceRoots.projectPmRoot) : 0,\n sourceGlobalItemCount: sourceRoots ? await countLinkedTestItemFiles(sourceRoots.globalPmRoot) : 0,\n schemaProjectItemCount: await countLinkedTestItemFiles(layout.schemaProjectPmPath),\n schemaGlobalItemCount: await countLinkedTestItemFiles(layout.schemaGlobalPmPath),\n trackerProjectItemCount: await countLinkedTestItemFiles(layout.trackerProjectPmPath),\n trackerGlobalItemCount: await countLinkedTestItemFiles(layout.trackerGlobalPmPath),\n };\n}\n\nfunction buildLinkedTestExecutionContext(params: {\n layout: LinkedTestSandboxLayout;\n counts: LinkedTestSandboxCounts;\n sourceRoots: LinkedTestSandboxSourceRoots | undefined;\n isPmCommand: boolean;\n isPmTrackerReadCommand: boolean;\n requestedPmContextMode: LinkedTestPmContextMode;\n effectivePmContextMode: ResolvedLinkedTestPmContextMode;\n autoPmContextApplied: boolean;\n}): NonNullable<TestRunResult[\"execution_context\"]> {\n const trackerMode = params.effectivePmContextMode === \"tracker\";\n const selectedSandboxProjectPmPath = trackerMode ? params.layout.trackerProjectPmPath : params.layout.schemaProjectPmPath;\n const selectedSandboxGlobalPmPath = trackerMode ? params.layout.trackerGlobalPmPath : params.layout.schemaGlobalPmPath;\n const selectedSandboxProjectItemCount = trackerMode ? params.counts.trackerProjectItemCount : params.counts.schemaProjectItemCount;\n const selectedSandboxGlobalItemCount = trackerMode ? params.counts.trackerGlobalItemCount : params.counts.schemaGlobalItemCount;\n return {\n requested_pm_context_mode: params.requestedPmContextMode,\n pm_context_mode: params.effectivePmContextMode,\n auto_pm_context_applied: params.autoPmContextApplied,\n is_pm_command: params.isPmCommand,\n is_pm_tracker_read_command: params.isPmTrackerReadCommand,\n source_project_pm_path: params.sourceRoots?.projectPmRoot ?? \"\",\n sandbox_project_pm_path: selectedSandboxProjectPmPath,\n source_global_pm_path: params.sourceRoots?.globalPmRoot ?? \"\",\n sandbox_global_pm_path: selectedSandboxGlobalPmPath,\n source_project_item_count: params.counts.sourceProjectItemCount,\n sandbox_project_item_count: selectedSandboxProjectItemCount,\n source_global_item_count: params.counts.sourceGlobalItemCount,\n sandbox_global_item_count: selectedSandboxGlobalItemCount,\n mismatch_detected: params.isPmCommand && params.counts.sourceProjectItemCount !== selectedSandboxProjectItemCount,\n project_extensions_seeded: Boolean(params.sourceRoots),\n global_extensions_seeded: Boolean(params.sourceRoots),\n };\n}\n\nfunction resolveLinkedTestCommandContext(params: {\n linkedTest: LinkedTest;\n layout: LinkedTestSandboxLayout;\n counts: LinkedTestSandboxCounts;\n sourceRoots: LinkedTestSandboxSourceRoots | undefined;\n runLevelPmContextMode: LinkedTestPmContextMode;\n options: RunLinkedTestsOptions | undefined;\n}): LinkedTestCommandContext {\n const linkedOverridePmContextMode =\n typeof params.linkedTest.pm_context_mode === \"string\" && params.linkedTest.pm_context_mode.trim().length > 0\n ? parsePmContextMode(params.linkedTest.pm_context_mode)\n : undefined;\n const command = typeof params.linkedTest.command === \"string\" && params.linkedTest.command.length > 0\n ? params.linkedTest.command\n : undefined;\n const isPmCommand = command ? commandInvokesPmCli(command) : false;\n const isPmTrackerReadCommand = isPmCommand && command ? commandInvokesPmTrackerReadCommand(command) : false;\n const autoPmContextApplied = params.options?.autoPmContext === true && isPmTrackerReadCommand;\n const requestedPmContextMode = autoPmContextApplied\n ? \"auto\"\n : resolveLinkedTestRequestedContextMode(\n params.linkedTest,\n params.runLevelPmContextMode,\n params.options?.overrideLinkedPmContext === true,\n );\n const effectivePmContextMode = resolveLinkedTestEffectiveContextMode(requestedPmContextMode, isPmTrackerReadCommand);\n return {\n linkedOverridePmContextMode,\n executionContext: buildLinkedTestExecutionContext({\n layout: params.layout,\n counts: params.counts,\n sourceRoots: params.sourceRoots,\n isPmCommand,\n isPmTrackerReadCommand,\n requestedPmContextMode,\n effectivePmContextMode,\n autoPmContextApplied,\n }),\n };\n}\n\nfunction buildLinkedTestSkippedResult(\n linkedTest: LinkedTest,\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>,\n error: string,\n): TestRunResult {\n return {\n command: linkedTest.command,\n path: linkedTest.path,\n status: \"skipped\",\n execution_context: executionContext,\n error,\n };\n}\n\nfunction buildLinkedTestAssertionFailureResult(\n linkedTest: LinkedTest,\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>,\n error: string,\n output?: Pick<LinkedTestExecutionResult, \"stdout\" | \"stderr\">,\n): TestRunResult {\n return {\n command: linkedTest.command,\n path: linkedTest.path,\n status: \"failed\",\n exit_code: 1,\n failure_category: \"assertion_failure\",\n execution_context: executionContext,\n ...(output ? { stdout: output.stdout, stderr: output.stderr } : {}),\n error,\n };\n}\n\nfunction resolveLinkedTestPreflightResult(params: {\n linkedTest: LinkedTest;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n runLevelPmContextMode: LinkedTestPmContextMode;\n linkedOverridePmContextMode: LinkedTestPmContextMode | undefined;\n options: RunLinkedTestsOptions | undefined;\n}): TestRunResult | null {\n if (!params.linkedTest.command) {\n return buildLinkedTestSkippedResult(params.linkedTest, params.executionContext, \"No command configured for this linked test.\");\n }\n const runtimeSafetySkipReason = getRuntimeSafetySkipReason(params.linkedTest.command);\n if (runtimeSafetySkipReason) {\n return buildLinkedTestSkippedResult(params.linkedTest, params.executionContext, runtimeSafetySkipReason);\n }\n const failOnMismatchByDefault =\n params.executionContext.pm_context_mode === \"schema\" &&\n params.executionContext.is_pm_tracker_read_command &&\n params.executionContext.mismatch_detected;\n const failOnMismatchByFlag =\n params.options?.failOnContextMismatch === true &&\n params.executionContext.is_pm_command &&\n params.executionContext.mismatch_detected;\n if (failOnMismatchByDefault || failOnMismatchByFlag) {\n const mismatchHint = buildPmContextMismatchHint({\n executionContext: params.executionContext,\n runLevelPmContextMode: params.runLevelPmContextMode,\n linkedOverridePmContextMode: params.linkedOverridePmContextMode,\n });\n const mismatchPrefix =\n params.options?.checkContext === true\n ? \"Linked test preflight PM context mismatch detected\"\n : \"Linked test PM context mismatch detected\";\n return buildLinkedTestAssertionFailureResult(\n params.linkedTest,\n params.executionContext,\n `${mismatchPrefix} (source_project_items=${params.executionContext.source_project_item_count}, ` +\n `sandbox_project_items=${params.executionContext.sandbox_project_item_count}).${mismatchHint}`,\n );\n }\n if (\n params.options?.requireAssertionsForPm === true &&\n params.executionContext.is_pm_command &&\n !hasLinkedTestAssertions(params.linkedTest)\n ) {\n return buildLinkedTestAssertionFailureResult(\n params.linkedTest,\n params.executionContext,\n \"Linked PM command requires assertions when --require-assertions-for-pm is enabled.\",\n );\n }\n return null;\n}\n\nfunction buildLinkedTestExecutionEnv(params: {\n runtimeDirectives: LinkedTestRuntimeDirectives;\n linkedTest: LinkedTest;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n}): NodeJS.ProcessEnv {\n const effectiveDirectives = resolveEffectiveLinkedTestDirectives(params.runtimeDirectives, params.linkedTest);\n const executionEnv: NodeJS.ProcessEnv = { ...process.env };\n applyEnvDirectiveStage(executionEnv, params.runtimeDirectives);\n applyEnvDirectiveStage(executionEnv, {\n env_set: params.linkedTest.env_set ?? {},\n env_clear: params.linkedTest.env_clear ?? [],\n });\n if (effectiveDirectives.shared_host_safe) {\n applySharedHostSafeDefaults(executionEnv);\n }\n executionEnv.FORCE_COLOR = \"0\";\n executionEnv.PM_PATH = params.executionContext.sandbox_project_pm_path;\n executionEnv.PM_GLOBAL_PATH = params.executionContext.sandbox_global_pm_path;\n return executionEnv;\n}\n\nfunction buildLinkedTestPassedResult(\n linkedTest: LinkedTest,\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>,\n execution: LinkedTestExecutionResult,\n): TestRunResult {\n return {\n command: linkedTest.command,\n path: linkedTest.path,\n status: \"passed\",\n exit_code: 0,\n execution_context: executionContext,\n stdout: execution.stdout,\n stderr: execution.stderr,\n };\n}\n\nfunction buildLinkedTestEmptyRunResult(params: {\n linkedTest: LinkedTest;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n execution: LinkedTestExecutionResult;\n emptyRunSignal: string;\n}): TestRunResult {\n return {\n command: params.linkedTest.command,\n path: params.linkedTest.path,\n status: \"failed\",\n exit_code: 1,\n failure_category: \"empty_run\",\n execution_context: params.executionContext,\n stdout: params.execution.stdout,\n stderr: params.execution.stderr,\n error:\n `Linked test reported an empty test run (${params.emptyRunSignal}) while --fail-on-empty-test-run is enabled. ` +\n \"Update test selection or disable --fail-on-empty-test-run for this run.\",\n };\n}\n\nfunction buildLinkedTestCommandFailureResult(params: {\n linkedTest: LinkedTest;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n execution: LinkedTestExecutionResult;\n timeoutMs: number;\n}): TestRunResult {\n return {\n command: params.linkedTest.command,\n path: params.linkedTest.path,\n status: \"failed\",\n exit_code: resolveLinkedTestFailureExitCode(params.execution),\n failure_category: classifyLinkedTestFailure(params.execution),\n execution_context: params.executionContext,\n stdout: params.execution.stdout,\n stderr: params.execution.stderr,\n error: formatLinkedTestExecutionError(params.execution, params.timeoutMs),\n };\n}\n\nfunction buildLinkedTestPassedExecutionResult(params: {\n linkedTest: LinkedTest;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n execution: LinkedTestExecutionResult;\n options: RunLinkedTestsOptions | undefined;\n}): TestRunResult {\n if (params.options?.failOnEmptyTestRun === true) {\n const emptyRunSignal = detectEmptyLinkedTestRun(params.execution.stdout, params.execution.stderr);\n if (emptyRunSignal) {\n return buildLinkedTestEmptyRunResult({ ...params, emptyRunSignal });\n }\n }\n const assertionFailures = evaluateLinkedTestAssertions(params.linkedTest, params.execution.stdout, params.execution.stderr);\n if (assertionFailures.length > 0) {\n return buildLinkedTestAssertionFailureResult(\n params.linkedTest,\n params.executionContext,\n `Linked test assertion(s) failed: ${assertionFailures.join(\"; \")}`,\n params.execution,\n );\n }\n return buildLinkedTestPassedResult(params.linkedTest, params.executionContext, params.execution);\n}\n\nasync function runSingleLinkedTest(params: {\n linkedTest: LinkedTest;\n index: number;\n total: number;\n defaultTimeoutSeconds: number | undefined;\n runtimeDirectives: LinkedTestRuntimeDirectives;\n progressMode: LinkedTestProgressMode;\n executionContext: NonNullable<TestRunResult[\"execution_context\"]>;\n options: RunLinkedTestsOptions | undefined;\n}): Promise<TestRunResult> {\n const command = params.linkedTest.command ?? \"\";\n const timeoutMs = (params.linkedTest.timeout_seconds ?? params.defaultTimeoutSeconds ?? 120) * 1000;\n const execution = await runLinkedTestCommand(\n command,\n timeoutMs,\n buildLinkedTestExecutionEnv(params),\n {\n index: params.index + 1,\n total: params.total,\n timeoutMs,\n command,\n },\n params.progressMode,\n );\n const passed = execution.exitCode === 0 && !execution.timedOut && !execution.maxBufferExceeded;\n return passed\n ? buildLinkedTestPassedExecutionResult({ ...params, execution })\n : buildLinkedTestCommandFailureResult({ ...params, execution, timeoutMs });\n}\n\n/**\n * Implements run linked tests for the public runtime surface of this module.\n */\nexport async function runLinkedTests(\n tests: LinkedTest[],\n defaultTimeoutSeconds: number | undefined,\n options?: RunLinkedTestsOptions,\n): Promise<TestRunResult[]> {\n const results: TestRunResult[] = [];\n const sandboxRoot = await mkdtemp(path.join(tmpdir(), \"pm-linked-test-\"));\n const layout = createLinkedTestSandboxLayout(sandboxRoot);\n const runLevelPmContextMode = parsePmContextMode(options?.pmContext);\n const progressMode: LinkedTestProgressMode = options?.progress === true ? \"always\" : \"auto\";\n const runtimeDirectives = resolveRuntimeDirectives(options?.envSet, options?.envClear, options?.sharedHostSafe);\n const sourceRoots = options?.sourceRoots;\n\n try {\n await initializeLinkedTestSandboxes(layout);\n await seedLinkedTestSandboxesFromSource(layout, sourceRoots);\n const counts = await countLinkedTestSandboxItems(layout, sourceRoots);\n\n for (let index = 0; index < tests.length; index += 1) {\n const linkedTest = tests[index];\n const commandContext = resolveLinkedTestCommandContext({\n linkedTest,\n layout,\n counts,\n sourceRoots,\n runLevelPmContextMode,\n options,\n });\n const preflightResult = resolveLinkedTestPreflightResult({\n linkedTest,\n executionContext: commandContext.executionContext,\n runLevelPmContextMode,\n linkedOverridePmContextMode: commandContext.linkedOverridePmContextMode,\n options,\n });\n if (preflightResult) {\n results.push(preflightResult);\n continue;\n }\n results.push(\n await runSingleLinkedTest({\n linkedTest,\n index,\n total: tests.length,\n defaultTimeoutSeconds,\n runtimeDirectives,\n progressMode,\n executionContext: commandContext.executionContext,\n options,\n }),\n );\n }\n } finally {\n await rm(layout.root, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });\n }\n return results;\n}\n\ninterface ResolvedTestItem {\n itemId: string;\n tests: LinkedTest[];\n changed: boolean;\n}\n\ninterface ResolvedTestRunOptions {\n defaultTimeoutSeconds: number | undefined;\n pmContextMode: LinkedTestPmContextMode;\n runSelection: LinkedTestRunSelection | undefined;\n testsToRun: LinkedTest[];\n}\n\nasync function readLinkedTestItem(params: {\n id: string;\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeToFolder: Record<string, string>;\n}): Promise<ResolvedTestItem> {\n const { id, pmRoot, settings, typeToFolder } = params;\n const located = await locateItem(pmRoot, id, settings.id_prefix, settings.item_format, typeToFolder);\n if (!located) {\n throw new PmCliError(`Item ${id} not found`, EXIT_CODE.NOT_FOUND);\n }\n const loaded = await readLocatedItem(located, { schema: settings.schema });\n return { itemId: located.id, tests: loaded.document.metadata.tests ?? [], changed: false };\n}\n\nfunction linkedTestsHaveSameIdentity(left: LinkedTest, right: LinkedTest): boolean {\n return (\n left.command === right.command &&\n left.path === right.path &&\n left.scope === right.scope &&\n left.pm_context_mode === right.pm_context_mode\n );\n}\n\nfunction appendMissingLinkedTests(current: LinkedTest[], additions: LinkedTest[]): LinkedTest[] {\n const next = [...current];\n for (const addition of additions) {\n if (!next.some((entry) => linkedTestsHaveSameIdentity(entry, addition))) {\n next.push(addition);\n }\n }\n return next;\n}\n\nfunction removeLinkedTestsBySelector(current: LinkedTest[], removals: string[]): LinkedTest[] {\n if (removals.length === 0) {\n return current;\n }\n return current.filter((entry) => !removals.includes(entry.path ?? \"\") && !removals.includes(entry.command ?? \"\"));\n}\n\nfunction applyLinkedTestMutations(previous: LinkedTest[], adds: LinkedTest[], removes: string[]): LinkedTest[] {\n return removeLinkedTestsBySelector(appendMissingLinkedTests(previous, adds), removes);\n}\n\nfunction hasTestRuntimeDirectiveFlags(options: TestCommandOptions): boolean {\n return (\n (options.envSet?.length ?? 0) > 0 ||\n (options.envClear?.length ?? 0) > 0 ||\n options.sharedHostSafe === true ||\n options.pmContext !== undefined ||\n options.overrideLinkedPmContext === true ||\n options.failOnContextMismatch === true ||\n options.failOnSkipped === true ||\n options.failOnEmptyTestRun === true ||\n options.requireAssertionsForPm === true ||\n options.checkContext === true ||\n options.autoPmContext === true\n );\n}\n\nfunction assertTestRunFlagUsage(options: TestCommandOptions): void {\n if (hasTestRuntimeDirectiveFlags(options) && options.run !== true) {\n throw new PmCliError(\n \"--env-set, --env-clear, --shared-host-safe, --pm-context, --override-linked-pm-context, --fail-on-context-mismatch, --fail-on-skipped, --fail-on-empty-test-run, --require-assertions-for-pm, --check-context, and --auto-pm-context require --run\",\n EXIT_CODE.USAGE,\n );\n }\n const hasSelectorFlags = options.match !== undefined || options.onlyIndex !== undefined || options.onlyLast === true;\n if (hasSelectorFlags && options.run !== true) {\n throw new PmCliError(\"--match, --only-index, and --only-last require --run\", EXIT_CODE.USAGE);\n }\n}\n\nasync function resolveLinkedTestItem(params: {\n id: string;\n options: TestCommandOptions;\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n typeToFolder: Record<string, string>;\n adds: LinkedTest[];\n removes: string[];\n}): Promise<ResolvedTestItem> {\n const { id, options, pmRoot, settings, typeToFolder, adds, removes } = params;\n if (adds.length === 0 && removes.length === 0) {\n return readLinkedTestItem({ id, pmRoot, settings, typeToFolder });\n }\n const result = await mutateItem({\n pmRoot,\n settings,\n id,\n op: \"tests_add\",\n author: resolveAuthor(options.author, settings.author_default),\n message: options.message,\n force: options.force,\n skipNoop: true,\n mutate(document) {\n const previous = document.metadata.tests ?? [];\n const next = applyLinkedTestMutations(previous, adds, removes);\n document.metadata.tests = next;\n return { changedFields: stableValueEquals(previous, next) ? [] : [\"tests\"] };\n },\n });\n return {\n itemId: result.item.id,\n tests: result.item.tests ?? [],\n changed: result.changedFields.length > 0,\n };\n}\n\nfunction resolveTestRunOptions(options: TestCommandOptions, tests: LinkedTest[]): ResolvedTestRunOptions {\n assertTestRunFlagUsage(options);\n const selectorInput = {\n match: options.match,\n onlyIndex: options.onlyIndex === undefined ? undefined : parseOnlyIndexValue(options.onlyIndex),\n onlyLast: options.onlyLast,\n };\n const runSelection = options.run === true ? resolveLinkedTestRunSelection(tests, selectorInput) : undefined;\n return {\n defaultTimeoutSeconds: options.timeout === undefined ? undefined : parseOptionalNumber(options.timeout, \"timeout\"),\n pmContextMode: parsePmContextMode(options.pmContext),\n runSelection,\n testsToRun: runSelection?.selected ?? tests,\n };\n}\n\nasync function executeSelectedLinkedTests(params: {\n options: TestCommandOptions;\n runOptions: ResolvedTestRunOptions;\n pmRoot: string;\n}): Promise<TestRunResult[]> {\n const { options, runOptions, pmRoot } = params;\n if (options.run !== true) {\n return [];\n }\n return await runLinkedTests(runOptions.testsToRun, runOptions.defaultTimeoutSeconds, {\n progress: options.progress,\n envSet: options.envSet,\n envClear: options.envClear,\n sharedHostSafe: options.sharedHostSafe,\n pmContext: runOptions.pmContextMode,\n overrideLinkedPmContext: options.overrideLinkedPmContext,\n failOnContextMismatch: options.failOnContextMismatch,\n failOnEmptyTestRun: options.failOnEmptyTestRun,\n requireAssertionsForPm: options.requireAssertionsForPm,\n checkContext: options.checkContext,\n autoPmContext: options.autoPmContext,\n sourceRoots: {\n projectPmRoot: pmRoot,\n globalPmRoot: resolveGlobalPmRoot(process.cwd()),\n },\n });\n}\n\nfunction buildTestWarnings(\n options: TestCommandOptions,\n runSelection: LinkedTestRunSelection | undefined,\n runResults: TestRunResult[],\n): string[] {\n const warnings: string[] = [];\n if (runSelection && runSelection.selector !== null) {\n warnings.push(\n `linked_test_selection:${runSelection.selector}=${runSelection.requested};selected=${runSelection.selected_count};skipped=${runSelection.skipped_count};indexes=${runSelection.selected_indexes.join(\",\")}`,\n );\n }\n if (options.run === true && options.checkContext === true) {\n const preflight = summarizeContextPreflight(runResults);\n warnings.push(\n `context_preflight:checked_pm_commands=${preflight.checked_pm_commands};` +\n `tracker_read_commands=${preflight.tracker_read_commands};` +\n `mismatches=${preflight.mismatches};` +\n `auto_remediated=${preflight.auto_remediated}`,\n );\n }\n return warnings;\n}\n\nasync function recordTestRunSummary(params: {\n options: TestCommandOptions;\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n itemId: string;\n runStartedAt: string | undefined;\n runResults: TestRunResult[];\n failOnSkippedTriggered: boolean;\n warnings: string[];\n}): Promise<void> {\n const { options, pmRoot, settings, itemId, runStartedAt, runResults, failOnSkippedTriggered, warnings } = params;\n if (options.run !== true || !runStartedAt || settings.testing.record_results_to_items !== true) {\n return;\n }\n const summary = summarizeRunResultStatuses(runResults);\n const trackedRunId = resolveTrackedRunId(\"test\");\n const attemptRaw = process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim();\n const parsedAttempt = attemptRaw ? Number.parseInt(attemptRaw, 10) : Number.NaN;\n const resumedFrom = process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim();\n try {\n await appendTrackedTestRunSummary({\n pmRoot,\n settings,\n itemId,\n author: resolveAuthor(options.author, settings.author_default),\n message: `Track test run summary (${trackedRunId})`,\n entry: {\n run_id: trackedRunId,\n kind: \"test\",\n status: summary.failed > 0 || failOnSkippedTriggered === true ? \"failed\" : \"passed\",\n started_at: runStartedAt,\n finished_at: nowIso(),\n recorded_at: nowIso(),\n attempt: Number.isFinite(parsedAttempt) && parsedAttempt >= 1 ? parsedAttempt : undefined,\n resumed_from: resumedFrom && resumedFrom.length > 0 ? resumedFrom : undefined,\n passed: summary.passed,\n failed: summary.failed,\n skipped: summary.skipped,\n fail_on_skipped_triggered: failOnSkippedTriggered ? true : undefined,\n },\n });\n } catch (error: unknown) {\n warnings.push(`test_result_tracking_failed:${itemId}:${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\n/**\n * Implements run test for the public runtime surface of this module.\n */\nexport async function runTest(id: string, options: TestCommandOptions, global: GlobalOptions): Promise<TestResult> {\n const stdinResolver = createStdinTokenResolver();\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n const settings = await readSettings(pmRoot);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const resolvedAdds = await stdinResolver.resolveList(options.add, \"--add\");\n const resolvedAddJsons = await stdinResolver.resolveList(options.addJson, \"--add-json\");\n const resolvedRemoves = await stdinResolver.resolveList(options.remove, \"--remove\");\n const adds = [...parseAddEntries(resolvedAdds), ...parseAddJsonEntries(resolvedAddJsons)];\n const removes = parseRemoveEntries(resolvedRemoves);\n const item = await resolveLinkedTestItem({\n id,\n options,\n pmRoot,\n settings,\n typeToFolder: typeRegistry.type_to_folder,\n adds,\n removes,\n });\n const runOptions = resolveTestRunOptions(options, item.tests);\n const runStartedAt = options.run === true ? nowIso() : undefined;\n const runResults = await executeSelectedLinkedTests({ options, runOptions, pmRoot });\n const failureCategories = countFailureCategories(runResults);\n const failOnSkippedTriggered =\n options.run === true && options.failOnSkipped === true && runResults.some((entry) => entry.status === \"skipped\");\n const warnings = buildTestWarnings(options, runOptions.runSelection, runResults);\n await recordTestRunSummary({ options, pmRoot, settings, itemId: item.itemId, runStartedAt, runResults, failOnSkippedTriggered, warnings });\n\n return {\n ok: runResults.every((entry) => entry.status !== \"failed\") && failOnSkippedTriggered !== true,\n id: item.itemId,\n tests: item.tests,\n run_results: runResults,\n failure_categories: failureCategories,\n selection: runOptions.runSelection\n ? {\n selector: runOptions.runSelection.selector,\n requested: runOptions.runSelection.requested,\n selected_indexes: runOptions.runSelection.selected_indexes,\n selected_count: runOptions.runSelection.selected_count,\n skipped_count: runOptions.runSelection.skipped_count,\n }\n : undefined,\n fail_on_skipped_triggered: failOnSkippedTriggered ? true : undefined,\n warnings: warnings.length > 0 ? warnings : undefined,\n changed: item.changed,\n count: item.tests.length,\n };\n}\n/* c8 ignore stop */\n\nexport const _testOnlyTestCommand = {\n buildPmContextMismatchHint,\n commandInvokesPmCli,\n commandInvokesPmTrackerReadCommand,\n copyIntoSandboxIfPresent,\n countLinkedTestItemFiles,\n ensureScope,\n evaluateLinkedTestAssertions,\n extractPmInvocationArgsFromSegment,\n firstDirectTestRunnerSubcommand,\n hasLinkedTestAssertions,\n parseAddJsonEntries,\n parsePmContextMode,\n readJsonPathValue,\n resolveAuthor,\n resolveDirectRunnerSubcommand,\n resolveLinkedTestEffectiveContextMode,\n resolveLinkedTestFailureExitCode,\n resolveLinkedTestRequestedContextMode,\n resolveTrackedRunId,\n runLinkedTestCommand,\n appendLinkedTestOutputChunk,\n seedLinkedTestSandbox,\n seedLinkedTestTrackerData,\n splitJsonPathSegments,\n summarizeRunResultStatuses,\n};\n", "/**\n * @module core/test/item-test-run-tracking\n *\n * Runs and records linked-test orchestration for Item Test Run Tracking.\n */\nimport { mutateItem } from \"../store/item-store.js\";\nimport { compareTimestampStrings } from \"../shared/time.js\";\nimport type { ItemTestRunSummary, PmSettings } from \"../../types/index.js\";\n\nconst DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT = 20;\n\nfunction trackedTestRunHistoryLimit(): number {\n const raw = process.env.PM_TRACKED_TEST_RUN_HISTORY_LIMIT;\n if (!raw || raw.trim().length === 0) {\n return DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT;\n }\n const parsed = Number.parseInt(raw, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return DEFAULT_TRACKED_TEST_RUN_HISTORY_LIMIT;\n }\n return parsed;\n}\n\nfunction normalizeTrackedTestRunSummaries(entries: ItemTestRunSummary[]): ItemTestRunSummary[] {\n return [...entries]\n .filter((entry) =>\n entry.run_id.trim().length > 0 &&\n entry.started_at.trim().length > 0 &&\n entry.finished_at.trim().length > 0 &&\n entry.recorded_at.trim().length > 0\n )\n .sort((left, right) => {\n const byRecorded = compareTimestampStrings(left.recorded_at, right.recorded_at);\n if (byRecorded !== 0) return byRecorded;\n const byRunId = left.run_id.localeCompare(right.run_id);\n if (byRunId !== 0) return byRunId;\n return left.kind.localeCompare(right.kind);\n });\n}\n\n/**\n * Implements append tracked test run summary for the public runtime surface of this module.\n */\nexport async function appendTrackedTestRunSummary(options: {\n pmRoot: string;\n settings: PmSettings;\n itemId: string;\n author: string;\n entry: ItemTestRunSummary;\n message?: string;\n}): Promise<void> {\n const historyLimit = trackedTestRunHistoryLimit();\n await mutateItem({\n pmRoot: options.pmRoot,\n settings: options.settings,\n id: options.itemId,\n op: \"test_run_track\",\n author: options.author,\n message: options.message,\n force: false,\n mutate(document) {\n const current = document.metadata.test_runs ?? [];\n const next = normalizeTrackedTestRunSummaries([...current, options.entry]);\n const bounded = next.length > historyLimit ? next.slice(next.length - historyLimit) : next;\n document.metadata.test_runs = bounded;\n return { changedFields: [\"test_runs\"] };\n },\n });\n}\n", "/**\n * @module core/test/run-selectors\n *\n * Runs and records linked-test orchestration for Run Selectors.\n */\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport type { LinkedTest } from \"../../types.js\";\n\n/**\n * Pure selection logic for `pm test --run` selectors (pm-p86h / GitHub #194).\n *\n * Selectors pick WHICH linked tests execute without mutating item metadata:\n * - `--match <substring>`: case-insensitive substring on command/path.\n * - `--only-index <n>`: 1-based index into the `--list` order.\n * - `--only-last`: most recently added entry (last in `--list` order).\n */\n\nexport type LinkedTestSelectorKind = \"match\" | \"only-index\" | \"only-last\";\n\n/**\n * Documents the linked test run selector payload exchanged by command, SDK, and package integrations.\n */\nexport interface LinkedTestRunSelector {\n match?: string;\n onlyIndex?: number;\n onlyLast?: boolean;\n}\n\n/**\n * Documents the linked test run selection payload exchanged by command, SDK, and package integrations.\n */\nexport interface LinkedTestRunSelection {\n selector: LinkedTestSelectorKind | null;\n requested: string | null;\n selected: LinkedTest[];\n /** 1-based positions of selected entries in the original `--list` order. */\n selected_indexes: number[];\n selected_count: number;\n skipped_count: number;\n}\n\nconst MAX_SELECTOR_ENTRY_LABEL_LENGTH = 100;\n\n/**\n * Implements parse only index value for the public runtime surface of this module.\n */\nexport function parseOnlyIndexValue(raw: string | number, optionName = \"--only-index\"): number {\n const value = typeof raw === \"number\" ? raw : Number(String(raw).trim());\n if (!Number.isInteger(value) || value < 1) {\n throw new PmCliError(\n `${optionName} requires a 1-based integer index into the linked-test list (got \"${raw}\"). Use pm test <id> --list to inspect positions.`,\n EXIT_CODE.USAGE,\n );\n }\n return value;\n}\n\nfunction summarizeSelectorEntry(entry: LinkedTest): string {\n const label = entry.command ?? entry.path ?? \"<no command>\";\n const normalized = label.replaceAll(/\\s+/g, \" \").trim() || \"<no command>\";\n if (normalized.length <= MAX_SELECTOR_ENTRY_LABEL_LENGTH) {\n return normalized;\n }\n return `${normalized.slice(0, MAX_SELECTOR_ENTRY_LABEL_LENGTH - 3)}...`;\n}\n\n/**\n * Implements describe linked test entries for the public runtime surface of this module.\n */\nexport function describeLinkedTestEntries(tests: LinkedTest[]): string {\n return tests.map((entry, index) => `${index + 1}. ${summarizeSelectorEntry(entry)}`).join(\"; \");\n}\n\nfunction activeSelectorKinds(selector: LinkedTestRunSelector): LinkedTestSelectorKind[] {\n const kinds: LinkedTestSelectorKind[] = [];\n if (selector.match !== undefined) {\n kinds.push(\"match\");\n }\n if (selector.onlyIndex !== undefined) {\n kinds.push(\"only-index\");\n }\n if (selector.onlyLast === true) {\n kinds.push(\"only-last\");\n }\n return kinds;\n}\n\nfunction entryMatchesSubstring(entry: LinkedTest, needle: string): boolean {\n const command = entry.command?.toLowerCase() ?? \"\";\n const entryPath = entry.path?.toLowerCase() ?? \"\";\n return command.includes(needle) || entryPath.includes(needle);\n}\n\n/**\n * Implements resolve linked test run selection for the public runtime surface of this module.\n */\nexport function resolveLinkedTestRunSelection(tests: LinkedTest[], selector: LinkedTestRunSelector): LinkedTestRunSelection {\n const kinds = activeSelectorKinds(selector);\n if (kinds.length === 0) {\n return {\n selector: null,\n requested: null,\n selected: tests,\n selected_indexes: tests.map((_, index) => index + 1),\n selected_count: tests.length,\n skipped_count: 0,\n };\n }\n if (kinds.length > 1) {\n throw new PmCliError(\n `Combine at most one linked-test selector per run: ${kinds.map((kind) => `--${kind}`).join(\" and \")} were provided. Pick one of --match, --only-index, --only-last.`,\n EXIT_CODE.USAGE,\n );\n }\n const kind = kinds[0];\n if (tests.length === 0) {\n throw new PmCliError(\n `--${kind} matched no linked tests because this item has none. Add one first with --add, --command, or --add-json.`,\n EXIT_CODE.USAGE,\n );\n }\n if (kind === \"match\") {\n // kind is \"match\" only when selector.match is defined (see activeSelectorKinds).\n const needle = (selector.match as string).trim().toLowerCase();\n if (needle.length === 0) {\n throw new PmCliError(\"--match requires a non-empty substring to match against linked-test command/path values\", EXIT_CODE.USAGE);\n }\n const selectedIndexes: number[] = [];\n const selected: LinkedTest[] = [];\n for (let index = 0; index < tests.length; index += 1) {\n if (entryMatchesSubstring(tests[index], needle)) {\n selected.push(tests[index]);\n selectedIndexes.push(index + 1);\n }\n }\n if (selected.length === 0) {\n throw new PmCliError(\n `--match \"${selector.match}\" matched none of the ${tests.length} linked test(s). Available entries: ${describeLinkedTestEntries(tests)}`,\n EXIT_CODE.USAGE,\n );\n }\n return {\n selector: \"match\",\n requested: selector.match as string,\n selected,\n selected_indexes: selectedIndexes,\n selected_count: selected.length,\n skipped_count: tests.length - selected.length,\n };\n }\n if (kind === \"only-index\") {\n const index = parseOnlyIndexValue(selector.onlyIndex as number);\n if (index > tests.length) {\n throw new PmCliError(\n `--only-index ${index} is out of range: this item has ${tests.length} linked test(s). Available entries: ${describeLinkedTestEntries(tests)}`,\n EXIT_CODE.USAGE,\n );\n }\n return {\n selector: \"only-index\",\n requested: String(index),\n selected: [tests[index - 1]],\n selected_indexes: [index],\n selected_count: 1,\n skipped_count: tests.length - 1,\n };\n }\n return {\n selector: \"only-last\",\n requested: \"last\",\n selected: [tests[tests.length - 1]],\n selected_indexes: [tests.length],\n selected_count: 1,\n skipped_count: tests.length - 1,\n };\n}\n", "/**\n * @module cli/commands/test/linked-command-detection\n *\n * Parses linked-test command invocations for sandbox and context-safety checks.\n */\n// Pure, leaf-level helpers for detecting how linked-test shell commands invoke\n// the pm CLI (directly, via npx/pnpm/npm exec, or a launcher subcommand) and for\n// pulling structured context (subcommand, referenced item ids, runner) out of a\n// normalized command string. Extracted from test.ts to keep that command file\n// under the per-file LOC budget; consumers re-export these from test.ts so no\n// caller outside test.ts changes.\n\nexport const PM_GLOBAL_FLAGS_WITH_VALUE = new Set([\"--path\"]);\nexport const NPX_FLAGS_WITH_VALUE = new Set([\"-p\", \"--package\", \"-c\", \"--call\"]);\nexport const PNPM_GLOBAL_FLAGS_WITH_VALUE = new Set([\n \"-c\",\n \"-C\",\n \"--config\",\n \"--dir\",\n \"--filter\",\n \"--workspace-dir\",\n]);\nexport const NPM_GLOBAL_FLAGS_WITH_VALUE = new Set([\"-C\", \"--prefix\", \"--userconfig\", \"--cache\"]);\nexport const YARN_GLOBAL_FLAGS_WITH_VALUE = new Set([\"--cwd\"]);\nexport const BUN_GLOBAL_FLAGS_WITH_VALUE = new Set([\"--cwd\"]);\nexport const NPM_EXEC_SUBCOMMANDS = new Set([\"exec\", \"x\"]);\nexport const SCRIPT_RUN_SUBCOMMANDS = new Set([\"run\", \"run-script\"]);\nexport const SCRIPT_RUN_FLAGS_WITH_VALUE = new Set([\"-C\", \"--dir\", \"--cwd\", \"-w\", \"--workspace\", \"--filter\"]);\n\n/**\n * Implements split normalized command segments for the public runtime surface of this module.\n */\nexport function splitNormalizedCommandSegments(normalizedCommand: string): string[] {\n return normalizedCommand\n .split(/&&|\\|\\||\\||;/)\n .map((segment) => segment.trim())\n .filter((segment) => segment.length > 0);\n}\n\n/**\n * Implements strip leading env assignments for the public runtime surface of this module.\n */\nexport function stripLeadingEnvAssignments(tokens: string[]): string[] {\n let start = 0;\n if (tokens[start] === \"env\") {\n start += 1;\n }\n while (start < tokens.length) {\n const token = tokens[start];\n if (/^(?:[a-z_][a-z0-9_]*|\\$env:[a-z_][a-z0-9_]*)=.*/.test(token)) {\n start += 1;\n continue;\n }\n break;\n }\n return tokens.slice(start);\n}\n\n/**\n * Implements first pm subcommand for the public runtime surface of this module.\n */\nexport function firstPmSubcommand(args: string[]): string | undefined {\n let index = 0;\n while (index < args.length) {\n const token = args[index];\n if (token === \"--\") {\n index += 1;\n continue;\n }\n if (token.startsWith(\"-\")) {\n if (PM_GLOBAL_FLAGS_WITH_VALUE.has(token)) {\n index += 2;\n continue;\n }\n index += 1;\n continue;\n }\n return token;\n }\n return undefined;\n}\n\n/**\n * Implements check whether pm executable token for the public runtime surface of this module.\n */\nexport function isPmExecutableToken(token: string): boolean {\n return (\n token === \"pm\" ||\n token === \"pm.cmd\" ||\n token === \"pm.exe\" ||\n token.endsWith(\"/pm\") ||\n token.endsWith(\"/pm.cmd\") ||\n token.endsWith(\"/pm.exe\")\n );\n}\n\n/**\n * Implements normalize package specifier for the public runtime surface of this module.\n */\nexport function normalizePackageSpecifier(token: string): string {\n const trimmed = token.trim();\n if (!trimmed.startsWith(\"@\")) {\n const versionSeparator = trimmed.indexOf(\"@\");\n return versionSeparator === -1 ? trimmed : trimmed.slice(0, versionSeparator);\n }\n const scopeSeparator = trimmed.indexOf(\"/\");\n if (scopeSeparator === -1) {\n return trimmed;\n }\n const versionSeparator = trimmed.indexOf(\"@\", scopeSeparator + 1);\n return versionSeparator === -1 ? trimmed : trimmed.slice(0, versionSeparator);\n}\n\n/**\n * Implements check whether pm cli package token for the public runtime surface of this module.\n */\nexport function isPmCliPackageToken(token: string): boolean {\n const normalizedSpecifier = normalizePackageSpecifier(token);\n return (\n normalizedSpecifier === \"pm-cli\" ||\n normalizedSpecifier.endsWith(\"/pm-cli\") ||\n token === \"pm-cli\" ||\n token.endsWith(\"/pm-cli\")\n );\n}\n\n/**\n * Implements check whether pm cli script token for the public runtime surface of this module.\n */\nexport function isPmCliScriptToken(token: string): boolean {\n return token === \"dist/cli.js\" || token === \"./dist/cli.js\" || token.endsWith(\"/dist/cli.js\");\n}\n\n/**\n * Implements parse npx command for the public runtime surface of this module.\n */\nexport function parseNpxCommand(tokens: string[]): { command: string; args: string[] } | null {\n let index = 0;\n while (index < tokens.length) {\n const token = tokens[index];\n if (token === \"--\") {\n index += 1;\n break;\n }\n if (!token.startsWith(\"-\")) {\n break;\n }\n if (token.includes(\"=\")) {\n index += 1;\n continue;\n }\n if (NPX_FLAGS_WITH_VALUE.has(token)) {\n index += 2;\n continue;\n }\n index += 1;\n }\n const command = tokens[index];\n if (!command) {\n return null;\n }\n return {\n command,\n args: tokens.slice(index + 1),\n };\n}\n\n/**\n * Implements parse launcher subcommand for the public runtime surface of this module.\n */\nexport function parseLauncherSubcommand(\n tokens: string[],\n flagsWithValue: Set<string>,\n): { subcommand: string; args: string[] } | null {\n let index = 0;\n while (index < tokens.length) {\n const token = tokens[index];\n if (token === \"--\") {\n index += 1;\n continue;\n }\n if (token.startsWith(\"-\")) {\n if (token.includes(\"=\")) {\n index += 1;\n continue;\n }\n if (flagsWithValue.has(token)) {\n index += 2;\n continue;\n }\n index += 1;\n continue;\n }\n return {\n subcommand: token,\n args: tokens.slice(index + 1),\n };\n }\n return null;\n}\n\n/**\n * Implements parse pnpm dlx command for the public runtime surface of this module.\n */\nexport function parsePnpmDlxCommand(tokens: string[]): { command: string; args: string[] } | null {\n const parsed = parseLauncherSubcommand(tokens, PNPM_GLOBAL_FLAGS_WITH_VALUE);\n if (parsed?.subcommand !== \"dlx\") {\n return null;\n }\n return parseNpxCommand(parsed.args);\n}\n\n/**\n * Implements parse npm exec command for the public runtime surface of this module.\n */\nexport function parseNpmExecCommand(tokens: string[]): { command: string; args: string[] } | null {\n const parsed = parseLauncherSubcommand(tokens, NPM_GLOBAL_FLAGS_WITH_VALUE);\n if (!parsed || !NPM_EXEC_SUBCOMMANDS.has(parsed.subcommand)) {\n return null;\n }\n return parseNpxCommand(parsed.args);\n}\n\n/**\n * Implements resolve pm subcommand context for the public runtime surface of this module.\n */\nexport function resolvePmSubcommandContext(args: string[]): { subcommand: string; remaining: string[] } | null {\n let index = 0;\n while (index < args.length) {\n const token = args[index];\n if (token === \"--\") {\n index += 1;\n continue;\n }\n if (token.startsWith(\"-\")) {\n if (PM_GLOBAL_FLAGS_WITH_VALUE.has(token)) {\n index += 2;\n continue;\n }\n index += 1;\n continue;\n }\n return {\n subcommand: token,\n remaining: args.slice(index + 1),\n };\n }\n return null;\n}\n\n/**\n * Implements first positional token for the public runtime surface of this module.\n */\nexport function firstPositionalToken(tokens: string[]): string | undefined {\n for (const token of tokens) {\n if (!token.startsWith(\"-\")) {\n return token;\n }\n }\n return undefined;\n}\n", "/**\n * @module cli/commands/test-all\n *\n * Implements the pm test all command surface and its agent-facing runtime behavior.\n */\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { parseOptionalNumber } from \"../../core/item/parse.js\";\nimport { normalizeStatusInput } from \"../../core/item/status.js\";\nimport { resolveRuntimeStatusRegistry, type RuntimeStatusRegistry } from \"../../core/schema/runtime-schema.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport { listAllFrontMatterLight } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolveGlobalPmRoot, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { appendTrackedTestRunSummary } from \"../../core/test/item-test-run-tracking.js\";\nimport { resolveAuthor } from \"../../core/shared/author.js\";\nimport type { ItemStatus, LinkedTest } from \"../../types/index.js\";\nimport {\n countFailureCategories,\n runLinkedTests,\n runTest,\n summarizeContextPreflight,\n type LinkedTestFailureCategory,\n type TestRunResult,\n} from \"./test.js\";\n\n/**\n * Documents the test all command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestAllCommandOptions {\n status?: string;\n limit?: string;\n offset?: string;\n timeout?: string;\n progress?: boolean;\n envSet?: string[];\n envClear?: string[];\n sharedHostSafe?: boolean;\n pmContext?: string;\n overrideLinkedPmContext?: boolean;\n failOnContextMismatch?: boolean;\n failOnSkipped?: boolean;\n failOnEmptyTestRun?: boolean;\n requireAssertionsForPm?: boolean;\n checkContext?: boolean;\n autoPmContext?: boolean;\n}\n\n/**\n * Documents the test all item result payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestAllItemResult {\n ok: boolean;\n id: string;\n status: ItemStatus;\n test_count: number;\n passed: number;\n failed: number;\n skipped: number;\n run_results: TestRunResult[];\n failure_categories: Record<LinkedTestFailureCategory, number>;\n}\n\n/**\n * Documents the test all result payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestAllResult {\n ok: boolean;\n totals: {\n items: number;\n linked_tests: number;\n passed: number;\n failed: number;\n skipped: number;\n failure_categories: Record<LinkedTestFailureCategory, number>;\n };\n failed: number;\n passed: number;\n skipped: number;\n fail_on_skipped_triggered?: boolean;\n fail_on_empty_test_run_triggered?: boolean;\n warnings?: string[];\n results: TestAllItemResult[];\n}\n\ntype TestAllSelectedItem = Awaited<ReturnType<typeof listAllFrontMatterLight>>[number];\n\ninterface TestAllItemTests {\n item: TestAllSelectedItem;\n tests: LinkedTest[];\n}\n\ninterface TestAllItemRunContext {\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n options: TestAllCommandOptions;\n defaultTimeoutSeconds: number | undefined;\n sourceRoots: { projectPmRoot: string; globalPmRoot: string };\n seenTestKeys: Set<string>;\n effectiveTimeoutByKey: Map<string, number | undefined>;\n trackingEnabled: boolean;\n trackingAuthor: string;\n trackingRunId: string;\n trackingAttempt: number | undefined;\n trackingResumedFrom: string | undefined;\n runStartedAt: string;\n}\n\ninterface TestAllItemExecution {\n result: TestAllItemResult;\n passed: number;\n failed: number;\n skipped: number;\n trackingWarnings: string[];\n failureCategories: Record<LinkedTestFailureCategory, number>;\n}\n\ninterface TestAllSelection {\n filteredItems: TestAllSelectedItem[];\n statusFilter: ItemStatus | undefined;\n limitFilter: number | undefined;\n offsetFilter: number;\n}\n\ninterface TestAllAccumulation {\n results: TestAllItemResult[];\n passed: number;\n failed: number;\n skipped: number;\n failureCategories: Record<LinkedTestFailureCategory, number>;\n trackingWarnings: string[];\n}\n\nfunction parseStatus(raw: string | undefined, statusRegistry: RuntimeStatusRegistry): ItemStatus | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const normalized = normalizeStatusInput(raw, statusRegistry);\n if (!normalized) {\n const allowedStatuses = statusRegistry.definitions.map((definition) => definition.id);\n throw new PmCliError(`Invalid --status value \"${raw}\". Allowed: ${allowedStatuses.join(\", \")}`, EXIT_CODE.USAGE);\n }\n return normalized;\n}\n\nfunction parseTimeout(raw: string | undefined): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n return parseOptionalNumber(raw, \"timeout\");\n}\n\nfunction parseNonNegativeInteger(raw: string | undefined, flag: string): number | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new PmCliError(`${flag} must be a non-negative integer`, EXIT_CODE.USAGE);\n }\n return parsed;\n}\n\nfunction formatTrackingError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction resolveTrackedRunId(): string {\n const fromEnv = process.env.PM_BACKGROUND_TEST_RUN_ID?.trim();\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return `test-all-local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n}\n\nfunction normalizeCommand(command: string): string {\n return command.trim().replaceAll(/\\s+/g, \" \");\n}\n\nfunction normalizeEnvSetSignature(value: LinkedTest[\"env_set\"]): string {\n if (!value || Object.keys(value).length === 0) {\n return \"{}\";\n }\n return JSON.stringify(\n Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right))),\n );\n}\n\nfunction normalizeEnvClearSignature(value: LinkedTest[\"env_clear\"]): string {\n if (!value || value.length === 0) {\n return \"[]\";\n }\n return JSON.stringify([...value].sort((left, right) => left.localeCompare(right)));\n}\n\nfunction normalizePmContextModeSignature(value: LinkedTest[\"pm_context_mode\"]): string {\n const normalized = value?.trim().toLowerCase();\n return normalized && normalized.length > 0 ? normalized : \"none\";\n}\n\nfunction normalizeAssertionSignature(test: LinkedTest): string {\n const normalized = {\n assert_stdout_contains: [...new Set(test.assert_stdout_contains ?? [])].sort((left, right) => left.localeCompare(right)),\n assert_stdout_regex: [...new Set(test.assert_stdout_regex ?? [])].sort((left, right) => left.localeCompare(right)),\n assert_stderr_contains: [...new Set(test.assert_stderr_contains ?? [])].sort((left, right) => left.localeCompare(right)),\n assert_stderr_regex: [...new Set(test.assert_stderr_regex ?? [])].sort((left, right) => left.localeCompare(right)),\n assert_stdout_min_lines: typeof test.assert_stdout_min_lines === \"number\" ? test.assert_stdout_min_lines : undefined,\n assert_json_field_equals: Object.fromEntries(\n Object.entries(test.assert_json_field_equals ?? {}).sort(([left], [right]) => left.localeCompare(right)),\n ),\n assert_json_field_gte: Object.fromEntries(\n Object.entries(test.assert_json_field_gte ?? {}).sort(([left], [right]) => left.localeCompare(right)),\n ),\n };\n return JSON.stringify(normalized);\n}\n\nfunction buildLinkedTestKey(test: LinkedTest): string {\n const command = test.command?.trim();\n if (command && command.length > 0) {\n const envSet = normalizeEnvSetSignature(test.env_set);\n const envClear = normalizeEnvClearSignature(test.env_clear);\n const pmContextMode = normalizePmContextModeSignature(test.pm_context_mode);\n const sharedHostSafe = test.shared_host_safe === true ? \"true\" : \"false\";\n const assertions = normalizeAssertionSignature(test);\n return `command:${test.scope}:${normalizeCommand(command)}:${envSet}:${envClear}:${pmContextMode}:${sharedHostSafe}:${assertions}`;\n }\n const linkedPath = test.path?.trim() ?? \"\";\n return `path:${test.scope}:${linkedPath}`;\n}\n\nfunction maxTimeoutSeconds(current: number | undefined, candidate: number | undefined): number | undefined {\n if (candidate === undefined) {\n /* c8 ignore next - exercised implicitly by duplicate timeout normalization */\n return current;\n }\n if (current === undefined || candidate > current) {\n return candidate;\n }\n return current;\n}\n\nfunction countStatuses(runResults: TestRunResult[]): { passed: number; failed: number; skipped: number } {\n let passed = 0;\n let failed = 0;\n let skipped = 0;\n for (const result of runResults) {\n if (result.status === \"passed\") {\n passed += 1;\n continue;\n }\n if (result.status === \"failed\") {\n failed += 1;\n continue;\n }\n skipped += 1;\n }\n return { passed, failed, skipped };\n}\n\nfunction mergeFailureCategoryCounts(\n target: Record<LinkedTestFailureCategory, number>,\n source: Record<LinkedTestFailureCategory, number>,\n): void {\n for (const [key, value] of Object.entries(source)) {\n target[key as LinkedTestFailureCategory] += value;\n }\n}\n\nfunction emitTestAllProgress(options: TestAllCommandOptions, message: string): void {\n if (options.progress !== true) {\n return;\n }\n try {\n process.stderr.write(`[pm test-all] ${message}\\n`);\n } catch {\n // Ignore transient stderr write failures.\n }\n}\n\nasync function collectTestAllItemTests(\n filteredItems: TestAllSelectedItem[],\n global: GlobalOptions,\n pmRoot: string,\n): Promise<{ itemTests: TestAllItemTests[]; linkedTests: number }> {\n const itemTests: TestAllItemTests[] = [];\n let linkedTests = 0;\n for (const item of filteredItems) {\n const readResult = await runTest(\n item.id,\n { run: false },\n {\n ...global,\n path: pmRoot,\n },\n );\n linkedTests += readResult.tests.length;\n itemTests.push({ item, tests: readResult.tests });\n }\n return { itemTests, linkedTests };\n}\n\nasync function selectTestAllItems(params: {\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n options: TestAllCommandOptions;\n}): Promise<TestAllSelection> {\n const statusRegistry = resolveRuntimeStatusRegistry(params.settings.schema);\n const typeRegistry = resolveItemTypeRegistry(params.settings, getActiveExtensionRegistrations());\n const statusFilter = parseStatus(params.options.status, statusRegistry);\n const limitFilter = parseNonNegativeInteger(params.options.limit, \"--limit\");\n const offsetFilter = parseNonNegativeInteger(params.options.offset, \"--offset\") ?? 0;\n const allItems = await listAllFrontMatterLight(\n params.pmRoot,\n params.settings.item_format,\n typeRegistry.type_to_folder,\n undefined,\n params.settings.schema,\n );\n const statusFilteredItems = allItems\n .filter((item) => (statusFilter ? item.status === statusFilter : true))\n .sort((a, b) => a.id.localeCompare(b.id));\n const filteredItems =\n limitFilter === undefined\n ? statusFilteredItems.slice(offsetFilter)\n : statusFilteredItems.slice(offsetFilter, offsetFilter + limitFilter);\n return { filteredItems, statusFilter, limitFilter, offsetFilter };\n}\n\nfunction buildEffectiveTimeoutByKey(itemTests: TestAllItemTests[]): Map<string, number | undefined> {\n const effectiveTimeoutByKey = new Map<string, number | undefined>();\n for (const { tests } of itemTests) {\n for (const test of tests) {\n const key = buildLinkedTestKey(test);\n if (!effectiveTimeoutByKey.has(key)) {\n effectiveTimeoutByKey.set(key, test.timeout_seconds);\n continue;\n }\n effectiveTimeoutByKey.set(key, maxTimeoutSeconds(effectiveTimeoutByKey.get(key), test.timeout_seconds));\n }\n }\n return effectiveTimeoutByKey;\n}\n\nasync function runTestAllItem(\n entry: TestAllItemTests,\n context: TestAllItemRunContext,\n): Promise<TestAllItemExecution> {\n const testsToRun: LinkedTest[] = [];\n const keyedTests = entry.tests.map((test) => {\n const key = buildLinkedTestKey(test);\n const duplicate = context.seenTestKeys.has(key);\n if (!duplicate) {\n context.seenTestKeys.add(key);\n const effectiveTimeoutSeconds = context.effectiveTimeoutByKey.get(key);\n testsToRun.push(effectiveTimeoutSeconds === undefined ? test : { ...test, timeout_seconds: effectiveTimeoutSeconds });\n }\n return { test, key, duplicate };\n });\n\n const executedResults =\n testsToRun.length > 0\n ? await runLinkedTests(testsToRun, context.defaultTimeoutSeconds, {\n progress: context.options.progress,\n sourceRoots: context.sourceRoots,\n envSet: context.options.envSet,\n envClear: context.options.envClear,\n sharedHostSafe: context.options.sharedHostSafe,\n pmContext: context.options.pmContext,\n overrideLinkedPmContext: context.options.overrideLinkedPmContext,\n failOnContextMismatch: context.options.failOnContextMismatch,\n failOnEmptyTestRun: context.options.failOnEmptyTestRun,\n requireAssertionsForPm: context.options.requireAssertionsForPm,\n checkContext: context.options.checkContext,\n autoPmContext: context.options.autoPmContext,\n })\n : [];\n let executedIndex = 0;\n const runResults = keyedTests.map(({ test, key, duplicate }) => {\n if (!duplicate) {\n const executed = executedResults[executedIndex];\n executedIndex += 1;\n return executed;\n }\n return {\n command: test.command,\n path: test.path,\n status: \"skipped\" as const,\n error: `Duplicate linked test skipped (key=${key}).`,\n };\n });\n const summary = countStatuses(runResults);\n const failureCategories = countFailureCategories(runResults);\n const trackingWarnings = await appendTestAllItemTracking(entry, summary, context);\n return {\n passed: summary.passed,\n failed: summary.failed,\n skipped: summary.skipped,\n trackingWarnings,\n failureCategories,\n result: {\n ok: summary.failed === 0 && !(context.options.failOnSkipped === true && summary.skipped > 0),\n id: entry.item.id,\n status: entry.item.status,\n test_count: entry.tests.length,\n passed: summary.passed,\n failed: summary.failed,\n skipped: summary.skipped,\n run_results: runResults,\n failure_categories: failureCategories,\n },\n };\n}\n\nasync function appendTestAllItemTracking(\n entry: TestAllItemTests,\n summary: { passed: number; failed: number; skipped: number },\n context: TestAllItemRunContext,\n): Promise<string[]> {\n if (!context.trackingEnabled) {\n return [];\n }\n try {\n await appendTrackedTestRunSummary({\n pmRoot: context.pmRoot,\n settings: context.settings,\n itemId: entry.item.id,\n author: context.trackingAuthor,\n message: `Track test-all run summary (${context.trackingRunId})`,\n entry: {\n run_id: context.trackingRunId,\n kind: \"test-all\",\n status: summary.failed > 0 || (context.options.failOnSkipped === true && summary.skipped > 0) ? \"failed\" : \"passed\",\n started_at: context.runStartedAt,\n finished_at: nowIso(),\n recorded_at: nowIso(),\n attempt: context.trackingAttempt,\n resumed_from: context.trackingResumedFrom,\n passed: summary.passed,\n failed: summary.failed,\n skipped: summary.skipped,\n items: 1,\n linked_tests: entry.tests.length,\n fail_on_skipped_triggered: context.options.failOnSkipped === true && summary.skipped > 0 ? true : undefined,\n },\n });\n } catch (error: unknown) {\n return [`test_result_tracking_failed:${entry.item.id}:${formatTrackingError(error)}`];\n }\n return [];\n}\n\nfunction buildTestAllItemRunContext(params: {\n pmRoot: string;\n settings: Awaited<ReturnType<typeof readSettings>>;\n options: TestAllCommandOptions;\n itemTests: TestAllItemTests[];\n defaultTimeoutSeconds: number | undefined;\n runStartedAt: string;\n}): TestAllItemRunContext {\n const trackingAttemptRaw = process.env.PM_BACKGROUND_TEST_RUN_ATTEMPT?.trim();\n const trackingParsedAttempt = trackingAttemptRaw ? Number.parseInt(trackingAttemptRaw, 10) : Number.NaN;\n const trackingResumedFrom = process.env.PM_BACKGROUND_TEST_RUN_RESUMED_FROM?.trim();\n return {\n pmRoot: params.pmRoot,\n settings: params.settings,\n options: params.options,\n defaultTimeoutSeconds: params.defaultTimeoutSeconds,\n sourceRoots: {\n projectPmRoot: params.pmRoot,\n globalPmRoot: resolveGlobalPmRoot(process.cwd()),\n },\n seenTestKeys: new Set<string>(),\n effectiveTimeoutByKey: buildEffectiveTimeoutByKey(params.itemTests),\n trackingEnabled: params.settings.testing.record_results_to_items === true,\n trackingAuthor: resolveAuthor(undefined, params.settings.author_default),\n trackingRunId: resolveTrackedRunId(),\n trackingAttempt: Number.isFinite(trackingParsedAttempt) && trackingParsedAttempt >= 1 ? trackingParsedAttempt : undefined,\n trackingResumedFrom: trackingResumedFrom && trackingResumedFrom.length > 0 ? trackingResumedFrom : undefined,\n runStartedAt: params.runStartedAt,\n };\n}\n\nfunction initializeTestAllAccumulation(\n options: TestAllCommandOptions,\n linkedTests: number,\n filteredItems: TestAllSelectedItem[],\n): { accumulation: TestAllAccumulation; failOnEmptyTestRunTriggered: boolean } {\n const accumulation: TestAllAccumulation = {\n results: [],\n passed: 0,\n failed: 0,\n skipped: 0,\n failureCategories: countFailureCategories([]),\n trackingWarnings: [],\n };\n const failOnEmptyTestRunTriggered = options.failOnEmptyTestRun === true && linkedTests === 0;\n if (failOnEmptyTestRunTriggered) {\n accumulation.failed += 1;\n accumulation.failureCategories.empty_run += 1;\n accumulation.trackingWarnings.push(\n `empty_linked_test_selection:items=${filteredItems.length};linked_tests=0;fail_on_empty_test_run=true`,\n );\n }\n return { accumulation, failOnEmptyTestRunTriggered };\n}\n\nasync function runTestAllItems(\n itemTests: TestAllItemTests[],\n context: TestAllItemRunContext,\n accumulation: TestAllAccumulation,\n): Promise<void> {\n for (const [itemIndex, entry] of itemTests.entries()) {\n emitTestAllProgress(context.options, `item ${itemIndex + 1}/${itemTests.length} start id=${entry.item.id} linked_tests=${entry.tests.length}`);\n const execution = await runTestAllItem(entry, context);\n mergeFailureCategoryCounts(accumulation.failureCategories, execution.failureCategories);\n accumulation.passed += execution.passed;\n accumulation.failed += execution.failed;\n accumulation.skipped += execution.skipped;\n accumulation.trackingWarnings.push(...execution.trackingWarnings);\n accumulation.results.push(execution.result);\n emitTestAllProgress(\n context.options,\n `item ${itemIndex + 1}/${itemTests.length} end id=${entry.item.id}` +\n ` status=${execution.failed === 0 ? \"passed\" : \"failed\"}` +\n ` passed=${execution.passed} failed=${execution.failed} skipped=${execution.skipped}`,\n );\n }\n}\n\nfunction appendContextPreflightWarning(options: TestAllCommandOptions, accumulation: TestAllAccumulation): void {\n if (options.checkContext !== true) {\n return;\n }\n const allRunResults = accumulation.results.flatMap((entry) => entry.run_results);\n const preflight = summarizeContextPreflight(allRunResults);\n accumulation.trackingWarnings.push(\n `context_preflight:checked_pm_commands=${preflight.checked_pm_commands};` +\n `tracker_read_commands=${preflight.tracker_read_commands};` +\n `mismatches=${preflight.mismatches};` +\n `auto_remediated=${preflight.auto_remediated}`,\n );\n}\n\nfunction buildTestAllResult(params: {\n ok: boolean;\n filteredItems: TestAllSelectedItem[];\n linkedTests: number;\n accumulation: TestAllAccumulation;\n failOnSkippedTriggered: boolean;\n failOnEmptyTestRunTriggered: boolean;\n}): TestAllResult {\n return {\n ok: params.ok,\n totals: {\n items: params.filteredItems.length,\n linked_tests: params.linkedTests,\n passed: params.accumulation.passed,\n failed: params.accumulation.failed,\n skipped: params.accumulation.skipped,\n failure_categories: params.accumulation.failureCategories,\n },\n failed: params.accumulation.failed,\n passed: params.accumulation.passed,\n skipped: params.accumulation.skipped,\n fail_on_skipped_triggered: params.failOnSkippedTriggered ? true : undefined,\n fail_on_empty_test_run_triggered: params.failOnEmptyTestRunTriggered ? true : undefined,\n warnings: params.accumulation.trackingWarnings.length > 0 ? params.accumulation.trackingWarnings : undefined,\n results: params.accumulation.results,\n };\n}\n\n/**\n * Implements run test all for the public runtime surface of this module.\n */\nexport async function runTestAll(options: TestAllCommandOptions, global: GlobalOptions): Promise<TestAllResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const { filteredItems, statusFilter, limitFilter, offsetFilter } = await selectTestAllItems({ pmRoot, settings, options });\n const defaultTimeoutSeconds = parseTimeout(options.timeout);\n const runStartedAt = nowIso();\n const { itemTests, linkedTests } = await collectTestAllItemTests(filteredItems, global, pmRoot);\n emitTestAllProgress(\n options,\n `selection items=${filteredItems.length} linked_tests=${linkedTests}` +\n `${statusFilter ? ` status=${statusFilter}` : \"\"}` +\n `${limitFilter === undefined ? \"\" : ` limit=${limitFilter}`}` +\n `${offsetFilter > 0 ? ` offset=${offsetFilter}` : \"\"}`,\n );\n\n const { accumulation, failOnEmptyTestRunTriggered } = initializeTestAllAccumulation(options, linkedTests, filteredItems);\n const itemRunContext = buildTestAllItemRunContext({\n pmRoot,\n settings,\n options,\n itemTests,\n defaultTimeoutSeconds,\n runStartedAt,\n });\n await runTestAllItems(itemTests, itemRunContext, accumulation);\n\n const failOnSkippedTriggered = options.failOnSkipped === true && accumulation.skipped > 0;\n appendContextPreflightWarning(options, accumulation);\n\n const ok = accumulation.failed === 0 && failOnSkippedTriggered !== true && failOnEmptyTestRunTriggered !== true;\n emitTestAllProgress(\n options,\n `end status=${ok ? \"passed\" : \"failed\"} items=${filteredItems.length} linked_tests=${linkedTests}` +\n ` passed=${accumulation.passed} failed=${accumulation.failed} skipped=${accumulation.skipped}`,\n );\n\n return buildTestAllResult({\n ok,\n filteredItems,\n linkedTests,\n accumulation,\n failOnSkippedTriggered,\n failOnEmptyTestRunTriggered,\n });\n}\n\nexport const _testOnlyTestAll = {\n formatTrackingError,\n};\n", "/**\n * @module cli/commands/test-runs\n *\n * Implements the pm test runs command surface and its agent-facing runtime behavior.\n */\nimport os from \"node:os\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport {\n type BackgroundLogStream,\n type BackgroundTestRunKind,\n type BackgroundTestRunStatus,\n getBackgroundTestRunStatus,\n listBackgroundTestRuns,\n readBackgroundTestRunLogs,\n resumeBackgroundTestRun,\n runBackgroundTestRunWorker,\n spawnBackgroundTestRunWorker,\n startBackgroundTestRun,\n stopBackgroundTestRun,\n} from \"../../core/test/background-runs.js\";\nimport { getSettingsPath, resolveGlobalPmRoot, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport { parseLimit } from \"../shared-parsers.js\";\n\nconst BACKGROUND_STATUS_VALUES: readonly BackgroundTestRunStatus[] = [\"queued\", \"running\", \"passed\", \"failed\", \"stopped\", \"canceled\"];\nconst BACKGROUND_STREAM_VALUES: readonly BackgroundLogStream[] = [\"stdout\", \"stderr\", \"both\"];\n\nfunction normalizeStatus(value: string | undefined): BackgroundTestRunStatus | undefined {\n if (value === undefined) {\n return undefined;\n }\n const normalized = value.trim().toLowerCase();\n if ((BACKGROUND_STATUS_VALUES as readonly string[]).includes(normalized)) {\n return normalized as BackgroundTestRunStatus;\n }\n throw new PmCliError(`Invalid --status value \"${value}\"`, EXIT_CODE.USAGE);\n}\n\nfunction normalizeStream(value: string | undefined): BackgroundLogStream {\n if (value === undefined || value.trim().length === 0) {\n return \"stderr\";\n }\n const normalized = value.trim().toLowerCase();\n if ((BACKGROUND_STREAM_VALUES as readonly string[]).includes(normalized)) {\n return normalized as BackgroundLogStream;\n }\n throw new PmCliError(`Invalid --stream value \"${value}\"`, EXIT_CODE.USAGE);\n}\n\nfunction resolveWhoamiFallback(): string | undefined {\n try {\n const username = os.userInfo().username.trim();\n if (username.length > 0) {\n return username;\n }\n } catch {\n // Fall back to environment-derived attribution.\n }\n return undefined;\n}\n\nfunction resolveRequestedBy(author: string | undefined, fallback: string): string {\n const candidates = [\n author,\n process.env.PM_AUTHOR,\n fallback,\n process.env.USER,\n process.env.LOGNAME,\n process.env.USERNAME,\n resolveWhoamiFallback(),\n ];\n for (const candidate of candidates) {\n if (typeof candidate !== \"string\") {\n continue;\n }\n const trimmed = candidate.trim();\n if (trimmed.length > 0) {\n return trimmed;\n }\n }\n return \"unknown\";\n}\n\nasync function ensureInitialized(pmRoot: string): Promise<void> {\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n}\n\n/**\n * Documents the start background run command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface StartBackgroundRunCommandOptions {\n kind: BackgroundTestRunKind;\n commandArgs: string[];\n targetId?: string;\n statusFilter?: string;\n author?: string;\n noExtensions?: boolean;\n}\n\n/**\n * Documents the start background run result payload exchanged by command, SDK, and package integrations.\n */\nexport interface StartBackgroundRunResult {\n started: boolean;\n duplicate_of?: string;\n run: unknown;\n}\n\n/**\n * Implements run start background run for the public runtime surface of this module.\n */\nexport async function runStartBackgroundRun(\n options: StartBackgroundRunCommandOptions,\n global: GlobalOptions,\n): Promise<StartBackgroundRunResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n const globalPmRoot = resolveGlobalPmRoot(process.cwd());\n await ensureInitialized(pmRoot);\n const settings = await readSettings(pmRoot);\n const requestedBy = resolveRequestedBy(options.author, settings.author_default);\n const started = await startBackgroundTestRun({\n pmRoot,\n globalPmRoot,\n kind: options.kind,\n commandArgs: options.commandArgs,\n requestedBy,\n targetId: options.targetId,\n statusFilter: options.statusFilter,\n });\n if (!started.started) {\n return {\n started: false,\n duplicate_of: started.duplicate_of,\n run: started.run,\n };\n }\n const spawned = await spawnBackgroundTestRunWorker({\n pmRoot,\n runId: started.run.id,\n noExtensions: options.noExtensions === true,\n });\n return {\n started: true,\n run: spawned,\n };\n}\n\n/**\n * Documents the test runs list command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestRunsListCommandOptions {\n status?: string;\n limit?: string;\n}\n\n/**\n * Implements run test runs list for the public runtime surface of this module.\n */\nexport async function runTestRunsList(options: TestRunsListCommandOptions, global: GlobalOptions): Promise<{\n runs: unknown[];\n count: number;\n filters: {\n status?: BackgroundTestRunStatus;\n limit?: number;\n };\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const status = normalizeStatus(options.status);\n const limit = parseLimit(options.limit, \"limit\");\n const runs = await listBackgroundTestRuns(pmRoot, { status, limit });\n return {\n runs,\n count: runs.length,\n filters: {\n status,\n limit,\n },\n };\n}\n\n/**\n * Implements run test runs status for the public runtime surface of this module.\n */\nexport async function runTestRunsStatus(runId: string, global: GlobalOptions): Promise<{\n run: unknown;\n health: unknown;\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const status = await getBackgroundTestRunStatus(pmRoot, runId);\n return {\n run: status.run,\n health: status.health,\n };\n}\n\n/**\n * Documents the test runs logs command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestRunsLogsCommandOptions {\n stream?: string;\n tail?: string;\n}\n\n/**\n * Implements run test runs logs for the public runtime surface of this module.\n */\nexport async function runTestRunsLogs(\n runId: string,\n options: TestRunsLogsCommandOptions,\n global: GlobalOptions,\n): Promise<{\n run: unknown;\n stream: BackgroundLogStream;\n tail: number;\n stdout: string[];\n stderr: string[];\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const stream = normalizeStream(options.stream);\n const tail = parseLimit(options.tail, \"tail\");\n const logs = await readBackgroundTestRunLogs(pmRoot, runId, stream, tail);\n return {\n run: logs.run,\n stream: logs.stream,\n tail: logs.tail,\n stdout: logs.stdout,\n stderr: logs.stderr,\n };\n}\n\n/**\n * Documents the test runs stop command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestRunsStopCommandOptions {\n force?: boolean;\n}\n\n/**\n * Implements run test runs stop for the public runtime surface of this module.\n */\nexport async function runTestRunsStop(\n runId: string,\n options: TestRunsStopCommandOptions,\n global: GlobalOptions,\n): Promise<{\n run: unknown;\n signal_sent: \"SIGTERM\" | \"SIGKILL\" | \"none\";\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const stopped = await stopBackgroundTestRun(pmRoot, runId, options.force === true);\n return {\n run: stopped.run,\n signal_sent: stopped.signal_sent,\n };\n}\n\n/**\n * Documents the test runs resume command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestRunsResumeCommandOptions {\n author?: string;\n noExtensions?: boolean;\n}\n\n/**\n * Implements run test runs resume for the public runtime surface of this module.\n */\nexport async function runTestRunsResume(\n runId: string,\n options: TestRunsResumeCommandOptions,\n global: GlobalOptions,\n): Promise<{\n resumed_from: string;\n run: unknown;\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const settings = await readSettings(pmRoot);\n const requestedBy = resolveRequestedBy(options.author, settings.author_default);\n const resumed = await resumeBackgroundTestRun(pmRoot, runId, requestedBy, options.noExtensions === true);\n return {\n resumed_from: runId,\n run: resumed,\n };\n}\n\n/**\n * Implements run test runs worker for the public runtime surface of this module.\n */\nexport async function runTestRunsWorker(runId: string, global: GlobalOptions): Promise<{\n id: string;\n status: BackgroundTestRunStatus;\n exit_code?: number;\n}> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n await ensureInitialized(pmRoot);\n const finished = await runBackgroundTestRunWorker(pmRoot, runId, global.noExtensions === true);\n return {\n id: finished.id,\n status: finished.status,\n exit_code: finished.exit_code,\n };\n}\n", "/**\n * @module core/test/background-runs\n *\n * Runs and records linked-test orchestration for Background Runs.\n */\nimport fs from \"node:fs/promises\";\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { createHash, randomBytes } from \"node:crypto\";\nimport path from \"node:path\";\nimport { ensureDir, pathExists, readFileIfExists, writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { nowIso } from \"../shared/time.js\";\nimport {\n getTestRunRecordPath,\n getTestRunResultPath,\n getTestRunStderrPath,\n getTestRunStdoutPath,\n getTestRunsPath,\n getTestRunsRecordsPath,\n getTestRunsResultsPath,\n getTestRunsStderrPath,\n getTestRunsStdoutPath,\n} from \"../store/paths.js\";\n\nconst BACKGROUND_RUN_ACTIVE_STATUSES = new Set<BackgroundTestRunStatus>([\"queued\", \"running\"]);\nconst BACKGROUND_RUN_TERMINAL_STATUSES = new Set<BackgroundTestRunStatus>([\"passed\", \"failed\", \"stopped\", \"canceled\"]);\nconst DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS = 3000;\nconst DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS = 3000;\nconst DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS = 30000;\nconst DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES = 100;\nconst PROC_STAT_TICKS_PER_SECOND = 100;\n\n/**\n * Restricts background test run kind values accepted by command, SDK, and storage contracts.\n */\nexport type BackgroundTestRunKind = \"test\" | \"test-all\";\n\n/**\n * Restricts background test run status values accepted by command, SDK, and storage contracts.\n */\nexport type BackgroundTestRunStatus = \"queued\" | \"running\" | \"passed\" | \"failed\" | \"stopped\" | \"canceled\";\n\n/**\n * Restricts background log stream values accepted by command, SDK, and storage contracts.\n */\nexport type BackgroundLogStream = \"stdout\" | \"stderr\" | \"both\";\n\n/**\n * Documents the background run progress payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunProgress {\n phase: \"queued\" | \"running\" | \"stopping\" | \"finished\";\n message?: string;\n item_index?: number;\n item_total?: number;\n item_id?: string;\n linked_test_index?: number;\n linked_test_total?: number;\n current_command?: string;\n elapsed_ms?: number;\n heartbeat_at?: string;\n}\n\n/**\n * Documents the background run resource snapshot payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunResourceSnapshot {\n recorded_at: string;\n rss_bytes?: number;\n cpu_user_seconds?: number;\n cpu_system_seconds?: number;\n uptime_seconds?: number;\n}\n\n/**\n * Documents the background run summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunSummary {\n items?: number;\n linked_tests?: number;\n passed: number;\n failed: number;\n skipped: number;\n fail_on_skipped_triggered?: boolean;\n}\n\n/**\n * Documents the background test run record payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundTestRunRecord {\n id: string;\n kind: BackgroundTestRunKind;\n status: BackgroundTestRunStatus;\n created_at: string;\n started_at?: string;\n finished_at?: string;\n updated_at: string;\n requested_by: string;\n fingerprint: string;\n command_args: string[];\n command_label: string;\n pm_root: string;\n global_pm_root: string;\n target_id?: string;\n status_filter?: string;\n attempt: number;\n resumed_from?: string;\n resumed_by?: string;\n worker_pid?: number;\n child_pid?: number;\n exit_code?: number;\n signal?: string;\n stdout_path: string;\n stderr_path: string;\n result_path: string;\n progress?: BackgroundRunProgress;\n resource?: BackgroundRunResourceSnapshot;\n summary?: BackgroundRunSummary;\n stop_requested_at?: string;\n duplicate_of?: string;\n error?: string;\n}\n\n/**\n * Documents the start background test run options payload exchanged by command, SDK, and package integrations.\n */\nexport interface StartBackgroundTestRunOptions {\n pmRoot: string;\n globalPmRoot: string;\n kind: BackgroundTestRunKind;\n commandArgs: string[];\n requestedBy: string;\n targetId?: string;\n statusFilter?: string;\n resumedFrom?: string;\n resumedBy?: string;\n attempt?: number;\n}\n\n/**\n * Documents the start background test run result payload exchanged by command, SDK, and package integrations.\n */\nexport interface StartBackgroundTestRunResult {\n started: boolean;\n run: BackgroundTestRunRecord;\n duplicate_of?: string;\n}\n\n/**\n * Documents the spawn background test run worker options payload exchanged by command, SDK, and package integrations.\n */\nexport interface SpawnBackgroundTestRunWorkerOptions {\n pmRoot: string;\n runId: string;\n noExtensions?: boolean;\n}\n\n/**\n * Documents the stop background test run result payload exchanged by command, SDK, and package integrations.\n */\nexport interface StopBackgroundTestRunResult {\n run: BackgroundTestRunRecord;\n signal_sent: \"SIGTERM\" | \"SIGKILL\" | \"none\";\n}\n\n/**\n * Documents the list background test run options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ListBackgroundTestRunOptions {\n status?: BackgroundTestRunStatus;\n limit?: number;\n}\n\n/**\n * Documents the background run health payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunHealth {\n state: \"healthy\" | \"stale\" | \"inactive\";\n last_heartbeat_at?: string;\n heartbeat_lag_ms?: number;\n worker_alive: boolean;\n child_alive: boolean;\n}\n\n/**\n * Documents the background run status view payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunStatusView {\n run: BackgroundTestRunRecord;\n health: BackgroundRunHealth;\n}\n\n/**\n * Documents the background run logs result payload exchanged by command, SDK, and package integrations.\n */\nexport interface BackgroundRunLogsResult {\n run: BackgroundTestRunRecord;\n stream: BackgroundLogStream;\n tail: number;\n stdout: string[];\n stderr: string[];\n}\n\ninterface WorkerEvaluationResult {\n summary: BackgroundRunSummary;\n parsedResult: unknown | null;\n}\n\ninterface BackgroundWorkerStopState {\n stopRequested: boolean;\n}\n\ninterface BackgroundRunRecordWriteScheduler {\n schedule: () => void;\n flush: () => Promise<void>;\n}\n\nfunction nowMs(): number {\n return Date.now();\n}\n\nfunction normalizeCommandArgs(args: string[]): string[] {\n return args.map((entry) => entry.trim()).filter((entry) => entry.length > 0);\n}\n\nfunction summarizeCommandLabel(args: string[]): string {\n const joined = args.join(\" \").replaceAll(/\\s+/g, \" \").trim();\n if (joined.length <= 180) {\n return joined;\n }\n return `${joined.slice(0, 177)}...`;\n}\n\nfunction buildRunId(): string {\n const timePart = Date.now().toString(36);\n const randomPart = randomBytes(3).toString(\"hex\");\n return `tr-${timePart}-${randomPart}`;\n}\n\n/**\n * Implements build background test run fingerprint for the public runtime surface of this module.\n */\nexport function buildBackgroundTestRunFingerprint(kind: BackgroundTestRunKind, commandArgs: string[], pmRoot: string): string {\n const payload = {\n kind,\n command: normalizeCommandArgs(commandArgs),\n pm_root: path.resolve(pmRoot),\n };\n return createHash(\"sha256\").update(JSON.stringify(payload)).digest(\"hex\");\n}\n\nfunction isPidRunning(pid: number | undefined): boolean {\n if (!Number.isInteger(pid) || !pid || pid <= 0) {\n return false;\n }\n try {\n process.kill(pid, 0);\n return true;\n } catch (error: unknown) {\n const code = typeof error === \"object\" && error !== null && \"code\" in error ? (error as { code?: string }).code : undefined;\n return code === \"EPERM\";\n }\n}\n\nasync function ensureBackgroundRunStorage(pmRoot: string): Promise<void> {\n await ensureDir(getTestRunsPath(pmRoot));\n await ensureDir(getTestRunsRecordsPath(pmRoot));\n await ensureDir(getTestRunsStdoutPath(pmRoot));\n await ensureDir(getTestRunsStderrPath(pmRoot));\n await ensureDir(getTestRunsResultsPath(pmRoot));\n}\n\nasync function parseBackgroundRunRecord(raw: string, recordPath: string): Promise<BackgroundTestRunRecord> {\n try {\n const parsed = JSON.parse(raw) as BackgroundTestRunRecord;\n if (!parsed || typeof parsed !== \"object\" || typeof parsed.id !== \"string\") {\n throw new Error(\"invalid run record payload\");\n }\n return parsed;\n } catch (error: unknown) {\n throw new PmCliError(\n `Failed to parse background test run record at ${recordPath}: ${error instanceof Error ? error.message : String(error)}`,\n EXIT_CODE.GENERIC_FAILURE,\n );\n }\n}\n\nasync function writeBackgroundRunRecord(pmRoot: string, record: BackgroundTestRunRecord): Promise<void> {\n const next: BackgroundTestRunRecord = {\n ...record,\n updated_at: nowIso(),\n };\n await writeFileAtomic(getTestRunRecordPath(pmRoot, record.id), `${JSON.stringify(next, null, 2)}\\n`);\n}\n\n/**\n * Implements read background test run record for the public runtime surface of this module.\n */\nexport async function readBackgroundTestRunRecord(pmRoot: string, runId: string): Promise<BackgroundTestRunRecord | null> {\n const recordPath = getTestRunRecordPath(pmRoot, runId);\n const raw = await readFileIfExists(recordPath);\n if (!raw) {\n return null;\n }\n return parseBackgroundRunRecord(raw, recordPath);\n}\n\nasync function listBackgroundRunRecordPaths(pmRoot: string): Promise<string[]> {\n const recordsRoot = getTestRunsRecordsPath(pmRoot);\n if (!(await pathExists(recordsRoot))) {\n return [];\n }\n const entries = await fs.readdir(recordsRoot, { withFileTypes: true });\n return entries\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map((entry) => path.join(recordsRoot, entry.name))\n .sort((left, right) => right.localeCompare(left));\n}\n\nfunction parseLinuxRssStatus(raw: string): number | undefined {\n const match = raw.match(/^VmRSS:\\s+(\\d+)\\s+kB$/m);\n if (!match) {\n return undefined;\n }\n return Number.parseInt(match[1], 10) * 1024;\n}\n\nasync function readLinuxRssBytes(pid: number): Promise<number | undefined> {\n if (process.platform !== \"linux\") {\n return undefined;\n }\n try {\n const raw = await fs.readFile(`/proc/${pid}/status`, \"utf8\");\n return parseLinuxRssStatus(raw);\n } catch {\n return undefined;\n }\n}\n\nfunction parseLinuxCpuStat(raw: string): { cpu_user_seconds?: number; cpu_system_seconds?: number } {\n const closeParenIndex = raw.lastIndexOf(\")\");\n if (closeParenIndex < 0) {\n return {};\n }\n const remainder = raw.slice(closeParenIndex + 2).trim();\n const parts = remainder.split(/\\s+/);\n const utimeTicks = Number.parseInt(parts[11], 10);\n const stimeTicks = Number.parseInt(parts[12], 10);\n if (!Number.isFinite(utimeTicks) || !Number.isFinite(stimeTicks)) {\n return {};\n }\n return {\n cpu_user_seconds: utimeTicks / PROC_STAT_TICKS_PER_SECOND,\n cpu_system_seconds: stimeTicks / PROC_STAT_TICKS_PER_SECOND,\n };\n}\n\nasync function readLinuxCpuSeconds(\n pid: number,\n): Promise<{ cpu_user_seconds?: number; cpu_system_seconds?: number }> {\n if (process.platform !== \"linux\") {\n return {};\n }\n try {\n const raw = await fs.readFile(`/proc/${pid}/stat`, \"utf8\");\n return parseLinuxCpuStat(raw);\n } catch {\n /* c8 ignore next -- /proc entries can disappear between liveness and stat reads. */\n return {};\n }\n}\n\nasync function buildResourceSnapshot(record: BackgroundTestRunRecord): Promise<BackgroundRunResourceSnapshot | undefined> {\n const pid = record.child_pid ?? record.worker_pid;\n if (!isPidRunning(pid)) {\n return undefined;\n }\n const rssBytes = await readLinuxRssBytes(pid as number);\n const cpu = await readLinuxCpuSeconds(pid as number);\n const startedAtMs = record.started_at ? Date.parse(record.started_at) : Number.NaN;\n const uptimeSeconds = Number.isFinite(startedAtMs) ? Math.max(0, (nowMs() - startedAtMs) / 1000) : undefined;\n return {\n recorded_at: nowIso(),\n rss_bytes: rssBytes,\n cpu_user_seconds: cpu.cpu_user_seconds,\n cpu_system_seconds: cpu.cpu_system_seconds,\n uptime_seconds: uptimeSeconds,\n };\n}\n\nfunction readCount(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\nfunction evaluateWorkerResult(kind: BackgroundTestRunKind, payload: unknown): WorkerEvaluationResult {\n if (!payload || typeof payload !== \"object\") {\n return {\n summary: {\n passed: 0,\n failed: 1,\n skipped: 0,\n },\n parsedResult: null,\n };\n }\n const record = payload as Record<string, unknown>;\n if (kind === \"test-all\") {\n const totals = (record.totals ?? {}) as Record<string, unknown>;\n return {\n summary: {\n items: typeof totals.items === \"number\" ? totals.items : undefined,\n linked_tests: typeof totals.linked_tests === \"number\" ? totals.linked_tests : undefined,\n passed: readCount(totals.passed),\n failed: readCount(totals.failed),\n skipped: readCount(totals.skipped),\n fail_on_skipped_triggered: record.fail_on_skipped_triggered === true ? true : undefined,\n },\n parsedResult: payload,\n };\n }\n const runResults = Array.isArray(record.run_results) ? record.run_results : [];\n let passed = 0;\n let failed = 0;\n let skipped = 0;\n for (const entry of runResults) {\n if (!entry || typeof entry !== \"object\") {\n continue;\n }\n const status = (entry as { status?: unknown }).status;\n if (status === \"passed\") {\n passed += 1;\n continue;\n }\n if (status === \"failed\") {\n failed += 1;\n continue;\n }\n skipped += 1;\n }\n return {\n summary: {\n passed,\n failed,\n skipped,\n fail_on_skipped_triggered: record.fail_on_skipped_triggered === true ? true : undefined,\n },\n parsedResult: payload,\n };\n}\n\nfunction parseProgressLine(stderrLine: string): Partial<BackgroundRunProgress> | null {\n const line = stderrLine.trim();\n if (line.length === 0) {\n return null;\n }\n const testAllMatch = line.match(/\\[pm test-all\\]\\s+item\\s+(\\d+)\\/(\\d+)\\s+(start|end)\\s+id=([^\\s]+)/i);\n if (testAllMatch) {\n const itemIndex = Number.parseInt(testAllMatch[1], 10);\n const itemTotal = Number.parseInt(testAllMatch[2], 10);\n return {\n item_index: itemIndex,\n item_total: itemTotal,\n item_id: testAllMatch[4],\n linked_test_index: undefined,\n linked_test_total: undefined,\n current_command: undefined,\n elapsed_ms: undefined,\n heartbeat_at: nowIso(),\n phase: testAllMatch[3]?.toLowerCase() === \"end\" ? \"finished\" : \"running\",\n };\n }\n const linkedTestMatch = line.match(/\\[pm test\\]\\s+linked-test\\s+(\\d+)\\/(\\d+)\\s+(start|running|end)(?:.*elapsed_ms=(\\d+))?/i);\n if (!linkedTestMatch) {\n return null;\n }\n const index = Number.parseInt(linkedTestMatch[1], 10);\n const total = Number.parseInt(linkedTestMatch[2], 10);\n const elapsed = linkedTestMatch[4] ? Number.parseInt(linkedTestMatch[4], 10) : undefined;\n const commandMatch = line.match(/\\scommand=\"((?:\\\\.|[^\"\\\\])*)\"/);\n const currentCommand = commandMatch\n ? commandMatch[1].replaceAll('\\\\\"', '\"').replaceAll(\"\\\\\\\\\", \"\\\\\")\n : undefined;\n return {\n linked_test_index: index,\n linked_test_total: total,\n current_command: currentCommand,\n elapsed_ms: Number.isFinite(elapsed) ? elapsed : undefined,\n heartbeat_at: nowIso(),\n phase: linkedTestMatch[3]?.toLowerCase() === \"end\" ? \"finished\" : \"running\",\n };\n}\n\nfunction splitLines(value: string): string[] {\n return value\n .split(/\\r?\\n/)\n .map((entry) => entry.trimEnd())\n .filter((entry) => entry.length > 0);\n}\n\nfunction tailLines(value: string, limit: number): string[] {\n if (limit <= 0) {\n return [];\n }\n const lines = splitLines(value);\n if (lines.length <= limit) {\n return lines;\n }\n return lines.slice(lines.length - limit);\n}\n\nasync function resolveBackgroundCliEntry(cwd: string): Promise<string> {\n const configured = process.env.PM_BACKGROUND_CLI_ENTRY?.trim();\n if (configured && configured.length > 0) {\n const resolvedConfigured = path.resolve(cwd, configured);\n if (await pathExists(resolvedConfigured)) {\n return resolvedConfigured;\n }\n }\n const distEntry = path.resolve(cwd, \"dist\", \"cli.js\");\n if (await pathExists(distEntry)) {\n return distEntry;\n }\n const argvEntry = process.argv[1]?.trim();\n if (argvEntry && argvEntry.length > 0) {\n const resolvedArgvEntry = path.resolve(cwd, argvEntry);\n if (await pathExists(resolvedArgvEntry)) {\n return resolvedArgvEntry;\n }\n }\n throw new PmCliError(\n \"Unable to resolve a CLI entrypoint for background test runs. Build the project or set PM_BACKGROUND_CLI_ENTRY.\",\n EXIT_CODE.GENERIC_FAILURE,\n );\n}\n\nasync function refreshRunIfStale(pmRoot: string, record: BackgroundTestRunRecord): Promise<BackgroundTestRunRecord> {\n if (!BACKGROUND_RUN_ACTIVE_STATUSES.has(record.status)) {\n return record;\n }\n const workerAlive = isPidRunning(record.worker_pid);\n if (workerAlive) {\n return record;\n }\n if (record.finished_at) {\n return record;\n }\n const next: BackgroundTestRunRecord = {\n ...record,\n status: \"failed\",\n finished_at: nowIso(),\n error: record.error ?? \"Background test run worker exited before writing terminal status.\",\n };\n await writeBackgroundRunRecord(pmRoot, next);\n return next;\n}\n\n/**\n * Implements start background test run for the public runtime surface of this module.\n */\nexport async function startBackgroundTestRun(options: StartBackgroundTestRunOptions): Promise<StartBackgroundTestRunResult> {\n await ensureBackgroundRunStorage(options.pmRoot);\n const normalizedArgs = normalizeCommandArgs(options.commandArgs);\n if (normalizedArgs.length === 0) {\n throw new PmCliError(\"Background test run requires command arguments.\", EXIT_CODE.USAGE);\n }\n const fingerprint = buildBackgroundTestRunFingerprint(options.kind, normalizedArgs, options.pmRoot);\n const existingRuns = await listBackgroundTestRuns(options.pmRoot, {});\n for (const existing of existingRuns) {\n const refreshed = await refreshRunIfStale(options.pmRoot, existing);\n if (refreshed.fingerprint !== fingerprint) {\n continue;\n }\n if (!BACKGROUND_RUN_ACTIVE_STATUSES.has(refreshed.status) || !isPidRunning(refreshed.worker_pid)) {\n continue;\n }\n return {\n started: false,\n run: {\n ...refreshed,\n duplicate_of: refreshed.id,\n },\n duplicate_of: refreshed.id,\n };\n }\n\n const runId = buildRunId();\n const createdAt = nowIso();\n const stdoutPath = getTestRunStdoutPath(options.pmRoot, runId);\n const stderrPath = getTestRunStderrPath(options.pmRoot, runId);\n const resultPath = getTestRunResultPath(options.pmRoot, runId);\n await fs.writeFile(stdoutPath, \"\", \"utf8\");\n await fs.writeFile(stderrPath, \"\", \"utf8\");\n const record: BackgroundTestRunRecord = {\n id: runId,\n kind: options.kind,\n status: \"queued\",\n created_at: createdAt,\n updated_at: createdAt,\n requested_by: options.requestedBy,\n fingerprint,\n command_args: normalizedArgs,\n command_label: summarizeCommandLabel(normalizedArgs),\n pm_root: options.pmRoot,\n global_pm_root: options.globalPmRoot,\n target_id: options.targetId,\n status_filter: options.statusFilter,\n attempt: typeof options.attempt === \"number\" && Number.isFinite(options.attempt) && options.attempt >= 1\n ? Math.floor(options.attempt)\n : 1,\n resumed_from: options.resumedFrom,\n resumed_by: options.resumedBy,\n stdout_path: stdoutPath,\n stderr_path: stderrPath,\n result_path: resultPath,\n progress: {\n phase: \"queued\",\n message: \"Queued for background execution.\",\n heartbeat_at: createdAt,\n },\n };\n await writeBackgroundRunRecord(options.pmRoot, record);\n return {\n started: true,\n run: record,\n };\n}\n\n/**\n * Implements spawn background test run worker for the public runtime surface of this module.\n */\nexport async function spawnBackgroundTestRunWorker(options: SpawnBackgroundTestRunWorkerOptions): Promise<BackgroundTestRunRecord> {\n const record = await readBackgroundTestRunRecord(options.pmRoot, options.runId);\n if (!record) {\n throw new PmCliError(`Background test run ${options.runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n if (BACKGROUND_RUN_TERMINAL_STATUSES.has(record.status)) {\n throw new PmCliError(`Background test run ${record.id} is already terminal (${record.status}).`, EXIT_CODE.CONFLICT);\n }\n const cliEntry = await resolveBackgroundCliEntry(process.cwd());\n const args: string[] = [];\n if (options.noExtensions === true) {\n args.push(\"--no-extensions\");\n }\n args.push(\"--path\", record.pm_root, \"test-runs-worker\", record.id);\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n PM_PATH: record.pm_root,\n PM_GLOBAL_PATH: record.global_pm_root,\n PM_BACKGROUND_TEST_RUN_ID: record.id,\n PM_BACKGROUND_TEST_RUN_ATTEMPT: String(record.attempt),\n PM_BACKGROUND_TEST_RUN_RESUMED_FROM: record.resumed_from ?? \"\",\n FORCE_COLOR: \"0\",\n };\n const child = spawn(process.execPath, [cliEntry, ...args], {\n cwd: process.cwd(),\n env,\n detached: true,\n stdio: \"ignore\",\n windowsHide: true,\n });\n child.unref();\n const next: BackgroundTestRunRecord = {\n ...record,\n status: \"queued\",\n worker_pid: child.pid as number | undefined,\n progress: {\n phase: \"queued\",\n message: \"Worker process started.\",\n heartbeat_at: nowIso(),\n },\n };\n await writeBackgroundRunRecord(options.pmRoot, next);\n return next;\n}\n\nasync function appendFileOrdered(queue: Promise<void>, filePath: string, text: string): Promise<void> {\n await queue;\n await fs.appendFile(filePath, text, \"utf8\");\n}\n\nfunction resolvePositiveEnvInteger(name: string, fallback: number): number {\n const parsed = Number.parseInt(process.env[name] ?? \"\", 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nfunction buildBackgroundWorkerEnv(record: BackgroundTestRunRecord): NodeJS.ProcessEnv {\n return {\n ...process.env,\n PM_PATH: record.pm_root,\n PM_GLOBAL_PATH: record.global_pm_root,\n FORCE_COLOR: \"0\",\n };\n}\n\nfunction buildBackgroundWorkerChildArgs(record: BackgroundTestRunRecord, noExtensions: boolean): string[] {\n return noExtensions ? [\"--no-extensions\", ...record.command_args] : [...record.command_args];\n}\n\nfunction createBackgroundRunRecordWriteScheduler(\n pmRoot: string,\n record: BackgroundTestRunRecord,\n): BackgroundRunRecordWriteScheduler {\n let writeQueue: Promise<void> = Promise.resolve();\n return {\n schedule(): void {\n writeQueue = writeQueue.then(async () => {\n try {\n await writeBackgroundRunRecord(pmRoot, record);\n } catch {\n // Keep worker alive even if a single metadata write fails.\n }\n });\n },\n async flush(): Promise<void> {\n await writeQueue;\n },\n };\n}\n\nfunction requestChildSignal(child: ChildProcess, signal: NodeJS.Signals): void {\n try {\n child.kill(signal);\n } catch {\n // Child may already be gone.\n }\n}\n\nasync function requestBackgroundWorkerStop(\n record: BackgroundTestRunRecord,\n child: ChildProcess,\n state: BackgroundWorkerStopState,\n scheduleRecordWrite: () => void,\n): Promise<void> {\n if (state.stopRequested) {\n return;\n }\n state.stopRequested = true;\n record.stop_requested_at = nowIso();\n record.progress = {\n ...record.progress,\n phase: \"stopping\",\n message: \"Stop requested for background run.\",\n heartbeat_at: nowIso(),\n };\n scheduleRecordWrite();\n requestChildSignal(child, \"SIGTERM\");\n const forceTimer = setTimeout(() => requestChildSignal(child, \"SIGKILL\"), resolvePositiveEnvInteger(\n \"PM_BACKGROUND_RUN_FORCE_KILL_DELAY_MS\",\n DEFAULT_BACKGROUND_RUN_FORCE_KILL_DELAY_MS,\n ));\n forceTimer.unref?.();\n}\n\nfunction buildItemBackgroundProgress(line: string, progressPatch: Partial<BackgroundRunProgress>, phase: \"running\" | \"stopping\"): BackgroundRunProgress {\n return {\n phase,\n message: line,\n heartbeat_at: nowIso(),\n item_index: progressPatch.item_index,\n item_total: progressPatch.item_total,\n item_id: progressPatch.item_id,\n linked_test_index: undefined,\n linked_test_total: undefined,\n current_command: undefined,\n elapsed_ms: undefined,\n };\n}\n\nfunction buildLinkedTestBackgroundProgress(\n line: string,\n record: BackgroundTestRunRecord,\n progressPatch: Partial<BackgroundRunProgress>,\n phase: \"running\" | \"stopping\",\n): BackgroundRunProgress {\n return {\n phase,\n message: line,\n heartbeat_at: nowIso(),\n item_index: progressPatch.item_index ?? record.progress?.item_index,\n item_total: progressPatch.item_total ?? record.progress?.item_total,\n item_id: progressPatch.item_id ?? record.progress?.item_id,\n linked_test_index: progressPatch.linked_test_index,\n linked_test_total: progressPatch.linked_test_total,\n current_command: progressPatch.current_command,\n elapsed_ms: progressPatch.elapsed_ms,\n };\n}\n\nfunction applyBackgroundWorkerProgressLine(record: BackgroundTestRunRecord, line: string, stopRequested: boolean): boolean {\n const progressPatch = parseProgressLine(line);\n if (!progressPatch) {\n return false;\n }\n const phase = record.progress?.phase === \"stopping\" ? \"stopping\" : \"running\";\n record.progress = progressPatch.item_id\n ? buildItemBackgroundProgress(line, progressPatch, phase)\n : buildLinkedTestBackgroundProgress(line, record, progressPatch, phase);\n if (progressPatch.phase === \"finished\" && !stopRequested) {\n record.progress.phase = \"running\";\n }\n return true;\n}\n\nfunction parseBackgroundWorkerStdout(stdoutBuffer: string): unknown | null {\n if (stdoutBuffer.trim().length === 0) {\n return null;\n }\n try {\n return JSON.parse(stdoutBuffer) as unknown;\n } catch {\n return null;\n }\n}\n\nfunction resolveBackgroundWorkerFinalStatus(record: BackgroundTestRunRecord, stopRequested: boolean): BackgroundTestRunStatus {\n if (stopRequested) {\n return \"stopped\";\n }\n const passed = record.exit_code === 0 && (record.summary?.failed ?? 0) === 0 && record.summary?.fail_on_skipped_triggered !== true;\n return passed ? \"passed\" : \"failed\";\n}\n\nfunction buildFinishedBackgroundProgress(record: BackgroundTestRunRecord, stopRequested: boolean): BackgroundRunProgress {\n return {\n phase: \"finished\",\n message: stopRequested ? \"Background run stopped.\" : `Background run finished with status=${record.status}.`,\n heartbeat_at: nowIso(),\n item_index: record.progress?.item_index,\n item_total: record.progress?.item_total,\n item_id: record.progress?.item_id,\n linked_test_index: record.progress?.linked_test_index,\n linked_test_total: record.progress?.linked_test_total,\n current_command: record.progress?.current_command,\n elapsed_ms: record.progress?.elapsed_ms,\n };\n}\n\nasync function writeBackgroundWorkerResult(record: BackgroundTestRunRecord, parsedResult: unknown | null, stdoutBuffer: string): Promise<void> {\n if (parsedResult !== null) {\n await writeFileAtomic(record.result_path, `${JSON.stringify(parsedResult, null, 2)}\\n`);\n return;\n }\n await writeFileAtomic(\n record.result_path,\n `${JSON.stringify(\n {\n parse_error: \"Background run output was not valid JSON.\",\n stdout_excerpt: tailLines(stdoutBuffer, DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES),\n },\n null,\n 2,\n )}\\n`,\n );\n}\n\n/**\n * Implements run background test run worker for the public runtime surface of this module.\n */\nexport async function runBackgroundTestRunWorker(pmRoot: string, runId: string, noExtensions = false): Promise<BackgroundTestRunRecord> {\n const loaded = await readBackgroundTestRunRecord(pmRoot, runId);\n if (!loaded) {\n throw new PmCliError(`Background test run ${runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n const record: BackgroundTestRunRecord = {\n ...loaded,\n status: \"running\",\n started_at: loaded.started_at ?? nowIso(),\n worker_pid: process.pid,\n progress: {\n phase: \"running\",\n message: \"Worker started.\",\n heartbeat_at: nowIso(),\n },\n };\n const cliEntry = await resolveBackgroundCliEntry(process.cwd());\n const env = buildBackgroundWorkerEnv(record);\n await writeBackgroundRunRecord(pmRoot, record);\n\n const childArgs = buildBackgroundWorkerChildArgs(record, noExtensions);\n const child = spawn(process.execPath, [cliEntry, ...childArgs], {\n cwd: process.cwd(),\n env,\n detached: false,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n windowsHide: true,\n });\n record.child_pid = child.pid as number | undefined;\n\n const recordWriteScheduler = createBackgroundRunRecordWriteScheduler(pmRoot, record);\n const scheduleRecordWrite = recordWriteScheduler.schedule;\n\n let stdoutWriteQueue: Promise<void> = Promise.resolve();\n let stderrWriteQueue: Promise<void> = Promise.resolve();\n let stdoutBuffer = \"\";\n let stderrBuffer = \"\";\n const stopState: BackgroundWorkerStopState = { stopRequested: false };\n\n const onSignal = (): void => {\n void requestBackgroundWorkerStop(record, child, stopState, scheduleRecordWrite);\n };\n process.on(\"SIGTERM\", onSignal);\n process.on(\"SIGINT\", onSignal);\n\n const resourceTimer = setInterval(() => {\n void (async () => {\n record.resource = await buildResourceSnapshot(record);\n (record.progress as BackgroundRunProgress).heartbeat_at = nowIso();\n scheduleRecordWrite();\n })();\n }, resolvePositiveEnvInteger(\"PM_BACKGROUND_RUN_RESOURCE_INTERVAL_MS\", DEFAULT_BACKGROUND_RUN_RESOURCE_SNAPSHOT_INTERVAL_MS));\n resourceTimer.unref?.();\n\n child.stdout?.on(\"data\", (chunk) => {\n const text = chunk.toString(\"utf8\");\n stdoutBuffer += text;\n stdoutWriteQueue = appendFileOrdered(stdoutWriteQueue, record.stdout_path, text);\n });\n\n child.stderr?.on(\"data\", (chunk) => {\n const text = chunk.toString(\"utf8\");\n stderrWriteQueue = appendFileOrdered(stderrWriteQueue, record.stderr_path, text);\n stderrBuffer += text;\n const parts = stderrBuffer.split(/\\r?\\n/);\n stderrBuffer = parts.pop()!;\n let progressChanged = false;\n for (const part of parts) {\n const line = part.trimEnd();\n if (line.length > 0 && applyBackgroundWorkerProgressLine(record, line, stopState.stopRequested)) {\n progressChanged = true;\n }\n }\n if (progressChanged) {\n scheduleRecordWrite();\n }\n });\n\n let exitCode: number | null = null;\n let signal: NodeJS.Signals | null = null;\n try {\n ({ code: exitCode, signal } = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {\n child.on(\"close\", (code, closeSignal) => {\n resolve({ code, signal: closeSignal });\n });\n }));\n } finally {\n clearInterval(resourceTimer);\n process.off(\"SIGTERM\", onSignal);\n process.off(\"SIGINT\", onSignal);\n }\n\n await stdoutWriteQueue;\n await stderrWriteQueue;\n const trailingStderrLine = stderrBuffer.trimEnd();\n if (trailingStderrLine.length > 0 && applyBackgroundWorkerProgressLine(record, trailingStderrLine, stopState.stopRequested)) {\n scheduleRecordWrite();\n }\n stderrBuffer = \"\";\n\n const parsedResult = parseBackgroundWorkerStdout(stdoutBuffer);\n const evaluated = evaluateWorkerResult(record.kind, parsedResult);\n record.summary = evaluated.summary;\n record.exit_code = typeof exitCode === \"number\" ? exitCode : undefined;\n record.signal = signal ?? undefined;\n record.finished_at = nowIso();\n record.status = resolveBackgroundWorkerFinalStatus(record, stopState.stopRequested);\n record.progress = buildFinishedBackgroundProgress(record, stopState.stopRequested);\n record.resource = await buildResourceSnapshot(record);\n await writeBackgroundWorkerResult(record, parsedResult, stdoutBuffer);\n await writeBackgroundRunRecord(pmRoot, record);\n await recordWriteScheduler.flush();\n return record;\n}\n\n/**\n * Implements list background test runs for the public runtime surface of this module.\n */\nexport async function listBackgroundTestRuns(\n pmRoot: string,\n options: ListBackgroundTestRunOptions,\n): Promise<BackgroundTestRunRecord[]> {\n const recordPaths = await listBackgroundRunRecordPaths(pmRoot);\n const runs: BackgroundTestRunRecord[] = [];\n for (const recordPath of recordPaths) {\n const raw = await readFileIfExists(recordPath);\n if (!raw) {\n continue;\n }\n const parsed = await parseBackgroundRunRecord(raw, recordPath);\n runs.push(parsed);\n }\n const refreshed: BackgroundTestRunRecord[] = [];\n for (const run of runs) {\n refreshed.push(await refreshRunIfStale(pmRoot, run));\n }\n const filtered = options.status ? refreshed.filter((entry) => entry.status === options.status) : refreshed;\n const sorted = filtered.sort((left, right) => {\n const byUpdated = Date.parse(right.updated_at) - Date.parse(left.updated_at);\n if (Number.isFinite(byUpdated) && byUpdated !== 0) {\n return byUpdated;\n }\n return right.id.localeCompare(left.id);\n });\n const limit = typeof options.limit === \"number\" && options.limit >= 0 ? options.limit : undefined;\n return limit === undefined ? sorted : sorted.slice(0, limit);\n}\n\n/**\n * Implements get background test run status for the public runtime surface of this module.\n */\nexport async function getBackgroundTestRunStatus(pmRoot: string, runId: string): Promise<BackgroundRunStatusView> {\n const loaded = await readBackgroundTestRunRecord(pmRoot, runId);\n if (!loaded) {\n throw new PmCliError(`Background test run ${runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n const refreshed = await refreshRunIfStale(pmRoot, loaded);\n const workerAlive = isPidRunning(refreshed.worker_pid);\n const childAlive = isPidRunning(refreshed.child_pid);\n if (refreshed.status === \"running\" && !childAlive && !refreshed.finished_at && !workerAlive) {\n refreshed.status = \"failed\";\n refreshed.finished_at = nowIso();\n refreshed.error = refreshed.error ?? \"Background run process exited unexpectedly.\";\n await writeBackgroundRunRecord(pmRoot, refreshed);\n }\n if (refreshed.status === \"running\") {\n refreshed.resource = await buildResourceSnapshot(refreshed);\n await writeBackgroundRunRecord(pmRoot, refreshed);\n }\n const heartbeatAt = refreshed.progress?.heartbeat_at;\n const heartbeatAtMs = heartbeatAt ? Date.parse(heartbeatAt) : Number.NaN;\n const lagMs = Number.isFinite(heartbeatAtMs) ? Math.max(0, nowMs() - heartbeatAtMs) : undefined;\n const staleMs = Number.parseInt(process.env.PM_BACKGROUND_RUN_HEARTBEAT_STALE_MS ?? \"\", 10);\n const staleThresholdMs = Number.isFinite(staleMs) && staleMs > 0 ? staleMs : DEFAULT_BACKGROUND_RUN_HEARTBEAT_STALE_MS;\n const healthState = refreshed.status === \"running\"\n ? lagMs !== undefined && lagMs > staleThresholdMs\n ? \"stale\"\n : \"healthy\"\n : \"inactive\";\n return {\n run: refreshed,\n health: {\n state: healthState,\n last_heartbeat_at: heartbeatAt,\n heartbeat_lag_ms: lagMs,\n worker_alive: workerAlive,\n child_alive: childAlive,\n },\n };\n}\n\n/* v8 ignore start -- stop-signal branches depend on live process state; command tests cover observable stop behavior */\nfunction sendBackgroundRunStopSignal(record: BackgroundTestRunRecord, force: boolean): \"SIGTERM\" | \"SIGKILL\" | \"none\" {\n const signal: NodeJS.Signals = force ? \"SIGKILL\" : \"SIGTERM\";\n if (!isPidRunning(record.worker_pid) || !record.worker_pid) {\n return \"none\";\n }\n try {\n process.kill(record.worker_pid, signal);\n return signal;\n } catch {\n return \"none\";\n }\n}\n/* v8 ignore stop */\n\nfunction buildStoppingBackgroundProgress(\n record: BackgroundTestRunRecord,\n signalSent: \"SIGTERM\" | \"SIGKILL\" | \"none\",\n): BackgroundRunProgress {\n return {\n phase: \"stopping\",\n message: signalSent === \"none\" ? \"Run marked stopped.\" : `Stop requested via ${signalSent}.`,\n heartbeat_at: nowIso(),\n item_index: record.progress?.item_index,\n item_total: record.progress?.item_total,\n item_id: record.progress?.item_id,\n linked_test_index: record.progress?.linked_test_index,\n linked_test_total: record.progress?.linked_test_total,\n current_command: record.progress?.current_command,\n elapsed_ms: record.progress?.elapsed_ms,\n };\n}\n\n/**\n * Implements stop background test run for the public runtime surface of this module.\n */\nexport async function stopBackgroundTestRun(pmRoot: string, runId: string, force = false): Promise<StopBackgroundTestRunResult> {\n const loaded = await readBackgroundTestRunRecord(pmRoot, runId);\n if (!loaded) {\n throw new PmCliError(`Background test run ${runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n const refreshed = await refreshRunIfStale(pmRoot, loaded);\n if (BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status)) {\n return {\n run: refreshed,\n signal_sent: \"none\",\n };\n }\n const signalSent = sendBackgroundRunStopSignal(refreshed, force);\n if (signalSent === \"none\") {\n refreshed.status = \"stopped\";\n refreshed.finished_at = refreshed.finished_at ?? nowIso();\n }\n refreshed.stop_requested_at = nowIso();\n refreshed.progress = buildStoppingBackgroundProgress(refreshed, signalSent);\n await writeBackgroundRunRecord(pmRoot, refreshed);\n return {\n run: refreshed,\n signal_sent: signalSent,\n };\n}\n\n/**\n * Implements resume background test run for the public runtime surface of this module.\n */\nexport async function resumeBackgroundTestRun(\n pmRoot: string,\n runId: string,\n requestedBy: string,\n noExtensions = false,\n): Promise<BackgroundTestRunRecord> {\n const loaded = await readBackgroundTestRunRecord(pmRoot, runId);\n if (!loaded) {\n throw new PmCliError(`Background test run ${runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n const refreshed = await refreshRunIfStale(pmRoot, loaded);\n if (!BACKGROUND_RUN_TERMINAL_STATUSES.has(refreshed.status)) {\n throw new PmCliError(`Background test run ${runId} is not terminal and cannot be resumed.`, EXIT_CODE.CONFLICT);\n }\n const started = await startBackgroundTestRun({\n pmRoot: refreshed.pm_root,\n globalPmRoot: refreshed.global_pm_root,\n kind: refreshed.kind,\n commandArgs: refreshed.command_args,\n requestedBy,\n targetId: refreshed.target_id,\n statusFilter: refreshed.status_filter,\n resumedFrom: refreshed.id,\n resumedBy: requestedBy,\n attempt: refreshed.attempt + 1,\n });\n if (!started.started) {\n return started.run;\n }\n const spawned = await spawnBackgroundTestRunWorker({\n pmRoot,\n runId: started.run.id,\n noExtensions,\n });\n const prior: BackgroundTestRunRecord = {\n ...refreshed,\n resumed_by: spawned.id,\n };\n await writeBackgroundRunRecord(pmRoot, prior);\n return spawned;\n}\n\n/**\n * Implements read background test run logs for the public runtime surface of this module.\n */\nexport async function readBackgroundTestRunLogs(\n pmRoot: string,\n runId: string,\n stream: BackgroundLogStream,\n tail: number | undefined,\n): Promise<BackgroundRunLogsResult> {\n const loaded = await readBackgroundTestRunRecord(pmRoot, runId);\n if (!loaded) {\n throw new PmCliError(`Background test run ${runId} not found`, EXIT_CODE.NOT_FOUND);\n }\n const resolvedTail = typeof tail === \"number\" && Number.isFinite(tail) && tail >= 0 ? Math.floor(tail) : DEFAULT_BACKGROUND_RUN_LOG_TAIL_LINES;\n const stdoutRaw = stream === \"stdout\" || stream === \"both\" ? (await readFileIfExists(loaded.stdout_path)) ?? \"\" : \"\";\n const stderrRaw = stream === \"stderr\" || stream === \"both\" ? (await readFileIfExists(loaded.stderr_path)) ?? \"\" : \"\";\n return {\n run: loaded,\n stream,\n tail: resolvedTail,\n stdout: stream === \"stdout\" || stream === \"both\" ? tailLines(stdoutRaw, resolvedTail) : [],\n stderr: stream === \"stderr\" || stream === \"both\" ? tailLines(stderrRaw, resolvedTail) : [],\n };\n}\n\nexport const _testOnly = {\n buildResourceSnapshot,\n evaluateWorkerResult,\n isPidRunning,\n parseLinuxCpuStat,\n parseLinuxRssStatus,\n parseProgressLine,\n readLinuxCpuSeconds,\n readLinuxRssBytes,\n refreshRunIfStale,\n splitLines,\n tailLines,\n};\n", "/**\n * @module cli/commands/validate\n *\n * Implements the pm validate command surface and its agent-facing runtime behavior.\n */\nimport fs from \"node:fs/promises\";\nimport { realpathSync } from \"node:fs\";\nimport type { Dirent } from \"node:fs\";\nimport { execFile } from \"node:child_process\";\nimport path from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { buildRemediationCommands } from \"../../core/diagnostics/remediation.js\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { scanHistoryDrift } from \"../../core/history/drift-scan.js\";\nimport { normalizeStatusInput } from \"../../core/item/status.js\";\nimport { resolveItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { resolveRuntimeStatusRegistry, type RuntimeStatusRegistry } from \"../../core/schema/runtime-schema.js\";\nimport {\n DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS,\n DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS,\n EXIT_CODE,\n PM_DIRNAME,\n} from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { toNonEmptyStringOrUndefined } from \"../../core/shared/primitives.js\";\nimport { nowIso } from \"../../core/shared/time.js\";\nimport {\n CURRENT_ITEM_FORMAT_VERSION,\n effectiveItemFormatVersion,\n scanItemFormatVersions,\n} from \"../../core/item/item-format-version.js\";\nimport { listAllFrontMatterWithBody } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport {\n partitionFixesByGrant,\n planCloseReasonBackfillFixes,\n planEstimateBackfillFixes,\n planResolutionBackfillFixes,\n planStaleLinkPruneFixes,\n planTerminalParentFixes,\n resolveGrantedFixScopes,\n toFixOutputRow,\n type CloseReasonBackfillRow,\n type EstimateBackfillRow,\n type ResolutionBackfillRow,\n type StaleLinkPruneRow,\n type TerminalParentFixRow,\n type ValidateFixScope,\n type ValidateFixRecord,\n} from \"../../core/validate/fix-planning.js\";\nimport { findDuplicateIssueCodes, type DuplicateIssueCode } from \"../../core/governance/issue-codes.js\";\nimport { buildMissingByTypeCounts, type MissingFieldOccurrence } from \"../../core/validate/missing-by-type.js\";\nimport {\n classifyStaleLinkedPaths,\n summarizeStaleLinkedPathClassifications,\n} from \"../../core/validate/stale-file-classification.js\";\nimport { isRemoteLinkedArtifactReference } from \"../../core/validate/linked-artifact-reference.js\";\nimport {\n buildMissingLinkedPathRows,\n summarizeMissingLinkedPathRows,\n type StaleLinkOwnerInput,\n} from \"../../core/validate/missing-link-owners.js\";\nimport type { ValidateMetadataProfile, ValidateMetadataRequiredField } from \"../../types/index.js\";\nimport { extractReferencedPmItemIdsFromCommand } from \"./test.js\";\n\ntype ValidateCheckName =\n | \"metadata\"\n | \"resolution\"\n | \"lifecycle\"\n | \"files\"\n | \"command_references\"\n | \"history_drift\"\n | \"format_version\";\ntype ValidateStatus = \"ok\" | \"warn\" | \"error\";\ntype ValidateDependencyCycleSeverity = \"off\" | \"warn\" | \"error\";\ntype ValidateFileScanMode = \"default\" | \"tracked-all\" | \"tracked-all-strict\";\ntype ItemWithBody = Awaited<ReturnType<typeof listAllFrontMatterWithBody>>[number];\ntype FileCandidateSource = \"default-curated\" | \"tracked-git\" | \"tracked-all-fallback-default\";\ntype OrphanedPathClassification = \"docs_unowned\" | \"tests_unowned\" | \"source_unowned\" | \"unlinked_existing\";\n\nconst FILE_SCAN_DIRECTORIES = [\"src\", \"tests\", \"docs\"] as const;\nconst FILE_SCAN_ROOT_FILES = [\n \"README.md\",\n \"PRD.md\",\n \"CHANGELOG.md\",\n \"AGENTS.md\",\n \"CONTRIBUTING.md\",\n \"SECURITY.md\",\n \"CODE_OF_CONDUCT.md\",\n \"LICENSE\",\n] as const;\nconst DIRECTORY_IGNORE_SET = new Set([\"node_modules\", \".git\", \".cursor\", \".agents\", \"dist\", \"coverage\"]);\nconst RESOLUTION_FIELD_KEYS = [\"resolution\", \"expected_result\", \"actual_result\"] as const;\ntype ResolutionFieldKey = (typeof RESOLUTION_FIELD_KEYS)[number];\nconst VALIDATE_FILE_SCAN_MODES = [\"default\", \"tracked-all\", \"tracked-all-strict\"] as const;\nconst VALIDATE_METADATA_PROFILE_VALUES = [\"core\", \"strict\", \"custom\"] as const;\nconst VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES = [\"off\", \"warn\", \"error\"] as const;\nconst LIFECYCLE_PATTERN_FIELD_KEYS = [\"blocked_reason\", \"resolution\", \"actual_result\"] as const;\ntype LifecyclePatternFieldKey = (typeof LIFECYCLE_PATTERN_FIELD_KEYS)[number];\nconst CORE_METADATA_REQUIRED_FIELDS = [\"author\", \"acceptance_criteria\", \"estimated_minutes\", \"close_reason\"] as const;\nconst STRICT_METADATA_REQUIRED_FIELDS = [\n ...CORE_METADATA_REQUIRED_FIELDS,\n \"reviewer\",\n \"risk\",\n \"confidence\",\n \"sprint\",\n \"release\",\n] as const;\n// Keep this deduplicated so future list edits cannot double-count metadata diagnostics.\nconst SUPPORTED_METADATA_REQUIRED_FIELDS: readonly ValidateMetadataRequiredField[] = Array.from(\n new Set<ValidateMetadataRequiredField>(STRICT_METADATA_REQUIRED_FIELDS),\n);\nconst METADATA_REQUIRED_FIELD_ALIASES: Record<string, ValidateMetadataRequiredField> = {\n author: \"author\",\n acceptance_criteria: \"acceptance_criteria\",\n \"acceptance-criteria\": \"acceptance_criteria\",\n estimated_minutes: \"estimated_minutes\",\n \"estimated-minutes\": \"estimated_minutes\",\n estimate: \"estimated_minutes\",\n close_reason: \"close_reason\",\n \"close-reason\": \"close_reason\",\n reviewer: \"reviewer\",\n risk: \"risk\",\n confidence: \"confidence\",\n sprint: \"sprint\",\n release: \"release\",\n};\nconst METADATA_WARNING_TOKEN_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"validate_metadata_missing_author\",\n acceptance_criteria: \"validate_metadata_missing_acceptance_criteria\",\n estimated_minutes: \"validate_metadata_missing_estimate\",\n close_reason: \"validate_metadata_missing_close_reason\",\n reviewer: \"validate_metadata_missing_reviewer\",\n risk: \"validate_metadata_missing_risk\",\n confidence: \"validate_metadata_missing_confidence\",\n sprint: \"validate_metadata_missing_sprint\",\n release: \"validate_metadata_missing_release\",\n};\nconst METADATA_COUNT_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author\",\n acceptance_criteria: \"missing_acceptance_criteria\",\n estimated_minutes: \"missing_estimated_minutes\",\n close_reason: \"closed_missing_close_reason\",\n reviewer: \"missing_reviewer\",\n risk: \"missing_risk\",\n confidence: \"missing_confidence\",\n sprint: \"missing_sprint\",\n release: \"missing_release\",\n};\nconst METADATA_ITEM_IDS_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author_item_ids\",\n acceptance_criteria: \"missing_acceptance_criteria_item_ids\",\n estimated_minutes: \"missing_estimated_minutes_item_ids\",\n close_reason: \"closed_missing_close_reason_item_ids\",\n reviewer: \"missing_reviewer_item_ids\",\n risk: \"missing_risk_item_ids\",\n confidence: \"missing_confidence_item_ids\",\n sprint: \"missing_sprint_item_ids\",\n release: \"missing_release_item_ids\",\n};\nconst METADATA_TRUNCATED_KEY_BY_FIELD: Record<ValidateMetadataRequiredField, string> = {\n author: \"missing_author_truncated\",\n acceptance_criteria: \"missing_acceptance_criteria_truncated\",\n estimated_minutes: \"missing_estimated_minutes_truncated\",\n close_reason: \"closed_missing_close_reason_truncated\",\n reviewer: \"missing_reviewer_truncated\",\n risk: \"missing_risk_truncated\",\n confidence: \"missing_confidence_truncated\",\n sprint: \"missing_sprint_truncated\",\n release: \"missing_release_truncated\",\n};\nconst GIT_LS_FILES_MAX_BUFFER = 32 * 1024 * 1024;\nconst FILE_LIST_SUMMARY_LIMIT = 40;\nconst DIAGNOSTIC_LIST_SUMMARY_LIMIT = 5;\n// Conservative pre-stat guard for common filesystem limits; over-limit links are unreadable, not prune-safe.\nconst LINKED_ARTIFACT_MAX_PATH_LENGTH = 4096;\nconst LINKED_ARTIFACT_MAX_SEGMENT_LENGTH = 255;\nconst execFileAsync = promisify(execFile);\n\n/**\n * Documents the validate command options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ValidateCommandOptions {\n checkMetadata?: boolean;\n checkResolution?: boolean;\n checkLifecycle?: boolean;\n checkStaleBlockers?: boolean;\n dependencyCycleSeverity?: string;\n parentCycleSeverity?: string;\n checkFiles?: boolean;\n includePmInternals?: boolean;\n verboseFileLists?: boolean;\n verboseDiagnostics?: boolean;\n /** Emit complete *_item_ids diagnostic lists (no 5-item cap); implied by --json. */\n allAffectedIds?: boolean;\n checkHistoryDrift?: boolean;\n checkCommandReferences?: boolean;\n scanMode?: string;\n metadataProfile?: string;\n fixHints?: boolean;\n autoFix?: boolean;\n dryRun?: boolean;\n fixScope?: string[];\n pruneMissing?: boolean;\n}\n\n/**\n * Documents the validate check payload exchanged by command, SDK, and package integrations.\n */\nexport interface ValidateCheck {\n name: ValidateCheckName;\n status: ValidateStatus;\n details: Record<string, unknown>;\n}\n\n/**\n * Documents the validate fixes summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface ValidateFixesSummary {\n mode: \"apply\" | \"dry_run\";\n auto_fix: boolean;\n prune_missing: boolean;\n granted_fix_scopes: string[];\n planned_count: number;\n applied_count: number;\n gated_count: number;\n failed_count: number;\n planned_fixes: Array<Record<string, unknown>>;\n applied_fixes: Array<Record<string, unknown>>;\n gated_fixes: Array<Record<string, unknown>>;\n failed_fixes: Array<Record<string, unknown>>;\n}\n\n/**\n * Documents the validate result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ValidateResult {\n ok: boolean;\n has_warnings: boolean;\n checks: ValidateCheck[];\n warnings: string[];\n /** Present when --auto-fix or --prune-missing was requested; checks always reflect the PRE-fix state. */\n fixes?: ValidateFixesSummary;\n generated_at: string;\n}\n\nfunction normalizeRelativePath(value: string): string {\n return value.replaceAll(\"\\\\\", \"/\").replace(/^\\.\\/+/, \"\").replace(/^\\/+/, \"\");\n}\n\nfunction normalizeRelativeDirectoryPath(value: string): string {\n const normalized = normalizeRelativePath(value);\n return normalized.replace(/\\/+$/, \"\");\n}\n\n\n\nfunction toMeaningfulString(value: unknown): string | undefined {\n const normalized = toNonEmptyStringOrUndefined(value);\n if (!normalized) {\n return undefined;\n }\n const lowered = normalized.toLowerCase();\n if (lowered === \"none\" || lowered === \"null\" || lowered === \"n/a\" || lowered === \"na\") {\n return undefined;\n }\n return normalized;\n}\n\n/* c8 ignore start -- runtime-status alias normalization is covered by status-registry integration tests */\nfunction normalizeStatusForRegistry(status: string, statusRegistry: RuntimeStatusRegistry): string {\n return normalizeStatusInput(status, statusRegistry) ?? status;\n}\n/* c8 ignore stop */\n\nfunction isTerminalStatus(status: string, statusRegistry: RuntimeStatusRegistry): boolean {\n return statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(status, statusRegistry));\n}\n\ninterface ValidateMetadataPolicy {\n profile: ValidateMetadataProfile;\n profile_source: \"default\" | \"settings\" | \"option\";\n required_fields: ValidateMetadataRequiredField[];\n configured_custom_fields: ValidateMetadataRequiredField[];\n fallback_to_core: boolean;\n warnings: string[];\n}\n\ntype LifecyclePatternSource = \"default\" | \"settings\";\n\ninterface LifecyclePatternPolicy {\n stale_blocker_reason_patterns: string[];\n stale_blocker_reason_pattern_source: LifecyclePatternSource;\n closure_like_metadata_field_patterns: Record<LifecyclePatternFieldKey, string[]>;\n closure_like_metadata_field_pattern_sources: Record<LifecyclePatternFieldKey, LifecyclePatternSource>;\n}\n\ninterface LifecyclePatternSettingsSource {\n validation: {\n lifecycle_stale_blocker_reason_patterns: string[];\n lifecycle_closure_like_blocked_reason_patterns: string[];\n lifecycle_closure_like_resolution_patterns: string[];\n lifecycle_closure_like_actual_result_patterns: string[];\n };\n}\n\n/* c8 ignore start -- lifecycle pattern normalization/default-vs-settings matrix is covered by lifecycle integration tests */\nfunction normalizeLifecyclePatternList(values: readonly string[] | undefined): string[] {\n return [...new Set((values ?? []).map((value) => value.trim().toLowerCase()).filter((value) => value.length > 0))].sort(\n (left, right) => left.localeCompare(right),\n );\n}\n\nfunction areSortedStringListsEqual(left: readonly string[], right: readonly string[]): boolean {\n if (left.length !== right.length) {\n return false;\n }\n return left.every((value, index) => value === right[index]);\n}\n\nfunction resolveLifecyclePatternPolicy(settings: LifecyclePatternSettingsSource): LifecyclePatternPolicy {\n const defaultStalePatterns = normalizeLifecyclePatternList(DEFAULT_VALIDATE_STALE_BLOCKER_REASON_PATTERNS);\n const defaultClosureLikePatterns = {\n blocked_reason: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.blocked_reason),\n resolution: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.resolution),\n actual_result: normalizeLifecyclePatternList(DEFAULT_VALIDATE_CLOSURE_LIKE_METADATA_FIELD_PATTERNS.actual_result),\n } satisfies Record<LifecyclePatternFieldKey, string[]>;\n const staleBlockerReasonPatterns = normalizeLifecyclePatternList(\n settings.validation.lifecycle_stale_blocker_reason_patterns,\n );\n const closureLikePatterns = {\n blocked_reason: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_blocked_reason_patterns),\n resolution: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_resolution_patterns),\n actual_result: normalizeLifecyclePatternList(settings.validation.lifecycle_closure_like_actual_result_patterns),\n } satisfies Record<LifecyclePatternFieldKey, string[]>;\n return {\n stale_blocker_reason_patterns: staleBlockerReasonPatterns,\n stale_blocker_reason_pattern_source: areSortedStringListsEqual(staleBlockerReasonPatterns, defaultStalePatterns)\n ? \"default\"\n : \"settings\",\n closure_like_metadata_field_patterns: closureLikePatterns,\n closure_like_metadata_field_pattern_sources: {\n blocked_reason: areSortedStringListsEqual(closureLikePatterns.blocked_reason, defaultClosureLikePatterns.blocked_reason)\n ? \"default\"\n : \"settings\",\n resolution: areSortedStringListsEqual(closureLikePatterns.resolution, defaultClosureLikePatterns.resolution)\n ? \"default\"\n : \"settings\",\n actual_result: areSortedStringListsEqual(closureLikePatterns.actual_result, defaultClosureLikePatterns.actual_result)\n ? \"default\"\n : \"settings\",\n },\n };\n}\n/* c8 ignore stop */\n\nfunction resolveValidateMetadataProfile(value: string | undefined): ValidateMetadataProfile {\n const normalized = value?.trim().toLowerCase();\n if (!normalized || normalized.length === 0) {\n return \"core\";\n }\n if ((VALIDATE_METADATA_PROFILE_VALUES as readonly string[]).includes(normalized)) {\n return normalized as ValidateMetadataProfile;\n }\n throw new PmCliError(\n `Unknown --metadata-profile value \"${value}\". Supported values: ${VALIDATE_METADATA_PROFILE_VALUES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveDependencyCycleSeverity(value: string | undefined): ValidateDependencyCycleSeverity {\n const normalized = value?.trim().toLowerCase();\n if (!normalized || normalized.length === 0) {\n return \"warn\";\n }\n if ((VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES as readonly string[]).includes(normalized)) {\n return normalized as ValidateDependencyCycleSeverity;\n }\n throw new PmCliError(\n `Unknown --dependency-cycle-severity value \"${value}\". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveParentCycleSeverity(value: string | undefined): ValidateDependencyCycleSeverity {\n const normalized = value?.trim().toLowerCase();\n if (!normalized || normalized.length === 0) {\n return \"warn\";\n }\n if ((VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES as readonly string[]).includes(normalized)) {\n return normalized as ValidateDependencyCycleSeverity;\n }\n throw new PmCliError(\n `Unknown --parent-cycle-severity value \"${value}\". Supported values: ${VALIDATE_DEPENDENCY_CYCLE_SEVERITY_VALUES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\n/* c8 ignore start -- metadata required-field alias normalization is covered by metadata-policy integration tests */\nfunction normalizeMetadataRequiredFieldsFromSettings(\n values: readonly ValidateMetadataRequiredField[] | undefined,\n): ValidateMetadataRequiredField[] {\n const normalized = [...new Set((values ?? []).map((value) => value.trim().toLowerCase().replaceAll(\"-\", \"_\")))];\n return normalized\n .map((value) => METADATA_REQUIRED_FIELD_ALIASES[value])\n .filter((value): value is ValidateMetadataRequiredField => value !== undefined)\n .sort((left, right) => left.localeCompare(right));\n}\n/* c8 ignore stop */\n\nfunction resolveValidateMetadataPolicy(\n profile: ValidateMetadataProfile,\n profileSource: \"default\" | \"settings\" | \"option\",\n configuredCustomFields: readonly ValidateMetadataRequiredField[],\n): ValidateMetadataPolicy {\n const normalizedCustomFields = normalizeMetadataRequiredFieldsFromSettings(configuredCustomFields);\n if (profile === \"core\") {\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...CORE_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n if (profile === \"strict\") {\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...STRICT_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n if (normalizedCustomFields.length > 0) {\n return {\n profile,\n profile_source: profileSource,\n required_fields: normalizedCustomFields,\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: false,\n warnings: [],\n };\n }\n return {\n profile,\n profile_source: profileSource,\n required_fields: [...CORE_METADATA_REQUIRED_FIELDS],\n configured_custom_fields: normalizedCustomFields,\n fallback_to_core: true,\n warnings: [\"validate_metadata_custom_profile_missing_required_fields:0\"],\n };\n}\n\n/**\n * Planning fields whose absence is only actionable on live work (GH-276): an\n * agent backfills an estimate or acceptance criteria to plan/execute an item,\n * so flagging them on a terminal (closed/canceled) historical item is pure\n * noise. Under the `strict` profile these are still enforced everywhere for\n * projects that want full historical coverage.\n */\nconst TERMINAL_EXEMPT_PLANNING_FIELDS: ReadonlySet<ValidateMetadataRequiredField> = new Set([\n \"acceptance_criteria\",\n \"estimated_minutes\",\n]);\n\nfunction isMetadataFieldMissing(\n item: ItemWithBody,\n field: ValidateMetadataRequiredField,\n statusRegistry: RuntimeStatusRegistry,\n enforcePlanningFieldsOnTerminal: boolean,\n): boolean {\n // GH-276: skip planning-field gaps on retired (closed/canceled) items unless\n // the resolved profile explicitly demands strict historical coverage.\n if (\n !enforcePlanningFieldsOnTerminal &&\n TERMINAL_EXEMPT_PLANNING_FIELDS.has(field) &&\n isTerminalStatus(item.status, statusRegistry)\n ) {\n return false;\n }\n if (field === \"author\") {\n return !toNonEmptyStringOrUndefined(item.author);\n }\n if (field === \"acceptance_criteria\") {\n return !toNonEmptyStringOrUndefined(item.acceptance_criteria);\n }\n if (field === \"estimated_minutes\") {\n return !Number.isFinite(item.estimated_minutes);\n }\n if (field === \"close_reason\") {\n return normalizeStatusForRegistry(item.status, statusRegistry) === statusRegistry.close_status && !toNonEmptyStringOrUndefined(item.close_reason);\n }\n if (field === \"reviewer\") {\n return !toNonEmptyStringOrUndefined(item.reviewer);\n }\n if (field === \"risk\") {\n return !toNonEmptyStringOrUndefined(item.risk);\n }\n if (field === \"confidence\") {\n if (typeof item.confidence === \"number\") {\n return !Number.isFinite(item.confidence);\n }\n return !toNonEmptyStringOrUndefined(item.confidence);\n }\n if (field === \"sprint\") {\n return !toNonEmptyStringOrUndefined(item.sprint);\n }\n return !toNonEmptyStringOrUndefined(item.release);\n}\n\nfunction resolveFileScanMode(scanMode: string | undefined): ValidateFileScanMode {\n if (scanMode === undefined) {\n return \"default\";\n }\n const normalized = scanMode.trim().toLowerCase();\n if (normalized.length === 0) {\n return \"default\";\n }\n if (normalized === \"default\") {\n return \"default\";\n }\n if (normalized === \"tracked-all\" || normalized === \"tracked_all\") {\n return \"tracked-all\";\n }\n if (normalized === \"tracked-all-strict\" || normalized === \"tracked_all_strict\") {\n return \"tracked-all-strict\";\n }\n throw new PmCliError(\n `Unknown --scan-mode value \"${scanMode}\". Supported values: ${VALIDATE_FILE_SCAN_MODES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n}\n\nfunction resolveWorkspaceRoot(pmRoot: string): string {\n const resolvedPmRoot = path.resolve(pmRoot);\n const normalizedPmRoot = resolvedPmRoot.replaceAll(\"\\\\\", \"/\");\n if (normalizedPmRoot.endsWith(\"/.agents/pm\")) {\n return path.dirname(path.dirname(resolvedPmRoot));\n }\n const resolvedCwd = path.resolve(process.cwd());\n const canonicalPmRoot = realpathForWorkspaceRoot(resolvedPmRoot);\n const canonicalCwd = realpathForWorkspaceRoot(resolvedCwd);\n const relativeFromPmRoot = path.relative(canonicalPmRoot, canonicalCwd);\n const cwdInsidePmRoot =\n relativeFromPmRoot.length === 0 ||\n (!relativeFromPmRoot.startsWith(\"..\") && !path.isAbsolute(relativeFromPmRoot));\n if (cwdInsidePmRoot) {\n return resolvedPmRoot;\n }\n /* c8 ignore next 2 -- non-standard PM root layouts are integration-only edge cases. */\n return resolvedCwd;\n}\n\nfunction realpathForWorkspaceRoot(inputPath: string): string {\n try {\n return realpathSync.native(inputPath);\n } catch {\n return path.resolve(inputPath);\n }\n}\n\n/* c8 ignore start -- recursive file-walk dirent/permission edge cases are covered by filesystem integration suites */\nasync function listFilesRecursive(basePath: string, relativePath: string, output: string[]): Promise<void> {\n const targetDirectory = relativePath.length > 0 ? path.join(basePath, relativePath) : basePath;\n let entries: Dirent[];\n try {\n entries = await fs.readdir(targetDirectory, { withFileTypes: true });\n } catch (error: unknown) {\n if (typeof error === \"object\" && error !== null && \"code\" in error && (error as { code?: string }).code === \"ENOENT\") {\n return;\n }\n throw error;\n }\n\n for (const entry of entries) {\n if (entry.name.startsWith(\".\")) {\n continue;\n }\n const childRelative = relativePath.length > 0 ? path.join(relativePath, entry.name) : entry.name;\n if (entry.isDirectory()) {\n if (DIRECTORY_IGNORE_SET.has(entry.name)) {\n continue;\n }\n await listFilesRecursive(basePath, childRelative, output);\n continue;\n }\n /* c8 ignore next 3 -- non-file dirent variants (symlink/socket) are filesystem-specific. */\n if (!entry.isFile()) {\n continue;\n }\n output.push(normalizeRelativePath(childRelative));\n }\n}\n/* c8 ignore stop */\n\nasync function collectDefaultProjectFileCandidates(workspaceRoot: string): Promise<string[]> {\n const discovered: string[] = [];\n for (const directory of FILE_SCAN_DIRECTORIES) {\n await listFilesRecursive(workspaceRoot, directory, discovered);\n }\n for (const candidate of FILE_SCAN_ROOT_FILES) {\n const absolute = path.join(workspaceRoot, candidate);\n try {\n const stats = await fs.stat(absolute);\n /* c8 ignore start -- root-candidate presence depends on fixture workspace composition. */\n if (stats.isFile()) {\n discovered.push(normalizeRelativePath(candidate));\n }\n /* c8 ignore stop */\n } catch {\n // Ignore root-file candidates that are not present in this workspace.\n }\n }\n return [...new Set(discovered)].sort((left, right) => left.localeCompare(right));\n}\n\nasync function collectTrackedGitFileCandidates(workspaceRoot: string): Promise<string[] | null> {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"ls-files\", \"-z\"], {\n cwd: workspaceRoot,\n encoding: \"utf8\",\n maxBuffer: GIT_LS_FILES_MAX_BUFFER,\n windowsHide: true,\n });\n const discovered = stdout\n .split(\"\\0\")\n .map((value) => normalizeRelativePath(value))\n .filter((value) => value.length > 0);\n return [...new Set(discovered)].sort((left, right) => left.localeCompare(right));\n } catch {\n /* c8 ignore start -- fallback path exercised only when git metadata is unavailable. */\n return null;\n /* c8 ignore stop */\n }\n}\n\ninterface FileCandidateCollection {\n requestedMode: ValidateFileScanMode;\n appliedMode: ValidateFileScanMode;\n source: FileCandidateSource;\n candidateFiles: string[];\n candidateTotal: number;\n candidateScanned: number;\n}\n\n/* c8 ignore start -- PM-internal prefix derivation permutations are covered by file-scan integration tests */\nfunction resolvePmInternalCandidatePrefixes(pmRoot: string, workspaceRoot: string): string[] {\n const prefixes = new Set<string>();\n const configuredDefault = normalizeRelativeDirectoryPath(PM_DIRNAME);\n if (configuredDefault.length > 0) {\n prefixes.add(configuredDefault);\n }\n const relativePmRoot = normalizeRelativeDirectoryPath(path.relative(workspaceRoot, pmRoot));\n if (relativePmRoot.length > 0 && !relativePmRoot.startsWith(\"..\")) {\n prefixes.add(relativePmRoot);\n }\n return [...prefixes].sort((left, right) => left.localeCompare(right));\n}\n/* c8 ignore stop */\n\nfunction hasPathPrefix(candidate: string, prefixes: string[]): boolean {\n for (const prefix of prefixes) {\n if (candidate === prefix || candidate.startsWith(`${prefix}/`)) {\n return true;\n }\n }\n return false;\n}\n\nasync function collectProjectFileCandidates(\n workspaceRoot: string,\n scanMode: ValidateFileScanMode,\n): Promise<FileCandidateCollection> {\n if (scanMode === \"tracked-all\" || scanMode === \"tracked-all-strict\") {\n const trackedCandidates = await collectTrackedGitFileCandidates(workspaceRoot);\n /* c8 ignore start -- tracked-git availability fallback is covered by git/non-git integration fixtures */\n if (trackedCandidates) {\n return {\n requestedMode: scanMode,\n appliedMode: scanMode,\n source: \"tracked-git\",\n candidateFiles: trackedCandidates,\n candidateTotal: trackedCandidates.length,\n candidateScanned: trackedCandidates.length,\n };\n }\n /* c8 ignore stop */\n /* c8 ignore start -- deterministic fallback retained for non-git workspaces. */\n const fallbackCandidates = await collectDefaultProjectFileCandidates(workspaceRoot);\n return {\n requestedMode: scanMode,\n appliedMode: \"default\",\n source: \"tracked-all-fallback-default\",\n candidateFiles: fallbackCandidates,\n candidateTotal: fallbackCandidates.length,\n candidateScanned: fallbackCandidates.length,\n };\n /* c8 ignore stop */\n }\n\n const defaultCandidates = await collectDefaultProjectFileCandidates(workspaceRoot);\n return {\n requestedMode: scanMode,\n appliedMode: \"default\",\n source: \"default-curated\",\n candidateFiles: defaultCandidates,\n candidateTotal: defaultCandidates.length,\n candidateScanned: defaultCandidates.length,\n };\n}\n\nfunction summarizeList(values: string[], limit = DIAGNOSTIC_LIST_SUMMARY_LIMIT): { values: string[]; truncated: boolean } {\n /* c8 ignore start -- truncation behavior only surfaces with very large synthetic datasets. */\n if (values.length <= limit) {\n return { values, truncated: false };\n }\n return {\n values: values.slice(0, limit),\n truncated: true,\n };\n /* c8 ignore stop */\n}\n\nfunction summarizeFileList(\n values: string[],\n verboseFileLists: boolean,\n): {\n values: string[];\n truncated: boolean;\n total: number;\n} {\n if (verboseFileLists) {\n return {\n values,\n truncated: false,\n total: values.length,\n };\n }\n const summary = summarizeList(values, FILE_LIST_SUMMARY_LIMIT);\n return {\n values: summary.values,\n truncated: summary.truncated,\n total: values.length,\n };\n}\n\nconst RESOLUTION_REMEDIATION_FLAG_BY_FIELD: Record<ResolutionFieldKey, string> = {\n resolution: \"--resolution\",\n expected_result: \"--expected-result\",\n actual_result: \"--actual-result\",\n};\n\nconst RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD: Record<ResolutionFieldKey, string> = {\n resolution: \"Describe how this item was resolved\",\n expected_result: \"Describe the expected result\",\n actual_result: \"Describe the actual result\",\n};\n\nfunction buildResolutionRemediationCommand(row: { id: string; missing_fields: ResolutionFieldKey[] }): string {\n const fieldArguments = row.missing_fields\n .map((field) => `${RESOLUTION_REMEDIATION_FLAG_BY_FIELD[field]} \"${RESOLUTION_REMEDIATION_PLACEHOLDER_BY_FIELD[field]}\"`)\n .join(\" \");\n return `pm update ${row.id} ${fieldArguments} --message \"Backfill resolution metadata\"`;\n}\n\n/**\n * Attach a uniform, machine-executable `fix_hints` array to a validate check's\n * details when `--fix-hints` is requested. The resolution check's existing\n * per-row remediation commands (which already carry concrete item ids) are\n * aliased in so agents read one uniform field across every check; all other\n * checks derive one generic command per distinct warning code from the shared\n * remediation registry. Generic hints may contain `<id>`/`<field>`/`<path>`\n * placeholders the caller substitutes before running — they are templates, not\n * always directly executable as-is. Read-only: this only enriches the diagnostic\n * output, never mutates any item.\n */\n/* c8 ignore start -- fix-hint projection/truncation combinations are covered by validate output integration tests */\nfunction attachValidateFixHints(check: ValidateCheck, checkWarnings: string[]): void {\n const existingResolutionHints = check.details?.missing_resolution_remediation_hints;\n const aliasedResolution = Array.isArray(existingResolutionHints) && existingResolutionHints.length > 0;\n const fixHints = aliasedResolution\n ? (existingResolutionHints as unknown[]).filter((hint): hint is string => typeof hint === \"string\")\n : buildRemediationCommands(checkWarnings);\n if (fixHints.length === 0) {\n return;\n }\n // The resolution check truncates its per-row hint list for low-token output;\n // carry that marker onto fix_hints so an agent knows the list is partial and\n // there are more items to repair beyond the ones shown.\n const truncated = aliasedResolution && check.details?.missing_resolution_remediation_hints_truncated === true;\n check.details = {\n ...check.details,\n fix_hints: fixHints,\n ...(truncated ? { fix_hints_truncated: true } : {}),\n };\n}\n/* c8 ignore stop */\n\nfunction resolveRequestedChecks(options: ValidateCommandOptions): Set<ValidateCheckName> {\n const requested = new Set<ValidateCheckName>();\n if (options.checkMetadata) {\n requested.add(\"metadata\");\n }\n if (options.checkResolution) {\n requested.add(\"resolution\");\n }\n if (options.checkLifecycle || options.checkStaleBlockers) {\n requested.add(\"lifecycle\");\n }\n if (options.checkFiles) {\n requested.add(\"files\");\n }\n if (options.checkHistoryDrift) {\n requested.add(\"history_drift\");\n }\n if (options.checkCommandReferences) {\n requested.add(\"command_references\");\n }\n if (requested.size === 0) {\n // Remediation flags without explicit --check-* flags scope the run to the\n // checks that can produce fixes: --auto-fix plans metadata/resolution\n // backfills and gated lifecycle fixes; --prune-missing needs the files\n // scan. With neither, the historical run-everything default applies.\n if (options.autoFix) {\n requested.add(\"metadata\");\n requested.add(\"resolution\");\n requested.add(\"lifecycle\");\n }\n if (options.pruneMissing) {\n requested.add(\"files\");\n }\n if (requested.size === 0) {\n requested.add(\"metadata\");\n requested.add(\"resolution\");\n requested.add(\"lifecycle\");\n requested.add(\"files\");\n requested.add(\"command_references\");\n requested.add(\"history_drift\");\n requested.add(\"format_version\");\n }\n return requested;\n }\n // Explicit check flags are respected as-is, except --prune-missing always\n // needs the files scan it acts on.\n if (options.pruneMissing) {\n requested.add(\"files\");\n }\n return requested;\n}\n\nconst DUPLICATE_ISSUE_CODE_WARNING_TOKEN = \"validate_metadata_duplicate_issue_codes\";\n\n/**\n * Project the duplicate logical issue-code findings (GH-235) into the\n * metadata-check `details` shape plus an advisory warning token. Duplicate\n * codes are advisory (warn), never an error — matching every other metadata\n * finding — so an otherwise clean tracker that simply reuses a title prefix is\n * not failed by `pm validate`. Kept outside the c8-ignored builder block so the\n * projection/remediation logic is fully covered by unit tests.\n */\nfunction summarizeDuplicateIssueCodes(\n duplicates: DuplicateIssueCode[],\n verboseDiagnostics: boolean,\n): { rows: Array<Record<string, unknown>>; truncated: boolean; warnings: string[] } {\n if (duplicates.length === 0) {\n return { rows: [], truncated: false, warnings: [] };\n }\n const limit = verboseDiagnostics ? duplicates.length : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const shown = duplicates.slice(0, limit);\n const rows = shown.map((duplicate) => ({\n code: duplicate.code,\n count: duplicate.count,\n ids: duplicate.ids,\n titles: duplicate.titles,\n remediation_hint: `Items ${duplicate.ids.join(\", \")} share issue code \"${duplicate.code}\"; rename or merge so each logical code maps to one item.`,\n }));\n return {\n rows,\n truncated: shown.length < duplicates.length,\n warnings: [`${DUPLICATE_ISSUE_CODE_WARNING_TOKEN}:${duplicates.length}`],\n };\n}\n\nfunction initializeMissingMetadataByField(): Record<ValidateMetadataRequiredField, string[]> {\n return Object.fromEntries(\n SUPPORTED_METADATA_REQUIRED_FIELDS.map((field) => [field, [] as string[]]),\n ) as Record<ValidateMetadataRequiredField, string[]>;\n}\n\nfunction collectMissingMetadataByField(\n items: ItemWithBody[],\n statusRegistry: RuntimeStatusRegistry,\n enforcePlanningFieldsOnTerminal: boolean,\n): Record<ValidateMetadataRequiredField, string[]> {\n const missingByField = initializeMissingMetadataByField();\n for (const item of items) {\n for (const field of SUPPORTED_METADATA_REQUIRED_FIELDS) {\n if (isMetadataFieldMissing(item, field, statusRegistry, enforcePlanningFieldsOnTerminal)) {\n missingByField[field].push(item.id);\n }\n }\n }\n return missingByField;\n}\n\nfunction buildMetadataWarningTokens(\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n duplicateWarnings: string[],\n): string[] {\n const warningTokens = [...metadataPolicy.warnings];\n for (const field of metadataPolicy.required_fields) {\n const missingItems = missingByField[field];\n if (missingItems.length > 0) {\n warningTokens.push(`${METADATA_WARNING_TOKEN_BY_FIELD[field]}:${missingItems.length}`);\n }\n }\n warningTokens.push(...duplicateWarnings);\n return warningTokens;\n}\n\nfunction buildMetadataCounts(\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const field of metadataPolicy.required_fields) {\n const missing = missingByField[field];\n const value = missing ? missing.length : 0;\n const countKey = METADATA_COUNT_KEY_BY_FIELD[field];\n if (value > 0 && countKey) {\n counts[countKey] = value;\n }\n }\n return counts;\n}\n\nfunction buildMissingFieldOccurrences(\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n itemsById: Map<string, ItemWithBody>,\n): MissingFieldOccurrence[] {\n const occurrences: MissingFieldOccurrence[] = [];\n for (const field of metadataPolicy.required_fields) {\n const missing = missingByField[field];\n if (!missing) {\n continue;\n }\n for (const itemId of missing) {\n const itemType = itemsById.get(itemId)?.type;\n const normalizedItemType = typeof itemType === \"string\" && itemType.length > 0 ? itemType : \"Unknown\";\n occurrences.push({ item_type: normalizedItemType, field });\n }\n }\n return occurrences;\n}\n\n/* v8 ignore start -- metadata policy keys are validated before this summarizer; fallback branches are defensive */\nfunction attachMissingMetadataItemIds(\n details: Record<string, unknown>,\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n verboseDiagnostics: boolean,\n): void {\n for (const field of metadataPolicy.required_fields) {\n const missing = missingByField[field];\n if (!missing || missing.length === 0) {\n continue;\n }\n const idsKey = METADATA_ITEM_IDS_KEY_BY_FIELD[field];\n const truncatedKey = METADATA_TRUNCATED_KEY_BY_FIELD[field];\n if (!idsKey || !truncatedKey) {\n continue;\n }\n const summarized = summarizeList(missing, verboseDiagnostics ? missing.length : DIAGNOSTIC_LIST_SUMMARY_LIMIT);\n details[idsKey] = summarized.values;\n details[truncatedKey] = summarized.truncated;\n }\n}\n/* v8 ignore stop */\n\nfunction buildCloseReasonBackfillRows(\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n itemsById: Map<string, ItemWithBody>,\n): CloseReasonBackfillRow[] {\n if (!metadataPolicy.required_fields.includes(\"close_reason\")) {\n return [];\n }\n const missing = missingByField.close_reason;\n if (!missing) {\n return [];\n }\n return missing.map((itemId) => ({\n id: itemId,\n resolution: toNonEmptyStringOrUndefined(itemsById.get(itemId)?.resolution),\n }));\n}\n\nfunction buildEstimateBackfillRows(\n metadataPolicy: ValidateMetadataPolicy,\n missingByField: Record<ValidateMetadataRequiredField, string[]>,\n itemsById: Map<string, ItemWithBody>,\n): EstimateBackfillRow[] {\n if (!metadataPolicy.required_fields.includes(\"estimated_minutes\")) {\n return [];\n }\n const missing = missingByField.estimated_minutes;\n if (!missing) {\n return [];\n }\n return missing.map((itemId) => ({\n id: itemId,\n type: toNonEmptyStringOrUndefined(itemsById.get(itemId)?.type),\n }));\n}\n\n/* c8 ignore start -- metadata diagnostics/backfill planning permutations are covered by validate integration suites */\nfunction buildMetadataCheck(\n items: ItemWithBody[],\n metadataPolicy: ValidateMetadataPolicy,\n statusRegistry: RuntimeStatusRegistry,\n verboseDiagnostics: boolean,\n): {\n check: ValidateCheck;\n warnings: string[];\n closeReasonBackfillRows: CloseReasonBackfillRow[];\n estimateBackfillRows: EstimateBackfillRow[];\n} {\n const itemsById = new Map(items.map((item) => [item.id, item]));\n\n // GH-276: only the `strict` profile enforces planning fields on terminal\n // (closed/canceled) historical items; core/minimal/custom profiles treat a\n // retired item's missing estimate or acceptance criteria as resolved.\n const enforcePlanningFieldsOnTerminal = metadataPolicy.profile === \"strict\";\n const missingByField = collectMissingMetadataByField(items, statusRegistry, enforcePlanningFieldsOnTerminal);\n\n // Duplicate logical issue-code detection (GH-235): advisory warning when two\n // or more items share a leading title issue code (e.g. `ISSUE-004`).\n const duplicateIssueCodes = findDuplicateIssueCodes(items);\n const duplicateIssueCodeSummary = summarizeDuplicateIssueCodes(duplicateIssueCodes, verboseDiagnostics);\n const warningTokens = buildMetadataWarningTokens(metadataPolicy, missingByField, duplicateIssueCodeSummary.warnings);\n\n // Zero-suppress counts to reduce agent token cost (telemetry pm-tylj).\n // Only emit counts for the ACTIVE required fields of the resolved profile so a\n // looser profile (e.g. core) never reports missing reviewer/risk/sprint/etc.\n // Defensive guards (Gemini high #1, PR #78 follow-up): a future settings\n // shape could include an unsupported field in required_fields — fall back\n // to 0 instead of throwing TypeError, and skip writing when the count-key\n // mapping is undefined.\n const counts = buildMetadataCounts(metadataPolicy, missingByField);\n // Per-item-type grouping of missing required-field counts (pm-pmyq /\n // GH-172): counts only — never row dumps — and only for the ACTIVE required\n // fields, so the grouping mirrors `counts` at type granularity (e.g.\n // `{ Task: { close_reason: 3 } }`). Zero-suppressed at both levels.\n const missingFieldOccurrences = buildMissingFieldOccurrences(metadataPolicy, missingByField, itemsById);\n const missingByType = buildMissingByTypeCounts(missingFieldOccurrences);\n const details: Record<string, unknown> = {\n checked_items: items.length,\n metadata_profile: metadataPolicy.profile,\n metadata_profile_source: metadataPolicy.profile_source,\n metadata_profile_fallback_to_core: metadataPolicy.fallback_to_core,\n required_fields: [...metadataPolicy.required_fields],\n supported_required_fields: [...SUPPORTED_METADATA_REQUIRED_FIELDS],\n counts,\n missing_by_type: missingByType,\n duplicate_issue_codes_count: duplicateIssueCodes.length,\n duplicate_issue_codes: duplicateIssueCodeSummary.rows,\n duplicate_issue_codes_truncated: duplicateIssueCodeSummary.truncated,\n };\n if (metadataPolicy.configured_custom_fields.length > 0) {\n details.configured_custom_required_fields = [...metadataPolicy.configured_custom_fields];\n }\n\n // Only emit per-field item_ids/truncated keys for the ACTIVE required fields of\n // the resolved profile (and only when there are missing items). This stops a\n // looser profile (e.g. core) from emitting the identical full ID array for\n // reviewer/risk/confidence/sprint/release that it does not even require\n // (pm-edge #2 — ~150 redundant lines per validate run on minimal/core).\n // Defensive guard (Gemini high #2, PR #78 follow-up): same optional-chain\n // safety as the counts loop above — never throw if a future settings shape\n // includes an unsupported field.\n attachMissingMetadataItemIds(details, metadataPolicy, missingByField, verboseDiagnostics);\n\n // Auto-fix planning input (pm-c3sz): closed items flagged for a missing\n // close_reason whose resolution can serve as the derivable source value.\n // Only collected when close_reason is an active required field, so fixes\n // always trace back to an actual finding of this run.\n const closeReasonBackfillRows = buildCloseReasonBackfillRows(metadataPolicy, missingByField, itemsById);\n\n // Estimate auto-fix planning input (GH-212): items flagged for a missing\n // estimated_minutes whose type drives the config-driven default backfill.\n // Only collected when estimated_minutes is an active required field, so fixes\n // always trace back to an actual finding of this run.\n const estimateBackfillRows = buildEstimateBackfillRows(metadataPolicy, missingByField, itemsById);\n\n return {\n check: {\n name: \"metadata\",\n status: warningTokens.length === 0 ? \"ok\" : \"warn\",\n details,\n },\n warnings: warningTokens,\n closeReasonBackfillRows,\n estimateBackfillRows,\n };\n}\n/* c8 ignore stop */\n\nfunction buildResolutionCheck(\n items: ItemWithBody[],\n statusRegistry: RuntimeStatusRegistry,\n verboseDiagnostics: boolean,\n): { check: ValidateCheck; warnings: string[]; resolutionBackfillRows: ResolutionBackfillRow[] } {\n const terminalDoneStatuses = new Set<string>(statusRegistry.terminal_done_statuses);\n terminalDoneStatuses.add(statusRegistry.close_status);\n const closedItems = items.filter((item) => terminalDoneStatuses.has(normalizeStatusForRegistry(item.status, statusRegistry)));\n const missingResolutionRows: Array<{ id: string; missing_fields: ResolutionFieldKey[] }> = [];\n const resolutionBackfillRows: ResolutionBackfillRow[] = [];\n\n for (const item of closedItems) {\n const missingFields = RESOLUTION_FIELD_KEYS.filter((field) => !toNonEmptyStringOrUndefined(item[field]));\n if (missingFields.length === 0) {\n continue;\n }\n missingResolutionRows.push({\n id: item.id,\n missing_fields: missingFields,\n });\n // Auto-fix planning input (pm-c3sz): the planner backfills only the\n // `resolution` field, deriving from the item's close_reason when present.\n resolutionBackfillRows.push({\n id: item.id,\n missing_fields: missingFields,\n close_reason: toNonEmptyStringOrUndefined(item.close_reason),\n });\n }\n\n const warnings =\n missingResolutionRows.length > 0 ? [`validate_resolution_missing_fields:${missingResolutionRows.length}`] : [];\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedRows = summarizeList(\n missingResolutionRows.map((row) => `${row.id}:${row.missing_fields.join(\",\")}`),\n diagnosticLimit,\n );\n const remediationHints = missingResolutionRows.map((row) => buildResolutionRemediationCommand(row));\n const summarizedHints = summarizeList(remediationHints, diagnosticLimit);\n return {\n check: {\n name: \"resolution\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_closed_items: closedItems.length,\n missing_resolution_items: missingResolutionRows.length,\n missing_resolution_rows: summarizedRows.values,\n missing_resolution_rows_truncated: summarizedRows.truncated,\n missing_resolution_remediation_hints: summarizedHints.values,\n missing_resolution_remediation_hints_truncated: summarizedHints.truncated,\n },\n },\n warnings,\n resolutionBackfillRows,\n };\n}\n\n/* c8 ignore start -- lifecycle dependency-graph cycle analysis is covered by lifecycle integration fixtures */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction buildLifecycleDependencyGraph(activeItems: ItemWithBody[], idPrefix = \"pm\"): Map<string, string[]> {\n const activeItemIds = new Set(activeItems.map((item) => item.id));\n const graph = new Map<string, string[]>();\n const sortedItems = [...activeItems].sort((left, right) => left.id.localeCompare(right.id));\n for (const item of sortedItems) {\n const edges = new Set<string>();\n const blockedBy = toMeaningfulString(item.blocked_by);\n if (blockedBy && activeItemIds.has(blockedBy)) {\n edges.add(blockedBy);\n }\n for (const dependency of item.dependencies ?? []) {\n const dependencyId = toMeaningfulString(dependency.id);\n if (!dependencyId || !activeItemIds.has(dependencyId)) {\n continue;\n }\n edges.add(dependencyId);\n }\n const definitionOfReady = toMeaningfulString(item.definition_of_ready);\n if (definitionOfReady) {\n for (const referencedId of extractItemIds(definitionOfReady, idPrefix)) {\n if (activeItemIds.has(referencedId)) {\n edges.add(referencedId);\n }\n }\n }\n graph.set(item.id, [...edges].sort((left, right) => left.localeCompare(right)));\n }\n return graph;\n}\n/* c8 ignore stop */\n\nfunction extractItemIds(value: string, idPrefix = \"pm\"): string[] {\n const normalizedPrefix = (idPrefix.trim().toLowerCase() || \"pm\").replace(/-+$/g, \"\");\n const pattern = new RegExp(`(?:^|[^a-z0-9-])(${escapeRegExp(normalizedPrefix)}-[a-z0-9][a-z0-9-]*)`, \"gi\");\n return [...new Set([...value.matchAll(pattern)].map((match) => match[1]!.toLowerCase()))].sort(\n (left, right) => left.localeCompare(right),\n );\n}\n\n/* c8 ignore start -- Tarjan SCC traversal branch matrix is covered by lifecycle cycle integration fixtures */\nfunction findLifecycleDependencyCycleComponents(graph: Map<string, string[]>): string[][] {\n let nextIndex = 0;\n const indexById = new Map<string, number>();\n const lowLinkById = new Map<string, number>();\n const stack: string[] = [];\n const inStack = new Set<string>();\n const components: string[][] = [];\n\n const visit = (id: string): void => {\n indexById.set(id, nextIndex);\n lowLinkById.set(id, nextIndex);\n nextIndex += 1;\n stack.push(id);\n inStack.add(id);\n\n for (const dependencyId of graph.get(id) ?? []) {\n if (!indexById.has(dependencyId)) {\n visit(dependencyId);\n lowLinkById.set(id, Math.min(lowLinkById.get(id)!, lowLinkById.get(dependencyId)!));\n } else if (inStack.has(dependencyId)) {\n lowLinkById.set(id, Math.min(lowLinkById.get(id)!, indexById.get(dependencyId)!));\n }\n }\n\n if (lowLinkById.get(id) !== indexById.get(id)) {\n return;\n }\n const component: string[] = [];\n while (stack.length > 0) {\n const member = stack.pop()!;\n inStack.delete(member);\n component.push(member);\n if (member === id) {\n break;\n }\n }\n component.sort((left, right) => left.localeCompare(right));\n components.push(component);\n };\n\n const sortedNodeIds = [...graph.keys()].sort((left, right) => left.localeCompare(right));\n for (const id of sortedNodeIds) {\n if (!indexById.has(id)) {\n visit(id);\n }\n }\n\n const cycleComponents = components.filter((component) => {\n if (component.length > 1) {\n return true;\n }\n const selfId = component[0];\n return (graph.get(selfId) ?? []).includes(selfId);\n });\n return cycleComponents.sort(\n (left, right) =>\n left[0].localeCompare(right[0]) ||\n left.length - right.length ||\n left.join(\",\").localeCompare(right.join(\",\")),\n );\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- cycle sample-path fallback branches are covered by lifecycle graph integration tests */\nfunction resolveLifecycleDependencyCycleSamplePath(component: string[], graph: Map<string, string[]>): string[] {\n const start = component[0];\n if (component.length === 1) {\n return [start, start];\n }\n const componentSet = new Set(component);\n const path: string[] = [start];\n const visited = new Set<string>([start]);\n\n const search = (current: string): boolean => {\n const neighbors = (graph.get(current) ?? []).filter((candidate) => componentSet.has(candidate));\n for (const next of neighbors) {\n if (next === start && path.length > 1) {\n path.push(start);\n return true;\n }\n if (visited.has(next)) {\n continue;\n }\n visited.add(next);\n path.push(next);\n if (search(next)) {\n return true;\n }\n path.pop();\n visited.delete(next);\n }\n return false;\n };\n\n if (search(start)) {\n return [...path];\n }\n return [...component, start];\n}\n/* c8 ignore stop */\n\nfunction detectLifecycleDependencyCycles(activeItems: ItemWithBody[], idPrefix = \"pm\"): {\n cycle_count: number;\n cycle_item_ids: string[];\n cycle_sample_paths: string[];\n} {\n const graph = buildLifecycleDependencyGraph(activeItems, idPrefix);\n const cycleComponents = findLifecycleDependencyCycleComponents(graph);\n const cycleItemIds = [...new Set(cycleComponents.flat())].sort((left, right) => left.localeCompare(right));\n const cycleSamplePaths = cycleComponents.map((component) =>\n resolveLifecycleDependencyCycleSamplePath(component, graph).join(\"->\"),\n );\n return {\n cycle_count: cycleComponents.length,\n cycle_item_ids: cycleItemIds,\n cycle_sample_paths: cycleSamplePaths,\n };\n}\n\n// Parent (composition) cycle detection (pm-8vul / GH-280). The dependency-cycle\n// path above only walks blocked_by/definition_of_ready edges across ACTIVE items;\n// it never traverses item.parent, so a parent cycle (A.parent=B, B.parent=A, or\n// any longer ring) goes undetected while it silently breaks `pm list --tree`,\n// orphan detection, and progress rollups. We reuse the generic Tarjan SCC helper\n// on a child->[parent] adjacency map. Unlike dependency cycles we scan ALL items\n// (not just active ones) because a parent cycle among closed items is still\n// structural corruption of the hierarchy.\nfunction buildLifecycleParentGraph(items: ItemWithBody[]): Map<string, string[]> {\n // PR #279 made parent matching case-insensitive (e.g. `parent: PM-FK49`\n // resolves to `id: pm-fk49`). Resolve parent references to their canonical\n // item id the same way so a casing mismatch can never silently drop a cycle\n // edge and hide a parent cycle (false negative).\n const canonicalIdByLowercase = new Map(items.map((item) => [item.id.toLowerCase(), item.id]));\n const graph = new Map<string, string[]>();\n const sortedItems = [...items].sort((left, right) => left.id.localeCompare(right.id));\n for (const item of sortedItems) {\n const edges: string[] = [];\n const parentId = toMeaningfulString(item.parent);\n const canonicalParentId = parentId ? canonicalIdByLowercase.get(parentId.toLowerCase()) : undefined;\n if (canonicalParentId) {\n edges.push(canonicalParentId);\n }\n graph.set(item.id, edges);\n }\n return graph;\n}\n\nfunction detectLifecycleParentCycles(items: ItemWithBody[]): {\n cycle_count: number;\n cycle_item_ids: string[];\n cycle_sample_paths: string[];\n} {\n const graph = buildLifecycleParentGraph(items);\n const cycleComponents = findLifecycleDependencyCycleComponents(graph);\n const cycleItemIds = [...new Set(cycleComponents.flat())].sort((left, right) => left.localeCompare(right));\n const cycleSamplePaths = cycleComponents.map((component) =>\n resolveLifecycleDependencyCycleSamplePath(component, graph).join(\"->\"),\n );\n return {\n cycle_count: cycleComponents.length,\n cycle_item_ids: cycleItemIds,\n cycle_sample_paths: cycleSamplePaths,\n };\n}\n\ninterface OrphanedPathRow {\n path: string;\n classification: OrphanedPathClassification;\n owner_candidate: {\n id: string;\n type: string;\n title: string;\n status: string;\n confidence: \"path_prefix\" | \"same_directory\" | \"shared_directory\";\n } | null;\n remediation_hint: string;\n}\n\nfunction classifyOrphanedPath(pathValue: string): OrphanedPathClassification {\n if (pathValue.startsWith(\"docs/\")) {\n return \"docs_unowned\";\n }\n if (pathValue.startsWith(\"tests/\")) {\n return \"tests_unowned\";\n }\n if (pathValue.startsWith(\"src/\")) {\n return \"source_unowned\";\n }\n if (pathValue.endsWith(\".md\")) {\n return \"docs_unowned\";\n }\n return \"unlinked_existing\";\n}\n\nfunction directoryOf(relativePath: string): string {\n const slash = relativePath.lastIndexOf(\"/\");\n return slash === -1 ? \"\" : relativePath.slice(0, slash);\n}\n\nfunction sharedDirectoryPrefixLength(left: string, right: string): number {\n const leftParts = directoryOf(left).split(\"/\").filter(Boolean);\n const rightParts = directoryOf(right).split(\"/\").filter(Boolean);\n let count = 0;\n while (count < leftParts.length && count < rightParts.length && leftParts[count] === rightParts[count]) {\n count += 1;\n }\n return count;\n}\n\ninterface OrphanOwnerCandidateScore {\n score: number;\n confidence: \"path_prefix\" | \"same_directory\" | \"shared_directory\";\n}\n\nfunction scoreOrphanOwnerCandidate(pathValue: string, linkedPath: string): OrphanOwnerCandidateScore | null {\n const linkedDir = directoryOf(linkedPath);\n const orphanDir = directoryOf(pathValue);\n const directoryPrefix = linkedPath.endsWith(\"/\") ? linkedPath : `${linkedPath}/`;\n const isDirectoryPrefix = pathValue.startsWith(directoryPrefix);\n const sameDirectory = linkedDir.length > 0 && linkedDir === orphanDir;\n const sharedPrefixLength = sharedDirectoryPrefixLength(pathValue, linkedPath);\n if (!isDirectoryPrefix && !sameDirectory && sharedPrefixLength === 0) {\n return null;\n }\n if (isDirectoryPrefix) {\n return { score: linkedPath.length + 1000, confidence: \"path_prefix\" };\n }\n return sameDirectory\n ? { score: sharedPrefixLength + 500, confidence: \"same_directory\" }\n : { score: sharedPrefixLength, confidence: \"shared_directory\" };\n}\n\nfunction shouldReplaceOrphanOwnerCandidate(\n best: { item: ItemWithBody; score: number } | undefined,\n item: ItemWithBody,\n score: number,\n): boolean {\n return best === undefined || score > best.score || (score === best.score && item.id.localeCompare(best.item.id) < 0);\n}\n\nfunction findOrphanOwnerCandidate(\n pathValue: string,\n classification: OrphanedPathClassification,\n items: readonly ItemWithBody[],\n): OrphanedPathRow[\"owner_candidate\"] {\n const linkKind = classification === \"docs_unowned\" ? \"docs\" : \"files\";\n let best:\n | {\n item: ItemWithBody;\n score: number;\n confidence: \"path_prefix\" | \"same_directory\" | \"shared_directory\";\n }\n | undefined;\n for (const item of items) {\n const links = linkKind === \"docs\" ? item.docs ?? [] : item.files ?? [];\n for (const link of links) {\n if (link.scope !== \"project\") {\n continue;\n }\n const linkedPath = normalizeRelativePath(link.path);\n if (linkedPath.length === 0 || linkedPath === pathValue) {\n continue;\n }\n const scored = scoreOrphanOwnerCandidate(pathValue, linkedPath);\n if (scored === null) {\n continue;\n }\n if (shouldReplaceOrphanOwnerCandidate(best, item, scored.score)) {\n best = {\n item,\n score: scored.score,\n confidence: scored.confidence,\n };\n }\n }\n }\n if (!best) {\n return null;\n }\n return {\n id: best.item.id,\n type: best.item.type,\n title: best.item.title,\n status: best.item.status,\n confidence: best.confidence,\n };\n}\n\nfunction buildOrphanedPathRows(orphanedFiles: readonly string[], items: readonly ItemWithBody[]): OrphanedPathRow[] {\n return orphanedFiles.map((pathValue) => {\n const classification = classifyOrphanedPath(pathValue);\n const linkCommand = classification === \"docs_unowned\" ? \"docs\" : \"files\";\n const ownerCandidate = findOrphanOwnerCandidate(pathValue, classification, items);\n const target = ownerCandidate?.id ?? \"<id>\";\n return {\n path: pathValue,\n classification,\n owner_candidate: ownerCandidate,\n remediation_hint: `pm ${linkCommand} ${target} --add path=${pathValue},scope=project,note=\"<why this artifact belongs to the item>\"`,\n };\n });\n}\n\nfunction summarizeOrphanedPathRows(rows: readonly OrphanedPathRow[]): string[] {\n return rows.map(\n (row) =>\n `${row.path}:${row.classification} owner_candidate=${row.owner_candidate?.id ?? \"unowned\"} hint=${JSON.stringify(row.remediation_hint)}`,\n );\n}\n\ninterface LifecycleScanRows {\n activeItems: ItemWithBody[];\n closureLikeRows: Array<{ id: string; fields: string[] }>;\n terminalParentRows: Array<{ id: string; parent_id: string; parent_status: string }>;\n terminalParentFixRows: TerminalParentFixRow[];\n staleBlockerRows: Array<{ id: string; status: string; reasons: string[] }>;\n}\n\nfunction closureLikeFieldsForItem(item: ItemWithBody, lifecyclePatternPolicy: LifecyclePatternPolicy): string[] {\n return Object.entries(lifecyclePatternPolicy.closure_like_metadata_field_patterns)\n .filter(([field, patterns]) => {\n const value = toMeaningfulString(item[field as keyof ItemWithBody]);\n return value ? patterns.some((pattern) => value.toLowerCase().includes(pattern)) : false;\n })\n .map(([field]) => field)\n .sort((left, right) => left.localeCompare(right));\n}\n\nfunction buildTerminalParentFixRow(\n item: ItemWithBody,\n parent: ItemWithBody,\n itemsById: Map<string, ItemWithBody>,\n canonicalIdByLowercase: Map<string, string>,\n statusRegistry: RuntimeStatusRegistry,\n): TerminalParentFixRow {\n const grandparentId = toMeaningfulString(parent.parent);\n const grandparent = grandparentId\n ? itemsById.get(canonicalIdByLowercase.get(grandparentId.toLowerCase()) ?? grandparentId)\n : undefined;\n return {\n id: item.id,\n parent_id: parent.id,\n grandparent_id: grandparent?.id,\n grandparent_active: grandparent !== undefined && !isTerminalStatus(grandparent.status, statusRegistry),\n };\n}\n\n/* v8 ignore start -- stale-blocker reason variants are covered through command-level diagnostics; helper branch counters are defensive */\nfunction staleBlockerReasonsForItem(\n item: ItemWithBody,\n blockedStatuses: Set<string>,\n statusRegistry: RuntimeStatusRegistry,\n lifecyclePatternPolicy: LifecyclePatternPolicy,\n): string[] {\n const blockedBy = toMeaningfulString(item.blocked_by);\n const blockedReason = toMeaningfulString(item.blocked_reason);\n const blockedReasonNormalized = blockedReason?.toLowerCase();\n const normalizedStatus = normalizeStatusForRegistry(item.status, statusRegistry);\n const reasons: string[] = [];\n if (!blockedStatuses.has(normalizedStatus)) {\n if (blockedBy) {\n reasons.push(\"non_blocked_status_has_blocked_by\");\n }\n if (blockedReason) {\n reasons.push(\"non_blocked_status_has_blocked_reason\");\n }\n return reasons;\n }\n if (!blockedBy && !blockedReason) {\n /* v8 ignore start -- blocked-status creation paths seed either blocked_by or blocked_reason before lifecycle validation */\n reasons.push(\"blocked_status_missing_blocker_context\");\n /* v8 ignore stop */\n }\n if (blockedReasonNormalized?.includes(\"no active blocker\")) {\n reasons.push(\"blocked_status_reason_reports_no_active_blocker\");\n }\n if (\n blockedReasonNormalized &&\n lifecyclePatternPolicy.stale_blocker_reason_patterns.some((pattern) => blockedReasonNormalized.includes(pattern))\n ) {\n reasons.push(\"blocked_status_reason_matches_stale_pattern\");\n }\n return reasons;\n}\n/* v8 ignore stop */\n\nfunction collectLifecycleScanRows(\n items: ItemWithBody[],\n includeStaleBlockers: boolean,\n statusRegistry: RuntimeStatusRegistry,\n lifecyclePatternPolicy: LifecyclePatternPolicy,\n): LifecycleScanRows {\n const itemsById = new Map(items.map((item) => [item.id, item]));\n const canonicalIdByLowercase = new Map(items.map((item) => [item.id.toLowerCase(), item.id]));\n /* v8 ignore start -- runtime status registry normally supplies blocked statuses; fallback preserves legacy settings safety */\n const blockedStatuses =\n statusRegistry.blocked_statuses.size > 0 ? statusRegistry.blocked_statuses : new Set<string>([\"blocked\"]);\n /* v8 ignore stop */\n const rows: LifecycleScanRows = {\n activeItems: items.filter((item) => !isTerminalStatus(item.status, statusRegistry)),\n closureLikeRows: [],\n terminalParentRows: [],\n terminalParentFixRows: [],\n staleBlockerRows: [],\n };\n for (const item of rows.activeItems) {\n const closureLikeFields = closureLikeFieldsForItem(item, lifecyclePatternPolicy);\n if (closureLikeFields.length > 0) {\n rows.closureLikeRows.push({ id: item.id, fields: closureLikeFields });\n }\n const parentId = toMeaningfulString(item.parent);\n const parent = parentId ? itemsById.get(canonicalIdByLowercase.get(parentId.toLowerCase()) ?? parentId) : undefined;\n if (parent && isTerminalStatus(parent.status, statusRegistry)) {\n rows.terminalParentRows.push({ id: item.id, parent_id: parent.id, parent_status: parent.status });\n rows.terminalParentFixRows.push(buildTerminalParentFixRow(item, parent, itemsById, canonicalIdByLowercase, statusRegistry));\n }\n /* v8 ignore start -- stale-blocker reason presence is covered by command diagnostics; branch accounting here is defensive */\n if (includeStaleBlockers) {\n const reasons = staleBlockerReasonsForItem(item, blockedStatuses, statusRegistry, lifecyclePatternPolicy);\n if (reasons.length > 0) {\n rows.staleBlockerRows.push({\n id: item.id,\n status: item.status,\n reasons: [...new Set(reasons)].sort((left, right) => left.localeCompare(right)),\n });\n }\n }\n /* v8 ignore stop */\n }\n return rows;\n}\n\nfunction sortLifecycleScanRows(rows: LifecycleScanRows): void {\n rows.closureLikeRows.sort((left, right) => left.id.localeCompare(right.id));\n /* v8 ignore start -- parent-id tie breakers only matter for duplicate legacy ids, which the tracker writer prevents */\n rows.terminalParentRows.sort(\n (left, right) => left.id.localeCompare(right.id) || left.parent_id.localeCompare(right.parent_id),\n );\n rows.terminalParentFixRows.sort(\n (left, right) => left.id.localeCompare(right.id) || left.parent_id.localeCompare(right.parent_id),\n );\n /* v8 ignore stop */\n rows.staleBlockerRows.sort((left, right) => left.id.localeCompare(right.id));\n}\n\nfunction lifecycleCycleWarningToken(\n prefix: \"validate_lifecycle_dependency_cycles\" | \"validate_hierarchy_parent_cycle\",\n severity: ValidateDependencyCycleSeverity,\n count: number,\n): string | null {\n if (count <= 0 || severity === \"off\") {\n return null;\n }\n return `${severity === \"error\" ? `${prefix}_error` : prefix}:${count}`;\n}\n\nfunction buildLifecycleWarnings(\n rows: LifecycleScanRows,\n includeStaleBlockers: boolean,\n dependencyCycleSeverity: ValidateDependencyCycleSeverity,\n parentCycleSeverity: ValidateDependencyCycleSeverity,\n dependencyCycleCount: number,\n parentCycleCount: number,\n): string[] {\n const warnings: string[] = [];\n if (rows.closureLikeRows.length > 0) {\n warnings.push(`validate_lifecycle_active_closure_like_metadata:${rows.closureLikeRows.length}`);\n }\n if (rows.terminalParentRows.length > 0) {\n warnings.push(`validate_lifecycle_active_terminal_parent:${rows.terminalParentRows.length}`);\n }\n if (includeStaleBlockers && rows.staleBlockerRows.length > 0) {\n warnings.push(`validate_lifecycle_stale_blockers:${rows.staleBlockerRows.length}`);\n }\n const dependencyWarning = lifecycleCycleWarningToken(\n \"validate_lifecycle_dependency_cycles\",\n dependencyCycleSeverity,\n dependencyCycleCount,\n );\n const parentWarning = lifecycleCycleWarningToken(\"validate_hierarchy_parent_cycle\", parentCycleSeverity, parentCycleCount);\n return [...warnings, ...(dependencyWarning ? [dependencyWarning] : []), ...(parentWarning ? [parentWarning] : [])];\n}\n\ninterface LinkedPathScanState {\n linkedProjectPaths: Set<string>;\n remoteLinkedPaths: Set<string>;\n missingLinkedPaths: string[];\n staleLinkRows: Array<{ item_id: string; path: string; link_kind: \"files\" | \"docs\" }>;\n}\n\nfunction linkedArtifactPathExceedsFilesystemLimits(artifactPath: string): boolean {\n const normalized = normalizeRelativePath(artifactPath);\n return (\n normalized.length > LINKED_ARTIFACT_MAX_PATH_LENGTH ||\n normalized.split(/[\\\\/]/).some((segment) => segment.length > LINKED_ARTIFACT_MAX_SEGMENT_LENGTH)\n );\n}\n\nasync function linkedArtifactIsMissing(workspaceRoot: string, artifactPath: string): Promise<boolean> {\n const absolutePath = path.isAbsolute(artifactPath) ? artifactPath : path.resolve(workspaceRoot, artifactPath);\n if (linkedArtifactPathExceedsFilesystemLimits(absolutePath)) {\n return false;\n }\n try {\n const stats = await fs.stat(absolutePath);\n return !stats.isFile() && !stats.isDirectory();\n } catch (error) {\n const code =\n typeof error === \"object\" && error !== null && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n return code === \"ENOENT\" || code === \"ENOTDIR\";\n }\n}\n\nasync function collectLinkedPathScanState(items: ItemWithBody[], workspaceRoot: string): Promise<LinkedPathScanState> {\n const state: LinkedPathScanState = {\n linkedProjectPaths: new Set<string>(),\n remoteLinkedPaths: new Set<string>(),\n missingLinkedPaths: [],\n staleLinkRows: [],\n };\n for (const item of items) {\n const linkedArtifactGroups = [\n { link_kind: \"files\" as const, artifacts: item.files ?? [] },\n { link_kind: \"docs\" as const, artifacts: item.docs ?? [] },\n ];\n for (const group of linkedArtifactGroups) {\n for (const artifact of group.artifacts) {\n if (artifact.scope !== \"project\") {\n continue;\n }\n if (isRemoteLinkedArtifactReference(artifact.path)) {\n state.remoteLinkedPaths.add(artifact.path.trim());\n continue;\n }\n const normalizedPath = normalizeRelativePath(artifact.path);\n if (normalizedPath.length === 0) {\n continue;\n }\n state.linkedProjectPaths.add(normalizedPath);\n if (await linkedArtifactIsMissing(workspaceRoot, artifact.path)) {\n state.missingLinkedPaths.push(normalizedPath);\n state.staleLinkRows.push({ item_id: item.id, path: normalizedPath, link_kind: group.link_kind });\n }\n }\n }\n }\n return state;\n}\n\ninterface FileCandidatePartition {\n strictTrackedAllMode: boolean;\n strictModeForcesPmInternals: boolean;\n includePmInternalsEffective: boolean;\n pmInternalCandidatePrefixes: string[];\n excludedPmInternalPaths: string[];\n candidateFiles: string[];\n excludedByReason: Record<string, unknown>;\n}\n\nfunction partitionFileCandidates(\n fileCandidates: FileCandidateCollection,\n pmRoot: string,\n workspaceRoot: string,\n fileScanMode: ValidateFileScanMode,\n includePmInternals: boolean,\n verboseFileLists: boolean,\n): FileCandidatePartition {\n const strictTrackedAllMode = fileScanMode === \"tracked-all-strict\";\n const strictModeForcesPmInternals = strictTrackedAllMode && !includePmInternals;\n const includePmInternalsEffective = includePmInternals || strictTrackedAllMode;\n const pmInternalCandidatePrefixes = includePmInternalsEffective ? [] : resolvePmInternalCandidatePrefixes(pmRoot, workspaceRoot);\n const excludedPmInternalPaths =\n pmInternalCandidatePrefixes.length === 0\n ? []\n : fileCandidates.candidateFiles.filter((candidate) => hasPathPrefix(candidate, pmInternalCandidatePrefixes));\n const candidateFiles =\n pmInternalCandidatePrefixes.length === 0\n ? fileCandidates.candidateFiles\n : fileCandidates.candidateFiles.filter((candidate) => !hasPathPrefix(candidate, pmInternalCandidatePrefixes));\n const excludedByReason: Record<string, unknown> = {};\n if (excludedPmInternalPaths.length > 0) {\n const summarizedPmInternalPaths = summarizeFileList(excludedPmInternalPaths, verboseFileLists);\n excludedByReason.pm_internals = {\n count: excludedPmInternalPaths.length,\n paths: summarizedPmInternalPaths.values,\n paths_truncated: summarizedPmInternalPaths.truncated,\n paths_total: summarizedPmInternalPaths.total,\n };\n }\n return {\n strictTrackedAllMode,\n strictModeForcesPmInternals,\n includePmInternalsEffective,\n pmInternalCandidatePrefixes,\n excludedPmInternalPaths,\n candidateFiles,\n excludedByReason,\n };\n}\n\n/* c8 ignore start -- lifecycle stale/terminal/dependency diagnostics matrix is covered by end-to-end validate integration runs */\nfunction buildLifecycleCheck(\n items: ItemWithBody[],\n includeStaleBlockers: boolean,\n dependencyCycleSeverity: ValidateDependencyCycleSeverity,\n parentCycleSeverity: ValidateDependencyCycleSeverity,\n statusRegistry: RuntimeStatusRegistry,\n lifecyclePatternPolicy: LifecyclePatternPolicy,\n verboseDiagnostics: boolean,\n idPrefix = \"pm\",\n): { check: ValidateCheck; warnings: string[]; terminalParentFixRows: TerminalParentFixRow[] } {\n const rows = collectLifecycleScanRows(items, includeStaleBlockers, statusRegistry, lifecyclePatternPolicy);\n sortLifecycleScanRows(rows);\n const dependencyCycleDiagnostics = detectLifecycleDependencyCycles(rows.activeItems, idPrefix);\n const parentCycleDiagnostics = detectLifecycleParentCycles(items);\n const warnings = buildLifecycleWarnings(\n rows,\n includeStaleBlockers,\n dependencyCycleSeverity,\n parentCycleSeverity,\n dependencyCycleDiagnostics.cycle_count,\n parentCycleDiagnostics.cycle_count,\n );\n\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedClosureLikeRows = summarizeList(\n rows.closureLikeRows.map((row) => `${row.id}:${row.fields.join(\",\")}`),\n diagnosticLimit,\n );\n const summarizedTerminalParentRows = summarizeList(\n rows.terminalParentRows.map((row) => `${row.id}:${row.parent_id}:${row.parent_status}`),\n diagnosticLimit,\n );\n const summarizedStaleBlockerRows = summarizeList(\n rows.staleBlockerRows.map((row) => `${row.id}:${row.status}:${row.reasons.join(\",\")}`),\n diagnosticLimit,\n );\n const summarizedDependencyCycleItemIds = summarizeList(dependencyCycleDiagnostics.cycle_item_ids, diagnosticLimit);\n const summarizedDependencyCycleSamplePaths = summarizeList(dependencyCycleDiagnostics.cycle_sample_paths, diagnosticLimit);\n const summarizedParentCycleItemIds = summarizeList(parentCycleDiagnostics.cycle_item_ids, diagnosticLimit);\n const summarizedParentCycleSamplePaths = summarizeList(parentCycleDiagnostics.cycle_sample_paths, diagnosticLimit);\n\n const hasErrorSeverityCycle =\n (dependencyCycleDiagnostics.cycle_count > 0 && dependencyCycleSeverity === \"error\") ||\n (parentCycleDiagnostics.cycle_count > 0 && parentCycleSeverity === \"error\");\n\n return {\n check: {\n name: \"lifecycle\",\n status: hasErrorSeverityCycle\n ? \"error\"\n : warnings.length === 0\n ? \"ok\"\n : \"warn\",\n details: {\n checked_active_items: rows.activeItems.length,\n active_closure_like_metadata_items: rows.closureLikeRows.length,\n active_closure_like_metadata_rows: summarizedClosureLikeRows.values,\n active_closure_like_metadata_rows_truncated: summarizedClosureLikeRows.truncated,\n active_terminal_parent_items: rows.terminalParentRows.length,\n active_terminal_parent_rows: summarizedTerminalParentRows.values,\n active_terminal_parent_rows_truncated: summarizedTerminalParentRows.truncated,\n stale_blocker_checks_enabled: includeStaleBlockers,\n stale_blocker_items: rows.staleBlockerRows.length,\n stale_blocker_rows: summarizedStaleBlockerRows.values,\n stale_blocker_rows_truncated: summarizedStaleBlockerRows.truncated,\n dependency_cycle_severity_policy: dependencyCycleSeverity,\n dependency_cycle_count: dependencyCycleDiagnostics.cycle_count,\n dependency_cycle_item_count: dependencyCycleDiagnostics.cycle_item_ids.length,\n dependency_cycle_item_ids: summarizedDependencyCycleItemIds.values,\n dependency_cycle_item_ids_truncated: summarizedDependencyCycleItemIds.truncated,\n dependency_cycle_sample_paths: summarizedDependencyCycleSamplePaths.values,\n dependency_cycle_sample_paths_truncated: summarizedDependencyCycleSamplePaths.truncated,\n parent_cycle_severity_policy: parentCycleSeverity,\n parent_cycle_count: parentCycleDiagnostics.cycle_count,\n parent_cycle_item_count: parentCycleDiagnostics.cycle_item_ids.length,\n parent_cycle_item_ids: summarizedParentCycleItemIds.values,\n parent_cycle_item_ids_truncated: summarizedParentCycleItemIds.truncated,\n parent_cycle_sample_paths: summarizedParentCycleSamplePaths.values,\n parent_cycle_sample_paths_truncated: summarizedParentCycleSamplePaths.truncated,\n stale_blocker_reason_patterns: [...lifecyclePatternPolicy.stale_blocker_reason_patterns],\n stale_blocker_reason_pattern_source: lifecyclePatternPolicy.stale_blocker_reason_pattern_source,\n closure_like_blocked_reason_patterns: [\n ...lifecyclePatternPolicy.closure_like_metadata_field_patterns.blocked_reason,\n ],\n closure_like_blocked_reason_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.blocked_reason,\n closure_like_resolution_patterns: [...lifecyclePatternPolicy.closure_like_metadata_field_patterns.resolution],\n closure_like_resolution_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.resolution,\n closure_like_actual_result_patterns: [...lifecyclePatternPolicy.closure_like_metadata_field_patterns.actual_result],\n closure_like_actual_result_pattern_source:\n lifecyclePatternPolicy.closure_like_metadata_field_pattern_sources.actual_result,\n },\n },\n warnings,\n terminalParentFixRows: rows.terminalParentFixRows,\n };\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- files-check candidate filtering/classification permutations are covered by file-audit integration suites */\nasync function buildFilesCheck(\n items: ItemWithBody[],\n workspaceRoot: string,\n pmRoot: string,\n fileScanMode: ValidateFileScanMode,\n includePmInternals: boolean,\n verboseFileLists: boolean,\n): Promise<{ check: ValidateCheck; warnings: string[]; staleLinkPruneRows: StaleLinkPruneRow[] }> {\n const linkedPathState = await collectLinkedPathScanState(items, workspaceRoot);\n const itemsById = new Map(items.map((item) => [item.id, item]));\n const uniqueMissingLinkedPaths = [...new Set(linkedPathState.missingLinkedPaths)].sort((left, right) => left.localeCompare(right));\n const fileCandidates = await collectProjectFileCandidates(workspaceRoot, fileScanMode);\n const partition = partitionFileCandidates(fileCandidates, pmRoot, workspaceRoot, fileScanMode, includePmInternals, verboseFileLists);\n const orphanedFiles = partition.candidateFiles.filter((candidate) => !linkedPathState.linkedProjectPaths.has(candidate));\n const orphanedPathRows = buildOrphanedPathRows(orphanedFiles, items);\n // Stale-path classification (pm-0v2m / GH-184): a missing linked path whose\n // basename still exists in the candidate scan is reported as `moved` (with\n // relink candidates); otherwise it is `deleted` and safe to prune.\n const classifiedStalePaths = classifyStaleLinkedPaths(uniqueMissingLinkedPaths, partition.candidateFiles);\n const classificationByPath = new Map(classifiedStalePaths.map((entry) => [entry.path, entry.classification]));\n const movedStalePathCount = classifiedStalePaths.filter((entry) => entry.classification === \"moved\").length;\n const staleLinkPruneRows: StaleLinkPruneRow[] = linkedPathState.staleLinkRows\n .map((row) => ({\n ...row,\n classification: classificationByPath.get(row.path) ?? (\"deleted\" as const),\n }))\n .sort(\n (left, right) =>\n left.item_id.localeCompare(right.item_id) ||\n left.path.localeCompare(right.path) ||\n left.link_kind.localeCompare(right.link_kind),\n );\n const warnings: string[] = [];\n if (partition.strictModeForcesPmInternals) {\n warnings.push(\"validate_files_tracked_all_strict_forces_pm_internals\");\n }\n if (uniqueMissingLinkedPaths.length > 0) {\n warnings.push(`validate_files_missing_linked_paths:${uniqueMissingLinkedPaths.length}`);\n }\n if (orphanedFiles.length > 0) {\n warnings.push(`validate_files_orphaned_paths:${orphanedFiles.length}`);\n }\n const uniqueRemoteLinkedPaths = [...linkedPathState.remoteLinkedPaths].sort((left, right) => left.localeCompare(right));\n const summarizedRemote = summarizeFileList(uniqueRemoteLinkedPaths, verboseFileLists);\n const summarizedMissing = summarizeFileList(uniqueMissingLinkedPaths, verboseFileLists);\n const summarizedOrphaned = summarizeFileList(orphanedFiles, verboseFileLists);\n const summarizedOrphanedClassifications = summarizeFileList(\n orphanedPathRows.map((row) => `${row.path}:${row.classification}:owner_candidate=${row.owner_candidate?.id ?? \"unowned\"}`),\n verboseFileLists,\n );\n const orphanedPathRowDetail = verboseFileLists\n ? orphanedPathRows\n : summarizeFileList(summarizeOrphanedPathRows(orphanedPathRows), false).values;\n const summarizedClassifications = summarizeFileList(\n summarizeStaleLinkedPathClassifications(classifiedStalePaths),\n verboseFileLists,\n );\n // Owner attribution for missing linked paths (GH-210): per-path rows naming\n // the owning item(s) so cleanup is evidence-based instead of requiring a\n // reverse lookup. Full structured objects under --verbose-file-lists; compact\n // `path:classification owner=… field=…` one-liners (capped) otherwise — same\n // full/summary split as the other file-check lists (file_list_detail_mode).\n const missingLinkedPathRows: StaleLinkOwnerInput[] = staleLinkPruneRows.map((row) => ({\n item_id: row.item_id,\n path: row.path,\n link_kind: row.link_kind,\n classification: row.classification,\n }));\n const ownerRows = buildMissingLinkedPathRows(missingLinkedPathRows, (id) => {\n const owner = itemsById.get(id);\n return owner ? { type: owner.type, title: owner.title, status: owner.status } : undefined;\n });\n // Default to token-efficient compact one-liners; expose the full structured\n // rows (the GH-210 JSON shape) under --verbose-file-lists.\n const ownerRowDetail = verboseFileLists\n ? ownerRows\n : summarizeFileList(summarizeMissingLinkedPathRows(ownerRows), false).values;\n\n return {\n check: {\n name: \"files\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n workspace_root: workspaceRoot,\n scan_mode_requested: fileCandidates.requestedMode,\n scan_mode_applied: fileCandidates.appliedMode,\n strict_tracked_all_mode: partition.strictTrackedAllMode,\n strict_mode_forces_pm_internals: partition.strictModeForcesPmInternals,\n strict_mode_forces_pm_internals_notice: partition.strictModeForcesPmInternals\n ? \"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.\"\n : null,\n file_list_detail_mode: verboseFileLists ? \"full\" : \"summary\",\n file_list_summary_limit: FILE_LIST_SUMMARY_LIMIT,\n candidate_scan_source: fileCandidates.source,\n include_pm_internals: partition.includePmInternalsEffective,\n include_pm_internals_requested: includePmInternals,\n pm_internal_candidate_prefixes: partition.pmInternalCandidatePrefixes,\n pm_internal_excluded_count: partition.excludedPmInternalPaths.length,\n excluded_total: partition.excludedPmInternalPaths.length,\n excluded_by_reason: partition.excludedByReason,\n linked_project_paths: linkedPathState.linkedProjectPaths.size,\n remote_linked_paths_count: uniqueRemoteLinkedPaths.length,\n remote_linked_paths_total: summarizedRemote.total,\n remote_linked_paths: summarizedRemote.values,\n remote_linked_paths_truncated: summarizedRemote.truncated,\n candidate_total_raw: fileCandidates.candidateTotal,\n candidate_scanned_raw: fileCandidates.candidateScanned,\n candidate_total: partition.candidateFiles.length,\n candidate_scanned: partition.candidateFiles.length,\n scanned_candidate_files: partition.candidateFiles.length,\n missing_linked_paths_count: uniqueMissingLinkedPaths.length,\n missing_linked_paths_total: summarizedMissing.total,\n missing_linked_paths: summarizedMissing.values,\n missing_linked_paths_truncated: summarizedMissing.truncated,\n missing_linked_paths_moved_count: movedStalePathCount,\n missing_linked_paths_deleted_count: uniqueMissingLinkedPaths.length - movedStalePathCount,\n missing_linked_path_classifications: summarizedClassifications.values,\n missing_linked_path_classifications_truncated: summarizedClassifications.truncated,\n missing_linked_path_rows_count: ownerRows.length,\n missing_linked_path_rows: ownerRowDetail,\n orphaned_paths_count: orphanedFiles.length,\n orphaned_paths_total: summarizedOrphaned.total,\n orphaned_paths: summarizedOrphaned.values,\n orphaned_paths_truncated: summarizedOrphaned.truncated,\n orphaned_path_classifications: summarizedOrphanedClassifications.values,\n orphaned_path_classifications_truncated: summarizedOrphanedClassifications.truncated,\n orphaned_path_rows_count: orphanedPathRows.length,\n orphaned_path_rows: orphanedPathRowDetail,\n },\n },\n warnings,\n staleLinkPruneRows,\n };\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- history-drift warning/count projection permutations are covered by drift integration tests */\nasync function buildHistoryDriftCheck(\n pmRoot: string,\n items: ItemWithBody[],\n verboseDiagnostics: boolean,\n): Promise<{ check: ValidateCheck; warnings: string[] }> {\n const { missingStreams, unreadableStreams, hashMismatches, chainMismatches, driftedItems } = await scanHistoryDrift(\n pmRoot,\n items,\n );\n const warnings: string[] = [];\n if (missingStreams.length > 0) {\n warnings.push(`validate_history_drift_missing_streams:${missingStreams.length}`);\n }\n if (unreadableStreams.length > 0) {\n warnings.push(`validate_history_drift_unreadable_streams:${unreadableStreams.length}`);\n }\n if (hashMismatches.length > 0) {\n warnings.push(`validate_history_drift_hash_mismatches:${hashMismatches.length}`);\n }\n if (chainMismatches.length > 0) {\n warnings.push(`validate_history_drift_chain_mismatches:${chainMismatches.length}`);\n }\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedDrifted = summarizeList(driftedItems, diagnosticLimit);\n return {\n check: {\n name: \"history_drift\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_items: items.length,\n drifted_items_count: driftedItems.length,\n drifted_items: summarizedDrifted.values,\n drifted_items_truncated: summarizedDrifted.truncated,\n counts: {\n missing_streams: missingStreams.length,\n unreadable_streams: unreadableStreams.length,\n hash_mismatches: hashMismatches.length,\n chain_mismatches: chainMismatches.length,\n },\n },\n },\n warnings,\n };\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- command preview truncation formatting is covered by command-reference integration fixtures */\nfunction summarizeCommandReferenceRow(ownerId: string, referencedId: string, command: string): string {\n const normalizedCommand = command.trim().replaceAll(/\\s+/g, \" \");\n const commandPreview = normalizedCommand.length > 120 ? `${normalizedCommand.slice(0, 117)}...` : normalizedCommand;\n return `${ownerId}:${referencedId}:${commandPreview}`;\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- command-reference discovery/stale-id permutations are covered by linked-test integration suites */\nfunction buildCommandReferencesCheck(\n items: ItemWithBody[],\n idPrefix: string,\n verboseDiagnostics: boolean,\n): { check: ValidateCheck; warnings: string[] } {\n const knownIds = new Set(items.map((item) => item.id.toLowerCase()));\n let linkedCommandsScanned = 0;\n let referencedPmIdCount = 0;\n const referencedPmIds = new Set<string>();\n const staleReferenceRows: string[] = [];\n\n for (const item of items) {\n for (const linkedTest of item.tests ?? []) {\n if (typeof linkedTest.command !== \"string\" || linkedTest.command.trim().length === 0) {\n continue;\n }\n linkedCommandsScanned += 1;\n const referencedIds = extractReferencedPmItemIdsFromCommand(linkedTest.command, idPrefix);\n if (referencedIds.length === 0) {\n continue;\n }\n referencedPmIdCount += referencedIds.length;\n for (const referencedId of referencedIds) {\n referencedPmIds.add(referencedId);\n if (!knownIds.has(referencedId.toLowerCase())) {\n staleReferenceRows.push(summarizeCommandReferenceRow(item.id, referencedId, linkedTest.command));\n }\n }\n }\n }\n\n const uniqueStaleReferenceRows = [...new Set(staleReferenceRows)].sort((left, right) => left.localeCompare(right));\n const stalePmIds = [...new Set(uniqueStaleReferenceRows.map((row) => row.split(\":\")[1] ?? \"\"))]\n .filter((value) => value.length > 0)\n .sort((left, right) => left.localeCompare(right));\n const warnings =\n uniqueStaleReferenceRows.length > 0 ? [`validate_command_references_stale_pm_ids:${uniqueStaleReferenceRows.length}`] : [];\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedRows = summarizeList(uniqueStaleReferenceRows, diagnosticLimit);\n const summarizedStalePmIds = summarizeList(stalePmIds, diagnosticLimit);\n const summarizedReferencedPmIds = summarizeList(\n [...referencedPmIds].sort((left, right) => left.localeCompare(right)),\n diagnosticLimit,\n );\n\n return {\n check: {\n name: \"command_references\",\n status: warnings.length === 0 ? \"ok\" : \"warn\",\n details: {\n checked_items: items.length,\n linked_commands_scanned: linkedCommandsScanned,\n referenced_pm_ids_count: referencedPmIdCount,\n unique_referenced_pm_ids_count: referencedPmIds.size,\n unique_referenced_pm_ids: summarizedReferencedPmIds.values,\n unique_referenced_pm_ids_truncated: summarizedReferencedPmIds.truncated,\n stale_pm_id_references_count: uniqueStaleReferenceRows.length,\n stale_pm_ids_count: stalePmIds.length,\n stale_pm_ids: summarizedStalePmIds.values,\n stale_pm_ids_truncated: summarizedStalePmIds.truncated,\n stale_pm_id_reference_rows: summarizedRows.values,\n stale_pm_id_reference_rows_truncated: summarizedRows.truncated,\n },\n },\n warnings,\n };\n}\n/* c8 ignore stop */\n\n/* c8 ignore start -- format-version diagnostics projection is covered by validate format-version integration fixtures */\nfunction buildFormatVersionCheck(\n items: ItemWithBody[],\n verboseDiagnostics: boolean,\n): { check: ValidateCheck; warnings: string[] } {\n const scan = scanItemFormatVersions(\n items.map((item) => ({ ref: item.id, version: effectiveItemFormatVersion(item) })),\n );\n const warnings: string[] = [];\n if (scan.outdated.length > 0) {\n warnings.push(`validate_format_version_outdated_items:${scan.outdated.length}`);\n }\n if (scan.ahead.length > 0) {\n warnings.push(`validate_format_version_ahead_items:${scan.ahead.length}`);\n }\n const diagnosticLimit = verboseDiagnostics ? Number.POSITIVE_INFINITY : DIAGNOSTIC_LIST_SUMMARY_LIMIT;\n const summarizedOutdated = summarizeList(scan.outdated, diagnosticLimit);\n const summarizedAhead = summarizeList(scan.ahead, diagnosticLimit);\n // `ahead` items were written by a newer pm than this runtime: validation\n // cannot vouch for fields it does not understand, so it is an error (upgrade\n // pm). `outdated` items are a non-fatal warning (a migration would rewrite\n // them). At the current baseline version neither list is populated.\n const status: ValidateStatus = scan.ahead.length > 0 ? \"error\" : scan.outdated.length > 0 ? \"warn\" : \"ok\";\n return {\n check: {\n name: \"format_version\",\n status,\n details: {\n checked_items: items.length,\n current_format_version: CURRENT_ITEM_FORMAT_VERSION,\n outdated_items_count: scan.outdated.length,\n outdated_items: summarizedOutdated.values,\n outdated_items_truncated: summarizedOutdated.truncated,\n ahead_items_count: scan.ahead.length,\n ahead_items: summarizedAhead.values,\n ahead_items_truncated: summarizedAhead.truncated,\n },\n },\n warnings,\n };\n}\n/* c8 ignore stop */\n\nconst VALIDATE_AUTO_FIX_MESSAGE = \"pm validate auto-fix\";\n\n/**\n * Apply one planned fix through the SAME audited command paths an operator\n * would use by hand (`pm update` / `pm files --remove` / `pm docs --remove`),\n * so every applied fix carries normal history, locking, and hook behavior.\n * Command modules are imported lazily: plain validate runs stay read-only and\n * never pay the mutation-stack import cost.\n */\n/* c8 ignore start -- lazy mutation-command dispatch branches are covered by validate auto-fix integration tests */\nasync function applyValidateFix(fix: ValidateFixRecord, global: GlobalOptions): Promise<void> {\n switch (fix.kind) {\n case \"set_resolution\":\n case \"set_close_reason\":\n case \"set_estimate\":\n case \"reparent\":\n case \"unset_parent\": {\n const { runUpdate } = await import(\"./update.js\");\n const updateOptions: Record<string, unknown> = { message: VALIDATE_AUTO_FIX_MESSAGE };\n if (fix.kind === \"set_resolution\") {\n updateOptions.resolution = fix.value;\n } else if (fix.kind === \"set_close_reason\") {\n updateOptions.closeReason = fix.value;\n } else if (fix.kind === \"set_estimate\") {\n updateOptions.estimatedMinutes = fix.value;\n } else if (fix.kind === \"reparent\") {\n updateOptions.parent = fix.parent_id;\n } else {\n updateOptions.unset = [\"parent\"];\n }\n await runUpdate(fix.item_id, updateOptions, global);\n return;\n }\n case \"prune_file_link\": {\n throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`);\n }\n case \"prune_doc_link\": {\n throw new Error(`Unsupported non-batched fix kind: ${fix.kind}`);\n }\n }\n}\n/* c8 ignore stop */\n\nfunction pruneBatchKey(fix: ValidateFixRecord): string | null {\n if (fix.kind !== \"prune_file_link\" && fix.kind !== \"prune_doc_link\") {\n return null;\n }\n return `${fix.kind}:${fix.item_id}`;\n}\n\n/* c8 ignore start -- batched prune/apply failure fan-out permutations are covered by auto-fix integration suites */\nasync function applyValidateFixes(applicable: ValidateFixRecord[], global: GlobalOptions): Promise<{\n applied: ValidateFixRecord[];\n failed: Array<{ fix: ValidateFixRecord; error: unknown }>;\n}> {\n const applied: ValidateFixRecord[] = [];\n const failed: Array<{ fix: ValidateFixRecord; error: unknown }> = [];\n const pruneBatches = new Map<string, ValidateFixRecord[]>();\n\n for (const fix of applicable) {\n const batchKey = pruneBatchKey(fix);\n if (batchKey === null) {\n try {\n await applyValidateFix(fix, global);\n applied.push(fix);\n } catch (error) {\n failed.push({ fix, error });\n }\n continue;\n }\n const existing = pruneBatches.get(batchKey);\n if (existing) {\n existing.push(fix);\n } else {\n pruneBatches.set(batchKey, [fix]);\n }\n }\n\n for (const batch of pruneBatches.values()) {\n const first = batch[0];\n /* c8 ignore next 2 -- pruneBatches values are only created with at least one fix */\n if (!first) {\n continue;\n }\n const remove = batch\n .map((fix) => fix.path)\n .filter((value): value is string => typeof value === \"string\" && value.length > 0);\n try {\n if (first.kind === \"prune_file_link\") {\n const { runFiles } = await import(\"./files.js\");\n await runFiles(first.item_id, { remove, message: VALIDATE_AUTO_FIX_MESSAGE }, global);\n } else {\n const { runDocs } = await import(\"./docs.js\");\n await runDocs(first.item_id, { remove, message: VALIDATE_AUTO_FIX_MESSAGE }, global);\n }\n applied.push(...batch);\n } catch (error) {\n failed.push(...batch.map((fix) => ({ fix, error })));\n }\n }\n\n return { applied, failed };\n}\n/* c8 ignore stop */\n\nexport const _testOnlyValidateCommand = {\n applyValidateFix,\n applyValidateFixes,\n attachValidateFixHints,\n buildCommandReferencesCheck,\n buildCloseReasonBackfillRows,\n buildFilesCheck,\n buildLifecycleCheck,\n buildLifecycleDependencyGraph,\n buildLifecycleParentGraph,\n buildEstimateBackfillRows,\n buildMetadataCounts,\n buildMissingFieldOccurrences,\n buildOrphanedPathRows,\n classifyOrphanedPath,\n collectDefaultProjectFileCandidates,\n collectTrackedGitFileCandidates,\n detectLifecycleDependencyCycles,\n detectLifecycleParentCycles,\n escapeRegExp,\n extractItemIds,\n findLifecycleDependencyCycleComponents,\n isMetadataFieldMissing,\n linkedArtifactPathExceedsFilesystemLimits,\n listFilesRecursive,\n resolveDependencyCycleSeverity,\n resolveParentCycleSeverity,\n resolveFileScanMode,\n resolveLifecycleDependencyCycleSamplePath,\n resolveRequestedChecks,\n resolveValidateMetadataProfile,\n resolveWorkspaceRoot,\n sharedDirectoryPrefixLength,\n summarizeOrphanedPathRows,\n summarizeDuplicateIssueCodes,\n toMeaningfulString,\n};\n\ntype LoadedValidateSettings = Awaited<ReturnType<typeof readSettings>>;\n\ninterface ValidateCheckExecutionState {\n checks: ValidateCheck[];\n warnings: string[];\n closeReasonBackfillRows: CloseReasonBackfillRow[];\n estimateBackfillRows: EstimateBackfillRow[];\n resolutionBackfillRows: ResolutionBackfillRow[];\n terminalParentFixRows: TerminalParentFixRow[];\n staleLinkPruneRows: StaleLinkPruneRow[];\n}\n\nfunction recordValidateCheck(\n state: ValidateCheckExecutionState,\n built: { check: ValidateCheck; warnings: string[] },\n fixHintsEnabled: boolean,\n): void {\n if (fixHintsEnabled) {\n attachValidateFixHints(built.check, built.warnings);\n }\n state.checks.push(built.check);\n state.warnings.push(...built.warnings);\n}\n\nasync function executeRequestedValidateChecks(params: {\n requestedChecks: Set<ValidateCheckName>;\n options: ValidateCommandOptions;\n global: GlobalOptions;\n pmRoot: string;\n workspaceRoot: string;\n settings: LoadedValidateSettings;\n items: ItemWithBody[];\n statusRegistry: RuntimeStatusRegistry;\n metadataPolicy: ValidateMetadataPolicy;\n lifecyclePatternPolicy: LifecyclePatternPolicy;\n dependencyCycleSeverity: ValidateDependencyCycleSeverity;\n parentCycleSeverity: ValidateDependencyCycleSeverity;\n fileScanMode: ValidateFileScanMode;\n initialWarnings: string[];\n}): Promise<ValidateCheckExecutionState> {\n const state: ValidateCheckExecutionState = {\n checks: [],\n warnings: [...params.initialWarnings],\n closeReasonBackfillRows: [],\n estimateBackfillRows: [],\n resolutionBackfillRows: [],\n terminalParentFixRows: [],\n staleLinkPruneRows: [],\n };\n const fixHintsEnabled = params.options.fixHints === true;\n const fullDiagnostics =\n params.options.verboseDiagnostics === true || params.options.allAffectedIds === true || params.global.json === true;\n if (params.requestedChecks.has(\"metadata\")) {\n const built = buildMetadataCheck(params.items, params.metadataPolicy, params.statusRegistry, fullDiagnostics);\n state.closeReasonBackfillRows = built.closeReasonBackfillRows;\n state.estimateBackfillRows = built.estimateBackfillRows;\n recordValidateCheck(state, built, fixHintsEnabled);\n }\n if (params.requestedChecks.has(\"resolution\")) {\n const built = buildResolutionCheck(params.items, params.statusRegistry, fullDiagnostics);\n state.resolutionBackfillRows = built.resolutionBackfillRows;\n recordValidateCheck(state, built, fixHintsEnabled);\n }\n if (params.requestedChecks.has(\"lifecycle\")) {\n const built = buildLifecycleCheck(\n params.items,\n Boolean(params.options.checkStaleBlockers),\n params.dependencyCycleSeverity,\n params.parentCycleSeverity,\n params.statusRegistry,\n params.lifecyclePatternPolicy,\n fullDiagnostics,\n params.settings.id_prefix,\n );\n state.terminalParentFixRows = built.terminalParentFixRows;\n recordValidateCheck(state, built, fixHintsEnabled);\n }\n if (params.requestedChecks.has(\"files\")) {\n const built = await buildFilesCheck(\n params.items,\n params.workspaceRoot,\n params.pmRoot,\n params.fileScanMode,\n Boolean(params.options.includePmInternals),\n Boolean(params.options.verboseFileLists),\n );\n state.staleLinkPruneRows = built.staleLinkPruneRows;\n recordValidateCheck(state, built, fixHintsEnabled);\n }\n if (params.requestedChecks.has(\"command_references\")) {\n recordValidateCheck(\n state,\n buildCommandReferencesCheck(params.items, params.settings.id_prefix, fullDiagnostics),\n fixHintsEnabled,\n );\n }\n if (params.requestedChecks.has(\"history_drift\")) {\n recordValidateCheck(state, await buildHistoryDriftCheck(params.pmRoot, params.items, fullDiagnostics), fixHintsEnabled);\n }\n if (params.requestedChecks.has(\"format_version\")) {\n recordValidateCheck(state, buildFormatVersionCheck(params.items, fullDiagnostics), fixHintsEnabled);\n }\n return state;\n}\n\nfunction planValidateFixes(\n options: ValidateCommandOptions,\n state: ValidateCheckExecutionState,\n settings: LoadedValidateSettings,\n): ValidateFixRecord[] {\n const planned: ValidateFixRecord[] = [];\n if (options.autoFix === true) {\n planned.push(...planCloseReasonBackfillFixes(state.closeReasonBackfillRows));\n planned.push(...planResolutionBackfillFixes(state.resolutionBackfillRows));\n planned.push(...planEstimateBackfillFixes(state.estimateBackfillRows, settings.validation.estimate_defaults_by_type));\n planned.push(...planTerminalParentFixes(state.terminalParentFixRows));\n }\n if (options.pruneMissing === true) {\n planned.push(...planStaleLinkPruneFixes(state.staleLinkPruneRows));\n }\n return planned;\n}\n\n/* v8 ignore start -- validate fix-summary matrix is covered end-to-end; direct helper fallback branches are defensive */\nasync function buildValidateFixesSummary(\n options: ValidateCommandOptions,\n state: ValidateCheckExecutionState,\n settings: LoadedValidateSettings,\n grantedFixScopes: Set<ValidateFixScope>,\n global: GlobalOptions,\n): Promise<ValidateFixesSummary | undefined> {\n if (options.autoFix !== true && options.pruneMissing !== true) {\n return undefined;\n }\n const planned = planValidateFixes(options, state, settings);\n const { applicable, gated } = partitionFixesByGrant(planned, grantedFixScopes);\n const dryRun = options.dryRun === true;\n const appliedFixRows: Array<Record<string, unknown>> = [];\n const failedFixRows: Array<Record<string, unknown>> = [];\n if (!dryRun) {\n const applied = await applyValidateFixes(applicable, global);\n appliedFixRows.push(...applied.applied.map(toFixOutputRow));\n failedFixRows.push(\n ...applied.failed.map(({ fix, error }) => ({\n ...toFixOutputRow(fix),\n error: error instanceof Error ? error.message : String(error),\n })),\n );\n }\n return {\n mode: dryRun ? \"dry_run\" : \"apply\",\n auto_fix: options.autoFix === true,\n prune_missing: options.pruneMissing === true,\n granted_fix_scopes: [...grantedFixScopes].sort((left, right) => left.localeCompare(right)),\n planned_count: planned.length,\n applied_count: appliedFixRows.length,\n gated_count: gated.length,\n failed_count: failedFixRows.length,\n planned_fixes: planned.map(toFixOutputRow),\n applied_fixes: appliedFixRows,\n gated_fixes: gated.map((fix) => ({\n ...toFixOutputRow(fix),\n gate_hint: `Withheld: re-run with --fix-scope ${fix.gate} to apply.`,\n })),\n failed_fixes: failedFixRows,\n };\n}\n/* v8 ignore stop */\n\n/* c8 ignore start -- validate orchestration + fix-application matrices are covered by end-to-end command integration runs */\n/**\n * Implements run validate for the public runtime surface of this module.\n */\nexport async function runValidate(options: ValidateCommandOptions, global: GlobalOptions): Promise<ValidateResult> {\n const fixesRequested = options.autoFix === true || options.pruneMissing === true;\n if (options.dryRun === true && !fixesRequested) {\n throw new PmCliError(\n \"--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).\",\n EXIT_CODE.USAGE,\n );\n }\n if (options.fixScope !== undefined && options.fixScope.length > 0 && options.autoFix !== true) {\n throw new PmCliError(\"--fix-scope requires --auto-fix.\", EXIT_CODE.USAGE);\n }\n // Resolved up-front so unknown --fix-scope values fail fast before any scan.\n const grantedFixScopes = resolveGrantedFixScopes(options.fixScope);\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n if (!(await pathExists(getSettingsPath(pmRoot)))) {\n throw new PmCliError(`Tracker is not initialized at ${pmRoot}. Run pm init first.`, EXIT_CODE.NOT_FOUND);\n }\n\n const settings = await readSettings(pmRoot);\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const itemReadWarnings: string[] = [];\n const items = await listAllFrontMatterWithBody(\n pmRoot,\n settings.item_format,\n typeRegistry.type_to_folder,\n itemReadWarnings,\n settings.schema,\n );\n const requestedChecks = resolveRequestedChecks(options);\n const metadataProfileSource: \"default\" | \"settings\" | \"option\" =\n typeof options.metadataProfile === \"string\" ? \"option\" : \"settings\";\n const metadataProfile = resolveValidateMetadataProfile(\n typeof options.metadataProfile === \"string\" ? options.metadataProfile : settings.validation.metadata_profile,\n );\n const metadataPolicy = resolveValidateMetadataPolicy(\n metadataProfile,\n metadataProfileSource,\n settings.validation.metadata_required_fields,\n );\n const lifecyclePatternPolicy = resolveLifecyclePatternPolicy(settings);\n const dependencyCycleSeverity = resolveDependencyCycleSeverity(options.dependencyCycleSeverity);\n const parentCycleSeverity = resolveParentCycleSeverity(options.parentCycleSeverity);\n const fileScanMode = resolveFileScanMode(options.scanMode);\n const workspaceRoot = resolveWorkspaceRoot(pmRoot);\n const state = await executeRequestedValidateChecks({\n requestedChecks,\n options,\n global,\n pmRoot,\n workspaceRoot,\n settings,\n items,\n statusRegistry,\n metadataPolicy,\n lifecyclePatternPolicy,\n dependencyCycleSeverity,\n parentCycleSeverity,\n fileScanMode,\n initialWarnings: [...new Set(itemReadWarnings)],\n });\n\n // Remediation phase (pm-c3sz / pm-8jss / pm-0v2m). Plans are derived from\n // the findings of THIS run; checks above always report the pre-fix state.\n // Safe field backfills apply by default under --auto-fix; gated lifecycle\n // fixes are planned but withheld unless --fix-scope lifecycle grants them;\n // --dry-run previews without mutating; failures never abort the run.\n const fixes = fixesRequested\n ? await buildValidateFixesSummary(options, state, settings, grantedFixScopes, global)\n : undefined;\n\n const normalizedWarnings = [...new Set(state.warnings)].sort((left, right) => left.localeCompare(right));\n const hasErrors = state.checks.some((check) => check.status === \"error\");\n return {\n ok: !hasErrors,\n has_warnings: normalizedWarnings.length > 0,\n checks: state.checks,\n warnings: normalizedWarnings,\n ...(fixes !== undefined ? { fixes } : {}),\n generated_at: nowIso(),\n };\n}\n/* c8 ignore stop */\n", "/**\n * Fix planning for `pm validate --auto-fix` / `--prune-missing` (pm-c3sz,\n * pm-8jss, pm-0v2m).\n *\n * Pure module: planners turn check findings into declarative\n * {@link ValidateFixRecord}s; the validate command decides whether to apply\n * them (apply mode), preview them (`--dry-run`), or withhold gated fixes\n * (lifecycle structural changes require an explicit `--fix-scope lifecycle`).\n *\n * Safety invariants:\n * - Every planned fix is deterministic and non-destructive: it only sets a\n * derivable field value or removes a stale LINK (never a real file).\n * - No fix ever closes, deletes, or cancels an item.\n * - Lifecycle fixes (reparent / unset parent) are structural, so they are\n * planned with `gate: \"lifecycle\"` and only applied when that scope was\n * explicitly granted.\n */\n\nimport { EXIT_CODE } from \"../shared/constants.js\";\nimport { PmCliError } from \"../shared/errors.js\";\nimport { resolveEstimateDefaultMinutes } from \"./estimate-defaults.js\";\n\n/**\n * Restricts validate fix check values accepted by command, SDK, and storage contracts.\n */\nexport type ValidateFixCheck = \"metadata\" | \"resolution\" | \"lifecycle\" | \"files\";\n\n/**\n * Restricts validate fix kind values accepted by command, SDK, and storage contracts.\n */\nexport type ValidateFixKind =\n | \"set_resolution\"\n | \"set_close_reason\"\n | \"set_estimate\"\n | \"reparent\"\n | \"unset_parent\"\n | \"prune_file_link\"\n | \"prune_doc_link\";\n\n/**\n * Restricts validate fix scope values accepted by command, SDK, and storage contracts.\n */\nexport type ValidateFixScope = \"metadata\" | \"resolution\" | \"estimates\" | \"lifecycle\";\n\n/** Scopes auto-applied without an explicit `--fix-scope` (safe field backfills). */\nexport const DEFAULT_GRANTED_FIX_SCOPES: readonly ValidateFixScope[] = [\"metadata\", \"resolution\"];\n\n/**\n * Scopes accepted by `--fix-scope`. `estimates` and `lifecycle` are opt-in:\n * estimate backfills are heuristic per-type guesses (not derived facts) and\n * lifecycle changes are structural, so neither is granted by default.\n */\nexport const SUPPORTED_FIX_SCOPES: readonly ValidateFixScope[] = [\"metadata\", \"resolution\", \"estimates\", \"lifecycle\"];\n\n/**\n * Documents the validate fix record payload exchanged by command, SDK, and package integrations.\n */\nexport interface ValidateFixRecord {\n /** Item the fix targets. */\n item_id: string;\n /** Validate check the finding came from. */\n check: ValidateFixCheck;\n /** Front-matter field (or link list) the fix changes. */\n field: string;\n /** Declarative fix kind the applier dispatches on. */\n kind: ValidateFixKind;\n /** Equivalent standalone `pm` command for the fix. */\n command: string;\n /** New value for set-field fixes. */\n value?: string;\n /** Stale link path for prune fixes. */\n path?: string;\n /** Target parent id for reparent fixes. */\n parent_id?: string;\n /**\n * Fix scope the `--fix-scope` allowlist must grant for the fix to be\n * applied. Every `--auto-fix` record carries one (the granted default is\n * metadata+resolution; lifecycle must be named explicitly). Absent only on\n * `--prune-missing` records, which are governed by their own flag.\n */\n gate?: ValidateFixScope;\n}\n\n/** Default resolution backfilled onto closed items with no derivable source text. */\nconst DEFAULT_RESOLUTION_BACKFILL_VALUE = \"completed\";\n\nfunction quoteForCommand(value: string): string {\n return `\"${value.replaceAll(\"\\\\\", \"\\\\\\\\\").replaceAll('\"', '\\\\\"')}\"`;\n}\n\nfunction toMeaningfulValue(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed !== undefined && trimmed.length > 0 ? trimmed : undefined;\n}\n\n/**\n * Documents the resolution backfill row payload exchanged by command, SDK, and package integrations.\n */\nexport interface ResolutionBackfillRow {\n id: string;\n /** Resolution-check missing field keys for this closed item. */\n missing_fields: readonly string[];\n /** The item's close_reason, when present (preferred derivation source). */\n close_reason?: string;\n}\n\n/**\n * Plan resolution backfills for closed items flagged by the resolution check.\n * Only the `resolution` field is mechanical enough to auto-fix: it derives\n * from the item's own `close_reason` when present and falls back to the\n * `\"completed\"` default. `expected_result` / `actual_result` stay hint-only —\n * no deterministic source text exists for them.\n */\nexport function planResolutionBackfillFixes(rows: readonly ResolutionBackfillRow[]): ValidateFixRecord[] {\n const fixes: ValidateFixRecord[] = [];\n for (const row of rows) {\n if (!row.missing_fields.includes(\"resolution\")) {\n continue;\n }\n const value = toMeaningfulValue(row.close_reason) ?? DEFAULT_RESOLUTION_BACKFILL_VALUE;\n fixes.push({\n item_id: row.id,\n check: \"resolution\",\n field: \"resolution\",\n kind: \"set_resolution\",\n value,\n command: `pm update ${row.id} --resolution ${quoteForCommand(value)}`,\n gate: \"resolution\",\n });\n }\n return fixes;\n}\n\n/**\n * Documents the close reason backfill row payload exchanged by command, SDK, and package integrations.\n */\nexport interface CloseReasonBackfillRow {\n id: string;\n /** The item's resolution, when present (the only derivation source). */\n resolution?: string;\n}\n\n/**\n * Plan close_reason backfills for closed items flagged by the metadata check.\n * Only derivable when the item already carries a resolution; items missing\n * both stay hint-only (any synthesized reason would be fabricated, not\n * derived).\n */\nexport function planCloseReasonBackfillFixes(rows: readonly CloseReasonBackfillRow[]): ValidateFixRecord[] {\n const fixes: ValidateFixRecord[] = [];\n for (const row of rows) {\n const value = toMeaningfulValue(row.resolution);\n if (value === undefined) {\n continue;\n }\n fixes.push({\n item_id: row.id,\n check: \"metadata\",\n field: \"close_reason\",\n kind: \"set_close_reason\",\n value,\n command: `pm update ${row.id} --close-reason ${quoteForCommand(value)}`,\n gate: \"metadata\",\n });\n }\n return fixes;\n}\n\n/**\n * Documents the estimate backfill row payload exchanged by command, SDK, and package integrations.\n */\nexport interface EstimateBackfillRow {\n id: string;\n /** Item type, used to resolve the per-type default estimate. */\n type?: string;\n}\n\n/**\n * Plan estimate backfills for items flagged by the metadata check as missing\n * `estimated_minutes` (GH-212). The value is a config-driven per-type default\n * (overrides > built-in map > fallback), never a derived fact — so these fixes\n * carry `gate: \"estimates\"`, an opt-in scope that is NOT granted by default.\n * `overrides` is the already-normalized `validation.estimate_defaults_by_type`\n * map; pass `undefined`/`{}` to use the built-in defaults.\n */\nexport function planEstimateBackfillFixes(\n rows: readonly EstimateBackfillRow[],\n overrides?: Readonly<Record<string, number>>,\n): ValidateFixRecord[] {\n return rows.map((row) => {\n const minutes = resolveEstimateDefaultMinutes(row.type, overrides);\n return {\n item_id: row.id,\n check: \"metadata\" as const,\n field: \"estimated_minutes\",\n kind: \"set_estimate\" as const,\n value: String(minutes),\n command: `pm update ${row.id} --estimate ${minutes}`,\n gate: \"estimates\" as const,\n };\n });\n}\n\n/**\n * Documents the terminal parent fix row payload exchanged by command, SDK, and package integrations.\n */\nexport interface TerminalParentFixRow {\n id: string;\n parent_id: string;\n /** The terminal parent's own parent, when one exists. */\n grandparent_id?: string;\n /** True when the grandparent exists and is NOT terminal (safe reparent target). */\n grandparent_active?: boolean;\n}\n\n/**\n * Plan lifecycle fixes for active items whose parent is terminal (pm-8jss /\n * GH-168). When the terminal parent has an active grandparent, the child is\n * reparented one level up (it stays inside the same hierarchy); otherwise the\n * parent link is cleared so the item surfaces as unparented active work.\n * Either way the item itself is never closed or mutated beyond `parent` —\n * and every fix carries `gate: \"lifecycle\"` so it is only applied under an\n * explicit `--fix-scope lifecycle`.\n */\nexport function planTerminalParentFixes(rows: readonly TerminalParentFixRow[]): ValidateFixRecord[] {\n return rows.map((row) => {\n if (row.grandparent_id !== undefined && row.grandparent_active === true) {\n return {\n item_id: row.id,\n check: \"lifecycle\" as const,\n field: \"parent\",\n kind: \"reparent\" as const,\n parent_id: row.grandparent_id,\n command: `pm update ${row.id} --parent ${row.grandparent_id}`,\n gate: \"lifecycle\" as const,\n };\n }\n return {\n item_id: row.id,\n check: \"lifecycle\" as const,\n field: \"parent\",\n kind: \"unset_parent\" as const,\n command: `pm update ${row.id} --unset parent`,\n gate: \"lifecycle\" as const,\n };\n });\n}\n\n/**\n * Documents the stale link prune row payload exchanged by command, SDK, and package integrations.\n */\nexport interface StaleLinkPruneRow {\n item_id: string;\n path: string;\n link_kind: \"files\" | \"docs\";\n classification: \"moved\" | \"deleted\";\n}\n\n/**\n * Plan link prunes for `--prune-missing` (pm-0v2m / GH-184). Only links whose\n * stale path classified as `deleted` are pruned; `moved` links keep their\n * relink candidates in the files-check details instead of being dropped, so\n * recoverable link information is never destroyed. Link removal only — real\n * files are never touched.\n */\nexport function planStaleLinkPruneFixes(rows: readonly StaleLinkPruneRow[]): ValidateFixRecord[] {\n const fixes: ValidateFixRecord[] = [];\n for (const row of rows) {\n if (row.classification !== \"deleted\") {\n continue;\n }\n const noun = row.link_kind === \"files\" ? \"files\" : \"docs\";\n fixes.push({\n item_id: row.item_id,\n check: \"files\",\n field: row.link_kind,\n kind: row.link_kind === \"files\" ? \"prune_file_link\" : \"prune_doc_link\",\n path: row.path,\n command: `pm ${noun} ${row.item_id} --remove ${quoteForCommand(row.path)}`,\n });\n }\n return fixes;\n}\n\n/**\n * Resolve the granted `--fix-scope` set (repeatable and/or comma-separated).\n * With no explicit scopes the safe field-backfill scopes (metadata,\n * resolution) are granted; lifecycle must always be named explicitly. Unknown\n * values fail fast with the supported list.\n */\nexport function resolveGrantedFixScopes(rawScopes: readonly string[] | undefined): Set<ValidateFixScope> {\n const tokens = (rawScopes ?? [])\n .flatMap((raw) => raw.split(\",\"))\n .map((raw) => raw.trim())\n .filter((raw) => raw.length > 0);\n if (tokens.length === 0) {\n if (rawScopes !== undefined && rawScopes.length > 0) {\n throw new PmCliError(\n `--fix-scope values must not be empty. Supported values: ${SUPPORTED_FIX_SCOPES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n }\n return new Set(DEFAULT_GRANTED_FIX_SCOPES);\n }\n const granted = new Set<ValidateFixScope>();\n for (const raw of tokens) {\n const normalized = raw.toLowerCase().replaceAll(\"-\", \"_\");\n if ((SUPPORTED_FIX_SCOPES as readonly string[]).includes(normalized)) {\n granted.add(normalized as ValidateFixScope);\n continue;\n }\n throw new PmCliError(\n `Unknown --fix-scope value \"${raw}\". Supported values: ${SUPPORTED_FIX_SCOPES.join(\", \")}.`,\n EXIT_CODE.USAGE,\n );\n }\n return granted;\n}\n\n/**\n * Split a fix plan into the records that may be applied under the granted\n * scopes and the gated records that were withheld. `--fix-scope` is an exact\n * allowlist: every `--auto-fix` record requires its gate scope in `granted`.\n * Ungated records (`--prune-missing` link prunes, governed by their own flag)\n * are always applicable.\n */\nexport function partitionFixesByGrant(\n fixes: readonly ValidateFixRecord[],\n granted: ReadonlySet<ValidateFixScope>,\n): { applicable: ValidateFixRecord[]; gated: ValidateFixRecord[] } {\n const applicable: ValidateFixRecord[] = [];\n const gated: ValidateFixRecord[] = [];\n for (const fix of fixes) {\n if (fix.gate !== undefined && !granted.has(fix.gate)) {\n gated.push(fix);\n } else {\n applicable.push(fix);\n }\n }\n return { applicable, gated };\n}\n\n/** Compact serialization of a fix for planned/applied output rows. */\nexport function toFixOutputRow(fix: ValidateFixRecord): Record<string, unknown> {\n return {\n item_id: fix.item_id,\n check: fix.check,\n field: fix.field,\n command: fix.command,\n ...(fix.gate !== undefined ? { gate: fix.gate } : {}),\n };\n}\n", "/**\n * Logical issue-code governance primitives (GH-235).\n *\n * Trackers frequently adopt a title convention that embeds a logical issue\n * code at the START of the title, e.g. `ISSUE-004: ...`, `BUG-12 ...`,\n * `TASK-7 — ...`, `ADR-001`, `RFC-9`. When two distinct items share the same\n * logical code, auditability and duplicate detection both suffer: a human or\n * agent searching for \"ISSUE-004\" can no longer assume a single canonical item.\n *\n * These primitives detect that condition. They are pure: no IO, no heavy\n * runtime dependencies. Callers pass plain structural item shapes so the logic\n * stays trivially unit-testable.\n */\n\n/** Minimal structural shape needed to detect duplicate issue codes. */\nexport interface IssueCodeItem {\n id: string;\n title?: string | null;\n /**\n * The id of this item's parent, when it is a child in a hierarchy. Used to\n * suppress false positives where a child intentionally reuses its parent's\n * code prefix (the `PARENT` + `PARENT-T0n` task-breakdown convention, GH-275):\n * when an item's parent is another item in the same code group, the shared\n * code is by design and the child does not constitute a collision.\n */\n parent?: string | null;\n /**\n * The id of the canonical item this one was closed as a duplicate of, when\n * set. A closed-as-duplicate item has already been adjudicated, so it is\n * excluded from collision detection entirely (GH-278) — re-flagging a\n * resolved duplicate is permanent noise that erodes trust in `validate`.\n */\n duplicate_of?: string | null;\n}\n\n/** A logical issue code shared by two or more items. */\nexport interface DuplicateIssueCode {\n /** The canonical (normalized, upper-case) issue code, e.g. `ISSUE-004`. */\n code: string;\n /** How many items carry this code. */\n count: number;\n /** The ids of the items carrying this code, sorted ascending. */\n ids: string[];\n /** The titles of the items carrying this code, in the same order as `ids`. */\n titles: string[];\n}\n\n/**\n * Match a conventional leading logical issue code: an upper-case alphanumeric\n * prefix (starting with a letter) followed by a `-` separator and a number, at\n * the very start of the title (after optional leading whitespace).\n *\n * Examples that match: `ISSUE-004`, `BUG-12`, `TASK-7`, `ADR-001`, `RFC-9`,\n * `GH-235`, `PM2-14`. The trailing `\\b` requires the digit run to end at a word\n * boundary, so `ISSUE-004-extra` extracts `ISSUE-004` while `ISSUE-004foo`\n * (digit immediately followed by a letter — no boundary) does not match.\n */\nconst ISSUE_CODE_PATTERN = /^([A-Z][A-Z0-9]*-\\d+)\\b/;\n\n/**\n * Extract the leading logical issue code from a title, or `null` when the title\n * does not begin with one. The title is trimmed and upper-cased before matching\n * so case differences (`issue-004` vs `ISSUE-004`) collapse to one logical\n * code; the returned code is therefore always normalized upper-case.\n *\n * Accepts unknown-ish input defensively (exported helper SDK consumers may call\n * from untyped JS): a non-string or empty title resolves to `null`.\n */\nexport function extractIssueCode(title: string | null | undefined): string | null {\n if (typeof title !== \"string\") {\n return null;\n }\n const normalized = title.trim().toUpperCase();\n if (normalized.length === 0) {\n return null;\n }\n const match = ISSUE_CODE_PATTERN.exec(normalized);\n return match ? match[1] : null;\n}\n\n/** Test whether a value is a usable (non-empty after trim) item-id reference. */\nfunction isNonEmptyIdReference(value: string | null | undefined): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\n/**\n * Find logical issue codes used by 2+ items. Any item whose title begins with a\n * conventional issue code contributes; codes used by a single item are not\n * reported. Status is intentionally NOT considered for genuine collisions — a\n * closed item and an open item sharing a code still collide for audit purposes.\n *\n * Two adjudicated/by-design cases are excluded so `validate` output stays\n * trustworthy in real trackers (GH-275, GH-278):\n *\n * - **Closed-as-duplicate** (GH-278): an item with a non-empty `duplicate_of`\n * has already been resolved against its canonical keeper, so it is dropped\n * before grouping and never contributes to a collision.\n * - **Parent/child prefix sharing** (GH-275): the `PARENT` + `PARENT-T0n`\n * task-breakdown convention makes a child's title share the parent's code.\n * Within each code group, any item whose `parent` is another item in the same\n * group is dropped, because the shared code is intentional hierarchy, not a\n * collision. A genuine duplicate (two items with the same code, neither the\n * parent of the other) still surfaces after this filtering.\n *\n * Results are deterministic: duplicate groups are sorted by code, and the\n * `ids`/`titles` within each group are sorted by id. The first-seen title for a\n * given (id) is used; duplicate ids (should not occur for a valid corpus) are\n * de-duplicated so an item never inflates its own code's count.\n */\nexport function findDuplicateIssueCodes(items: readonly IssueCodeItem[]): DuplicateIssueCode[] {\n const byCode = new Map<string, Array<{ id: string; title: string; parent: string | null }>>();\n for (const item of items) {\n // A non-string title can never carry a code, so skip it before extraction;\n // this also guarantees every stored title below is a real string.\n if (typeof item.title !== \"string\") {\n continue;\n }\n // GH-278: an item closed as a duplicate of another is already adjudicated.\n if (isNonEmptyIdReference(item.duplicate_of)) {\n continue;\n }\n const code = extractIssueCode(item.title);\n if (code === null) {\n continue;\n }\n let entries = byCode.get(code);\n if (!entries) {\n entries = [];\n byCode.set(code, entries);\n }\n if (!entries.some((entry) => entry.id === item.id)) {\n entries.push({ id: item.id, title: item.title, parent: isNonEmptyIdReference(item.parent) ? item.parent.trim() : null });\n }\n }\n\n const duplicates: DuplicateIssueCode[] = [];\n for (const [code, entries] of byCode) {\n if (entries.length < 2) {\n continue;\n }\n // GH-275: drop children whose parent is another item carrying the same code\n // (intentional `PARENT` + `PARENT-T0n` breakdown), then re-check the group.\n // The parent reference is resolved only against the same-code group on\n // purpose: a child is by-design noise solely when its parent shares the code\n // (resolving against the full corpus would suppress genuinely colliding\n // siblings whose parent merely exists elsewhere). Comparison is\n // case-insensitive so a `parent` reference recorded in a different case than\n // the canonical id (e.g. an upper-case `id_prefix`) still matches.\n const idsInGroup = new Set(entries.map((entry) => entry.id.toLowerCase()));\n const collisionEntries = entries.filter(\n (entry) => entry.parent === null || !idsInGroup.has(entry.parent.toLowerCase()),\n );\n if (collisionEntries.length < 2) {\n continue;\n }\n const sorted = [...collisionEntries].sort((left, right) => left.id.localeCompare(right.id));\n duplicates.push({\n code,\n count: sorted.length,\n ids: sorted.map((entry) => entry.id),\n titles: sorted.map((entry) => entry.title),\n });\n }\n return duplicates.sort((left, right) => left.code.localeCompare(right.code));\n}\n", "/**\n * Per-item-type grouping of missing-required-field counts for\n * `pm validate --check-metadata` (pm-pmyq / GH-172).\n *\n * Pure module: callers stream `(item_type, field)` pairs — one per missing\n * required field occurrence — and receive a compact, deterministically sorted\n * `missing_by_type` map of counts (never row dumps), e.g.\n * `{ Task: { close_reason: 3, reviewer: 1 } }`.\n */\n\n/** One missing required metadata field observed on an item of a specific type. */\nexport interface MissingFieldOccurrence {\n /** Item type name as stored in front matter (e.g. \"Task\"). */\n item_type: string;\n /** Required metadata field that is missing on the item. */\n field: string;\n}\n\n/**\n * Aggregate missing-field occurrences into `{ type: { field: count } }` with\n * both levels sorted lexicographically for stable, diff-friendly output.\n * Zero counts never appear (only observed occurrences are aggregated).\n */\nexport function buildMissingByTypeCounts(\n occurrences: Iterable<MissingFieldOccurrence>,\n): Record<string, Record<string, number>> {\n const countsByType = new Map<string, Map<string, number>>();\n for (const occurrence of occurrences) {\n let fieldCounts = countsByType.get(occurrence.item_type);\n if (!fieldCounts) {\n fieldCounts = new Map<string, number>();\n countsByType.set(occurrence.item_type, fieldCounts);\n }\n fieldCounts.set(occurrence.field, (fieldCounts.get(occurrence.field) ?? 0) + 1);\n }\n\n const result: Record<string, Record<string, number>> = {};\n for (const type of [...countsByType.keys()].sort((left, right) => left.localeCompare(right))) {\n const fieldCounts = countsByType.get(type)!;\n const fields: Record<string, number> = {};\n for (const field of [...fieldCounts.keys()].sort((left, right) => left.localeCompare(right))) {\n fields[field] = fieldCounts.get(field)!;\n }\n result[type] = fields;\n }\n return result;\n}\n", "/**\n * Classification of stale linked paths reported by `pm validate --check-files`.\n *\n * A linked file path that no longer exists is either:\n * - `moved`: a file with the same basename still exists elsewhere in the\n * scanned candidate set — the candidates are reported so an agent can relink\n * the item to the new location instead of dropping the link, or\n * - `deleted`: no candidate with that basename exists anywhere in the scan,\n * so the link points at content that is gone and pruning it is safe.\n *\n * Pure module (pm-0v2m / GH-184): no filesystem access — callers pass the\n * already-collected candidate file list from the files check scan.\n */\n\n/** Classification labels for linked paths that no longer exist on disk. */\nexport type StaleLinkedPathClassification = \"moved\" | \"deleted\";\n\n/**\n * Documents the classified stale linked path payload exchanged by command, SDK, and package integrations.\n */\nexport interface ClassifiedStaleLinkedPath {\n /** Normalized workspace-relative stale linked path. */\n path: string;\n classification: StaleLinkedPathClassification;\n /**\n * Candidate new locations (same basename, different path), sorted and capped\n * at `candidateLimit`. Empty for `deleted`.\n */\n candidates: string[];\n /** True when more candidates existed than `candidateLimit` allowed. */\n candidates_truncated: boolean;\n}\n\nexport const DEFAULT_STALE_PATH_CANDIDATE_LIMIT = 3;\n\nfunction basenameOf(relativePath: string): string {\n const lastSlash = Math.max(relativePath.lastIndexOf(\"/\"), relativePath.lastIndexOf(\"\\\\\"));\n return lastSlash === -1 ? relativePath : relativePath.slice(lastSlash + 1);\n}\n\n/**\n * Classify each stale (missing) linked path as `moved` or `deleted` by\n * matching its basename against the candidate file list. Output preserves the\n * input order of `stalePaths` (callers pass an already-sorted unique list).\n * A candidate equal to the stale path itself never matches (the path is known\n * missing; an identical candidate would be self-referential noise).\n */\nexport function classifyStaleLinkedPaths(\n stalePaths: readonly string[],\n candidateFiles: readonly string[],\n candidateLimit: number = DEFAULT_STALE_PATH_CANDIDATE_LIMIT,\n): ClassifiedStaleLinkedPath[] {\n const limit = Number.isFinite(candidateLimit) && candidateLimit >= 1 ? Math.floor(candidateLimit) : DEFAULT_STALE_PATH_CANDIDATE_LIMIT;\n const candidatesByBasename = new Map<string, string[]>();\n for (const candidate of candidateFiles) {\n const basename = basenameOf(candidate);\n if (basename.length === 0) {\n continue;\n }\n const bucket = candidatesByBasename.get(basename);\n if (bucket) {\n bucket.push(candidate);\n } else {\n candidatesByBasename.set(basename, [candidate]);\n }\n }\n\n return stalePaths.map((stalePath) => {\n const matches = (candidatesByBasename.get(basenameOf(stalePath)) ?? [])\n .filter((candidate) => candidate !== stalePath)\n .sort((left, right) => left.localeCompare(right));\n if (matches.length === 0) {\n return {\n path: stalePath,\n classification: \"deleted\" as const,\n candidates: [],\n candidates_truncated: false,\n };\n }\n return {\n path: stalePath,\n classification: \"moved\" as const,\n candidates: matches.slice(0, limit),\n candidates_truncated: matches.length > limit,\n };\n });\n}\n\n/**\n * Render compact `<path>:moved:<top-candidate>` / `<path>:deleted` rows for\n * the files check details (token-efficient counterpart to the full\n * classification objects).\n */\nexport function summarizeStaleLinkedPathClassifications(classified: readonly ClassifiedStaleLinkedPath[]): string[] {\n return classified.map((entry) =>\n entry.classification === \"moved\" ? `${entry.path}:moved:${entry.candidates[0]}` : `${entry.path}:deleted`,\n );\n}\n", "/**\n * Owner attribution for stale linked paths reported by `pm validate --check-files`.\n *\n * The files check collects, per item, the linked paths (from the item's `files`\n * and `docs` link lists) that no longer resolve on disk. By default those are\n * surfaced as bare path strings + `path:classification` rows, which forces a\n * reverse lookup to discover which item owns each stale link. This module turns\n * the already-collected stale-link rows into owner-attributed, path-grouped rows\n * so an agent can perform evidence-based cleanup (relink/prune) without that\n * reverse lookup.\n *\n * Pure module (GH-210): no filesystem access and no heavy imports — callers pass\n * the already-collected stale-link rows plus a metadata `lookup` closure.\n */\n\n/** Classification assigned to a stale linked path during files validation. */\nexport type StaleLinkClassification = \"moved\" | \"deleted\";\n\n/**\n * Documents the stale link owner input payload exchanged by command, SDK, and package integrations.\n */\nexport interface StaleLinkOwnerInput {\n item_id: string;\n /** Normalized workspace-relative path that no longer resolves. */\n path: string;\n /** Which link list of the owning item the path lives in. */\n link_kind: \"files\" | \"docs\";\n classification: StaleLinkClassification;\n}\n\n/**\n * Documents the missing linked path owner payload exchanged by command, SDK, and package integrations.\n */\nexport interface MissingLinkedPathOwner {\n id: string;\n /** Owning item type, `\"Unknown\"` if metadata is absent. */\n type: string;\n /** Owning item title, `\"\"` if absent. */\n title: string;\n /** Owning item status, `\"\"` if absent. */\n status: string;\n /** The link list the path lives in (= the input `link_kind`). */\n field: \"files\" | \"docs\";\n}\n\n/**\n * Documents the missing linked path row payload exchanged by command, SDK, and package integrations.\n */\nexport interface MissingLinkedPathRow {\n path: string;\n classification: StaleLinkClassification;\n items: MissingLinkedPathOwner[];\n}\n\n/**\n * Documents the owner item metadata payload exchanged by command, SDK, and package integrations.\n */\nexport interface OwnerItemMetadata {\n type?: string;\n title?: string;\n status?: string;\n}\n\ninterface PathBucket {\n classification: StaleLinkClassification;\n /** Keyed by `<id> <field>` so identical owners de-duplicate. */\n owners: Map<string, StaleLinkOwnerInput>;\n}\n\n/**\n * `moved` wins over `deleted` when a single path's rows disagree on\n * classification: `moved` means a relink candidate exists, which is the safer,\n * more-actionable signal (relink instead of risk pruning a still-reachable\n * link). In practice all rows for one path share a classification; this is a\n * deterministic tie-break for the degenerate case.\n */\nfunction preferClassification(\n current: StaleLinkClassification,\n next: StaleLinkClassification,\n): StaleLinkClassification {\n return current === \"moved\" || next === \"moved\" ? \"moved\" : \"deleted\";\n}\n\nfunction ownerKey(input: StaleLinkOwnerInput): string {\n return `${input.item_id} ${input.link_kind}`;\n}\n\n/**\n * Group stale-link owner inputs by linked path and attach owning-item metadata.\n *\n * - Paths sorted ascending (`localeCompare`); items within a path sorted by `id`\n * then `field`.\n * - De-duplicates identical `(id, field)` owners for the same path.\n * - `classification` per path follows {@link preferClassification} (moved wins).\n * - Missing metadata falls back: type `\"Unknown\"`, title `\"\"`, status `\"\"`.\n */\nexport function buildMissingLinkedPathRows(\n rows: readonly StaleLinkOwnerInput[],\n lookup: (itemId: string) => OwnerItemMetadata | undefined,\n): MissingLinkedPathRow[] {\n const buckets = new Map<string, PathBucket>();\n for (const row of rows) {\n const bucket = buckets.get(row.path);\n if (bucket) {\n bucket.classification = preferClassification(bucket.classification, row.classification);\n bucket.owners.set(ownerKey(row), row);\n } else {\n buckets.set(row.path, {\n classification: row.classification,\n owners: new Map([[ownerKey(row), row]]),\n });\n }\n }\n\n return [...buckets.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([path, bucket]) => ({\n path,\n classification: bucket.classification,\n items: [...bucket.owners.values()]\n .map((owner): MissingLinkedPathOwner => {\n const metadata = lookup(owner.item_id);\n return {\n id: owner.item_id,\n type: metadata?.type ?? \"Unknown\",\n title: metadata?.title ?? \"\",\n status: metadata?.status ?? \"\",\n field: owner.link_kind,\n };\n })\n .sort((leftOwner, rightOwner) => {\n const byId = leftOwner.id.localeCompare(rightOwner.id);\n return byId !== 0 ? byId : leftOwner.field.localeCompare(rightOwner.field);\n }),\n }));\n}\n\nfunction escapeTitle(title: string): string {\n return title.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Token-efficient one-line-per-owner serialization for the files-check details\n * (compact text counterpart to the full {@link MissingLinkedPathRow} objects).\n * Format per owner row:\n * `<path>:<classification> owner=<id> status=<status> field=<field> title=\"<title>\"`\n * Title is double-quoted with backslash/quote escaping; empty status/title still\n * render (`status=` and `title=\"\"`). Order follows\n * {@link buildMissingLinkedPathRows} output order.\n */\nexport function summarizeMissingLinkedPathRows(rows: readonly MissingLinkedPathRow[]): string[] {\n const lines: string[] = [];\n for (const row of rows) {\n for (const owner of row.items) {\n lines.push(\n `${row.path}:${row.classification} owner=${owner.id} status=${owner.status} field=${owner.field} title=\"${escapeTitle(owner.title)}\"`,\n );\n }\n }\n return lines;\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgBM,SAAU,iCAAiC,gBAAqC;AACpF,SAAO,iCAAiC,eAAe,cAAc,KAAK,eAAe;AAC3F;;;;;;;;;;ACyCA,eAAsB,SACpB,IACA,OACAA,SACA,UAAgC,CAAA,GAAE;AAElC,QAAM,SAAS,cAAc,QAAQ,IAAG,GAAIA,QAAO,IAAI;AACvD,MAAI,CAAE,MAAM,WAAW,gBAAgB,MAAM,CAAC,GAAI;AAChD,UAAM,IAAI,WAAW,iCAAiC,MAAM,wBAAwB,UAAU,SAAS;EACzG;AACA,QAAM,WAAW,MAAM,aAAa,MAAM;AAC1C,QAAM,iBAAiB,6BAA6B,SAAS,MAAM;AACnE,QAAM,SAAS,cAAc,QAAQ,QAAQ,SAAS,cAAc;AACpE,MAAI,mBAAkC;AACtC,MAAI,UAAU;AACd,QAAM,mBAA6B,CAAA;AAEnC,QAAM,SAAS,MAAM,WAAW;IAC9B;IACA;IACA;IACA,IAAI;IACJ;IACA,SAAS,QAAQ;IACjB;IACA,UAAU;IACV,OAAO,UAAQ;AACb,YAAM,kBAAkB,SAAS,SAAS;AAC1C,YAAM,sBAAsB,OAAO,oBAAoB,WAAW,kBAAkB;AACpF,yBAAmB,oBAAoB,KAAI,EAAG,S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F,QAAM,sBAAsB,2BAA2B,QAAQ,mBAAmB;AAClF,QAAM,eAAe,oBAAoB,QAAQ,QAAQ;AACzD,QAAM,gBAAgB,qBAAqB,MAAM;AACjD,QAAM,QAAQ,MAAM,+BAA+B;IACjD;IACA;IACA,QAAAA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,iBAAiB,CAAC,GAAG,IAAI,IAAI,gBAAgB,CAAC;GAC/C;AAOD,QAAM,QAAQ,iBACV,MAAM,0BAA0B,SAAS,OAAO,UAAU,kBAAkBA,OAAM,IAClF;AAEJ,QAAM,qBAAqB,CAAC,GAAG,IAAI,IAAI,MAAM,QAAQ,CAAC,EAAE,KAAK,CAAC,MAAM,UAAU,KAAK,cAAc,KAAK,CAAC;AACvG,QAAM,YAAY,MAAM,OAAO,KAAK,CAAC,UAAU,MAAM,WAAW,OAAO;AACvE,SAAO;IACL,IAAI,CAAC;IACL,cAAc,mBAAmB,SAAS;IAC1C,QAAQ,MAAM;IACd,UAAU;IACV,GAAI,UAAU,SAAY,EAAE,MAAK,IAAK,CAAA;IACtC,cAAc,OAAM;;AAExB;",
|
|
6
|
-
"names": ["global", "global", "fs", "path", "nowMs", "fs", "path", "isErrno", "nowMs", "isErrno", "path", "fs", "global", "fs", "path", "path", "fs", "global", "global", "fs", "path", "path", "fs", "global", "fs", "path", "TELEMETRY_QUEUE_RELATIVE_PATH", "path", "TELEMETRY_STATE_RELATIVE_PATH", "parseTelemetryQueue", "fs", "path", "kind", "versionSeparator", "resolveAuthor", "path", "global", "resolveTrackedRunId", "global", "fs", "spawn", "path", "path", "fs", "spawn", "global", "fs", "path", "path", "normalizeRelativePath", "path", "fs", "summarizeList", "buildHistoryDriftCheck", "global", "buildHistoryDriftCheck", "global"]
|
|
7
|
-
}
|