@unbrained/pm-cli 2026.7.1 → 2026.7.3
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/.claude-plugin/marketplace.json +3 -3
- package/CHANGELOG.md +25 -0
- package/CONTRIBUTING.md +2 -2
- package/README.md +1 -1
- package/dist/cli/commander-usage.d.ts +2 -0
- package/dist/cli/commander-usage.js +110 -86
- package/dist/cli/commander-usage.js.map +1 -1
- package/dist/cli/commands/activity.js +79 -57
- package/dist/cli/commands/activity.js.map +1 -1
- package/dist/cli/commands/aggregate.js +102 -79
- package/dist/cli/commands/aggregate.js.map +1 -1
- package/dist/cli/commands/calendar.js +278 -243
- package/dist/cli/commands/calendar.js.map +1 -1
- package/dist/cli/commands/close-many.js +176 -114
- package/dist/cli/commands/close-many.js.map +1 -1
- package/dist/cli/commands/close.js +157 -129
- package/dist/cli/commands/close.js.map +1 -1
- package/dist/cli/commands/comments-audit.js +50 -42
- package/dist/cli/commands/comments-audit.js.map +1 -1
- package/dist/cli/commands/config.d.ts +2 -0
- package/dist/cli/commands/config.js +443 -879
- package/dist/cli/commands/config.js.map +1 -1
- package/dist/cli/commands/context.js +365 -287
- package/dist/cli/commands/context.js.map +1 -1
- package/dist/cli/commands/contracts.js +352 -238
- package/dist/cli/commands/contracts.js.map +1 -1
- package/dist/cli/commands/create.js +32 -17
- package/dist/cli/commands/create.js.map +1 -1
- package/dist/cli/commands/dedupe-audit.js +46 -39
- package/dist/cli/commands/dedupe-audit.js.map +1 -1
- package/dist/cli/commands/dedupe-merge.js +88 -69
- package/dist/cli/commands/dedupe-merge.js.map +1 -1
- package/dist/cli/commands/extension/doctor.js +56 -67
- package/dist/cli/commands/extension/doctor.js.map +1 -1
- package/dist/cli/commands/extension/shared.js +21 -15
- package/dist/cli/commands/extension/shared.js.map +1 -1
- package/dist/cli/commands/get.js +114 -81
- package/dist/cli/commands/get.js.map +1 -1
- package/dist/cli/commands/health.d.ts +17 -0
- package/dist/cli/commands/health.js +545 -417
- package/dist/cli/commands/health.js.map +1 -1
- package/dist/cli/commands/history-compact.js +209 -140
- package/dist/cli/commands/history-compact.js.map +1 -1
- package/dist/cli/commands/history-redact.js +162 -119
- package/dist/cli/commands/history-redact.js.map +1 -1
- package/dist/cli/commands/history-repair.js +120 -85
- package/dist/cli/commands/history-repair.js.map +1 -1
- package/dist/cli/commands/init-agent-guidance.js +32 -19
- package/dist/cli/commands/init-agent-guidance.js.map +1 -1
- package/dist/cli/commands/init.d.ts +8 -2
- package/dist/cli/commands/init.js +263 -162
- package/dist/cli/commands/init.js.map +1 -1
- package/dist/cli/commands/list.js +152 -102
- package/dist/cli/commands/list.js.map +1 -1
- package/dist/cli/commands/next.js +60 -40
- package/dist/cli/commands/next.js.map +1 -1
- package/dist/cli/commands/plan.js +373 -298
- package/dist/cli/commands/plan.js.map +1 -1
- package/dist/cli/commands/profile.js +23 -15
- package/dist/cli/commands/profile.js.map +1 -1
- package/dist/cli/commands/recurrence-parsers.js +43 -25
- package/dist/cli/commands/recurrence-parsers.js.map +1 -1
- package/dist/cli/commands/reindex.d.ts +21 -5
- package/dist/cli/commands/reindex.js +345 -205
- package/dist/cli/commands/reindex.js.map +1 -1
- package/dist/cli/commands/restore.d.ts +8 -7
- package/dist/cli/commands/restore.js +105 -69
- package/dist/cli/commands/restore.js.map +1 -1
- package/dist/cli/commands/schema.js +33 -30
- package/dist/cli/commands/schema.js.map +1 -1
- package/dist/cli/commands/search.d.ts +10 -2
- package/dist/cli/commands/search.js +503 -470
- package/dist/cli/commands/search.js.map +1 -1
- package/dist/cli/commands/telemetry.js +98 -87
- package/dist/cli/commands/telemetry.js.map +1 -1
- package/dist/cli/commands/test-all.js +237 -168
- package/dist/cli/commands/test-all.js.map +1 -1
- package/dist/cli/commands/test.d.ts +6 -5
- package/dist/cli/commands/test.js +424 -344
- package/dist/cli/commands/test.js.map +1 -1
- package/dist/cli/commands/update-many.js +57 -42
- package/dist/cli/commands/update-many.js.map +1 -1
- package/dist/cli/commands/update.d.ts +1 -1
- package/dist/cli/commands/update.js +738 -671
- package/dist/cli/commands/update.js.map +1 -1
- package/dist/cli/commands/validate.d.ts +20 -1
- package/dist/cli/commands/validate.js +478 -343
- package/dist/cli/commands/validate.js.map +1 -1
- package/dist/cli/error-guidance.js +406 -361
- package/dist/cli/error-guidance.js.map +1 -1
- package/dist/cli/extension-command-help.js +27 -19
- package/dist/cli/extension-command-help.js.map +1 -1
- package/dist/cli/help-json-payload.js +57 -49
- package/dist/cli/help-json-payload.js.map +1 -1
- package/dist/cli/main.d.ts +47 -0
- package/dist/cli/main.js +474 -371
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/migration-gates.js +22 -45
- package/dist/cli/migration-gates.js.map +1 -1
- package/dist/cli/register-list-query.js +299 -310
- package/dist/cli/register-list-query.js.map +1 -1
- package/dist/cli/register-mutation.js +763 -779
- package/dist/cli/register-mutation.js.map +1 -1
- package/dist/cli/register-operations.js +386 -362
- package/dist/cli/register-operations.js.map +1 -1
- package/dist/cli/register-setup.js +120 -101
- package/dist/cli/register-setup.js.map +1 -1
- package/dist/cli/registration-helpers.d.ts +4 -0
- package/dist/cli/registration-helpers.js +45 -56
- package/dist/cli/registration-helpers.js.map +1 -1
- package/dist/cli-bundle/chunks/{activity-DBLQVIP6.js → activity-5YWLSPGE.js} +9 -9
- package/dist/cli-bundle/chunks/activity-BIML7K2D.js +16 -0
- package/dist/cli-bundle/chunks/{aggregate-SDF7DUOD.js → aggregate-2V2M3JZU.js} +107 -83
- package/dist/cli-bundle/chunks/{aggregate-SDF7DUOD.js.map → aggregate-2V2M3JZU.js.map} +2 -2
- package/dist/cli-bundle/chunks/{aggregate-JTEF4BP7.js → aggregate-EK7DXML7.js} +108 -84
- package/dist/cli-bundle/chunks/aggregate-EK7DXML7.js.map +1 -0
- package/dist/cli-bundle/chunks/{append-LOVPGVPT.js → append-EZESUVJT.js} +8 -8
- package/dist/cli-bundle/chunks/{append-QCFJSDFL.js → append-JFG4WQMG.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-TP5Q5ZD3.js → chunk-32IUNTG4.js} +158 -119
- package/dist/cli-bundle/chunks/chunk-32IUNTG4.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-BHO33VBQ.js → chunk-3W2HJKJX.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-VARHOHYV.js → chunk-4EXFFP7T.js} +86 -52
- package/dist/cli-bundle/chunks/chunk-4EXFFP7T.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-4DUVCVLZ.js → chunk-4PFVUUYV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JSU5P7VS.js → chunk-4WB6S4YX.js} +308 -184
- package/dist/cli-bundle/chunks/chunk-4WB6S4YX.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-HXTQJXWT.js → chunk-572FKBRL.js} +61 -102
- package/dist/cli-bundle/chunks/chunk-572FKBRL.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-IJYK2T43.js → chunk-5E7N4T2Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NKZAN7BD.js → chunk-5IZUBZBR.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-NOLPZMSV.js → chunk-5JIWFWOZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FFMQB7WR.js → chunk-67LARBDL.js} +493 -404
- package/dist/cli-bundle/chunks/chunk-67LARBDL.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-6AQZPVHQ.js → chunk-6CDCWKSX.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-3K2M5OYU.js → chunk-6KRFL33E.js} +308 -184
- package/dist/cli-bundle/chunks/chunk-6KRFL33E.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-LB6TP6MC.js → chunk-6NYJGMTY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SLMUGTK3.js → chunk-7CLLC75T.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-2466X6E4.js → chunk-7LYO6S5A.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-W4ULYO7Z.js → chunk-A3OQ7TFW.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-5CGRF3L5.js → chunk-AIKU3IIL.js} +153 -90
- package/dist/cli-bundle/chunks/chunk-AIKU3IIL.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-WYDHYJPO.js → chunk-AJHYQCBJ.js} +39 -5
- package/dist/cli-bundle/chunks/chunk-AJHYQCBJ.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-VZDBVEZR.js → chunk-B4O5S7I3.js} +79 -57
- package/dist/cli-bundle/chunks/{chunk-VZDBVEZR.js.map → chunk-B4O5S7I3.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OTUHB4HS.js → chunk-BE2SR6QL.js} +92 -77
- package/dist/cli-bundle/chunks/chunk-BE2SR6QL.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-JLM7BHI7.js → chunk-BI4R7HI2.js} +75 -53
- package/dist/cli-bundle/chunks/chunk-BI4R7HI2.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-AXIDKKAT.js → chunk-CXR3CMBQ.js} +33 -6
- package/dist/cli-bundle/chunks/chunk-CXR3CMBQ.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-ZETXE4SE.js → chunk-ECU6MMTQ.js} +713 -613
- package/dist/cli-bundle/chunks/chunk-ECU6MMTQ.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-2D4HATP2.js → chunk-EJ2OCBHF.js} +54 -30
- package/dist/cli-bundle/chunks/chunk-EJ2OCBHF.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-BDTISOSD.js → chunk-EQURFOMH.js} +41 -26
- package/dist/cli-bundle/chunks/chunk-EQURFOMH.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-GJ326ZKX.js → chunk-ER4ME5U2.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-HZZEHPRG.js → chunk-ERG65A2L.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IZBR4NRW.js → chunk-F6WNBITZ.js} +157 -113
- package/dist/cli-bundle/chunks/chunk-F6WNBITZ.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-L5OEFZQG.js → chunk-FH2H3CBD.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-JPECA746.js → chunk-FUFFPIYA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-CF7RL6FR.js → chunk-FZJM2TXF.js} +110 -73
- package/dist/cli-bundle/chunks/chunk-FZJM2TXF.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-27BXPBAY.js → chunk-GUYNUXQT.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-MAUKX7JC.js → chunk-GVJE5T7Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3J6JRJ3I.js → chunk-HB4FAT3O.js} +42 -60
- package/dist/cli-bundle/chunks/chunk-HB4FAT3O.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-55SNVXRQ.js → chunk-HQAF23Q2.js} +626 -484
- package/dist/cli-bundle/chunks/chunk-HQAF23Q2.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-ZRP4VG5U.js → chunk-JBZ2NTKX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RMMQ74TG.js → chunk-JPATY4SE.js} +54 -30
- package/dist/cli-bundle/chunks/chunk-JPATY4SE.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-IPYBJWTE.js → chunk-K5DT2YKM.js} +109 -72
- package/dist/cli-bundle/chunks/chunk-K5DT2YKM.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-EJUDVUYZ.js → chunk-KEZOIPCR.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-RVUALSJF.js → chunk-KHVGM5CS.js} +466 -365
- package/dist/cli-bundle/chunks/chunk-KHVGM5CS.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-YITK2PJ6.js → chunk-KS6ATO47.js} +288 -175
- package/dist/cli-bundle/chunks/chunk-KS6ATO47.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-7R4QEMZZ.js → chunk-L4SLHV6G.js} +463 -362
- package/dist/cli-bundle/chunks/chunk-L4SLHV6G.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-RLDHZHQS.js → chunk-LBE5QFMZ.js} +158 -114
- package/dist/cli-bundle/chunks/chunk-LBE5QFMZ.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-22WKIL3H.js → chunk-LCWQP6NM.js} +76 -54
- package/dist/cli-bundle/chunks/chunk-LCWQP6NM.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-KNPEF7QG.js → chunk-LOWVNZBZ.js} +91 -76
- package/dist/cli-bundle/chunks/chunk-LOWVNZBZ.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-HYTGA6GI.js → chunk-MDHWWBNZ.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-N74UMG5H.js → chunk-MEZZZBYX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V3NOKJF2.js → chunk-MHRS5FUX.js} +288 -175
- package/dist/cli-bundle/chunks/chunk-MHRS5FUX.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-3XZCOZ5J.js → chunk-NOIEVOK5.js} +391 -313
- package/dist/cli-bundle/chunks/chunk-NOIEVOK5.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-SDR5J34Q.js → chunk-NZ7QIUP5.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-UYUYDGIB.js → chunk-OGLGI22K.js} +115 -67
- package/dist/cli-bundle/chunks/{chunk-UYUYDGIB.js.map → chunk-OGLGI22K.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-DDPTYJIM.js → chunk-P5L7Z2O6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BZCEN4JA.js → chunk-PULUSQAV.js} +492 -403
- package/dist/cli-bundle/chunks/chunk-PULUSQAV.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-3VGN2UWE.js → chunk-QCDTQCMW.js} +22 -30
- package/dist/cli-bundle/chunks/chunk-QCDTQCMW.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-4A3BJ675.js → chunk-QNNQAAZ5.js} +24 -18
- package/dist/cli-bundle/chunks/{chunk-4A3BJ675.js.map → chunk-QNNQAAZ5.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-MDPEOIGN.js → chunk-RAHINBVP.js} +60 -101
- package/dist/cli-bundle/chunks/chunk-RAHINBVP.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-CWFNTKQJ.js → chunk-RJH5VQHW.js} +43 -61
- package/dist/cli-bundle/chunks/chunk-RJH5VQHW.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-OGXLACHC.js → chunk-SU2E4AWU.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-HPPFYYOV.js → chunk-SU3TB4NS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JWXRETDF.js → chunk-SYE6WMV6.js} +626 -484
- package/dist/cli-bundle/chunks/chunk-SYE6WMV6.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-NWMZWYYB.js → chunk-T3P7PMZP.js} +42 -27
- package/dist/cli-bundle/chunks/chunk-T3P7PMZP.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-G7I7DEZA.js → chunk-T4XBKJ3F.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-RH5ZBYFD.js → chunk-T6AXEBOP.js} +23 -17
- package/dist/cli-bundle/chunks/{chunk-RH5ZBYFD.js.map → chunk-T6AXEBOP.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5QFDBI4F.js → chunk-TQ6AX5SQ.js} +58 -69
- package/dist/cli-bundle/chunks/{chunk-5QFDBI4F.js.map → chunk-TQ6AX5SQ.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4XOIEKSD.js → chunk-U3S2B7TA.js} +86 -52
- package/dist/cli-bundle/chunks/chunk-U3S2B7TA.js.map +1 -0
- package/dist/cli-bundle/chunks/{chunk-VICZWYGZ.js → chunk-U5TR4N7J.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-EVMTBV6V.js → chunk-UMNQZS4H.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-A7FPBAQS.js → chunk-WJA3PXW7.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-RGEMWD6Q.js → chunk-WRYERRZX.js} +157 -118
- package/dist/cli-bundle/chunks/chunk-WRYERRZX.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-NUHHPVVS.js → chunk-WYOIIFSE.js} +712 -612
- package/dist/cli-bundle/chunks/chunk-WYOIIFSE.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-4DSGXSBL.js → chunk-XRYSCRZR.js} +116 -68
- package/dist/cli-bundle/chunks/{chunk-4DSGXSBL.js.map → chunk-XRYSCRZR.js.map} +3 -3
- package/dist/cli-bundle/chunks/{chunk-NU2UEROZ.js → chunk-YF746GTH.js} +59 -70
- package/dist/cli-bundle/chunks/{chunk-NU2UEROZ.js.map → chunk-YF746GTH.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-JMP4E6D7.js → chunk-YPWUSH72.js} +390 -312
- package/dist/cli-bundle/chunks/{chunk-JMP4E6D7.js.map → chunk-YPWUSH72.js.map} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QCWF6IYD.js → chunk-YSDFIY7N.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-UZIWVBE6.js → chunk-YSGTMDWC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NFDPYAIP.js → chunk-YVKZ3ANP.js} +21 -29
- package/dist/cli-bundle/chunks/chunk-YVKZ3ANP.js.map +7 -0
- package/dist/cli-bundle/chunks/{chunk-OKQ22KTH.js → chunk-Z4DGFQDH.js} +80 -58
- package/dist/cli-bundle/chunks/{chunk-OKQ22KTH.js.map → chunk-Z4DGFQDH.js.map} +1 -1
- package/dist/cli-bundle/chunks/{chunk-64HNBBFQ.js → chunk-Z5F6XZXE.js} +6 -6
- package/dist/cli-bundle/chunks/{chunk-AVEE5EHK.js → chunk-Z7RPDF2Y.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-3S2KT7NG.js → chunk-ZFTKYWIF.js} +152 -89
- package/dist/cli-bundle/chunks/chunk-ZFTKYWIF.js.map +7 -0
- package/dist/cli-bundle/chunks/{claim-T3GCKV7C.js → claim-2BGBGSVI.js} +8 -8
- package/dist/cli-bundle/chunks/{claim-EMQLYPRW.js → claim-5GU7OE67.js} +8 -8
- package/dist/cli-bundle/chunks/close-6YODBUIV.js +14 -0
- package/dist/cli-bundle/chunks/{close-TQYAAFJP.js → close-AFVKPR57.js} +7 -7
- package/dist/cli-bundle/chunks/{close-many-BG5QQIDQ.js → close-many-7KLOSYLP.js} +186 -122
- package/dist/cli-bundle/chunks/close-many-7KLOSYLP.js.map +7 -0
- package/dist/cli-bundle/chunks/{close-many-LDRVEQY2.js → close-many-JKUJMHLG.js} +187 -123
- package/dist/cli-bundle/chunks/close-many-JKUJMHLG.js.map +1 -0
- package/dist/cli-bundle/chunks/{comments-YUXJRZPQ.js → comments-DNWHEBOS.js} +9 -9
- package/dist/cli-bundle/chunks/{comments-QCKR2YY2.js → comments-RW23R3VE.js} +9 -9
- package/dist/cli-bundle/chunks/config-AUM5WBYA.js +1072 -0
- package/dist/cli-bundle/chunks/config-AUM5WBYA.js.map +7 -0
- package/dist/cli-bundle/chunks/config-OZWSA2NP.js +1062 -0
- package/dist/cli-bundle/chunks/config-OZWSA2NP.js.map +1 -0
- package/dist/cli-bundle/chunks/{context-B6275WPX.js → context-OYXRGY7S.js} +12 -12
- package/dist/cli-bundle/chunks/{context-OCZ3FJ4Z.js → context-PKCEHQY3.js} +12 -12
- package/dist/cli-bundle/chunks/{contracts-HN7ABKLP.js → contracts-L6ODXNUM.js} +320 -199
- package/dist/cli-bundle/chunks/contracts-L6ODXNUM.js.map +7 -0
- package/dist/cli-bundle/chunks/{contracts-W4FZVVD6.js → contracts-X74F2GSM.js} +321 -200
- package/dist/cli-bundle/chunks/contracts-X74F2GSM.js.map +1 -0
- package/dist/cli-bundle/chunks/{copy-DEM4DATS.js → copy-6XOR3HKN.js} +5 -5
- package/dist/cli-bundle/chunks/{copy-BTJOSKKT.js → copy-I4NCLBR4.js} +5 -5
- package/dist/cli-bundle/chunks/{create-RLRJMRTM.js → create-PM45M6PE.js} +12 -12
- package/dist/cli-bundle/chunks/create-Z7YCH3BE.js +28 -0
- package/dist/cli-bundle/chunks/{delete-BHK7VB2Z.js → delete-7YXHYG67.js} +5 -5
- package/dist/cli-bundle/chunks/{delete-LSVHAB4Y.js → delete-LPISP43T.js} +5 -5
- package/dist/cli-bundle/chunks/{deps-XHYXWEPT.js → deps-N2T26FME.js} +5 -5
- package/dist/cli-bundle/chunks/{deps-4UDFJRUA.js → deps-WATKQDE3.js} +5 -5
- package/dist/cli-bundle/chunks/{docs-GYZNVS26.js → docs-6LQ3GLM7.js} +7 -7
- package/dist/cli-bundle/chunks/{docs-26S44RXU.js → docs-Z3X6JZLT.js} +7 -7
- package/dist/cli-bundle/chunks/{eval-UYF3ZPVO.js → eval-6DCLG52D.js} +10 -10
- package/dist/cli-bundle/chunks/{eval-PGRVIJQU.js → eval-Y3ZCUTHK.js} +10 -10
- package/dist/cli-bundle/chunks/{extension-CPSLJQVE.js → extension-BNINIMT7.js} +11 -11
- package/dist/cli-bundle/chunks/{extension-CXJ6RELI.js → extension-QWE4YYK5.js} +11 -11
- package/dist/cli-bundle/chunks/{files-NQHEXUZD.js → files-6SGKHS6O.js} +7 -7
- package/dist/cli-bundle/chunks/{files-MBNICQFM.js → files-FUYPSOFJ.js} +7 -7
- package/dist/cli-bundle/chunks/{focus-DWYIG7GU.js → focus-2Q3K76G2.js} +6 -6
- package/dist/cli-bundle/chunks/{focus-XZW5423D.js → focus-ATLBWXXD.js} +6 -6
- package/dist/cli-bundle/chunks/{gc-LPVMKJQJ.js → gc-RUYEMNRF.js} +3 -3
- package/dist/cli-bundle/chunks/{gc-7GQYOS2G.js → gc-TDWSDR66.js} +3 -3
- package/dist/cli-bundle/chunks/{get-A7MAOHCU.js → get-2WGLX74N.js} +120 -80
- package/dist/cli-bundle/chunks/get-2WGLX74N.js.map +7 -0
- package/dist/cli-bundle/chunks/{get-DSDEKJ3L.js → get-LY6M2JIM.js} +121 -81
- package/dist/cli-bundle/chunks/get-LY6M2JIM.js.map +1 -0
- package/dist/cli-bundle/chunks/{health-3IPFLKXB.js → health-4RKHYS3T.js} +535 -371
- package/dist/cli-bundle/chunks/health-4RKHYS3T.js.map +1 -0
- package/dist/cli-bundle/chunks/{health-GZXGBZ36.js → health-TMFVNYRA.js} +534 -370
- package/dist/cli-bundle/chunks/health-TMFVNYRA.js.map +7 -0
- package/dist/cli-bundle/chunks/history-CGNQJXFE.js +18 -0
- package/dist/cli-bundle/chunks/{history-NERDJNUB.js → history-SGRRS72R.js} +8 -8
- package/dist/cli-bundle/chunks/{history-compact-2WRZ2WK4.js → history-compact-LOED43R3.js} +213 -134
- package/dist/cli-bundle/chunks/history-compact-LOED43R3.js.map +7 -0
- package/dist/cli-bundle/chunks/{history-compact-HR7BB4LR.js → history-compact-V5DNAQHH.js} +214 -135
- package/dist/cli-bundle/chunks/history-compact-V5DNAQHH.js.map +1 -0
- package/dist/cli-bundle/chunks/{history-redact-O3NBCNWC.js → history-redact-IRL7WJ3E.js} +9 -9
- package/dist/cli-bundle/chunks/history-redact-N3JK7VBW.js +19 -0
- package/dist/cli-bundle/chunks/{history-repair-XA3LC4GA.js → history-repair-4WVBVHFR.js} +124 -84
- package/dist/cli-bundle/chunks/history-repair-4WVBVHFR.js.map +1 -0
- package/dist/cli-bundle/chunks/{history-repair-LCMOS45X.js → history-repair-PGYQJMGD.js} +123 -83
- package/dist/cli-bundle/chunks/history-repair-PGYQJMGD.js.map +7 -0
- package/dist/cli-bundle/chunks/{init-64XDLQJB.js → init-4GESW7RM.js} +12 -12
- package/dist/cli-bundle/chunks/init-XIDPABA4.js +22 -0
- package/dist/cli-bundle/chunks/{learnings-LPKCSJX7.js → learnings-4BHWFFUV.js} +9 -9
- package/dist/cli-bundle/chunks/{learnings-JR6MA5TI.js → learnings-4FJY7WIW.js} +9 -9
- package/dist/cli-bundle/chunks/{list-G5Y65VF6.js → list-472TIOVK.js} +8 -8
- package/dist/cli-bundle/chunks/{list-DNBJVO3E.js → list-D7BF5CL2.js} +8 -8
- package/dist/cli-bundle/chunks/{next-FYTQF6HG.js → next-D5STGWI2.js} +71 -46
- package/dist/cli-bundle/chunks/next-D5STGWI2.js.map +1 -0
- package/dist/cli-bundle/chunks/{next-BCERKDUR.js → next-SFQZVX2B.js} +70 -45
- package/dist/cli-bundle/chunks/next-SFQZVX2B.js.map +7 -0
- package/dist/cli-bundle/chunks/{notes-2BMU3VVQ.js → notes-6KNOSLIT.js} +9 -9
- package/dist/cli-bundle/chunks/{notes-6KTGO2OJ.js → notes-W4UEICGF.js} +9 -9
- package/dist/cli-bundle/chunks/{plan-RKZHQVXR.js → plan-JO6V7BXO.js} +373 -279
- package/dist/cli-bundle/chunks/plan-JO6V7BXO.js.map +1 -0
- package/dist/cli-bundle/chunks/{plan-4WXEQCTN.js → plan-MJQW5XK3.js} +372 -278
- package/dist/cli-bundle/chunks/plan-MJQW5XK3.js.map +7 -0
- package/dist/cli-bundle/chunks/{profile-4OMM32CD.js → profile-3TOTMUR4.js} +27 -19
- package/dist/cli-bundle/chunks/profile-3TOTMUR4.js.map +7 -0
- package/dist/cli-bundle/chunks/{profile-QLER5ENE.js → profile-WIQY2KCV.js} +28 -20
- package/dist/cli-bundle/chunks/profile-WIQY2KCV.js.map +1 -0
- package/dist/cli-bundle/chunks/register-list-query-ELBHCCFI.js +416 -0
- package/dist/cli-bundle/chunks/register-list-query-ELBHCCFI.js.map +7 -0
- package/dist/cli-bundle/chunks/register-list-query-GAPQ6DM3.js +406 -0
- package/dist/cli-bundle/chunks/register-list-query-GAPQ6DM3.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-mutation-KK7PHYYU.js → register-mutation-ROFE2YPC.js} +729 -702
- package/dist/cli-bundle/chunks/register-mutation-ROFE2YPC.js.map +7 -0
- package/dist/cli-bundle/chunks/{register-mutation-ENNDUAZG.js → register-mutation-SJWMVIJ2.js} +730 -703
- package/dist/cli-bundle/chunks/register-mutation-SJWMVIJ2.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-operations-HZ6XERQG.js → register-operations-IADFVH53.js} +389 -365
- package/dist/cli-bundle/chunks/register-operations-IADFVH53.js.map +7 -0
- package/dist/cli-bundle/chunks/register-operations-MEKU3AKC.js +510 -0
- package/dist/cli-bundle/chunks/register-operations-MEKU3AKC.js.map +1 -0
- package/dist/cli-bundle/chunks/{register-setup-ZKJ53RS7.js → register-setup-3QJY43CY.js} +128 -103
- package/dist/cli-bundle/chunks/register-setup-3QJY43CY.js.map +7 -0
- package/dist/cli-bundle/chunks/{register-setup-P67EMBDJ.js → register-setup-AJWUSSQX.js} +129 -104
- package/dist/cli-bundle/chunks/register-setup-AJWUSSQX.js.map +1 -0
- package/dist/cli-bundle/chunks/{restore-4MHZFJ2E.js → restore-44IHMMZZ.js} +9 -9
- package/dist/cli-bundle/chunks/restore-EXHU34EU.js +17 -0
- package/dist/cli-bundle/chunks/{scheduling-shortcuts-LB6DOLRL.js → scheduling-shortcuts-OLHNLAZY.js} +12 -12
- package/dist/cli-bundle/chunks/{scheduling-shortcuts-UTOYKLXQ.js → scheduling-shortcuts-TSBK4AY5.js} +12 -12
- package/dist/cli-bundle/chunks/{schema-73HR2OJW.js → schema-IB2NZZWD.js} +7 -7
- package/dist/cli-bundle/chunks/{schema-U6LJKSIR.js → schema-VBCELP5G.js} +7 -7
- package/dist/cli-bundle/chunks/{search-AXPXKZER.js → search-7UBETML4.js} +10 -10
- package/dist/cli-bundle/chunks/{search-KILGT37L.js → search-R227JOL6.js} +10 -10
- package/dist/cli-bundle/chunks/{stats-W5KNVJWQ.js → stats-FAG7COEH.js} +6 -6
- package/dist/cli-bundle/chunks/{stats-PSYVVTNZ.js → stats-MCK7PLYS.js} +6 -6
- package/dist/cli-bundle/chunks/{telemetry-GAHHQTOS.js → telemetry-DRPDZMAO.js} +84 -70
- package/dist/cli-bundle/chunks/telemetry-DRPDZMAO.js.map +7 -0
- package/dist/cli-bundle/chunks/{telemetry-BZUF6H7G.js → telemetry-GVVUQSJQ.js} +85 -71
- package/dist/cli-bundle/chunks/telemetry-GVVUQSJQ.js.map +1 -0
- package/dist/cli-bundle/chunks/{test-PWDIZ255.js → test-QY44WAMR.js} +15 -15
- package/dist/cli-bundle/chunks/{test-ACD52Z3S.js → test-SY76DZTO.js} +15 -15
- package/dist/cli-bundle/chunks/test-all-QD6QAEG7.js +430 -0
- package/dist/cli-bundle/chunks/test-all-QD6QAEG7.js.map +7 -0
- package/dist/cli-bundle/chunks/test-all-USPJHXFR.js +427 -0
- package/dist/cli-bundle/chunks/test-all-USPJHXFR.js.map +1 -0
- package/dist/cli-bundle/chunks/{test-runs-UXIXPDKU.js → test-runs-MG5VIGSK.js} +185 -147
- package/dist/cli-bundle/chunks/test-runs-MG5VIGSK.js.map +1 -0
- package/dist/cli-bundle/chunks/{test-runs-PLRAZEFW.js → test-runs-QIR5MJPL.js} +184 -146
- package/dist/cli-bundle/chunks/test-runs-QIR5MJPL.js.map +7 -0
- package/dist/cli-bundle/chunks/update-A7EICML6.js +24 -0
- package/dist/cli-bundle/chunks/{update-KFX2SIAC.js → update-IKJZWLQC.js} +15 -15
- package/dist/cli-bundle/chunks/{update-many-RNSBX2TA.js → update-many-BEMTDA2X.js} +84 -69
- package/dist/cli-bundle/chunks/{update-many-RNSBX2TA.js.map → update-many-BEMTDA2X.js.map} +1 -1
- package/dist/cli-bundle/chunks/{update-many-Z5GJS5LC.js → update-many-RATAARHU.js} +83 -68
- package/dist/cli-bundle/chunks/{update-many-Z5GJS5LC.js.map → update-many-RATAARHU.js.map} +2 -2
- package/dist/cli-bundle/chunks/{upgrade-BRL6KCOJ.js → upgrade-NWMR3VQL.js} +11 -11
- package/dist/cli-bundle/chunks/{upgrade-HAK6JG2O.js → upgrade-VU46BLJZ.js} +11 -11
- package/dist/cli-bundle/chunks/{validate-X5W76YJL.js → validate-GAJ6FUSI.js} +451 -321
- package/dist/cli-bundle/chunks/validate-GAJ6FUSI.js.map +1 -0
- package/dist/cli-bundle/chunks/{validate-MTUVL5VC.js → validate-NRY6MFXN.js} +450 -320
- package/dist/cli-bundle/chunks/validate-NRY6MFXN.js.map +7 -0
- package/dist/cli-bundle/main.js +1107 -916
- package/dist/cli-bundle/main.js.map +3 -3
- package/dist/core/config/nested-settings.js +89 -67
- package/dist/core/config/nested-settings.js.map +1 -1
- package/dist/core/governance/metadata-coverage.js +20 -28
- package/dist/core/governance/metadata-coverage.js.map +1 -1
- package/dist/core/history/drift-scan.js +93 -81
- package/dist/core/history/drift-scan.js.map +1 -1
- package/dist/core/item/item-type-definition.js +14 -14
- package/dist/core/item/item-type-definition.js.map +1 -1
- package/dist/core/item/type-registry.js +114 -99
- package/dist/core/item/type-registry.js.map +1 -1
- package/dist/core/output/mutation-projection.js +42 -26
- package/dist/core/output/mutation-projection.js.map +1 -1
- package/dist/core/schema/runtime-schema.js +97 -80
- package/dist/core/schema/runtime-schema.js.map +1 -1
- package/dist/core/schema/status-defs-file.js +26 -3
- package/dist/core/schema/status-defs-file.js.map +1 -1
- package/dist/core/search/corpus.js +25 -19
- package/dist/core/search/corpus.js.map +1 -1
- package/dist/core/search/semantic-defaults.js +64 -37
- package/dist/core/search/semantic-defaults.js.map +1 -1
- package/dist/core/search/vector-stores.js +32 -17
- package/dist/core/search/vector-stores.js.map +1 -1
- package/dist/core/sentry/helpers.js +31 -28
- package/dist/core/sentry/helpers.js.map +1 -1
- package/dist/core/sentry/instrument.js +54 -43
- package/dist/core/sentry/instrument.js.map +1 -1
- package/dist/core/shared/memo.d.ts +12 -0
- package/dist/core/shared/memo.js +25 -0
- package/dist/core/shared/memo.js.map +1 -0
- package/dist/core/shared/serialization.js +24 -14
- package/dist/core/shared/serialization.js.map +1 -1
- package/dist/core/shared/time.js +26 -4
- package/dist/core/shared/time.js.map +1 -1
- package/dist/core/store/front-matter-cache.d.ts +5 -0
- package/dist/core/store/front-matter-cache.js +316 -171
- package/dist/core/store/front-matter-cache.js.map +1 -1
- package/dist/core/store/item-store.js +33 -26
- package/dist/core/store/item-store.js.map +1 -1
- package/dist/core/store/settings.js +247 -203
- package/dist/core/store/settings.js.map +1 -1
- package/dist/core/test/background-runs.js +189 -160
- package/dist/core/test/background-runs.js.map +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +71 -99
- package/dist/sdk/cli-contracts/flag-contracts.js.map +1 -1
- package/dist/sdk/compose.js +51 -42
- package/dist/sdk/compose.js.map +1 -1
- package/docs/AGENT_GUIDE.md +2 -2
- package/docs/ARCHITECTURE.md +2 -2
- package/docs/COMMANDS.md +8 -4
- package/docs/CONFIGURATION.md +1 -1
- package/docs/EXTENSIONS.md +12 -12
- package/docs/ONBOARDING.md +4 -2
- package/docs/README.md +2 -0
- package/docs/examples/starter-extension/README.md +11 -10
- package/marketplace.json +3 -3
- package/package.json +2 -2
- package/packages/pm-beads/extensions/beads/runtime.ts +240 -167
- package/packages/pm-guide-shell/extensions/guide-shell/runtime.ts +65 -58
- package/packages/pm-todos/extensions/todos/runtime.ts +65 -42
- package/plugins/pm-claude/.claude-plugin/plugin.json +2 -2
- package/plugins/pm-claude/README.md +6 -3
- package/plugins/pm-claude/commands/pm-init.md +1 -1
- package/dist/cli-bundle/chunks/activity-AW6XVFH6.js +0 -16
- package/dist/cli-bundle/chunks/aggregate-JTEF4BP7.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-22WKIL3H.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-2D4HATP2.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-3J6JRJ3I.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-3K2M5OYU.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-3S2KT7NG.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-3VGN2UWE.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-3XZCOZ5J.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-4XOIEKSD.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-55SNVXRQ.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-5CGRF3L5.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-7R4QEMZZ.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-AXIDKKAT.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-BDTISOSD.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-BZCEN4JA.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-CF7RL6FR.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-CWFNTKQJ.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-FFMQB7WR.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-HXTQJXWT.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-IPYBJWTE.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-IZBR4NRW.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-JLM7BHI7.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-JSU5P7VS.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-JWXRETDF.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-KNPEF7QG.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-MDPEOIGN.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-NFDPYAIP.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-NUHHPVVS.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-NWMZWYYB.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-OTUHB4HS.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-RGEMWD6Q.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-RLDHZHQS.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-RMMQ74TG.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-RVUALSJF.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-TP5Q5ZD3.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-V3NOKJF2.js.map +0 -1
- package/dist/cli-bundle/chunks/chunk-VARHOHYV.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-WYDHYJPO.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-YITK2PJ6.js.map +0 -7
- package/dist/cli-bundle/chunks/chunk-ZETXE4SE.js.map +0 -1
- package/dist/cli-bundle/chunks/close-E6ZZGCJY.js +0 -14
- package/dist/cli-bundle/chunks/close-many-BG5QQIDQ.js.map +0 -7
- package/dist/cli-bundle/chunks/close-many-LDRVEQY2.js.map +0 -1
- package/dist/cli-bundle/chunks/config-DMSU64QO.js +0 -1541
- package/dist/cli-bundle/chunks/config-DMSU64QO.js.map +0 -7
- package/dist/cli-bundle/chunks/config-QH2DICD6.js +0 -1531
- package/dist/cli-bundle/chunks/config-QH2DICD6.js.map +0 -1
- package/dist/cli-bundle/chunks/contracts-HN7ABKLP.js.map +0 -7
- package/dist/cli-bundle/chunks/contracts-W4FZVVD6.js.map +0 -1
- package/dist/cli-bundle/chunks/create-OH3BDGBB.js +0 -28
- package/dist/cli-bundle/chunks/get-A7MAOHCU.js.map +0 -7
- package/dist/cli-bundle/chunks/get-DSDEKJ3L.js.map +0 -1
- package/dist/cli-bundle/chunks/health-3IPFLKXB.js.map +0 -1
- package/dist/cli-bundle/chunks/health-GZXGBZ36.js.map +0 -7
- package/dist/cli-bundle/chunks/history-WSZHY3PN.js +0 -18
- package/dist/cli-bundle/chunks/history-compact-2WRZ2WK4.js.map +0 -7
- package/dist/cli-bundle/chunks/history-compact-HR7BB4LR.js.map +0 -1
- package/dist/cli-bundle/chunks/history-redact-MP6CH7U5.js +0 -19
- package/dist/cli-bundle/chunks/history-repair-LCMOS45X.js.map +0 -7
- package/dist/cli-bundle/chunks/history-repair-XA3LC4GA.js.map +0 -1
- package/dist/cli-bundle/chunks/init-PAX32BJA.js +0 -22
- package/dist/cli-bundle/chunks/next-BCERKDUR.js.map +0 -7
- package/dist/cli-bundle/chunks/next-FYTQF6HG.js.map +0 -1
- package/dist/cli-bundle/chunks/plan-4WXEQCTN.js.map +0 -7
- package/dist/cli-bundle/chunks/plan-RKZHQVXR.js.map +0 -1
- package/dist/cli-bundle/chunks/profile-4OMM32CD.js.map +0 -7
- package/dist/cli-bundle/chunks/profile-QLER5ENE.js.map +0 -1
- package/dist/cli-bundle/chunks/register-list-query-7LV46VAU.js +0 -400
- package/dist/cli-bundle/chunks/register-list-query-7LV46VAU.js.map +0 -1
- package/dist/cli-bundle/chunks/register-list-query-SNG5PGA4.js +0 -410
- package/dist/cli-bundle/chunks/register-list-query-SNG5PGA4.js.map +0 -7
- package/dist/cli-bundle/chunks/register-mutation-ENNDUAZG.js.map +0 -1
- package/dist/cli-bundle/chunks/register-mutation-KK7PHYYU.js.map +0 -7
- package/dist/cli-bundle/chunks/register-operations-C6OWLDSH.js +0 -486
- package/dist/cli-bundle/chunks/register-operations-C6OWLDSH.js.map +0 -1
- package/dist/cli-bundle/chunks/register-operations-HZ6XERQG.js.map +0 -7
- package/dist/cli-bundle/chunks/register-setup-P67EMBDJ.js.map +0 -1
- package/dist/cli-bundle/chunks/register-setup-ZKJ53RS7.js.map +0 -7
- package/dist/cli-bundle/chunks/restore-YALDGTQR.js +0 -17
- package/dist/cli-bundle/chunks/telemetry-BZUF6H7G.js.map +0 -1
- package/dist/cli-bundle/chunks/telemetry-GAHHQTOS.js.map +0 -7
- package/dist/cli-bundle/chunks/test-all-L2MDDUCA.js +0 -358
- package/dist/cli-bundle/chunks/test-all-L2MDDUCA.js.map +0 -1
- package/dist/cli-bundle/chunks/test-all-RBZ6DLU2.js +0 -361
- package/dist/cli-bundle/chunks/test-all-RBZ6DLU2.js.map +0 -7
- package/dist/cli-bundle/chunks/test-runs-PLRAZEFW.js.map +0 -7
- package/dist/cli-bundle/chunks/test-runs-UXIXPDKU.js.map +0 -1
- package/dist/cli-bundle/chunks/update-AMRSOIWP.js +0 -24
- package/dist/cli-bundle/chunks/validate-MTUVL5VC.js.map +0 -7
- package/dist/cli-bundle/chunks/validate-X5W76YJL.js.map +0 -1
- /package/dist/cli-bundle/chunks/{activity-DBLQVIP6.js.map → activity-5YWLSPGE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{activity-AW6XVFH6.js.map → activity-BIML7K2D.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{append-LOVPGVPT.js.map → append-EZESUVJT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{append-QCFJSDFL.js.map → append-JFG4WQMG.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-BHO33VBQ.js.map → chunk-3W2HJKJX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-4DUVCVLZ.js.map → chunk-4PFVUUYV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-IJYK2T43.js.map → chunk-5E7N4T2Z.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-NKZAN7BD.js.map → chunk-5IZUBZBR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-NOLPZMSV.js.map → chunk-5JIWFWOZ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-6AQZPVHQ.js.map → chunk-6CDCWKSX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-LB6TP6MC.js.map → chunk-6NYJGMTY.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-SLMUGTK3.js.map → chunk-7CLLC75T.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-2466X6E4.js.map → chunk-7LYO6S5A.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-W4ULYO7Z.js.map → chunk-A3OQ7TFW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-GJ326ZKX.js.map → chunk-ER4ME5U2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-HZZEHPRG.js.map → chunk-ERG65A2L.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-L5OEFZQG.js.map → chunk-FH2H3CBD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-JPECA746.js.map → chunk-FUFFPIYA.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-27BXPBAY.js.map → chunk-GUYNUXQT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-MAUKX7JC.js.map → chunk-GVJE5T7Q.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-ZRP4VG5U.js.map → chunk-JBZ2NTKX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EJUDVUYZ.js.map → chunk-KEZOIPCR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-HYTGA6GI.js.map → chunk-MDHWWBNZ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-N74UMG5H.js.map → chunk-MEZZZBYX.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-SDR5J34Q.js.map → chunk-NZ7QIUP5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-DDPTYJIM.js.map → chunk-P5L7Z2O6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-OGXLACHC.js.map → chunk-SU2E4AWU.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-HPPFYYOV.js.map → chunk-SU3TB4NS.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-G7I7DEZA.js.map → chunk-T4XBKJ3F.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-VICZWYGZ.js.map → chunk-U5TR4N7J.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-EVMTBV6V.js.map → chunk-UMNQZS4H.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-A7FPBAQS.js.map → chunk-WJA3PXW7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-QCWF6IYD.js.map → chunk-YSDFIY7N.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-UZIWVBE6.js.map → chunk-YSGTMDWC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-64HNBBFQ.js.map → chunk-Z5F6XZXE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{chunk-AVEE5EHK.js.map → chunk-Z7RPDF2Y.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{claim-T3GCKV7C.js.map → claim-2BGBGSVI.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{claim-EMQLYPRW.js.map → claim-5GU7OE67.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-E6ZZGCJY.js.map → close-6YODBUIV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{close-TQYAAFJP.js.map → close-AFVKPR57.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{comments-YUXJRZPQ.js.map → comments-DNWHEBOS.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{comments-QCKR2YY2.js.map → comments-RW23R3VE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{context-B6275WPX.js.map → context-OYXRGY7S.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{context-OCZ3FJ4Z.js.map → context-PKCEHQY3.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{copy-DEM4DATS.js.map → copy-6XOR3HKN.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{copy-BTJOSKKT.js.map → copy-I4NCLBR4.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{create-RLRJMRTM.js.map → create-PM45M6PE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{create-OH3BDGBB.js.map → create-Z7YCH3BE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{delete-BHK7VB2Z.js.map → delete-7YXHYG67.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{delete-LSVHAB4Y.js.map → delete-LPISP43T.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{deps-XHYXWEPT.js.map → deps-N2T26FME.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{deps-4UDFJRUA.js.map → deps-WATKQDE3.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{docs-GYZNVS26.js.map → docs-6LQ3GLM7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{docs-26S44RXU.js.map → docs-Z3X6JZLT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{eval-UYF3ZPVO.js.map → eval-6DCLG52D.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{eval-PGRVIJQU.js.map → eval-Y3ZCUTHK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{extension-CPSLJQVE.js.map → extension-BNINIMT7.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{extension-CXJ6RELI.js.map → extension-QWE4YYK5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{files-NQHEXUZD.js.map → files-6SGKHS6O.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{files-MBNICQFM.js.map → files-FUYPSOFJ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{focus-DWYIG7GU.js.map → focus-2Q3K76G2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{focus-XZW5423D.js.map → focus-ATLBWXXD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{gc-LPVMKJQJ.js.map → gc-RUYEMNRF.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{gc-7GQYOS2G.js.map → gc-TDWSDR66.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-WSZHY3PN.js.map → history-CGNQJXFE.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-NERDJNUB.js.map → history-SGRRS72R.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-redact-O3NBCNWC.js.map → history-redact-IRL7WJ3E.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{history-redact-MP6CH7U5.js.map → history-redact-N3JK7VBW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{init-64XDLQJB.js.map → init-4GESW7RM.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{init-PAX32BJA.js.map → init-XIDPABA4.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{learnings-LPKCSJX7.js.map → learnings-4BHWFFUV.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{learnings-JR6MA5TI.js.map → learnings-4FJY7WIW.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{list-G5Y65VF6.js.map → list-472TIOVK.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{list-DNBJVO3E.js.map → list-D7BF5CL2.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{notes-2BMU3VVQ.js.map → notes-6KNOSLIT.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{notes-6KTGO2OJ.js.map → notes-W4UEICGF.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{restore-4MHZFJ2E.js.map → restore-44IHMMZZ.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{restore-YALDGTQR.js.map → restore-EXHU34EU.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{scheduling-shortcuts-LB6DOLRL.js.map → scheduling-shortcuts-OLHNLAZY.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{scheduling-shortcuts-UTOYKLXQ.js.map → scheduling-shortcuts-TSBK4AY5.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{schema-73HR2OJW.js.map → schema-IB2NZZWD.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{schema-U6LJKSIR.js.map → schema-VBCELP5G.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{search-AXPXKZER.js.map → search-7UBETML4.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{search-KILGT37L.js.map → search-R227JOL6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{stats-W5KNVJWQ.js.map → stats-FAG7COEH.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{stats-PSYVVTNZ.js.map → stats-MCK7PLYS.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{test-PWDIZ255.js.map → test-QY44WAMR.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{test-ACD52Z3S.js.map → test-SY76DZTO.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-AMRSOIWP.js.map → update-A7EICML6.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{update-KFX2SIAC.js.map → update-IKJZWLQC.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{upgrade-BRL6KCOJ.js.map → upgrade-NWMR3VQL.js.map} +0 -0
- /package/dist/cli-bundle/chunks/{upgrade-HAK6JG2O.js.map → upgrade-VU46BLJZ.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../cli/commands/calendar.ts","../../../../../../../../cli/commands/context.ts"],"sourcesContent":["/**\n * @module cli/commands/calendar\n *\n * Implements the pm calendar command surface and its agent-facing runtime behavior.\n */\nimport { encode as encodeToon } from \"@toon-format/toon\";\nimport { pathExists } from \"../../core/fs/fs-utils.js\";\nimport { getActiveExtensionRegistrations } from \"../../core/extensions/index.js\";\nimport { resolveItemTypeRegistry, type ItemTypeRegistry } from \"../../core/item/type-registry.js\";\nimport { parseIntegerLimit, parsePriority, parseType } from \"../shared-parsers.js\";\nimport { normalizeStatusInput } from \"../../core/item/status.js\";\nimport { collectRuntimeFilterValues, matchesRuntimeFilters } from \"../../core/schema/runtime-field-filters.js\";\nimport {\n resolveRuntimeFieldRegistry,\n resolveRuntimeStatusRegistry,\n type RuntimeStatusRegistry,\n} 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 { levenshteinDistanceWithinLimit } from \"../../core/shared/levenshtein.js\";\nimport { compareTimestampStrings, nowIso, resolveIsoOrRelative } from \"../../core/shared/time.js\";\nimport { listAllFrontMatterLight } from \"../../core/store/item-store.js\";\nimport { getSettingsPath, resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport type { ItemFrontMatter, ItemStatus, ItemType, RecurrenceRule } from \"../../types/index.js\";\nimport { RECURRENCE_WEEKDAY_VALUES, weekdayOrderIndex } from \"../../types/index.js\";\n\nexport const CALENDAR_VIEW_VALUES = [\"agenda\", \"day\", \"week\", \"month\"] as const;\n/**\n * Restricts calendar view values accepted by command, SDK, and storage contracts.\n */\nexport type CalendarView = (typeof CALENDAR_VIEW_VALUES)[number];\n\nexport const CALENDAR_OUTPUT_VALUES = [\"markdown\", \"toon\", \"json\"] as const;\n/**\n * Restricts calendar output format values accepted by command, SDK, and storage contracts.\n */\nexport type CalendarOutputFormat = (typeof CALENDAR_OUTPUT_VALUES)[number];\n\n/**\n * Documents the calendar options payload exchanged by command, SDK, and package integrations.\n */\nexport interface CalendarOptions {\n view?: string;\n date?: string;\n from?: string;\n to?: string;\n past?: boolean;\n fullPeriod?: boolean;\n limit?: string;\n type?: string;\n tag?: string;\n priority?: string;\n status?: string;\n assignee?: string;\n assigneeFilter?: string;\n sprint?: string;\n release?: string;\n include?: string;\n recurrenceLookaheadDays?: string;\n recurrenceLookbackDays?: string;\n occurrenceLimit?: string;\n format?: string;\n [key: string]: unknown;\n}\n\n/**\n * Documents the calendar row payload exchanged by command, SDK, and package integrations.\n */\nexport interface CalendarRow {\n at: string;\n date: string;\n kind: \"deadline\" | \"reminder\" | \"event\";\n reminder_text: string | null;\n event_title: string | null;\n event_end: string | null;\n event_location: string | null;\n event_all_day: boolean | null;\n event_timezone: string | null;\n event_recurring: boolean | null;\n event_recurrence_rule: string | null;\n item_id: string;\n item_title: string;\n item_type: ItemType;\n item_status: ItemStatus;\n item_priority: number;\n item_assignee: string | null;\n item_deadline: string | null;\n item_tags: string[];\n}\n\n/**\n * Documents the calendar day bucket payload exchanged by command, SDK, and package integrations.\n */\nexport interface CalendarDayBucket {\n date: string;\n count: number;\n events: CalendarRow[];\n}\n\n/**\n * Documents the calendar result payload exchanged by command, SDK, and package integrations.\n */\nexport interface CalendarResult {\n view: CalendarView;\n output_default: \"markdown\";\n now: string;\n anchor: string;\n range: {\n start: string | null;\n end: string | null;\n period_start: string | null;\n period_end: string | null;\n full_period: boolean;\n past: boolean;\n from: string | null;\n to: string | null;\n };\n filters: {\n type: string | null;\n tag: string | null;\n priority: string | null;\n status: string | null;\n assignee: string | null;\n assignee_filter: string | null;\n sprint: string | null;\n release: string | null;\n runtime_filters?: Record<string, unknown>;\n limit: string | null;\n include: string | null;\n full_period: string | null;\n recurrence_lookahead_days: string | null;\n recurrence_lookback_days: string | null;\n occurrence_limit: string | null;\n };\n summary: {\n events: number;\n items: number;\n deadlines: number;\n reminders: number;\n scheduled: number;\n by_kind: {\n deadline: number;\n reminder: number;\n event: number;\n };\n by_type: Record<string, number>;\n by_status: Record<string, number>;\n recurring_events: number;\n };\n events: CalendarRow[];\n days: CalendarDayBucket[];\n warnings?: string[];\n}\n\nconst UTC_DAY_TO_WEEKDAY = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"] as const;\nconst DEFAULT_RECURRENCE_LOOKAHEAD_DAYS = 365;\nconst DEFAULT_RECURRENCE_LOOKBACK_DAYS = 365;\nconst DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS = 28;\nconst MAX_RECURRENCE_OCCURRENCES = 1000;\n\nfunction parseNonNegativeInteger(raw: string | undefined, label: string): number | undefined {\n if (raw === undefined) return undefined;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new PmCliError(`${label} must be a non-negative integer`, EXIT_CODE.USAGE);\n }\n return parsed;\n}\n\ntype CalendarIncludeKind = \"deadlines\" | \"reminders\" | \"events\";\n\nfunction parseIncludeSources(raw: string | undefined): Set<CalendarIncludeKind> {\n if (!raw) {\n return new Set([\"deadlines\", \"reminders\", \"events\"]);\n }\n const normalized = raw.trim().toLowerCase();\n if (normalized === \"all\") {\n return new Set([\"deadlines\", \"reminders\", \"events\"]);\n }\n const values = normalized\n .split(/[\\|,]/)\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n if (values.length === 0) {\n throw new PmCliError(\"Calendar include filter must not be empty\", EXIT_CODE.USAGE);\n }\n const include = new Set<CalendarIncludeKind>();\n for (const value of values) {\n if (value === \"deadlines\" || value === \"deadline\") {\n include.add(\"deadlines\");\n continue;\n }\n if (value === \"reminders\" || value === \"reminder\") {\n include.add(\"reminders\");\n continue;\n }\n if (value === \"events\" || value === \"event\" || value === \"scheduled\") {\n include.add(\"events\");\n continue;\n }\n throw new PmCliError(\"Calendar include filter must be deadlines|reminders|events|scheduled|all\", EXIT_CODE.USAGE);\n }\n return include;\n}\n\n/**\n * Suggest the closest valid choice for a mistyped enum value (within edit\n * distance 2) so an agent gets an actionable \"did you mean\" hint instead of just\n * a list of choices (never-block UX).\n */\nfunction suggestClosestChoice(value: string, choices: readonly string[]): string | undefined {\n let best: { choice: string; distance: number } | undefined;\n for (const choice of choices) {\n const distance = levenshteinDistanceWithinLimit(value, choice, 2);\n if (distance !== null && (best === undefined || distance < best.distance)) {\n best = { choice, distance };\n }\n }\n return best?.choice;\n}\n\nfunction parseView(raw: string | undefined): CalendarView {\n if (!raw) return \"agenda\";\n const normalized = raw.trim().toLowerCase();\n if (!CALENDAR_VIEW_VALUES.includes(normalized as CalendarView)) {\n const suggestion = suggestClosestChoice(normalized, CALENDAR_VIEW_VALUES);\n throw new PmCliError(\n `Calendar view must be one of ${CALENDAR_VIEW_VALUES.join(\"|\")}${suggestion ? `. Did you mean \"${suggestion}\"?` : \".\"}`,\n EXIT_CODE.USAGE,\n );\n }\n return normalized as CalendarView;\n}\n\nfunction parseOutputFormat(raw: string | undefined): CalendarOutputFormat | undefined {\n if (!raw) return undefined;\n const normalized = raw.trim().toLowerCase();\n if (!CALENDAR_OUTPUT_VALUES.includes(normalized as CalendarOutputFormat)) {\n const suggestion = suggestClosestChoice(normalized, CALENDAR_OUTPUT_VALUES);\n throw new PmCliError(\n `Calendar format must be one of ${CALENDAR_OUTPUT_VALUES.join(\"|\")}${suggestion ? `. Did you mean \"${suggestion}\"?` : \".\"}`,\n EXIT_CODE.USAGE,\n );\n }\n return normalized as CalendarOutputFormat;\n}\n\n/**\n * Implements resolve calendar output format for the public runtime surface of this module.\n */\nexport function resolveCalendarOutputFormat(options: CalendarOptions, global: GlobalOptions): CalendarOutputFormat {\n const commandFormat = parseOutputFormat(options.format);\n if (global.json && commandFormat && commandFormat !== \"json\") {\n throw new PmCliError(\"Cannot combine --json with --format markdown|toon\", EXIT_CODE.USAGE);\n }\n if (global.json) {\n return \"json\";\n }\n return commandFormat ?? \"markdown\";\n}\n\nfunction parseStatus(raw: string | undefined, statusRegistry: RuntimeStatusRegistry): ItemStatus | undefined {\n if (raw === undefined) return undefined;\n const normalized = normalizeStatusInput(raw, statusRegistry);\n if (!normalized) {\n const allowedStatuses = statusRegistry.definitions.map((definition) => definition.id);\n throw new PmCliError(`Calendar status filter must be one of ${allowedStatuses.join(\"|\")}`, EXIT_CODE.USAGE);\n }\n return normalized;\n}\n\nfunction parseAssigneeFilter(raw: string | undefined): \"assigned\" | \"unassigned\" | undefined {\n if (raw === undefined) {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (!normalized) {\n throw new PmCliError(\"Calendar assignee filter must be one of assigned|unassigned\", EXIT_CODE.USAGE);\n }\n if (normalized !== \"assigned\" && normalized !== \"unassigned\") {\n throw new PmCliError(`Invalid calendar assignee filter \"${raw}\". Allowed: assigned|unassigned`, EXIT_CODE.USAGE);\n }\n return normalized;\n}\n\nfunction toUtcDayKey(timestamp: string): string {\n return new Date(timestamp).toISOString().slice(0, 10);\n}\n\n/**\n * Calendar day (YYYY-MM-DD) the instant falls on in the given IANA timezone.\n * Events carry an optional `timezone`; bucketing and clock rendering use it so a\n * 23:30Z instant tagged Asia/Tokyo correctly lands on the next local day rather\n * than the UTC day. Falls back to the UTC day when no/invalid timezone is given,\n * so existing UTC behavior is unchanged. Uses Intl (no timezone dependency).\n */\nfunction toLocalDayKey(timestamp: string, timezone?: string | null): string {\n if (!timezone || timezone === \"UTC\") {\n return toUtcDayKey(timestamp);\n }\n try {\n const parts = new Intl.DateTimeFormat(\"en-CA\", {\n timeZone: timezone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n }).formatToParts(new Date(timestamp));\n const year = parts.find((part) => part.type === \"year\")?.value;\n const month = parts.find((part) => part.type === \"month\")?.value;\n const day = parts.find((part) => part.type === \"day\")?.value;\n if (year && month && day) {\n return `${year}-${month}-${day}`;\n }\n } catch {\n // Invalid IANA zone — fall back to the UTC day key below.\n }\n return toUtcDayKey(timestamp);\n}\n\nfunction startOfUtcDay(timestamp: string): string {\n const date = new Date(timestamp);\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0, 0)).toISOString();\n}\n\nfunction addUtcDays(timestamp: string, days: number): string {\n const date = new Date(timestamp);\n return new Date(date.getTime() + days * 24 * 60 * 60 * 1000).toISOString();\n}\n\nfunction startOfUtcWeekMonday(timestamp: string): string {\n const base = new Date(startOfUtcDay(timestamp));\n const day = base.getUTCDay();\n const delta = day === 0 ? -6 : 1 - day;\n return addUtcDays(base.toISOString(), delta);\n}\n\nfunction startOfUtcMonth(timestamp: string): string {\n const date = new Date(timestamp);\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1, 0, 0, 0, 0)).toISOString();\n}\n\nfunction startOfNextUtcMonth(timestamp: string): string {\n const date = new Date(timestamp);\n return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1, 0, 0, 0, 0)).toISOString();\n}\n\nfunction maxTimestamp(left: string, right: string): string {\n return compareTimestampStrings(left, right) >= 0 ? left : right;\n}\n\nfunction toSortedCountRecord(values: Map<string, number>): Record<string, number> {\n return Object.fromEntries([...values.entries()].sort(([left], [right]) => left.localeCompare(right)));\n}\n\nfunction incrementCount(values: Map<string, number>, key: string): void {\n values.set(key, (values.get(key) ?? 0) + 1);\n}\n\nfunction formatRecurrenceRuleForSummary(rule: RecurrenceRule | undefined): string | null {\n if (!rule) {\n return null;\n }\n const parts: string[] = [`freq=${rule.freq}`];\n if (rule.interval !== undefined) {\n parts.push(`interval=${rule.interval}`);\n }\n if (rule.count !== undefined) {\n parts.push(`count=${rule.count}`);\n }\n if (rule.until) {\n parts.push(`until=${rule.until}`);\n }\n if (rule.by_weekday && rule.by_weekday.length > 0) {\n const weekdays = [...rule.by_weekday].sort((left, right) => weekdayOrderIndex(left) - weekdayOrderIndex(right));\n parts.push(`by_weekday=${weekdays.join(\"|\")}`);\n }\n if (rule.by_month_day && rule.by_month_day.length > 0) {\n const monthDays = [...rule.by_month_day].sort((left, right) => left - right);\n parts.push(`by_month_day=${monthDays.join(\"|\")}`);\n }\n if (rule.exdates && rule.exdates.length > 0) {\n const exdates = [...rule.exdates].sort((left, right) => left.localeCompare(right));\n parts.push(`exdates=${exdates.join(\"|\")}`);\n }\n return parts.join(\",\");\n}\n\nfunction buildUtcTimestamp(year: number, month: number, day: number, timeSource: Date): string | undefined {\n const candidate = new Date(\n Date.UTC(\n year,\n month,\n day,\n timeSource.getUTCHours(),\n timeSource.getUTCMinutes(),\n timeSource.getUTCSeconds(),\n timeSource.getUTCMilliseconds(),\n ),\n );\n if (candidate.getUTCFullYear() !== year || candidate.getUTCMonth() !== month || candidate.getUTCDate() !== day) {\n return undefined;\n }\n return candidate.toISOString();\n}\n\nfunction weekdayToken(timestamp: string): (typeof UTC_DAY_TO_WEEKDAY)[number] {\n return UTC_DAY_TO_WEEKDAY[new Date(timestamp).getUTCDay()];\n}\n\nfunction normalizeInstantKey(timestamp: string): string | null {\n const parsed = Date.parse(timestamp);\n return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;\n}\n\nfunction buildExcludedInstantSet(exdates: readonly string[] | undefined): Set<string> {\n const excluded = new Set<string>();\n for (const exdate of exdates ?? []) {\n const instantKey = normalizeInstantKey(exdate);\n if (instantKey) {\n excluded.add(instantKey);\n }\n }\n return excluded;\n}\n\nfunction buildRecurringEventWindow(\n start: string | undefined,\n end: string | undefined,\n nowValue: string,\n lookbackDays: number | undefined,\n lookaheadDays: number | undefined,\n): { start: string; end: string } {\n const windowStart = start ?? addUtcDays(nowValue, -(lookbackDays ?? DEFAULT_RECURRENCE_LOOKBACK_DAYS));\n const windowEnd = end ?? addUtcDays(start ?? nowValue, lookaheadDays ?? DEFAULT_RECURRENCE_LOOKAHEAD_DAYS);\n return {\n start: windowStart,\n end: compareTimestampStrings(windowEnd, windowStart) > 0 ? windowEnd : addUtcDays(windowStart, 1),\n };\n}\n\nfunction expandRecurringOccurrences(\n startAt: string,\n recurrence: RecurrenceRule,\n window: { start: string; end: string },\n occurrenceLimit: number | undefined,\n): string[] {\n const maxOccurrences = occurrenceLimit ?? MAX_RECURRENCE_OCCURRENCES;\n const interval = recurrence.interval ?? 1;\n const countLimit = recurrence.count ?? Number.POSITIVE_INFINITY;\n const until = recurrence.until;\n const excluded = buildExcludedInstantSet(recurrence.exdates);\n const recurrenceWeekdays =\n recurrence.by_weekday && recurrence.by_weekday.length > 0 ? [...recurrence.by_weekday] : [weekdayToken(startAt)];\n const recurrenceMonthDays =\n recurrence.by_month_day && recurrence.by_month_day.length > 0 ? [...recurrence.by_month_day] : [new Date(startAt).getUTCDate()];\n const weekdayFilter = recurrence.by_weekday ? new Set(recurrence.by_weekday) : undefined;\n const monthDayFilter = recurrence.by_month_day ? new Set(recurrence.by_month_day) : undefined;\n const sortedWeekdays = [...new Set(recurrenceWeekdays)].sort(\n (left, right) =>\n weekdayOrderIndex(left as (typeof RECURRENCE_WEEKDAY_VALUES)[number]) -\n weekdayOrderIndex(right as (typeof RECURRENCE_WEEKDAY_VALUES)[number]),\n );\n const sortedMonthDays = [...new Set(recurrenceMonthDays)].sort((left, right) => left - right);\n\n const occurrences: string[] = [];\n let produced = 0;\n const consumeCandidate = (candidateAt: string): \"continue\" | \"stop\" => {\n if (compareTimestampStrings(candidateAt, startAt) < 0) {\n return \"continue\";\n }\n if (until && compareTimestampStrings(candidateAt, until) > 0) {\n return \"stop\";\n }\n if (compareTimestampStrings(candidateAt, window.end) >= 0) {\n return \"stop\";\n }\n if (excluded.has(candidateAt)) {\n return \"continue\";\n }\n produced += 1;\n if (compareTimestampStrings(candidateAt, window.start) >= 0) {\n occurrences.push(candidateAt);\n }\n if (produced >= countLimit) {\n return \"stop\";\n }\n return \"continue\";\n };\n\n const startDate = new Date(startAt);\n if (recurrence.freq === \"daily\") {\n let candidateAt = startAt;\n for (let iteration = 0; iteration < maxOccurrences; iteration += 1) {\n const candidateWeekday = weekdayToken(candidateAt);\n const candidateMonthDay = new Date(candidateAt).getUTCDate();\n const weekdayMatches = !weekdayFilter || weekdayFilter.has(candidateWeekday);\n const monthDayMatches = !monthDayFilter || monthDayFilter.has(candidateMonthDay);\n if (weekdayMatches && monthDayMatches && consumeCandidate(candidateAt) === \"stop\") {\n break;\n }\n candidateAt = addUtcDays(candidateAt, interval);\n }\n return occurrences;\n }\n\n if (recurrence.freq === \"weekly\") {\n const weekStart = startOfUtcWeekMonday(startAt);\n for (let step = 0; step < maxOccurrences; step += 1) {\n const candidateWeekStart = addUtcDays(weekStart, step * interval * 7);\n for (const weekday of sortedWeekdays) {\n const dayOffset = weekdayOrderIndex(weekday as (typeof RECURRENCE_WEEKDAY_VALUES)[number]);\n const candidateDay = addUtcDays(candidateWeekStart, dayOffset);\n const dayDate = new Date(candidateDay);\n const candidateAt = new Date(\n Date.UTC(\n dayDate.getUTCFullYear(),\n dayDate.getUTCMonth(),\n dayDate.getUTCDate(),\n startDate.getUTCHours(),\n startDate.getUTCMinutes(),\n startDate.getUTCSeconds(),\n startDate.getUTCMilliseconds(),\n ),\n ).toISOString();\n const candidateMonthDay = dayDate.getUTCDate();\n if (monthDayFilter && !monthDayFilter.has(candidateMonthDay)) {\n continue;\n }\n const consumed = consumeCandidate(candidateAt);\n if (consumed === \"stop\") {\n return occurrences;\n }\n }\n }\n return occurrences;\n }\n\n if (recurrence.freq === \"monthly\") {\n const startYear = startDate.getUTCFullYear();\n const startMonth = startDate.getUTCMonth();\n for (let step = 0; step < maxOccurrences; step += 1) {\n const monthAnchor = new Date(Date.UTC(startYear, startMonth + step * interval, 1, 0, 0, 0, 0));\n const year = monthAnchor.getUTCFullYear();\n const month = monthAnchor.getUTCMonth();\n for (const monthDay of sortedMonthDays) {\n const candidateAt = buildUtcTimestamp(year, month, monthDay, startDate);\n if (!candidateAt) {\n continue;\n }\n const candidateWeekday = weekdayToken(candidateAt);\n if (weekdayFilter && !weekdayFilter.has(candidateWeekday)) {\n continue;\n }\n const consumed = consumeCandidate(candidateAt);\n if (consumed === \"stop\") {\n return occurrences;\n }\n }\n }\n return occurrences;\n }\n\n const year = startDate.getUTCFullYear();\n const month = startDate.getUTCMonth();\n for (let step = 0; step < maxOccurrences; step += 1) {\n const candidateYear = year + step * interval;\n for (const monthDay of sortedMonthDays) {\n const candidateAt = buildUtcTimestamp(candidateYear, month, monthDay, startDate);\n if (!candidateAt) {\n continue;\n }\n const candidateWeekday = weekdayToken(candidateAt);\n if (weekdayFilter && !weekdayFilter.has(candidateWeekday)) {\n continue;\n }\n const consumed = consumeCandidate(candidateAt);\n if (consumed === \"stop\") {\n return occurrences;\n }\n }\n }\n\n return occurrences;\n}\n\nfunction sortEvents(values: CalendarRow[]): CalendarRow[] {\n return [...values].sort((a, b) => {\n const byAt = compareTimestampStrings(a.at, b.at);\n if (byAt !== 0) return byAt;\n const byPriority = a.item_priority - b.item_priority;\n if (byPriority !== 0) return byPriority;\n const byId = a.item_id.localeCompare(b.item_id);\n if (byId !== 0) return byId;\n const byKind = a.kind.localeCompare(b.kind);\n if (byKind !== 0) return byKind;\n const byEventTitle = String(a.event_title).localeCompare(String(b.event_title));\n if (byEventTitle !== 0) return byEventTitle;\n return String(a.reminder_text).localeCompare(String(b.reminder_text));\n });\n}\n\nfunction buildEventSeed(\n items: ItemFrontMatter[],\n recurringWindow: { start: string; end: string },\n includeSources: Set<CalendarIncludeKind>,\n occurrenceLimit: number | undefined,\n): CalendarRow[] {\n const events: CalendarRow[] = [];\n for (const item of items) {\n if (includeSources.has(\"deadlines\") && item.deadline) {\n events.push({\n at: item.deadline,\n date: toUtcDayKey(item.deadline),\n kind: \"deadline\",\n reminder_text: null,\n event_title: null,\n event_end: null,\n event_location: null,\n event_all_day: null,\n event_timezone: null,\n event_recurring: null,\n event_recurrence_rule: null,\n item_id: item.id,\n item_title: item.title,\n item_type: item.type,\n item_status: item.status,\n item_priority: item.priority,\n item_assignee: item.assignee ?? null,\n item_deadline: item.deadline,\n item_tags: item.tags,\n });\n }\n for (const reminder of includeSources.has(\"reminders\") ? (item.reminders ?? []) : []) {\n events.push({\n at: reminder.at,\n date: toUtcDayKey(reminder.at),\n kind: \"reminder\",\n reminder_text: reminder.text,\n event_title: null,\n event_end: null,\n event_location: null,\n event_all_day: null,\n event_timezone: null,\n event_recurring: null,\n event_recurrence_rule: null,\n item_id: item.id,\n item_title: item.title,\n item_type: item.type,\n item_status: item.status,\n item_priority: item.priority,\n item_assignee: item.assignee ?? null,\n item_deadline: item.deadline ?? null,\n item_tags: item.tags,\n });\n }\n for (const event of includeSources.has(\"events\") ? (item.events ?? []) : []) {\n const recurrenceRuleSummary = formatRecurrenceRuleForSummary(event.recurrence);\n const recurringDurationMs = (() => {\n if (!event.end_at) {\n return null;\n }\n const duration = Date.parse(event.end_at) - Date.parse(event.start_at);\n return Number.isFinite(duration) && duration > 0 ? duration : null;\n })();\n const occurrences = event.recurrence\n ? expandRecurringOccurrences(event.start_at, event.recurrence, recurringWindow, occurrenceLimit)\n : [event.start_at];\n for (const occurrenceAt of occurrences) {\n const occurrenceEnd =\n event.recurrence && recurringDurationMs !== null\n ? new Date(new Date(occurrenceAt).getTime() + recurringDurationMs).toISOString()\n : (event.end_at ?? null);\n events.push({\n at: occurrenceAt,\n // All-day events are timezone-agnostic calendar dates: bucket by the\n // literal start date. Timed events bucket by their local day in the\n // event's timezone (defaults to UTC when unset).\n date:\n event.all_day === true\n ? occurrenceAt.slice(0, 10)\n : toLocalDayKey(occurrenceAt, event.timezone),\n kind: \"event\",\n reminder_text: event.description ?? null,\n event_title: event.title ?? item.title,\n event_end: occurrenceEnd,\n event_location: event.location ?? null,\n event_all_day: event.all_day ?? null,\n event_timezone: event.timezone ?? null,\n event_recurring: event.recurrence ? true : false,\n event_recurrence_rule: recurrenceRuleSummary,\n item_id: item.id,\n item_title: item.title,\n item_type: item.type,\n item_status: item.status,\n item_priority: item.priority,\n item_assignee: item.assignee ?? null,\n item_deadline: item.deadline ?? null,\n item_tags: item.tags,\n });\n }\n }\n }\n return sortEvents(events);\n}\n\nfunction filterItems(\n items: ItemFrontMatter[],\n options: CalendarOptions,\n typeRegistry: ItemTypeRegistry,\n statusRegistry: RuntimeStatusRegistry,\n runtimeFieldFilters: Record<string, unknown>,\n): ItemFrontMatter[] {\n const typeFilter = parseType(options.type, typeRegistry);\n const tagFilter = options.tag?.trim().toLowerCase();\n const priorityFilter = parsePriority(options.priority);\n const statusFilter = parseStatus(options.status, statusRegistry);\n const assigneeFilter = options.assignee?.trim();\n const assigneeModeFilter = parseAssigneeFilter(options.assigneeFilter);\n const sprintFilter = options.sprint?.trim();\n const releaseFilter = options.release?.trim();\n\n if (assigneeFilter && (assigneeFilter.toLowerCase() === \"none\" || assigneeFilter.toLowerCase() === \"null\")) {\n throw new PmCliError(\n '--assignee no longer accepts \"none\" or \"null\". Use --assignee-filter unassigned.',\n EXIT_CODE.USAGE,\n );\n }\n if (assigneeFilter !== undefined && assigneeModeFilter === \"unassigned\") {\n throw new PmCliError(\"Cannot combine --assignee with --assignee-filter unassigned\", EXIT_CODE.USAGE);\n }\n\n return items.filter((item) =>\n itemMatchesCalendarFilters(item, {\n typeFilter,\n tagFilter,\n priorityFilter,\n statusFilter,\n assigneeFilter,\n assigneeModeFilter,\n sprintFilter,\n releaseFilter,\n runtimeFieldFilters,\n }),\n );\n}\n\nfunction itemMatchesCalendarFilters(\n item: ItemFrontMatter,\n filters: {\n typeFilter: ItemType | undefined;\n tagFilter: string | undefined;\n priorityFilter: number | undefined;\n statusFilter: ItemStatus | undefined;\n assigneeFilter: string | undefined;\n assigneeModeFilter: \"assigned\" | \"unassigned\" | undefined;\n sprintFilter: string | undefined;\n releaseFilter: string | undefined;\n runtimeFieldFilters: Record<string, unknown>;\n },\n): boolean {\n return (\n itemMatchesCalendarIdentityFilters(item, filters) &&\n itemMatchesCalendarOwnerFilters(item, filters) &&\n matchesRuntimeFilters(item as Record<string, unknown>, filters.runtimeFieldFilters)\n );\n}\n\nfunction itemMatchesCalendarIdentityFilters(\n item: ItemFrontMatter,\n filters: Parameters<typeof itemMatchesCalendarFilters>[1],\n): boolean {\n if (filters.typeFilter && item.type !== filters.typeFilter) return false;\n if (filters.tagFilter && !item.tags.some((tag) => tag.trim().toLowerCase() === filters.tagFilter)) return false;\n if (filters.priorityFilter !== undefined && item.priority !== filters.priorityFilter) return false;\n if (filters.statusFilter && item.status !== filters.statusFilter) return false;\n return true;\n}\n\nfunction itemMatchesCalendarOwnerFilters(\n item: ItemFrontMatter,\n filters: Parameters<typeof itemMatchesCalendarFilters>[1],\n): boolean {\n if (filters.assigneeModeFilter === \"assigned\" && !item.assignee) return false;\n if (filters.assigneeModeFilter === \"unassigned\" && item.assignee) return false;\n if (filters.assigneeFilter !== undefined && item.assignee !== filters.assigneeFilter) return false;\n if (filters.sprintFilter !== undefined && item.sprint !== filters.sprintFilter) return false;\n if (filters.releaseFilter !== undefined && item.release !== filters.releaseFilter) return false;\n return true;\n}\n\nfunction includeEventInWindow(event: CalendarRow, start: string | undefined, end: string | undefined): boolean {\n if (start && compareTimestampStrings(event.at, start) < 0) {\n return false;\n }\n if (end && compareTimestampStrings(event.at, end) >= 0) {\n return false;\n }\n return true;\n}\n\nfunction resolveCalendarBoundaryInput(raw: string, nowValue: string, fieldLabel: \"--date\" | \"--from\" | \"--to\"): string {\n if (raw.trim().toLowerCase() === \"today\") {\n return startOfUtcDay(nowValue);\n }\n return resolveIsoOrRelative(raw, new Date(nowValue), fieldLabel);\n}\n\nfunction buildRange(\n view: CalendarView,\n options: CalendarOptions,\n nowValue: string,\n): {\n anchor: string;\n start?: string;\n end?: string;\n periodStart?: string;\n periodEnd?: string;\n fullPeriod: boolean;\n} {\n const anchor = options.date ? resolveCalendarBoundaryInput(options.date, nowValue, \"--date\") : nowValue;\n const includePast = options.past === true;\n const fullPeriodRequested = options.fullPeriod === true;\n\n const from = options.from ? resolveCalendarBoundaryInput(options.from, nowValue, \"--from\") : undefined;\n const to = options.to ? resolveCalendarBoundaryInput(options.to, nowValue, \"--to\") : undefined;\n if (from && to && compareTimestampStrings(from, to) >= 0) {\n throw new PmCliError(\"Calendar --from must be before --to\", EXIT_CODE.USAGE);\n }\n\n if (view !== \"agenda\" && (options.from !== undefined || options.to !== undefined)) {\n throw new PmCliError(\"--from and --to are only supported for --view agenda\", EXIT_CODE.USAGE);\n }\n\n if (view === \"agenda\") {\n return buildAgendaRange(anchor, options, nowValue, includePast, fullPeriodRequested, from, to);\n }\n\n if (view === \"day\") {\n const dayStart = startOfUtcDay(anchor);\n return buildFixedPeriodRange(anchor, nowValue, includePast, fullPeriodRequested, dayStart, addUtcDays(dayStart, 1));\n }\n\n if (view === \"week\") {\n const weekStart = startOfUtcWeekMonday(anchor);\n return buildFixedPeriodRange(anchor, nowValue, includePast, fullPeriodRequested, weekStart, addUtcDays(weekStart, 7));\n }\n\n const monthStart = startOfUtcMonth(anchor);\n return buildFixedPeriodRange(anchor, nowValue, includePast, fullPeriodRequested, monthStart, startOfNextUtcMonth(anchor));\n}\n\nfunction buildAgendaRange(\n anchor: string,\n options: CalendarOptions,\n nowValue: string,\n includePast: boolean,\n fullPeriodRequested: boolean,\n from: string | undefined,\n to: string | undefined,\n): ReturnType<typeof buildRange> {\n if (fullPeriodRequested) {\n throw new PmCliError(\n \"--full-period is only supported for --view day|week|month. For agenda windows, use --from and --to.\",\n EXIT_CODE.USAGE,\n );\n }\n return {\n anchor,\n start: from ?? (options.date ? anchor : includePast ? undefined : nowValue),\n end: to,\n fullPeriod: false,\n };\n}\n\nfunction buildFixedPeriodRange(\n anchor: string,\n nowValue: string,\n includePast: boolean,\n fullPeriodRequested: boolean,\n periodStart: string,\n periodEnd: string,\n): ReturnType<typeof buildRange> {\n const fullPeriod = includePast || fullPeriodRequested;\n return {\n anchor,\n start: fullPeriod ? periodStart : maxTimestamp(periodStart, nowValue),\n end: periodEnd,\n periodStart,\n periodEnd,\n fullPeriod,\n };\n}\n\nfunction bucketEventsByDay(events: CalendarRow[]): CalendarDayBucket[] {\n const dayMap = new Map<string, CalendarRow[]>();\n for (const event of events) {\n const list = dayMap.get(event.date) ?? [];\n list.push(event);\n dayMap.set(event.date, list);\n }\n return [...dayMap.entries()]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([date, dayEvents]) => ({\n date,\n count: dayEvents.length,\n events: sortEvents(dayEvents),\n }));\n}\n\nfunction summarize(events: CalendarRow[]): CalendarResult[\"summary\"] {\n const itemIds = new Set<string>();\n const byType = new Map<string, number>();\n const byStatus = new Map<string, number>();\n let deadlines = 0;\n let reminders = 0;\n let scheduled = 0;\n let recurringEvents = 0;\n for (const event of events) {\n itemIds.add(event.item_id);\n incrementCount(byType, event.item_type);\n incrementCount(byStatus, event.item_status);\n if (event.kind === \"deadline\") {\n deadlines += 1;\n } else if (event.kind === \"reminder\") {\n reminders += 1;\n } else {\n scheduled += 1;\n if (event.event_recurring === true) {\n recurringEvents += 1;\n }\n }\n }\n return {\n events: events.length,\n items: itemIds.size,\n deadlines,\n reminders,\n scheduled,\n by_kind: {\n deadline: deadlines,\n reminder: reminders,\n event: scheduled,\n },\n by_type: toSortedCountRecord(byType),\n by_status: toSortedCountRecord(byStatus),\n recurring_events: recurringEvents,\n };\n}\n\nfunction formatWindow(range: CalendarResult[\"range\"]): string {\n const start = range.start ?? \"unbounded\";\n const end = range.end ?? \"unbounded\";\n return `${start} -> ${end}`;\n}\n\nfunction formatClock(timestamp: string, timezone?: string | null): string {\n if (timezone && timezone !== \"UTC\") {\n try {\n const parts = new Intl.DateTimeFormat(\"en-GB\", {\n timeZone: timezone,\n hour: \"2-digit\",\n minute: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(new Date(timestamp));\n const hour = parts.find((part) => part.type === \"hour\")?.value;\n const minute = parts.find((part) => part.type === \"minute\")?.value;\n if (hour && minute) {\n // Local wall-clock time; the event line already prints `timezone=<zone>`.\n return `${hour}:${minute}`;\n }\n } catch {\n // Invalid IANA zone — fall back to the UTC clock below.\n }\n }\n return `${new Date(timestamp).toISOString().slice(11, 16)}Z`;\n}\n\nfunction formatSummaryCountRecord(values: Record<string, number>): string {\n const entries = Object.entries(values);\n if (entries.length === 0) {\n return \"empty\";\n }\n return entries.map(([key, value]) => `${key}=${value}`).join(\", \");\n}\n\nfunction formatEventEnd(event: CalendarRow): string | null {\n if (!event.event_end) {\n return null;\n }\n if (event.event_all_day === true) {\n return event.event_end.slice(0, 10);\n }\n if (event.date === toLocalDayKey(event.event_end, event.event_timezone)) {\n return formatClock(event.event_end, event.event_timezone);\n }\n return event.event_end;\n}\n\nfunction formatEventLine(event: CalendarRow): string {\n const core = `${formatClock(event.at, event.event_timezone)} [${event.kind}] ${event.item_id} type=${event.item_type} p${event.item_priority} ${event.item_status} ${event.item_title}`;\n if (event.kind === \"reminder\") {\n const reminderText = event.reminder_text ?? \"\";\n return `${core} — ${reminderText} reminder=${JSON.stringify(reminderText)}`;\n }\n if (event.kind === \"event\") {\n const details: string[] = [];\n const title = event.event_title ?? event.item_title;\n const titleDiffers = event.event_title !== null && event.event_title !== event.item_title;\n if (titleDiffers) {\n details.push(title);\n details.push(`title=${JSON.stringify(title)}`);\n }\n if (event.event_recurring) {\n details.push(\"(recurring)\");\n details.push(\"recurring=true\");\n }\n const end = formatEventEnd(event);\n if (end) {\n details.push(`end=${end}`);\n }\n if (event.event_all_day !== null) {\n details.push(`all_day=${event.event_all_day ? \"true\" : \"false\"}`);\n }\n if (event.event_timezone) {\n details.push(`timezone=${event.event_timezone}`);\n }\n if (event.event_location) {\n details.push(`@ ${event.event_location}`);\n details.push(`location=${JSON.stringify(event.event_location)}`);\n }\n if (event.event_recurrence_rule) {\n details.push(`recurrence=${event.event_recurrence_rule}`);\n }\n if (event.reminder_text) {\n details.push(`description=${JSON.stringify(event.reminder_text)}`);\n }\n return `${core} — ${details.join(\" \")}`;\n }\n return core;\n}\n\n/**\n * Implements render calendar markdown for the public runtime surface of this module.\n */\nexport function renderCalendarMarkdown(result: CalendarResult): string {\n const lines: string[] = [];\n lines.push(`# pm calendar (${result.view})`);\n lines.push(\"\");\n lines.push(`- now: ${result.now}`);\n lines.push(`- window: ${formatWindow(result.range)}`);\n if (result.range.period_start && result.range.period_end) {\n lines.push(`- period: ${result.range.period_start} -> ${result.range.period_end}`);\n lines.push(`- period-mode: ${result.range.full_period ? \"full-period\" : \"active-window\"}`);\n }\n lines.push(\n `- events: ${result.summary.events} (deadlines: ${result.summary.deadlines}, reminders: ${result.summary.reminders}, scheduled: ${result.summary.scheduled})`,\n );\n lines.push(`- items: ${result.summary.items}`);\n lines.push(`- by-kind: ${formatSummaryCountRecord(result.summary.by_kind)}`);\n lines.push(`- by-type: ${formatSummaryCountRecord(result.summary.by_type)}`);\n lines.push(`- by-status: ${formatSummaryCountRecord(result.summary.by_status)}`);\n lines.push(`- recurring-events: ${result.summary.recurring_events}`);\n lines.push(\"\");\n\n if (result.events.length === 0) {\n lines.push(\"No calendar events matched the selected filters.\");\n return lines.join(\"\\n\");\n }\n\n for (const day of result.days) {\n lines.push(`## ${day.date} (${day.count})`);\n for (const event of day.events) {\n lines.push(`- ${formatEventLine(event)}`);\n }\n lines.push(\"\");\n }\n if (result.warnings && result.warnings.length > 0) {\n lines.push(\"### warnings\");\n for (const warning of result.warnings) {\n lines.push(`- ${warning}`);\n }\n lines.push(\"\");\n }\n return trimTrailingNewlines(lines.join(\"\\n\"));\n}\n\n/**\n * Serializes a CalendarResult as TOON (the project's structured output format).\n *\n * The calendar result is JSON-serializable end-to-end (only strings, numbers,\n * booleans, null, plain objects, and arrays), so the value is fed directly to\n * `@toon-format/toon`'s encoder.\n */\nexport function renderCalendarToon(result: CalendarResult): string {\n return encodeToon(result as unknown as Parameters<typeof encodeToon>[0]);\n}\n\nfunction trimTrailingNewlines(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === \"\\n\") {\n end -= 1;\n }\n return value.slice(0, end);\n}\n\n/**\n * Implements run calendar for the public runtime surface of this module.\n */\nexport async function runCalendar(options: CalendarOptions, global: GlobalOptions): Promise<CalendarResult> {\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 nowValue = nowIso();\n const view = parseView(options.view);\n const rangeBounds = buildRange(view, options, nowValue);\n const limit = parseIntegerLimit(options.limit);\n const includeSources = parseIncludeSources(options.include);\n const explicitLookahead = parseNonNegativeInteger(options.recurrenceLookaheadDays, \"Calendar recurrence lookahead days\");\n const recurrenceLookbackDays = parseNonNegativeInteger(options.recurrenceLookbackDays, \"Calendar recurrence lookback days\");\n const occurrenceLimit = parseNonNegativeInteger(options.occurrenceLimit, \"Calendar occurrence limit\");\n if (occurrenceLimit !== undefined && occurrenceLimit < 1) {\n throw new PmCliError(\"Calendar occurrence limit must be >= 1\", EXIT_CODE.USAGE);\n }\n\n const eventsOnly = includeSources.has(\"events\") && !includeSources.has(\"deadlines\") && !includeSources.has(\"reminders\");\n const hasExplicitBounds = options.to !== undefined || explicitLookahead !== undefined || occurrenceLimit !== undefined;\n const eventsOnlyCapApplied = eventsOnly && !hasExplicitBounds;\n const recurrenceLookaheadDays = eventsOnlyCapApplied ? DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS : explicitLookahead;\n const recurrenceLookbackWindowDays =\n eventsOnlyCapApplied && recurrenceLookbackDays === undefined\n ? 0\n : recurrenceLookbackDays;\n\n const settings = await readSettings(pmRoot);\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const runtimeFieldRegistry = resolveRuntimeFieldRegistry(settings.schema);\n const runtimeFieldFilters = collectRuntimeFilterValues(options as Record<string, unknown>, runtimeFieldRegistry, \"calendar\");\n const typeRegistry = resolveItemTypeRegistry(settings, getActiveExtensionRegistrations());\n const listWarnings: string[] = [];\n if (eventsOnlyCapApplied) {\n listWarnings.push(\n `recurring_events_default_cap_applied:lookback=0d,lookahead=${DEFAULT_EVENTS_ONLY_LOOKAHEAD_DAYS}d -- use --recurrence-lookback-days/--recurrence-lookahead-days or --to for wider range`,\n );\n }\n const items = await listAllFrontMatterLight(pmRoot, settings.item_format, typeRegistry.type_to_folder, listWarnings, settings.schema);\n const filteredItems = filterItems(items, options, typeRegistry, statusRegistry, runtimeFieldFilters);\n const recurringWindow = buildRecurringEventWindow(\n rangeBounds.start,\n rangeBounds.end,\n nowValue,\n recurrenceLookbackWindowDays,\n recurrenceLookaheadDays,\n );\n const seededEvents = buildEventSeed(filteredItems, recurringWindow, includeSources, occurrenceLimit);\n const rangedEvents = seededEvents.filter((event) => includeEventInWindow(event, rangeBounds.start, rangeBounds.end));\n const limitedEvents = limit === undefined ? rangedEvents : rangedEvents.slice(0, limit);\n const days = bucketEventsByDay(limitedEvents);\n const warnings = [...new Set(listWarnings)].sort((left, right) => left.localeCompare(right));\n\n return {\n view,\n output_default: \"markdown\",\n now: nowValue,\n anchor: rangeBounds.anchor,\n range: {\n start: rangeBounds.start ?? null,\n end: rangeBounds.end ?? null,\n period_start: rangeBounds.periodStart ?? null,\n period_end: rangeBounds.periodEnd ?? null,\n full_period: rangeBounds.fullPeriod,\n past: options.past === true,\n from: options.from ?? null,\n to: options.to ?? null,\n },\n filters: {\n type: options.type ?? null,\n tag: options.tag ?? null,\n priority: options.priority ?? null,\n status: options.status ?? null,\n assignee: options.assignee ?? null,\n assignee_filter: options.assigneeFilter ?? null,\n sprint: options.sprint ?? null,\n release: options.release ?? null,\n runtime_filters: runtimeFieldFilters,\n limit: options.limit ?? null,\n include: options.include ?? null,\n full_period: options.fullPeriod === true ? \"true\" : null,\n recurrence_lookahead_days: options.recurrenceLookaheadDays ?? null,\n recurrence_lookback_days: options.recurrenceLookbackDays ?? null,\n occurrence_limit: options.occurrenceLimit ?? null,\n },\n summary: summarize(limitedEvents),\n events: limitedEvents,\n days,\n ...(warnings.length > 0 ? { warnings } : {}),\n };\n}\n","/**\n * @module cli/commands/context\n *\n * Implements the pm context command surface and its agent-facing runtime behavior.\n */\nimport { SETTINGS_DEFAULTS, EXIT_CODE } from \"../../core/shared/constants.js\";\nimport type { GlobalOptions } from \"../../core/shared/command-types.js\";\nimport { PmCliError } from \"../../core/shared/errors.js\";\nimport { compareTimestampStrings, nowIso } from \"../../core/shared/time.js\";\nimport { isTerminalStatus, normalizeStatusForRegistry, normalizeStatusInput } from \"../../core/item/status.js\";\nimport { resolveRuntimeStatusRegistry, type RuntimeStatusRegistry } from \"../../core/schema/runtime-schema.js\";\nimport { resolvePmRoot } from \"../../core/store/paths.js\";\nimport { readSettings } from \"../../core/store/settings.js\";\nimport type {\n ContextDepth,\n ContextSectionName,\n ContextSettings,\n ItemFrontMatter,\n ItemStatus,\n PmSettings,\n} from \"../../types/index.js\";\nimport { CONTEXT_DEPTH_VALUES, CONTEXT_SECTION_VALUES } from \"../../types/index.js\";\nimport { parseIntegerLimit } from \"../shared-parsers.js\";\nimport { runCalendar, type CalendarOptions, type CalendarRow } from \"./calendar.js\";\nimport { runList, type ListOptions } from \"./list.js\";\nimport { runActivity, type CompactActivityEntry } from \"./activity.js\";\n\n// ---------------------------------------------------------------------------\n// Output format\n// ---------------------------------------------------------------------------\n\nexport const CONTEXT_OUTPUT_VALUES = [\"markdown\", \"toon\", \"json\"] as const;\n/**\n * Restricts context output format values accepted by command, SDK, and storage contracts.\n */\nexport type ContextOutputFormat = (typeof CONTEXT_OUTPUT_VALUES)[number];\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Documents the context options payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContextOptions {\n date?: string;\n from?: string;\n to?: string;\n past?: boolean;\n type?: string;\n tag?: string;\n priority?: string;\n assignee?: string;\n assigneeFilter?: string;\n sprint?: string;\n release?: string;\n limit?: string;\n format?: string;\n depth?: string;\n fields?: string;\n section?: string[];\n activityLimit?: string;\n staleThreshold?: string;\n parent?: string;\n [key: string]: unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Focus item (unchanged from original)\n// ---------------------------------------------------------------------------\n\n/**\n * Documents the context focus item payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContextFocusItem {\n id: string;\n title: string;\n type: string;\n status: ItemStatus;\n priority: number;\n order: number | null;\n deadline: string | null;\n assignee: string | null;\n tags: string[];\n updated_at: string;\n parent: string | null;\n children_total?: number;\n children_closed?: number;\n completion_pct?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Section data types\n// ---------------------------------------------------------------------------\n\n/**\n * Documents the hierarchy child payload exchanged by command, SDK, and package integrations.\n */\nexport interface HierarchyChild {\n id: string;\n title: string;\n type: string;\n status: ItemStatus;\n children_total: number;\n children_closed: number;\n}\n\n/**\n * Documents the hierarchy node payload exchanged by command, SDK, and package integrations.\n */\nexport interface HierarchyNode {\n id: string;\n title: string;\n type: string;\n status: ItemStatus;\n children_total: number;\n children_closed: number;\n children_open: number;\n children_in_progress: number;\n children_blocked: number;\n children: HierarchyChild[];\n}\n\n/**\n * Documents the progress entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface ProgressEntry {\n id: string;\n title: string;\n type: string;\n total: number;\n closed: number;\n open: number;\n in_progress: number;\n blocked: number;\n completion_pct: number;\n}\n\n/**\n * Documents the blocker entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface BlockerEntry {\n id: string;\n title: string;\n blocked_by: string | null;\n blocked_by_title: string | null;\n blocked_by_status: ItemStatus | null;\n blocked_reason: string | null;\n unblock_note: string | null;\n}\n\n/**\n * Documents the hot file payload exchanged by command, SDK, and package integrations.\n */\nexport interface HotFile {\n path: string;\n references: number;\n items: string[];\n}\n\n/**\n * Documents the workload entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface WorkloadEntry {\n assignee: string | null;\n active: number;\n in_progress: number;\n items: string[];\n}\n\n/**\n * Documents the stale entry payload exchanged by command, SDK, and package integrations.\n */\nexport interface StaleEntry {\n id: string;\n title: string;\n status: ItemStatus;\n updated_at: string;\n stale_days: number;\n}\n\n/**\n * Documents the recent context item payload exchanged by command, SDK, and package integrations.\n */\nexport interface RecentContextItem extends ContextFocusItem {\n created_at?: string;\n}\n\n/**\n * Documents the test health summary payload exchanged by command, SDK, and package integrations.\n */\nexport interface TestHealthSummary {\n items_with_tests: number;\n items_with_recent_runs: number;\n recent_runs: {\n passed: number;\n failed: number;\n skipped: number;\n };\n items_failing: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Agenda / summary (unchanged)\n// ---------------------------------------------------------------------------\n\ninterface ContextAgendaSummary {\n events: number;\n items: number;\n deadlines: number;\n reminders: number;\n scheduled: number;\n}\n\ninterface ContextSummary {\n active_items: number;\n in_progress: number;\n open: number;\n blocked: number;\n blocked_fallback_used: boolean;\n high_level: number;\n low_level: number;\n agenda_events: number;\n total_items?: number;\n closed?: number;\n canceled?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Result\n// ---------------------------------------------------------------------------\n\n/**\n * Documents the context result payload exchanged by command, SDK, and package integrations.\n */\nexport interface ContextResult {\n output_default: \"toon\";\n now: string;\n depth: ContextDepth;\n sections_included: ContextSectionName[];\n window: {\n anchor: string;\n start: string | null;\n end: string | null;\n past: boolean;\n from: string | null;\n to: string | null;\n };\n filters: {\n type: string | null;\n tag: string | null;\n priority: string | null;\n assignee: string | null;\n assignee_filter: string | null;\n sprint: string | null;\n release: string | null;\n limit: string | null;\n parent: string | null;\n runtime_filters?: Record<string, unknown>;\n };\n summary: ContextSummary;\n high_level: ContextFocusItem[];\n low_level: ContextFocusItem[];\n blocked_fallback: ContextFocusItem[];\n agenda: {\n summary: ContextAgendaSummary;\n events: CalendarRow[];\n };\n hierarchy?: HierarchyNode[];\n activity?: CompactActivityEntry[];\n progress?: ProgressEntry[];\n blockers?: BlockerEntry[];\n recently_created?: RecentContextItem[];\n unparented?: ContextFocusItem[];\n files?: HotFile[];\n workload?: WorkloadEntry[];\n staleness?: StaleEntry[];\n tests?: TestHealthSummary;\n suggestions?: string[];\n /** Focus-row field subset requested via --fields; null/omitted means full rows. */\n focus_fields?: string[];\n warnings?: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nconst HIGH_LEVEL_TYPES = new Set<string>([\"Epic\", \"Feature\"]);\nconst DEFAULT_CONTEXT_LIMIT = 10;\n\nconst STANDARD_SECTIONS: ContextSectionName[] = [\"hierarchy\", \"activity\", \"progress\", \"recently_created\", \"unparented\", \"workload\"];\nconst DEEP_SECTIONS: ContextSectionName[] = [\n ...STANDARD_SECTIONS,\n \"blockers\",\n \"files\",\n \"staleness\",\n \"tests\",\n];\nconst LEADING_HYPHEN_DATE = /^(\\d{4})-(\\d{2})-(\\d{2})/;\nconst LEADING_COMPACT_DATE = /^(\\d{4})(\\d{2})(\\d{2})(?:[T ]?\\d{2}|$)/;\nconst COMPACT_DATE = /^(\\d{4})(\\d{2})(\\d{2})$/;\nconst COMPACT_DATETIME = /^(\\d{4})(\\d{2})(\\d{2})(?:[T\\s]?)(\\d{2})(\\d{2})(\\d{2})?(Z|[+-]\\d{2}:?\\d{2})?$/i;\n\n// ---------------------------------------------------------------------------\n// Parsers\n// ---------------------------------------------------------------------------\n\nfunction parseOutputFormat(raw: string | undefined): ContextOutputFormat | undefined {\n if (!raw) return undefined;\n const normalized = raw.trim().toLowerCase();\n if (!CONTEXT_OUTPUT_VALUES.includes(normalized as ContextOutputFormat)) {\n throw new PmCliError(\"Context format must be one of markdown|toon|json\", EXIT_CODE.USAGE);\n }\n return normalized as ContextOutputFormat;\n}\n\n// Fields selectable by `pm context --fields` for focus-row projection. Every\n// ContextFocusItem scalar plus `created_at` (carried by recently-created rows)\n// is addressable; unknown names are rejected with a usage hint.\nconst FOCUS_PROJECTION_FIELDS = new Set<string>([\n \"id\",\n \"title\",\n \"type\",\n \"status\",\n \"priority\",\n \"order\",\n \"deadline\",\n \"assignee\",\n \"tags\",\n \"updated_at\",\n \"parent\",\n \"children_total\",\n \"children_closed\",\n \"completion_pct\",\n \"created_at\",\n]);\n\n/**\n * Parses the comma-separated `--fields` value into a validated, de-duplicated\n * focus-row projection list. Returns undefined when no projection was requested.\n */\nexport function parseContextFocusFields(raw: string | undefined): string[] | undefined {\n if (raw === undefined) return undefined;\n const fields: string[] = [];\n for (const token of raw.split(\",\")) {\n const normalized = token.trim().toLowerCase();\n if (normalized.length === 0) continue;\n if (!FOCUS_PROJECTION_FIELDS.has(normalized)) {\n throw new PmCliError(\n `Context --fields value not projectable: ${normalized} (valid: ${[...FOCUS_PROJECTION_FIELDS].join(\", \")})`,\n EXIT_CODE.USAGE,\n );\n }\n if (!fields.includes(normalized)) fields.push(normalized);\n }\n if (fields.length === 0) {\n throw new PmCliError(\"Context --fields requires at least one field name\", EXIT_CODE.USAGE);\n }\n return fields;\n}\n\n/**\n * Projects focus rows onto the requested field subset, preserving field order so\n * the rendered/serialized output mirrors the `--fields` argument.\n */\nexport function projectContextFocusRows<T extends ContextFocusItem>(rows: T[], fields: string[]): ContextFocusItem[] {\n return rows.map((row) => {\n const projected: Record<string, unknown> = {};\n const source = row as Record<string, unknown>;\n for (const field of fields) {\n projected[field] = source[field] ?? null;\n }\n return projected as unknown as ContextFocusItem;\n });\n}\n\n/**\n * Implements resolve context output format for the public runtime surface of this module.\n */\nexport function resolveContextOutputFormat(options: ContextOptions, global: GlobalOptions): ContextOutputFormat {\n const commandFormat = parseOutputFormat(options.format);\n if (global.json && commandFormat && commandFormat !== \"json\") {\n throw new PmCliError(\"Cannot combine --json with --format markdown|toon\", EXIT_CODE.USAGE);\n }\n if (global.json) {\n return \"json\";\n }\n return commandFormat ?? \"toon\";\n}\n\n// --depth full surfaces the entire backlog: when no explicit --limit is given,\n// every section returns all rows instead of the default top-N sample.\nfunction parseContextLimit(raw: string | undefined, depth: ContextDepth): number {\n return parseIntegerLimit(raw, \"--limit\") ?? (depth === \"full\" ? Number.MAX_SAFE_INTEGER : DEFAULT_CONTEXT_LIMIT);\n}\n\n/**\n * Implements parse context depth for the public runtime surface of this module.\n */\nexport function parseContextDepth(raw: string | undefined, settings: ContextSettings): ContextDepth {\n if (!raw) return settings.default_depth;\n const normalized = raw.trim().toLowerCase();\n if (!CONTEXT_DEPTH_VALUES.includes(normalized as ContextDepth)) {\n throw new PmCliError(`Context --depth must be one of ${CONTEXT_DEPTH_VALUES.join(\"|\")}`, EXIT_CODE.USAGE);\n }\n return normalized as ContextDepth;\n}\n\n/**\n * Implements parse context sections for the public runtime surface of this module.\n */\nexport function parseContextSections(\n raw: string[] | undefined,\n depth: ContextDepth,\n settings: ContextSettings,\n): ContextSectionName[] {\n if (raw && raw.length > 0) {\n const sections: ContextSectionName[] = [];\n for (const value of raw) {\n const normalized = value.trim().toLowerCase();\n if (!CONTEXT_SECTION_VALUES.includes(normalized as ContextSectionName)) {\n throw new PmCliError(\n `Context --section must be one of ${CONTEXT_SECTION_VALUES.join(\"|\")}`,\n EXIT_CODE.USAGE,\n );\n }\n if (!sections.includes(normalized as ContextSectionName)) {\n sections.push(normalized as ContextSectionName);\n }\n }\n return sections;\n }\n if (depth === \"brief\") return [];\n // --depth full is the comprehensive snapshot: every known section, regardless\n // of the per-section settings toggles that brief/standard/deep respect.\n if (depth === \"full\") return [...CONTEXT_SECTION_VALUES];\n const pool = depth === \"deep\" ? DEEP_SECTIONS : STANDARD_SECTIONS;\n return pool.filter((section) => settings.sections[section]);\n}\n\nfunction parseActivityLimit(raw: string | undefined, settings: ContextSettings): number {\n if (!raw) return settings.activity_limit;\n const parsed = parseIntegerLimit(raw, \"--activity-limit\");\n /* c8 ignore start -- parseIntegerLimit either throws or returns a number; fallback is defensive typing guard */\n return parsed ?? settings.activity_limit;\n /* c8 ignore stop */\n}\n\nfunction parseStaleThresholdDays(raw: string | undefined, settings: ContextSettings): number {\n if (!raw) return settings.stale_threshold_days;\n const trimmed = raw.trim().toLowerCase();\n const match = /^(\\d+)d?$/.exec(trimmed);\n if (!match) {\n throw new PmCliError(\"--stale-threshold must be a number of days (e.g. 7 or 7d)\", EXIT_CODE.USAGE);\n }\n const days = parseInt(match[1], 10);\n if (days <= 0) {\n throw new PmCliError(\"--stale-threshold must be positive\", EXIT_CODE.USAGE);\n }\n return days;\n}\n\n// ---------------------------------------------------------------------------\n// Status helpers\n// ---------------------------------------------------------------------------\n\nfunction statusRank(status: ItemStatus, statusRegistry: RuntimeStatusRegistry): number {\n const normalizedStatus = normalizeStatusForRegistry(status, statusRegistry);\n const inProgressStatus = normalizeStatusInput(\"in_progress\", statusRegistry);\n const openStatus = normalizeStatusInput(\"open\", statusRegistry);\n const blockedStatus = normalizeStatusInput(\"blocked\", statusRegistry);\n const draftStatus = normalizeStatusInput(\"draft\", statusRegistry);\n if (inProgressStatus && normalizedStatus === inProgressStatus) return 0;\n if (openStatus && normalizedStatus === openStatus) return 1;\n if (blockedStatus && normalizedStatus === blockedStatus) return 2;\n if (draftStatus && normalizedStatus === draftStatus) return 3;\n if (statusRegistry.active_statuses.has(normalizedStatus)) return 4;\n if (statusRegistry.blocked_statuses.has(normalizedStatus)) return 5;\n if (statusRegistry.terminal_statuses.has(normalizedStatus)) return 7;\n return 6;\n}\n\nfunction isClosedStatus(status: ItemStatus, statusRegistry: RuntimeStatusRegistry): boolean {\n const closeStatus = normalizeStatusInput(\"closed\", statusRegistry);\n return normalizeStatusForRegistry(status, statusRegistry) === closeStatus;\n}\n\nfunction isInProgressStatus(status: ItemStatus, statusRegistry: RuntimeStatusRegistry): boolean {\n const inProgressStatus = normalizeStatusInput(\"in_progress\", statusRegistry);\n return normalizeStatusForRegistry(status, statusRegistry) === inProgressStatus;\n}\n\nfunction isOpenStatus(status: ItemStatus, statusRegistry: RuntimeStatusRegistry): boolean {\n const openStatus = normalizeStatusInput(\"open\", statusRegistry);\n return normalizeStatusForRegistry(status, statusRegistry) === openStatus;\n}\n\nfunction isBlockedStatus(status: ItemStatus, statusRegistry: RuntimeStatusRegistry): boolean {\n return statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(status, statusRegistry));\n}\n\n// Projection flags belong to list/calendar/activity output shaping and must not\n// leak into runContext's downstream calls, which need full ItemFrontMatter rows.\n// --parent is a context-level subtree scope computed here transitively, so it\n// must not reach runList (whose --parent matches direct children only).\nconst LIST_PROJECTION_FLAGS = [\"compact\", \"brief\", \"fields\", \"includeBody\", \"include_body\", \"parent\"] as const;\n\nfunction stripListProjectionFlags(options: ContextOptions): Record<string, unknown> {\n const copy: Record<string, unknown> = { ...(options as Record<string, unknown>) };\n for (const key of LIST_PROJECTION_FLAGS) {\n delete copy[key];\n }\n return copy;\n}\n\n/**\n * Resolves the transitive subtree (the anchor item plus every descendant via\n * parent links) so `--parent` can scope a snapshot to one epic/milestone. Reuses\n * the same {@link buildChildrenByParent}/{@link collectDescendants} helpers the\n * hierarchy section relies on, so subtree membership stays consistent across the\n * snapshot. Ids are normalized to lowercase for case-insensitive membership; the\n * `found` flag is false when the anchor id is absent from the corpus. Exported so\n * sibling read commands (e.g. `pm next`) can apply the same subtree scoping.\n */\nexport function collectSubtreeIds(corpus: ItemFrontMatter[], parentId: string): { ids: Set<string>; found: boolean } {\n const target = parentId.trim().toLowerCase();\n const anchor = corpus.find((item) => item.id.trim().toLowerCase() === target);\n if (!anchor) {\n return { ids: new Set<string>(), found: false };\n }\n const childrenByParent = buildChildrenByParent(corpus);\n const descendants = collectDescendants(anchor.id, childrenByParent);\n // Store normalized ids so membership checks are case-insensitive end-to-end.\n const ids = new Set<string>([anchor.id, ...descendants.map((item) => item.id)].map((id) => id.trim().toLowerCase()));\n return { ids, found: true };\n}\n\nfunction parseContextParent(raw: string | undefined): string | undefined {\n if (raw === undefined) return undefined;\n const trimmed = raw.trim();\n if (trimmed.length === 0) {\n throw new PmCliError(\"Context --parent requires an item id\", EXIT_CODE.USAGE);\n }\n return trimmed;\n}\n\n// ---------------------------------------------------------------------------\n// Sorting / mapping helpers (unchanged from original)\n// ---------------------------------------------------------------------------\n\nfunction compareOptionalOrder(left: number | null | undefined, right: number | null | undefined): number {\n const leftValue = left ?? null;\n const rightValue = right ?? null;\n if (leftValue === null && rightValue === null) return 0;\n if (leftValue === null) return 1;\n if (rightValue === null) return -1;\n return leftValue - rightValue;\n}\n\nfunction compareOptionalDeadline(left: string | null | undefined, right: string | null | undefined): number {\n const leftValue = left ?? null;\n const rightValue = right ?? null;\n if (leftValue === null && rightValue === null) return 0;\n if (leftValue === null) return 1;\n if (rightValue === null) return -1;\n return compareTimestampStrings(leftValue, rightValue);\n}\n\nfunction daysInUtcMonth(year: number, monthIndex: number): number {\n return new Date(Date.UTC(year, monthIndex + 1, 0)).getUTCDate();\n}\n\nfunction hasNoInvalidDatePrefix(value: string): boolean {\n const match = LEADING_HYPHEN_DATE.exec(value) ?? LEADING_COMPACT_DATE.exec(value);\n if (!match) {\n return true;\n }\n const year = Number.parseInt(match[1], 10);\n const month = Number.parseInt(match[2], 10);\n const day = Number.parseInt(match[3], 10);\n return month >= 1 && month <= 12 && day >= 1 && day <= daysInUtcMonth(year, month - 1);\n}\n\nfunction normalizeTimestampCandidate(value: string): string {\n const compactDate = COMPACT_DATE.exec(value);\n if (compactDate) {\n return `${compactDate[1]}-${compactDate[2]}-${compactDate[3]}`;\n }\n const compactDateTime = COMPACT_DATETIME.exec(value);\n if (compactDateTime) {\n const [, year, month, day, hour, minute, secondRaw, offsetRaw] = compactDateTime;\n const second = secondRaw ? `:${secondRaw}` : \"\";\n const offset = offsetRaw && offsetRaw.length === 5 && offsetRaw !== \"Z\" ? `${offsetRaw.slice(0, 3)}:${offsetRaw.slice(3)}` : offsetRaw ?? \"\";\n return `${year}-${month}-${day}T${hour}:${minute}${second}${offset}`;\n }\n return value;\n}\n\nfunction parseContextTimestampMs(value: unknown): number {\n if (typeof value !== \"string\") {\n return Number.NaN;\n }\n const trimmed = value.trim();\n if (trimmed.length === 0 || !hasNoInvalidDatePrefix(trimmed)) {\n return Number.NaN;\n }\n const parsed = Date.parse(normalizeTimestampCandidate(trimmed));\n return Number.isFinite(parsed) ? parsed : Number.NaN;\n}\n\nfunction sortableTimestamp(value: unknown): string {\n const parsed = parseContextTimestampMs(value);\n return Number.isFinite(parsed) ? new Date(parsed).toISOString() : \"\";\n}\n\nfunction dateTokenForTimestamp(value: unknown): string {\n const parsed = parseContextTimestampMs(value);\n return Number.isFinite(parsed) ? new Date(parsed).toISOString().slice(0, 10) : \"unknown\";\n}\n\nfunction normalizedParentId(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\n/**\n * Ranks two items by work criticality: in-progress before open before blocked\n * before draft (via {@link statusRank}), then ascending priority, explicit order,\n * earliest deadline, most-recently-updated, and finally id for a total order.\n * Exported as the canonical focus ordering so sibling read commands (e.g.\n * `pm next`) recommend work in the exact same sequence as `pm context`.\n */\nexport function compareCriticalItems(left: ItemFrontMatter, right: ItemFrontMatter, statusRegistry: RuntimeStatusRegistry): number {\n const byStatus = statusRank(left.status, statusRegistry) - statusRank(right.status, statusRegistry);\n if (byStatus !== 0) return byStatus;\n const byPriority = left.priority - right.priority;\n if (byPriority !== 0) return byPriority;\n const byOrder = compareOptionalOrder(left.order, right.order);\n if (byOrder !== 0) return byOrder;\n const byDeadline = compareOptionalDeadline(left.deadline, right.deadline);\n if (byDeadline !== 0) return byDeadline;\n const byUpdated = compareTimestampStrings(sortableTimestamp(right.updated_at), sortableTimestamp(left.updated_at));\n const byId = left.id.localeCompare(right.id);\n return byUpdated !== 0 ? byUpdated : byId;\n}\n\nfunction completionPct(closed: number, total: number): number {\n return total > 0 ? Math.round((closed / total) * 100) : 0;\n}\n\n/**\n * Indexes items by their parent id, yielding a parent→direct-children map used by\n * the hierarchy/progress rollups and by focus-row child completion. Items without\n * a parent are skipped. Exported so sibling read commands reuse the same index.\n */\nexport function buildChildrenByParent(allItems: ItemFrontMatter[]): Map<string, ItemFrontMatter[]> {\n const childrenByParent = new Map<string, ItemFrontMatter[]>();\n for (const item of allItems) {\n const parent = normalizedParentId(item.parent);\n if (!parent) continue;\n const children = childrenByParent.get(parent) ?? [];\n children.push(item);\n childrenByParent.set(parent, children);\n }\n return childrenByParent;\n}\n\n/**\n * Projects an item onto the compact {@link ContextFocusItem} focus row. When both\n * a status registry and a parent→children index are supplied, it also folds in the\n * descendant rollup (`children_total`/`children_closed`/`completion_pct`). Exported\n * so sibling read commands (e.g. `pm next`) emit identically-shaped focus rows.\n */\nexport function toContextFocusItem(\n item: ItemFrontMatter,\n statusRegistry?: RuntimeStatusRegistry,\n childrenByParent?: Map<string, ItemFrontMatter[]>,\n): ContextFocusItem {\n const focus: ContextFocusItem = {\n id: item.id,\n title: item.title,\n type: item.type,\n status: item.status,\n priority: item.priority,\n order: item.order ?? null,\n deadline: item.deadline ?? null,\n assignee: item.assignee ?? null,\n tags: Array.isArray(item.tags) ? [...item.tags] : [],\n updated_at: item.updated_at,\n parent: normalizedParentId(item.parent),\n };\n if (statusRegistry && childrenByParent) {\n const descendants = collectDescendants(item.id, childrenByParent);\n const total = descendants.length;\n if (total > 0) {\n const closed = descendants.filter((desc) => isClosedStatus(desc.status, statusRegistry)).length;\n focus.children_total = total;\n focus.children_closed = closed;\n focus.completion_pct = completionPct(closed, total);\n }\n }\n return focus;\n}\n\nfunction summarizeAgenda(events: CalendarRow[]): ContextAgendaSummary {\n let deadlines = 0;\n let reminders = 0;\n let scheduled = 0;\n const itemIds = new Set<string>();\n for (const event of events) {\n itemIds.add(event.item_id);\n if (event.kind === \"deadline\") {\n deadlines += 1;\n continue;\n }\n if (event.kind === \"reminder\") {\n reminders += 1;\n continue;\n }\n scheduled += 1;\n }\n return {\n events: events.length,\n items: itemIds.size,\n deadlines,\n reminders,\n scheduled,\n };\n}\n\nfunction mergeSortedWarnings(...warningGroups: Array<string[] | undefined>): string[] {\n return [...new Set(warningGroups.flatMap((group) => group ?? []))].sort((left, right) => left.localeCompare(right));\n}\n\nfunction filterTerminalCalendarEvents(events: CalendarRow[], statusRegistry: RuntimeStatusRegistry): CalendarRow[] {\n return events.filter((event) => !statusRegistry.terminal_statuses.has(normalizeStatusForRegistry(event.item_status, statusRegistry)));\n}\n\n// ---------------------------------------------------------------------------\n// Section builders\n// ---------------------------------------------------------------------------\n\nfunction buildHierarchy(\n allItems: ItemFrontMatter[],\n activeItems: ItemFrontMatter[],\n statusRegistry: RuntimeStatusRegistry,\n limit: number,\n): HierarchyNode[] {\n const itemMap = new Map<string, ItemFrontMatter>();\n for (const item of allItems) {\n itemMap.set(item.id, item);\n }\n\n const childrenByParent = buildChildrenByParent(allItems);\n\n const activeHighLevelIds = new Set(\n activeItems.filter((item) => HIGH_LEVEL_TYPES.has(item.type)).map((item) => item.id),\n );\n\n const nodes: HierarchyNode[] = [];\n for (const parentId of activeHighLevelIds) {\n const parent = itemMap.get(parentId);\n if (!parent) continue;\n const allDescendants = collectDescendants(parentId, childrenByParent);\n const childItems = childrenByParent.get(parentId) ?? [];\n\n let closedCount = 0;\n let openCount = 0;\n let inProgressCount = 0;\n let blockedCount = 0;\n /* c8 ignore start -- chained status-classification branch accounting is noisy under v8 for mixed descendant sets */\n for (const desc of allDescendants) {\n if (isClosedStatus(desc.status, statusRegistry)) closedCount++;\n else if (isInProgressStatus(desc.status, statusRegistry)) inProgressCount++;\n else if (isBlockedStatus(desc.status, statusRegistry)) blockedCount++;\n else if (isOpenStatus(desc.status, statusRegistry)) openCount++;\n }\n /* c8 ignore stop */\n\n const children: HierarchyChild[] = childItems\n .sort((a, b) => compareCriticalItems(a, b, statusRegistry))\n .slice(0, limit)\n .map((child) => {\n const grandchildren = collectDescendants(child.id, childrenByParent);\n const gcClosed = grandchildren.filter((gc) => isClosedStatus(gc.status, statusRegistry)).length;\n return {\n id: child.id,\n title: child.title,\n type: child.type,\n status: child.status,\n children_total: grandchildren.length,\n children_closed: gcClosed,\n };\n });\n\n nodes.push({\n id: parent.id,\n title: parent.title,\n type: parent.type,\n status: parent.status,\n children_total: allDescendants.length,\n children_closed: closedCount,\n children_open: openCount,\n children_in_progress: inProgressCount,\n children_blocked: blockedCount,\n children,\n });\n }\n\n return nodes\n .sort((a, b) => {\n const aParent = itemMap.get(a.id)!;\n const bParent = itemMap.get(b.id)!;\n return compareCriticalItems(aParent, bParent, statusRegistry);\n })\n .slice(0, limit);\n}\n\nfunction collectDescendants(\n parentId: string,\n childrenByParent: Map<string, ItemFrontMatter[]>,\n): ItemFrontMatter[] {\n const result: ItemFrontMatter[] = [];\n const stack = [parentId];\n const visited = new Set<string>();\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (visited.has(current)) continue;\n visited.add(current);\n const children = childrenByParent.get(current) ?? [];\n for (const child of children) {\n result.push(child);\n stack.push(child.id);\n }\n }\n return result;\n}\n\nexport const _testOnly = {\n buildActivity,\n buildBlockers,\n buildChildrenByParent,\n buildHierarchy,\n buildHotFiles,\n buildProgress,\n buildRecentlyCreated,\n buildStaleness,\n buildTestHealth,\n buildUnparented,\n buildWorkload,\n collectDescendants,\n collectSubtreeIds,\n compareCriticalItems,\n compareOptionalDeadline,\n compareOptionalOrder,\n completionPct,\n dateTokenForTimestamp,\n filterTerminalCalendarEvents,\n isBlockedStatus,\n isClosedStatus,\n isInProgressStatus,\n isOpenStatus,\n mergeSortedWarnings,\n normalizedParentId,\n parseActivityLimit,\n parseContextLimit,\n parseContextParent,\n parseContextTimestampMs,\n parseStaleThresholdDays,\n sortableTimestamp,\n statusRank,\n stripListProjectionFlags,\n summarizeAgenda,\n toContextFocusItem,\n};\n\nasync function buildActivity(\n activityLimit: number,\n global: GlobalOptions,\n): Promise<CompactActivityEntry[]> {\n const result = await runActivity({ compact: true, limit: String(activityLimit) }, global);\n return result.compact_activity ?? [];\n}\n\nfunction buildProgress(\n allItems: ItemFrontMatter[],\n activeItems: ItemFrontMatter[],\n statusRegistry: RuntimeStatusRegistry,\n limit: number,\n): ProgressEntry[] {\n const childrenByParent = new Map<string, ItemFrontMatter[]>();\n for (const item of allItems) {\n if (!item.parent) continue;\n const children = childrenByParent.get(item.parent) ?? [];\n children.push(item);\n childrenByParent.set(item.parent, children);\n }\n\n const activeHighLevel = activeItems.filter((item) => HIGH_LEVEL_TYPES.has(item.type));\n const entries: ProgressEntry[] = [];\n for (const parent of activeHighLevel) {\n const descendants = collectDescendants(parent.id, childrenByParent);\n const total = descendants.length;\n if (total === 0) continue;\n\n let closed = 0;\n let open = 0;\n let inProgress = 0;\n let blocked = 0;\n /* c8 ignore start -- chained status-classification branch accounting is noisy under v8 for mixed descendant sets */\n for (const desc of descendants) {\n if (isClosedStatus(desc.status, statusRegistry)) closed++;\n else if (isInProgressStatus(desc.status, statusRegistry)) inProgress++;\n else if (isBlockedStatus(desc.status, statusRegistry)) blocked++;\n else if (isOpenStatus(desc.status, statusRegistry)) open++;\n }\n /* c8 ignore stop */\n\n entries.push({\n id: parent.id,\n title: parent.title,\n type: parent.type,\n total,\n closed,\n open,\n in_progress: inProgress,\n blocked,\n completion_pct: completionPct(closed, total),\n });\n }\n\n return entries\n .sort((a, b) => a.completion_pct - b.completion_pct)\n .slice(0, limit);\n}\n\nfunction buildBlockers(\n blockedItems: ItemFrontMatter[],\n itemMap: Map<string, ItemFrontMatter>,\n limit: number,\n): BlockerEntry[] {\n return blockedItems.slice(0, limit).map((item) => {\n const blockerItem = item.blocked_by ? itemMap.get(item.blocked_by) : undefined;\n return {\n id: item.id,\n title: item.title,\n blocked_by: item.blocked_by ?? null,\n blocked_by_title: blockerItem?.title ?? null,\n blocked_by_status: blockerItem?.status ?? null,\n blocked_reason: item.blocked_reason ?? null,\n unblock_note: item.unblock_note ?? null,\n };\n });\n}\n\nfunction buildHotFiles(\n activeItems: ItemFrontMatter[],\n limit: number,\n): HotFile[] {\n const fileMap = new Map<string, Set<string>>();\n for (const item of activeItems) {\n for (const file of item.files ?? []) {\n const existing = fileMap.get(file.path) ?? new Set<string>();\n existing.add(item.id);\n fileMap.set(file.path, existing);\n }\n }\n\n return [...fileMap.entries()]\n .map(([filePath, itemIds]) => ({\n path: filePath,\n references: itemIds.size,\n items: [...itemIds].sort(),\n }))\n .sort((a, b) => b.references - a.references)\n .slice(0, limit);\n}\n\nfunction buildWorkload(\n activeItems: ItemFrontMatter[],\n statusRegistry: RuntimeStatusRegistry,\n limit: number,\n): WorkloadEntry[] {\n const groups = new Map<string | null, ItemFrontMatter[]>();\n for (const item of activeItems) {\n const key = item.assignee ?? null;\n const existing = groups.get(key) ?? [];\n existing.push(item);\n groups.set(key, existing);\n }\n\n return [...groups.entries()]\n .map(([assignee, items]) => ({\n assignee,\n active: items.length,\n in_progress: items.filter((item) => isInProgressStatus(item.status, statusRegistry)).length,\n items: items.map((item) => item.id).sort(),\n }))\n .sort((a, b) => b.active - a.active)\n .slice(0, limit);\n}\n\nfunction buildStaleness(\n allNonTerminal: ItemFrontMatter[],\n staleThresholdDays: number,\n now: string,\n limit: number,\n): StaleEntry[] {\n const cutoffMs = new Date(now).getTime() - staleThresholdDays * 24 * 60 * 60 * 1000;\n\n return allNonTerminal\n .filter((item) => new Date(item.updated_at).getTime() < cutoffMs)\n .map((item) => ({\n id: item.id,\n title: item.title,\n status: item.status,\n updated_at: item.updated_at,\n stale_days: Math.floor((new Date(now).getTime() - new Date(item.updated_at).getTime()) / (24 * 60 * 60 * 1000)),\n }))\n .sort((a, b) => b.stale_days - a.stale_days)\n .slice(0, limit);\n}\n\nfunction buildRecentlyCreated(\n allNonTerminal: ItemFrontMatter[],\n statusRegistry: RuntimeStatusRegistry,\n childrenByParent: Map<string, ItemFrontMatter[]>,\n limit: number,\n): RecentContextItem[] {\n return allNonTerminal\n .map((item) => ({ item, sortKey: sortableTimestamp(item.created_at) }))\n .sort((left, right) => {\n const byCreated = compareTimestampStrings(right.sortKey, left.sortKey);\n return byCreated !== 0 ? byCreated : left.item.id.localeCompare(right.item.id);\n })\n .slice(0, limit)\n .map(({ item }) => ({\n ...toContextFocusItem(item, statusRegistry, childrenByParent),\n created_at: item.created_at,\n }));\n}\n\nfunction buildUnparented(\n allNonTerminal: ItemFrontMatter[],\n statusRegistry: RuntimeStatusRegistry,\n childrenByParent: Map<string, ItemFrontMatter[]>,\n limit: number,\n): ContextFocusItem[] {\n return allNonTerminal\n .filter((item) => !normalizedParentId(item.parent) && !HIGH_LEVEL_TYPES.has(item.type))\n .sort((left, right) => compareCriticalItems(left, right, statusRegistry))\n .slice(0, limit)\n .map((item) => toContextFocusItem(item, statusRegistry, childrenByParent));\n}\n\nfunction buildTestHealth(\n activeItems: ItemFrontMatter[],\n): TestHealthSummary {\n let itemsWithTests = 0;\n let itemsWithRecentRuns = 0;\n let passed = 0;\n let failed = 0;\n let skipped = 0;\n const itemsFailing: string[] = [];\n\n for (const item of activeItems) {\n if ((item.tests ?? []).length > 0) {\n itemsWithTests++;\n }\n const runs = item.test_runs ?? [];\n if (runs.length > 0) {\n itemsWithRecentRuns++;\n let itemHasFailure = false;\n for (const run of runs) {\n passed += run.passed ?? 0;\n failed += run.failed ?? 0;\n skipped += run.skipped ?? 0;\n if ((run.failed ?? 0) > 0) {\n itemHasFailure = true;\n }\n }\n if (itemHasFailure) {\n itemsFailing.push(item.id);\n }\n }\n }\n\n return {\n items_with_tests: itemsWithTests,\n items_with_recent_runs: itemsWithRecentRuns,\n recent_runs: { passed, failed, skipped },\n items_failing: itemsFailing.sort(),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Markdown formatting\n// ---------------------------------------------------------------------------\n\nfunction formatClock(timestamp: string): string {\n return `${new Date(timestamp).toISOString().slice(11, 16)}Z`;\n}\n\nfunction formatFocusLine(item: ContextFocusItem): string {\n const orderToken = item.order === null ? \"-\" : String(item.order);\n const deadlineToken = item.deadline ?? \"-\";\n const parentToken = item.parent ? ` parent:${item.parent}` : \"\";\n const progressToken =\n item.children_total !== undefined && item.children_closed !== undefined && item.completion_pct !== undefined\n ? ` children:${item.children_closed}/${item.children_total} done:${item.completion_pct}%`\n : \"\";\n return `${item.id} p${item.priority} ${item.status} ${item.type} order:${orderToken} deadline:${deadlineToken}${parentToken}${progressToken} ${item.title}`;\n}\n\n// Renders a focus row projected to a `--fields` subset as space-separated\n// field:value tokens, mirroring the projection field order. Array values join\n// with commas; missing/null values render as `-`.\nfunction formatProjectedFocusLine(item: ContextFocusItem, fields: string[]): string {\n const source = item as unknown as Record<string, unknown>;\n return fields\n .map((field) => {\n const value = source[field];\n if (Array.isArray(value)) return `${field}:${value.join(\",\")}`;\n return `${field}:${value ?? \"-\"}`;\n })\n .join(\" \");\n}\n\nfunction formatAgendaLine(event: CalendarRow): string {\n const base = `${formatClock(event.at)} [${event.kind}] ${event.item_id} p${event.item_priority} ${event.item_status} ${event.item_title}`;\n if (event.kind === \"reminder\") {\n return `${base} — ${event.reminder_text}`;\n }\n if (event.kind === \"event\") {\n const recurringSuffix = event.event_recurring ? \" (recurring)\" : \"\";\n const title = event.event_title ?? event.item_title;\n return `${base} — ${title}${recurringSuffix}`;\n }\n return base;\n}\n\n/**\n * Implements render context markdown for the public runtime surface of this module.\n */\nexport function renderContextMarkdown(result: ContextResult): string {\n const lines: string[] = [];\n const focusFields = result.focus_fields;\n const renderFocus = (item: ContextFocusItem): string =>\n focusFields ? formatProjectedFocusLine(item, focusFields) : formatFocusLine(item);\n lines.push(\"# pm context\");\n lines.push(\"\");\n lines.push(`- now: ${result.now}`);\n lines.push(`- depth: ${result.depth}`);\n if (result.filters.parent) {\n lines.push(`- scope: subtree of ${result.filters.parent}`);\n }\n lines.push(`- active_items: ${result.summary.active_items} (in_progress: ${result.summary.in_progress}, open: ${result.summary.open})`);\n if (result.summary.total_items !== undefined) {\n lines.push(`- total_items: ${result.summary.total_items} (closed: ${result.summary.closed ?? 0}, canceled: ${result.summary.canceled ?? 0})`);\n }\n lines.push(`- agenda_events: ${result.summary.agenda_events}`);\n lines.push(`- blocked_fallback_used: ${result.summary.blocked_fallback_used}`);\n const renderedSections = result.sections_included.filter(\n (section) => section !== \"blockers\" || (result.blockers?.length ?? 0) > 0,\n );\n if (renderedSections.length > 0) {\n lines.push(`- sections: ${renderedSections.join(\", \")}`);\n }\n lines.push(\"\");\n\n lines.push(\"## High-level focus\");\n if (result.high_level.length === 0) {\n lines.push(\"No high-level active items.\");\n } else {\n for (const item of result.high_level) {\n lines.push(`- ${renderFocus(item)}`);\n }\n }\n lines.push(\"\");\n\n lines.push(\"## Low-level focus\");\n if (result.low_level.length === 0) {\n lines.push(\"No low-level active items.\");\n } else {\n for (const item of result.low_level) {\n lines.push(`- ${renderFocus(item)}`);\n }\n }\n lines.push(\"\");\n\n if (result.blocked_fallback.length > 0) {\n lines.push(\"## Blocked fallback\");\n for (const item of result.blocked_fallback) {\n lines.push(`- ${renderFocus(item)}`);\n }\n lines.push(\"\");\n }\n\n lines.push(\"## Agenda\");\n lines.push(\n `- events: ${result.agenda.summary.events} (deadlines: ${result.agenda.summary.deadlines}, reminders: ${result.agenda.summary.reminders}, scheduled: ${result.agenda.summary.scheduled})`,\n );\n if (result.agenda.events.length === 0) {\n lines.push(\"No agenda events matched the selected filters.\");\n } else {\n for (const event of result.agenda.events) {\n lines.push(`- ${formatAgendaLine(event)}`);\n }\n }\n lines.push(\"\");\n\n if (result.hierarchy && result.hierarchy.length > 0) {\n lines.push(\"## Hierarchy\");\n for (const node of result.hierarchy) {\n const pct = node.children_total > 0 ? Math.round((node.children_closed / node.children_total) * 100) : 0;\n lines.push(`- ${node.id} ${node.type} ${node.status} \"${node.title}\" [${node.children_closed}/${node.children_total} done ${pct}%]`);\n for (const child of node.children) {\n const cpct = child.children_total > 0 ? Math.round((child.children_closed / child.children_total) * 100) : 0;\n lines.push(` - ${child.id} ${child.type} ${child.status} \"${child.title}\" [${child.children_closed}/${child.children_total} done ${cpct}%]`);\n }\n }\n lines.push(\"\");\n }\n\n if (result.progress && result.progress.length > 0) {\n lines.push(\"## Progress\");\n for (const entry of result.progress) {\n lines.push(`- ${entry.id} \"${entry.title}\" ${entry.completion_pct}% (${entry.closed}/${entry.total} closed, ${entry.in_progress} wip, ${entry.open} open, ${entry.blocked} blocked)`);\n }\n lines.push(\"\");\n }\n\n if (result.recently_created && result.recently_created.length > 0) {\n lines.push(\"## Recently created\");\n for (const item of result.recently_created) {\n // The date prefix is dropped under --fields: created_at may be projected\n // out, and the projected line already surfaces whatever fields were asked.\n lines.push(focusFields ? `- ${renderFocus(item)}` : `- ${dateTokenForTimestamp(item.created_at)} ${formatFocusLine(item)}`);\n }\n lines.push(\"\");\n }\n\n if (result.unparented && result.unparented.length > 0) {\n lines.push(\"## Unparented\");\n for (const item of result.unparented) {\n lines.push(`- ${renderFocus(item)}`);\n }\n lines.push(\"\");\n }\n\n if (result.activity && result.activity.length > 0) {\n lines.push(\"## Recent activity\");\n for (const entry of result.activity) {\n const msg = entry.msg ? ` ${entry.msg}` : \"\";\n lines.push(`- ${entry.ts.slice(0, 16)}Z ${entry.id} ${entry.op} by:${entry.author}${msg}`);\n }\n lines.push(\"\");\n }\n\n if (result.blockers && result.blockers.length > 0) {\n lines.push(\"## Blockers\");\n for (const entry of result.blockers) {\n const by = entry.blocked_by ? `blocked_by:${entry.blocked_by}(${entry.blocked_by_status ?? \"?\"})` : \"blocked_by:-\";\n const reason = entry.blocked_reason ? ` reason:\"${entry.blocked_reason}\"` : \"\";\n const note = entry.unblock_note ? ` unblock:\"${entry.unblock_note}\"` : \"\";\n lines.push(`- ${entry.id} \"${entry.title}\" ${by}${reason}${note}`);\n }\n lines.push(\"\");\n }\n\n if (result.files && result.files.length > 0) {\n lines.push(\"## Hot files\");\n for (const file of result.files) {\n lines.push(`- ${file.path} refs:${file.references} items:[${file.items.join(\",\")}]`);\n }\n lines.push(\"\");\n }\n\n if (result.workload && result.workload.length > 0) {\n lines.push(\"## Workload\");\n for (const entry of result.workload) {\n const who = entry.assignee ?? \"(unassigned)\";\n lines.push(`- ${who} active:${entry.active} wip:${entry.in_progress} items:[${entry.items.join(\",\")}]`);\n }\n lines.push(\"\");\n }\n\n if (result.staleness && result.staleness.length > 0) {\n lines.push(\"## Stale items\");\n for (const entry of result.staleness) {\n lines.push(`- ${entry.id} ${entry.status} stale:${entry.stale_days}d last:${entry.updated_at.slice(0, 10)} \"${entry.title}\"`);\n }\n lines.push(\"\");\n }\n\n if (result.tests) {\n lines.push(\"## Test health\");\n lines.push(`- items_with_tests: ${result.tests.items_with_tests}`);\n lines.push(`- items_with_recent_runs: ${result.tests.items_with_recent_runs}`);\n lines.push(`- passed: ${result.tests.recent_runs.passed}, failed: ${result.tests.recent_runs.failed}, skipped: ${result.tests.recent_runs.skipped}`);\n if (result.tests.items_failing.length > 0) {\n lines.push(`- items_failing: [${result.tests.items_failing.join(\",\")}]`);\n }\n lines.push(\"\");\n }\n\n const isEmpty =\n result.summary.active_items === 0 &&\n result.summary.blocked === 0 &&\n result.agenda.summary.events === 0;\n if (isEmpty) {\n lines.push(\"## Suggestions\");\n lines.push(\"No active work items or upcoming events. Consider:\");\n lines.push(\"- `pm create --type Task --title \\\"...\\\"` to add a new work item\");\n lines.push(\"- `pm list --status closed --limit 5` to review recent completions\");\n lines.push(\"- `pm search <keywords>` to find related past work\");\n lines.push(\"- `pm aggregate` for a full project status overview\");\n }\n\n return lines.join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// Main runner\n// ---------------------------------------------------------------------------\n\n/**\n * Implements run context for the public runtime surface of this module.\n */\nexport async function runContext(options: ContextOptions, global: GlobalOptions): Promise<ContextResult> {\n const pmRoot = resolvePmRoot(process.cwd(), global.path);\n const settings = await readSettings(pmRoot);\n /* c8 ignore start -- settings persistence currently always materializes context defaults */\n const contextSettings = settings.context ?? SETTINGS_DEFAULTS.context;\n /* c8 ignore stop */\n const statusRegistry = resolveRuntimeStatusRegistry(settings.schema);\n const depth = parseContextDepth(options.depth, contextSettings);\n const limit = parseContextLimit(options.limit, depth);\n const sectionsIncluded = parseContextSections(options.section, depth, contextSettings);\n const activityLimit = parseActivityLimit(options.activityLimit, contextSettings);\n const staleThresholdDays = parseStaleThresholdDays(options.staleThreshold, contextSettings);\n const parentScope = parseContextParent(options.parent);\n const focusFields = parseContextFocusFields(options.fields);\n\n const needsAllItems = sectionsIncluded.some((s) =>\n [\"hierarchy\", \"progress\", \"blockers\", \"staleness\", \"recently_created\", \"unparented\"].includes(s),\n );\n\n const baseListOptions = stripListProjectionFlags(options);\n // Structural reads must see the FULL corpus: --limit/--offset are per-section\n // display caps applied later via .slice(0, limit), not corpus filters. Passing\n // them to runList would truncate the data the hierarchy/progress rollups and\n // (critically) --parent subtree resolution depend on — yielding wrong rollups\n // or a false NOT_FOUND for an anchor that paginated out of view.\n const unpaginatedListOptions = (extra: Partial<ListOptions>): ListOptions => ({\n ...baseListOptions,\n ...extra,\n noTruncate: true,\n limit: undefined,\n offset: undefined,\n });\n // Subtree scoping also needs the complete active set before filtering, so the\n // focus rows aren't pre-truncated by --limit ahead of the parent filter.\n const listOptions: ListOptions = parentScope === undefined\n ? { ...baseListOptions, excludeTerminal: true }\n : unpaginatedListOptions({ excludeTerminal: true });\n const listed = await runList(undefined, listOptions, global);\n let listedFrontMatter = listed.items as ItemFrontMatter[];\n\n // --parent needs the whole corpus to walk descendants; so do hierarchy-style\n // sections. Fetch it once (unpaginated) and reuse for both.\n let allItems: ItemFrontMatter[] = listedFrontMatter;\n if (needsAllItems || parentScope !== undefined) {\n const allListed = await runList(undefined, unpaginatedListOptions({ excludeTerminal: false }), global);\n allItems = allListed.items as ItemFrontMatter[];\n }\n // The unfiltered corpus stays the reference for cross-item metadata resolution\n // (e.g. a subtree blocker whose blocked_by points OUTSIDE the subtree must still\n // resolve its title/status). Only the enumeration sets below get subtree-scoped.\n const fullCorpus = allItems;\n\n let subtreeIds: Set<string> | undefined;\n if (parentScope !== undefined) {\n const subtree = collectSubtreeIds(fullCorpus, parentScope);\n if (!subtree.found) {\n throw new PmCliError(`Context --parent item not found: ${parentScope}`, EXIT_CODE.NOT_FOUND);\n }\n subtreeIds = subtree.ids;\n listedFrontMatter = listedFrontMatter.filter((item) => subtreeIds?.has(item.id.trim().toLowerCase()));\n allItems = allItems.filter((item) => subtreeIds?.has(item.id.trim().toLowerCase()));\n }\n\n const ranked = [...listedFrontMatter].sort((left, right) => compareCriticalItems(left, right, statusRegistry));\n /* c8 ignore start -- fallback applies only to custom schemas that intentionally define no active statuses */\n const activeStatuses =\n statusRegistry.active_statuses.size > 0\n ? statusRegistry.active_statuses\n : new Set<ItemStatus>([statusRegistry.open_status]);\n /* c8 ignore stop */\n const blockedStatuses = statusRegistry.blocked_statuses;\n const activeItems = ranked.filter((item) => activeStatuses.has(normalizeStatusForRegistry(item.status, statusRegistry)));\n const blockedItems = ranked.filter((item) =>\n blockedStatuses.has(normalizeStatusForRegistry(item.status, statusRegistry)),\n );\n\n const childrenByParent = buildChildrenByParent(allItems);\n const focusChildrenByParent = needsAllItems ? childrenByParent : undefined;\n\n const highLevel = activeItems\n .filter((item) => HIGH_LEVEL_TYPES.has(item.type))\n .slice(0, limit)\n .map((item) => toContextFocusItem(item, statusRegistry, focusChildrenByParent));\n const lowLevel = activeItems\n .filter((item) => !HIGH_LEVEL_TYPES.has(item.type))\n .slice(0, limit)\n .map((item) => toContextFocusItem(item, statusRegistry, focusChildrenByParent));\n\n const blockedFallbackUsed = activeItems.length === 0;\n const blockedFallback = blockedFallbackUsed\n ? blockedItems.slice(0, limit).map((item) => toContextFocusItem(item, statusRegistry, focusChildrenByParent))\n : [];\n\n const calendarOptions: CalendarOptions = {\n ...baseListOptions,\n view: \"agenda\",\n include: \"all\",\n // When scoping to a subtree, pull the full agenda so the subtree filter sees\n // every candidate event before the final per-section slice.\n limit: parentScope === undefined ? String(limit) : undefined,\n };\n const agenda = await runCalendar(calendarOptions, global);\n const scopedAgenda =\n subtreeIds === undefined\n ? agenda.events\n : agenda.events.filter((event) => subtreeIds.has(event.item_id.trim().toLowerCase()));\n const agendaEvents = filterTerminalCalendarEvents(scopedAgenda, statusRegistry).slice(0, limit);\n const agendaSummary = summarizeAgenda(agendaEvents);\n const warnings = mergeSortedWarnings(listed.warnings, agenda.warnings);\n\n const inProgressStatus = normalizeStatusInput(\"in_progress\", statusRegistry);\n const openStatus = normalizeStatusInput(\"open\", statusRegistry);\n const inProgressCount = activeItems.filter(\n (item) => normalizeStatusForRegistry(item.status, statusRegistry) === inProgressStatus,\n ).length;\n const openCount = activeItems.filter((item) => normalizeStatusForRegistry(item.status, statusRegistry) === openStatus).length;\n\n const now = agenda.now;\n\n // Resolve blocker/dependency metadata against the full corpus so references\n // that point outside a --parent subtree still render their title/status.\n const itemMap = new Map<string, ItemFrontMatter>();\n for (const item of fullCorpus) {\n itemMap.set(item.id, item);\n }\n\n const allNonTerminal = allItems.filter((item) => !isTerminalStatus(item.status, statusRegistry));\n\n const has = (section: ContextSectionName) => sectionsIncluded.includes(section);\n\n const hierarchy = has(\"hierarchy\") ? buildHierarchy(allItems, activeItems, statusRegistry, limit) : undefined;\n const activity = has(\"activity\") ? await buildActivity(activityLimit, global) : undefined;\n const progress = has(\"progress\") ? buildProgress(allItems, activeItems, statusRegistry, limit) : undefined;\n const blockersSection = has(\"blockers\") ? buildBlockers(blockedItems, itemMap, limit) : undefined;\n const recentlyCreated = has(\"recently_created\")\n ? buildRecentlyCreated(allNonTerminal, statusRegistry, childrenByParent, limit)\n : undefined;\n const unparented = has(\"unparented\")\n ? buildUnparented(allNonTerminal, statusRegistry, childrenByParent, limit)\n : undefined;\n const filesSection = has(\"files\") ? buildHotFiles(activeItems, limit) : undefined;\n const workload = has(\"workload\") ? buildWorkload(activeItems, statusRegistry, limit) : undefined;\n const staleness = has(\"staleness\") ? buildStaleness(allNonTerminal, staleThresholdDays, now, limit) : undefined;\n const tests = has(\"tests\") ? buildTestHealth(activeItems) : undefined;\n\n const summaryExtras: Pick<ContextSummary, \"total_items\" | \"closed\" | \"canceled\"> =\n needsAllItems\n ? {\n total_items: allItems.length,\n closed: allItems.filter((i) => isClosedStatus(i.status, statusRegistry)).length,\n canceled: allItems.filter((i) => {\n const canceledStatus = normalizeStatusInput(\"canceled\", statusRegistry);\n return normalizeStatusForRegistry(i.status, statusRegistry) === canceledStatus;\n }).length,\n }\n : {};\n\n const result: ContextResult = {\n output_default: \"toon\",\n now,\n depth,\n sections_included: sectionsIncluded,\n window: {\n anchor: agenda.anchor,\n start: agenda.range.start,\n end: agenda.range.end,\n past: agenda.range.past,\n from: agenda.range.from,\n to: agenda.range.to,\n },\n filters: {\n type: options.type ?? null,\n tag: options.tag ?? null,\n priority: options.priority ?? null,\n assignee: options.assignee ?? null,\n assignee_filter: options.assigneeFilter ?? null,\n sprint: options.sprint ?? null,\n release: options.release ?? null,\n limit: options.limit ?? null,\n parent: parentScope ?? null,\n /* c8 ignore next -- listed/calendar runtime filters are always materialized by their command handlers */\n runtime_filters: (listed.filters.runtime_filters ?? agenda.filters.runtime_filters ?? {}) as Record<string, unknown>,\n },\n summary: {\n active_items: activeItems.length,\n in_progress: inProgressCount,\n open: openCount,\n blocked: blockedItems.length,\n blocked_fallback_used: blockedFallbackUsed,\n high_level: highLevel.length,\n low_level: lowLevel.length,\n agenda_events: agendaSummary.events,\n ...summaryExtras,\n },\n high_level: highLevel,\n low_level: lowLevel,\n blocked_fallback: blockedFallback,\n agenda: {\n summary: agendaSummary,\n events: agendaEvents,\n },\n };\n\n if (hierarchy) result.hierarchy = hierarchy;\n if (activity) result.activity = activity;\n if (progress) result.progress = progress;\n if (blockersSection) result.blockers = blockersSection;\n if (recentlyCreated) result.recently_created = recentlyCreated;\n if (unparented) result.unparented = unparented;\n if (filesSection) result.files = filesSection;\n if (workload) result.workload = workload;\n if (staleness) result.staleness = staleness;\n if (tests) result.tests = tests;\n if (focusFields) {\n result.focus_fields = focusFields;\n result.high_level = projectContextFocusRows(result.high_level, focusFields);\n result.low_level = projectContextFocusRows(result.low_level, focusFields);\n result.blocked_fallback = projectContextFocusRows(result.blocked_fallback, focusFields);\n if (result.recently_created) {\n result.recently_created = projectContextFocusRows(result.recently_created, focusFields) as RecentContextItem[];\n }\n if (result.unparented) {\n result.unparented = projectContextFocusRows(result.unparented, focusFields);\n }\n }\n if (warnings.length > 0) result.warnings = warnings;\n if (activeItems.length === 0 && blockedItems.length === 0 && agendaEvents.length === 0) {\n result.suggestions = [\n 'pm create --type Task --title \"...\" to add a new work item',\n \"pm list --status closed --limit 5 to review recent completions\",\n \"pm search <keywords> to find related past work\",\n \"pm aggregate for a full project status overview\",\n ];\n }\n\n return result;\n}\n"],"names":["year","month"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,SAAS,UAAU,kBAAkB;AAuB9B,IAAM,uBAAuB,CAAC,UAAU,OAAO,QAAQ,OAAO;AAgIrE,IAAM,qBAAqB,CAAC,OAAO,OAAO,OAAO,OAAO,OAAO,OAAO,KAAK;AAC3E,IAAM,oCAAoC;AAC1C,IAAM,mCAAmC;AACzC,IAAM,qCAAqC;AAC3C,IAAM,6BAA6B;AAEnC,SAAS,wBAAwB,KAAyB,OAAa;AACrE,MAAI,QAAQ;AAAW,WAAO;AAC9B,QAAM,SAAS,OAAO,GAAG;AACzB,MAAI,CAAC,OAAO,UAAU,MAAM,KAAK,SAAS,GAAG;AAC3C,UAAM,IAAI,WAAW,GAAG,KAAK,mCAAmC,UAAU,KAAK;EACjF;AACA,SAAO;AACT;AAIA,SAAS,oBAAoB,KAAuB;AAClD,MAAI,CAAC,KAAK;AACR,WAAO,oBAAI,IAAI,CAAC,aAAa,aAAa,QAAQ,CAAC;EAC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,wBAAwB,OAAO,kBAAkB,WAAW;IACxF;AACA,QAAI,OAAO,YAAY;AACrB,aAAO,aAAa,wBAAwB,OAAO,YAAY,WAAW;IAC5E;EACF;AACA,MAAI,SAAS,SAAS;AAAG,WAAO,WAAW;AAC3C,MAAI,YAAY,WAAW,KAAK,aAAa,WAAW,KAAK,aAAa,WAAW,GAAG;AACtF,WAAO,cAAc;MACnB;MACA;MACA;MACA;;EAEJ;AAEA,SAAO;AACT","debugId":"e7cb2510-fa36-55ab-b096-7ce46e2ac4b6"}
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../../../../../../../core/history/drift-scan.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * @module core/history/drift-scan\n *\n * Implements append-only history and replay behavior for Drift Scan.\n */\nimport fs from \"fs/promises\";\nimport { createHash } from \"node:crypto\";\nimport path from \"node:path\";\nimport { getHistoryPath } from \"../store/paths.js\";\nimport { writeFileAtomic } from \"../fs/fs-utils.js\";\nimport { hashDocument } from \"./history.js\";\nimport { verifyHistoryChain } from \"./replay.js\";\nimport type { HistoryEntry, ItemMetadata } from \"../../types/index.js\";\n\n/**\n * Documents the drift scan result payload exchanged by command, SDK, and package integrations.\n */\nexport interface DriftScanResult {\n missingStreams: string[];\n unreadableStreams: string[];\n hashMismatches: string[];\n chainMismatches: string[];\n driftedItems: string[];\n}\n\nconst DRIFT_CACHE_VERSION = 3;\nconst DRIFT_CACHE_FILENAME = \"history-drift-cache.json\";\n\n/**\n * Controls how cached history stream verification is trusted when the file stat\n * tuple still matches a previous scan.\n */\nexport type DriftCacheHitVerification = \"content_hash\" | \"metadata\";\n\n/**\n * Documents the history drift scan options shared by health, validate, and\n * repair callers.\n */\nexport interface DriftScanOptions {\n cacheHitVerification?: DriftCacheHitVerification;\n}\n\ninterface DriftCacheEntry {\n mtime_ms: number;\n ctime_ms: number;\n size: number;\n content_hash: string;\n latest_after_hash: string;\n chain_ok: boolean;\n}\n\ninterface DriftCacheEnvelope {\n version: number;\n entries: Record<string, DriftCacheEntry>;\n}\n\nfunction getDriftCachePath(pmRoot: string): string {\n return path.join(pmRoot, \"runtime\", DRIFT_CACHE_FILENAME);\n}\n\nasync function loadDriftCache(pmRoot: string): Promise<DriftCacheEnvelope | null> {\n try {\n const raw = await fs.readFile(getDriftCachePath(pmRoot), \"utf8\");\n const parsed = JSON.parse(raw) as DriftCacheEnvelope;\n if (parsed.version !== DRIFT_CACHE_VERSION || typeof parsed.entries !== \"object\" || parsed.entries === null) {\n return null;\n }\n return parsed;\n } catch {\n return null;\n }\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\ninterface StreamVerification {\n latestAfterHash: string;\n chainOk: boolean;\n contentHash: string;\n}\n\nfunction hashContent(raw: string): string {\n return createHash(\"sha256\").update(raw).digest(\"hex\");\n}\n\nasync function readHistoryContentHash(historyPath: string): Promise<string> {\n const raw = await fs.readFile(historyPath, \"utf8\");\n return hashContent(raw);\n}\n\n/**\n * Read and fully verify one history stream's hash chain. Returns null for an\n * empty/missing stream (caller records it as a missing stream).\n */\nasync function verifyHistoryStream(historyPath: string): Promise<StreamVerification | null> {\n const raw = await fs.readFile(historyPath, \"utf8\");\n const contentHash = hashContent(raw);\n if (raw.trim().length === 0) {\n return null;\n }\n const entries: HistoryEntry[] = [];\n let latestAfterHash: string | null = null;\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n const parsed = JSON.parse(trimmed) as HistoryEntry;\n if (typeof parsed.after_hash !== \"string\" || parsed.after_hash.trim().length === 0) {\n throw new Error(\"missing after_hash\");\n }\n entries.push(parsed);\n latestAfterHash = parsed.after_hash;\n }\n /* c8 ignore start -- defensive guard for future history schema changes. */\n if (!latestAfterHash) {\n return null;\n }\n /* c8 ignore stop */\n return {\n latestAfterHash,\n chainOk: verifyHistoryChain(entries).ok,\n contentHash,\n };\n}\n\n/**\n * Scan every item's history stream for drift (missing/unreadable streams, broken\n * hash chains, and item/history hash mismatches).\n *\n * Full chain re-verification of a large history tree is the dominant cost of\n * `pm health`. We cache the per-stream verification keyed by the history file's\n * mtime/ctime/size plus content hash. Strict callers keep recomputing the\n * content hash on metadata hits; latency-sensitive health checks can opt into\n * trusting the stat tuple and skip rereading unchanged streams.\n */\nexport async function scanHistoryDrift(\n pmRoot: string,\n items: Array<ItemMetadata & { body: string }>,\n options: DriftScanOptions = {},\n): Promise<DriftScanResult> {\n const missingStreams: string[] = [];\n const unreadableStreams: string[] = [];\n const hashMismatches: string[] = [];\n const chainMismatches: string[] = [];\n\n const cache = await loadDriftCache(pmRoot);\n const previousEntries: Record<string, DriftCacheEntry> = cache?.entries ?? {};\n const nextEntries: Record<string, DriftCacheEntry> = {};\n let cacheDirty = false;\n // Metadata mode does not open a stat-matched stream, so unreadable-after-stat\n // failures are intentionally deferred to strict validate/history-repair scans.\n const verifyCacheHitByContent = options.cacheHitVerification !== \"metadata\";\n\n for (const item of items) {\n const historyPath = getHistoryPath(pmRoot, item.id);\n\n let stat: Awaited<ReturnType<typeof fs.stat>>;\n try {\n stat = await fs.stat(historyPath);\n } catch (error: unknown) {\n if (isErrno(error, \"ENOENT\")) {\n missingStreams.push(item.id);\n } else {\n unreadableStreams.push(item.id);\n }\n continue;\n }\n\n const loadStreamVerification = async (): Promise<StreamVerification | null | \"unreadable\"> => {\n try {\n return await verifyHistoryStream(historyPath);\n } catch {\n return \"unreadable\";\n }\n };\n\n const loadFreshVerification = async (): Promise<StreamVerification | null> => {\n const loaded = await loadStreamVerification();\n if (loaded === \"unreadable\") {\n unreadableStreams.push(item.id);\n return null;\n }\n if (!loaded) {\n missingStreams.push(item.id);\n return null;\n }\n return loaded;\n };\n\n const cached = previousEntries[item.id];\n let verification: StreamVerification;\n const metadataMatchesCache =\n cached !== undefined &&\n cached.mtime_ms === stat.mtimeMs &&\n cached.ctime_ms === stat.ctimeMs &&\n cached.size === stat.size;\n const cachedContentHash =\n typeof cached?.content_hash === \"string\" && cached.content_hash.length > 0 ? cached.content_hash : undefined;\n const canUseCache = metadataMatchesCache && cachedContentHash !== undefined;\n if (canUseCache && cached) {\n let currentContentHash: string;\n if (verifyCacheHitByContent) {\n try {\n currentContentHash = await readHistoryContentHash(historyPath);\n } catch {\n unreadableStreams.push(item.id);\n continue;\n }\n } else {\n currentContentHash = cachedContentHash;\n }\n if (!verifyCacheHitByContent || currentContentHash === cachedContentHash) {\n verification = {\n latestAfterHash: cached.latest_after_hash,\n chainOk: cached.chain_ok,\n contentHash: currentContentHash,\n };\n } else {\n cacheDirty = true;\n const refreshed = await loadFreshVerification();\n if (!refreshed) {\n continue;\n }\n verification = refreshed;\n }\n } else {\n cacheDirty = true;\n const refreshed = await loadFreshVerification();\n if (!refreshed) {\n continue;\n }\n verification = refreshed;\n }\n\n if (!verification.chainOk) {\n chainMismatches.push(item.id);\n }\n nextEntries[item.id] = {\n mtime_ms: stat.mtimeMs,\n ctime_ms: stat.ctimeMs,\n size: stat.size,\n content_hash: verification.contentHash,\n latest_after_hash: verification.latestAfterHash,\n chain_ok: verification.chainOk,\n };\n\n const { body, ...frontMatter } = item;\n const currentHash = hashDocument({\n metadata: frontMatter as ItemMetadata,\n body,\n });\n if (currentHash !== verification.latestAfterHash) {\n hashMismatches.push(item.id);\n }\n }\n\n if (cacheDirty || Object.keys(previousEntries).length !== Object.keys(nextEntries).length) {\n const cachePath = getDriftCachePath(pmRoot);\n try {\n await fs.mkdir(path.dirname(cachePath), { recursive: true });\n await writeFileAtomic(cachePath, JSON.stringify({ version: DRIFT_CACHE_VERSION, entries: nextEntries }));\n } catch {\n // Best-effort cache write: a failed persist must never fail a health scan.\n }\n }\n\n const driftedItems = [...new Set([...missingStreams, ...unreadableStreams, ...hashMismatches, ...chainMismatches])].sort((a, b) =>\n a.localeCompare(b),\n );\n return { missingStreams, unreadableStreams, hashMismatches, chainMismatches, dri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