@unbrained/pm-cli 2026.11.30 → 2026.12.2
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 +1 -1
- package/dist/cli/commander-usage.js +10 -10
- package/dist/cli/error-guidance.js +5 -5
- package/dist/cli/extension-command-help.js +6 -6
- package/dist/cli/help-json-payload.js +7 -7
- package/dist/cli/main.js +5 -5
- package/dist/cli/register-list-query.js +10 -10
- package/dist/cli/register-mutation.js +3 -3
- package/dist/cli/runtime/invocation-command-path.js +2 -0
- package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-DCWGM7CY.js → chunk-3HKPVOAN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Z7YL2SUM.js → chunk-3KEMIPKG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TX74QJ4W.js → chunk-4YYFY33T.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-47ZS6RPL.js → chunk-7NAO7I75.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-IGEFPHV7.js → chunk-7V65VACG.js} +52 -52
- package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-5PNOVDVO.js → chunk-AHV3CSQG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KCVSSONY.js → chunk-C6WM6ZN4.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-CBUC4X7Q.js +127 -0
- package/dist/cli-bundle/chunks/{chunk-CCKM5YQM.js → chunk-G6TARHFK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TY55UX6M.js → chunk-GOEQXVOI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-I4SPJQQI.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-Q4VZSMUL.js → chunk-L2ZSSMYY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NHBG5ET3.js → chunk-MZZ4ZJ5Z.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +113 -0
- package/dist/cli-bundle/chunks/{chunk-YVTALIN3.js → chunk-OBPO6V7H.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KXTKLDKD.js → chunk-OXC5KBIQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HXQ3OHQR.js → chunk-PCDTWL6V.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AOTI76Q6.js → chunk-Q6K7HWZ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-NZSXWIX7.js → chunk-ROTEELDL.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-WFYE34TO.js → chunk-SDXCJZKB.js} +23 -23
- package/dist/cli-bundle/chunks/{chunk-2SBTXR6C.js → chunk-SY5C3U32.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-FR7ULTM4.js → chunk-TKUG2X24.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FECZV72T.js → chunk-UNBW2LF3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-V2S4XAX3.js +2 -0
- package/dist/cli-bundle/chunks/chunk-WSEIEDEK.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ZA5NS3PL.js → chunk-ZL6J6JYT.js} +6 -6
- package/dist/cli-bundle/chunks/{field-option-collisions-2F2Z7R7B.js → field-option-collisions-BBGTV7AD.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-56J5OCHA.js +2 -0
- package/dist/cli-bundle/chunks/{linked-resource-value-list-WXPPYUVQ.js → linked-resource-value-list-ZBIY4H23.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-actor-UK3QNEEB.js → mutation-actor-NHN33ITJ.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-UTDYPFWP.js → mutation-admission-PGKJTCG6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-DRA3CWHI.js → register-list-query-7S5QWDTI.js} +11 -11
- package/dist/cli-bundle/chunks/{register-mutation-WO74VLEQ.js → register-mutation-EK6DVIQK.js} +5 -5
- package/dist/cli-bundle/chunks/{register-operations-CRBKH7WN.js → register-operations-6MURXE4V.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-6V6NQB5C.js → register-setup-RW26X3GJ.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-DYEHGASU.js → stage-4ZCF74G4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RQYVX2T6.js → chunk-2DGKVXFT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-2UWKU2BQ.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-A3DORTXS.js → chunk-3COWDIPX.js} +54 -54
- package/dist/cli-bundle/focused-chunks/{chunk-UQJ4PY2Y.js → chunk-4SCFAWAW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7G7JIXLL.js → chunk-6BKT6XQN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-6IY5CVGJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-7A6SEZEY.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IJ3T3W4U.js → chunk-BHNBPCHP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LWBZ7UGG.js → chunk-EQCQTYKO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FM5WQ6ZU.js → chunk-HTDYNY4L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TQQO42C2.js → chunk-J72TRWR5.js} +26 -26
- package/dist/cli-bundle/focused-chunks/{chunk-L357ZAES.js → chunk-JPZGC3W4.js} +5 -5
- package/dist/cli-bundle/focused-chunks/{chunk-62AMZMR4.js → chunk-KNBGHCIP.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +100 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IIVDBAJM.js → chunk-OG57ESZK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MZNV26XE.js → chunk-P2H3GTJK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SXC3NVZI.js → chunk-TR22GU7M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-M57KDG7I.js → chunk-TXTPAFHJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VK3IE3TS.js +29 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NJTKGBSK.js → chunk-VQIC3UZB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-U35K7FSE.js → chunk-W4JMV7GF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{field-option-collisions-7TG7STO7.js → field-option-collisions-2C6DLUC4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-transaction-2IC2MLML.js → item-transaction-LQLQLZE7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-actor-LJVF2HVD.js → mutation-actor-DJMZUIZI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-SDWQVVHN.js +2 -0
- package/dist/cli-bundle/focused-chunks/{stage-MWR73LTZ.js → stage-QBZIK3T5.js} +2 -2
- package/dist/cli-bundle/main.js +27 -27
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +61 -61
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/extensions/reserved-host-flags.js +1 -1
- package/dist/core/shared/secret-rules.d.ts +86 -12
- package/dist/core/shared/secret-rules.js +7 -5
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +50 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension/install-sources.d.ts +2 -2
- package/dist/sdk/extension/install-sources.js +5 -5
- package/dist/sdk/lifecycle/expect-hash-admission.d.ts +15 -0
- package/dist/sdk/lifecycle/expect-hash-admission.js +2 -0
- package/dist/sdk/lifecycle/item-revision.d.ts +4 -1
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/mutation-guard.js +1 -1
- package/dist/sdk/output-contracts.js +1 -1
- package/dist/sdk/output-projection.d.ts +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/aggregate.js +1 -1
- package/dist/sdk/query/context.js +1 -1
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/next.js +1 -1
- package/dist/sdk/query/search-contracts.js +1 -1
- package/dist/sdk/read-output/surfaces.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +1 -1
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-rows.js +1 -1
- package/docs/COMMANDS.md +37 -0
- package/docs/MUTATION_INTEGRITY.md +226 -10
- package/docs/SDK.md +16 -6
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/node_modules/tar/README.md +1792 -1147
- package/node_modules/tar/dist/commonjs/bytes.d.ts +21 -0
- package/node_modules/tar/dist/commonjs/bytes.js +83 -0
- package/node_modules/tar/dist/commonjs/codec.d.ts +53 -0
- package/node_modules/tar/dist/commonjs/codec.js +35 -0
- package/node_modules/tar/dist/commonjs/concat.d.ts +3 -0
- package/node_modules/tar/dist/commonjs/concat.js +20 -0
- package/node_modules/tar/dist/commonjs/create.d.ts +39 -2
- package/node_modules/tar/dist/commonjs/create.js +150 -64
- package/node_modules/tar/dist/commonjs/dealias.d.ts +79 -0
- package/node_modules/tar/dist/commonjs/dealias.js +50 -0
- package/node_modules/tar/dist/commonjs/delete.d.ts +19 -0
- package/node_modules/tar/dist/commonjs/delete.js +121 -0
- package/node_modules/tar/dist/commonjs/entries.d.ts +82 -0
- package/node_modules/tar/dist/commonjs/entries.js +398 -0
- package/node_modules/tar/dist/commonjs/extract.d.ts +14 -2
- package/node_modules/tar/dist/commonjs/extract.js +40 -81
- package/node_modules/tar/dist/commonjs/fs.d.ts +201 -0
- package/node_modules/tar/dist/commonjs/fs.js +5 -0
- package/node_modules/tar/dist/commonjs/header.d.ts +4 -4
- package/node_modules/tar/dist/commonjs/header.js +71 -53
- package/node_modules/tar/dist/commonjs/index.d.ts +25 -18
- package/node_modules/tar/dist/commonjs/index.js +46 -18
- package/node_modules/tar/dist/commonjs/index.min.js +2 -3
- package/node_modules/tar/dist/commonjs/large-numbers.d.ts +2 -2
- package/node_modules/tar/dist/commonjs/large-numbers.js +4 -4
- package/node_modules/tar/dist/commonjs/list.d.ts +23 -6
- package/node_modules/tar/dist/commonjs/list.js +99 -138
- package/node_modules/tar/dist/commonjs/mkdir.d.ts +16 -11
- package/node_modules/tar/dist/commonjs/mkdir.js +121 -159
- package/node_modules/tar/dist/commonjs/normalize-unicode.js +9 -0
- package/node_modules/tar/dist/commonjs/options.d.ts +284 -513
- package/node_modules/tar/dist/commonjs/options.js +20 -61
- package/node_modules/tar/dist/commonjs/pack.d.ts +150 -96
- package/node_modules/tar/dist/commonjs/pack.js +752 -445
- package/node_modules/tar/dist/commonjs/parser.d.ts +98 -0
- package/node_modules/tar/dist/commonjs/parser.js +452 -0
- package/node_modules/tar/dist/commonjs/path-reservations.d.ts +17 -7
- package/node_modules/tar/dist/commonjs/path-reservations.js +110 -140
- package/node_modules/tar/dist/commonjs/path.d.ts +19 -0
- package/node_modules/tar/dist/commonjs/path.js +90 -0
- package/node_modules/tar/dist/commonjs/pax.d.ts +3 -1
- package/node_modules/tar/dist/commonjs/pax.js +67 -36
- package/node_modules/tar/dist/commonjs/read-entry.d.ts +97 -11
- package/node_modules/tar/dist/commonjs/read-entry.js +251 -97
- package/node_modules/tar/dist/commonjs/read-file.d.ts +22 -0
- package/node_modules/tar/dist/commonjs/read-file.js +104 -0
- package/node_modules/tar/dist/commonjs/replace.d.ts +45 -1
- package/node_modules/tar/dist/commonjs/replace.js +164 -211
- package/node_modules/tar/dist/commonjs/server/codecs.d.ts +38 -0
- package/node_modules/tar/dist/commonjs/server/codecs.js +252 -0
- package/node_modules/tar/dist/commonjs/server/index.d.ts +115 -0
- package/node_modules/tar/dist/commonjs/server/index.js +166 -0
- package/node_modules/tar/dist/commonjs/server/index.min.js +3 -0
- package/node_modules/tar/dist/commonjs/strip-absolute-path.d.ts +8 -0
- package/node_modules/tar/dist/commonjs/strip-absolute-path.js +17 -20
- package/node_modules/tar/dist/commonjs/to-stream.d.ts +7 -0
- package/node_modules/tar/dist/commonjs/to-stream.js +22 -0
- package/node_modules/tar/dist/commonjs/types.d.ts +4 -3
- package/node_modules/tar/dist/commonjs/types.js +4 -3
- package/node_modules/tar/dist/commonjs/unpack.d.ts +143 -89
- package/node_modules/tar/dist/commonjs/unpack.js +780 -725
- package/node_modules/tar/dist/commonjs/update.d.ts +11 -1
- package/node_modules/tar/dist/commonjs/update.js +37 -28
- package/node_modules/tar/dist/commonjs/warn.d.ts +27 -0
- package/node_modules/tar/dist/commonjs/warn.js +36 -0
- package/node_modules/tar/dist/commonjs/win32-path.d.ts +16 -0
- package/node_modules/tar/dist/commonjs/win32-path.js +67 -0
- package/node_modules/tar/dist/commonjs/write-entry.d.ts +64 -111
- package/node_modules/tar/dist/commonjs/write-entry.js +108 -672
- package/node_modules/tar/dist/commonjs/write-flag.d.ts +18 -0
- package/node_modules/tar/dist/commonjs/write-flag.js +29 -0
- package/node_modules/tar/dist/esm/bytes.d.ts +21 -0
- package/node_modules/tar/dist/esm/bytes.js +72 -0
- package/node_modules/tar/dist/esm/codec.d.ts +53 -0
- package/node_modules/tar/dist/esm/codec.js +32 -0
- package/node_modules/tar/dist/esm/concat.d.ts +3 -0
- package/node_modules/tar/dist/esm/concat.js +16 -0
- package/node_modules/tar/dist/esm/create.d.ts +39 -2
- package/node_modules/tar/dist/esm/create.js +144 -61
- package/node_modules/tar/dist/esm/dealias.d.ts +79 -0
- package/node_modules/tar/dist/esm/dealias.js +46 -0
- package/node_modules/tar/dist/esm/delete.d.ts +19 -0
- package/node_modules/tar/dist/esm/delete.js +117 -0
- package/node_modules/tar/dist/esm/entries.d.ts +82 -0
- package/node_modules/tar/dist/esm/entries.js +388 -0
- package/node_modules/tar/dist/esm/extract.d.ts +14 -2
- package/node_modules/tar/dist/esm/extract.js +37 -44
- package/node_modules/tar/dist/esm/fs.d.ts +201 -0
- package/node_modules/tar/dist/esm/fs.js +4 -0
- package/node_modules/tar/dist/esm/header.d.ts +4 -4
- package/node_modules/tar/dist/esm/header.js +71 -53
- package/node_modules/tar/dist/esm/index.d.ts +25 -18
- package/node_modules/tar/dist/esm/index.js +23 -18
- package/node_modules/tar/dist/esm/index.min.js +2 -3
- package/node_modules/tar/dist/esm/large-numbers.d.ts +2 -2
- package/node_modules/tar/dist/esm/large-numbers.js +4 -4
- package/node_modules/tar/dist/esm/list.d.ts +23 -6
- package/node_modules/tar/dist/esm/list.js +96 -101
- package/node_modules/tar/dist/esm/mkdir.d.ts +16 -11
- package/node_modules/tar/dist/esm/mkdir.js +119 -154
- package/node_modules/tar/dist/esm/normalize-unicode.js +9 -0
- package/node_modules/tar/dist/esm/options.d.ts +284 -513
- package/node_modules/tar/dist/esm/options.js +17 -51
- package/node_modules/tar/dist/esm/pack.d.ts +150 -96
- package/node_modules/tar/dist/esm/pack.js +750 -441
- package/node_modules/tar/dist/esm/parser.d.ts +98 -0
- package/node_modules/tar/dist/esm/parser.js +448 -0
- package/node_modules/tar/dist/esm/path-reservations.d.ts +17 -7
- package/node_modules/tar/dist/esm/path-reservations.js +110 -140
- package/node_modules/tar/dist/esm/path.d.ts +19 -0
- package/node_modules/tar/dist/esm/path.js +80 -0
- package/node_modules/tar/dist/esm/pax.d.ts +3 -1
- package/node_modules/tar/dist/esm/pax.js +66 -35
- package/node_modules/tar/dist/esm/read-entry.d.ts +97 -11
- package/node_modules/tar/dist/esm/read-entry.js +248 -96
- package/node_modules/tar/dist/esm/read-file.d.ts +22 -0
- package/node_modules/tar/dist/esm/read-file.js +99 -0
- package/node_modules/tar/dist/esm/replace.d.ts +45 -1
- package/node_modules/tar/dist/esm/replace.js +160 -207
- package/node_modules/tar/dist/esm/server/codecs.d.ts +38 -0
- package/node_modules/tar/dist/esm/server/codecs.js +214 -0
- package/node_modules/tar/dist/esm/server/index.d.ts +115 -0
- package/node_modules/tar/dist/esm/server/index.js +102 -0
- package/node_modules/tar/dist/esm/server/index.min.js +3 -0
- package/node_modules/tar/dist/esm/strip-absolute-path.d.ts +8 -0
- package/node_modules/tar/dist/esm/strip-absolute-path.js +17 -20
- package/node_modules/tar/dist/esm/to-stream.d.ts +7 -0
- package/node_modules/tar/dist/esm/to-stream.js +18 -0
- package/node_modules/tar/dist/esm/types.d.ts +4 -3
- package/node_modules/tar/dist/esm/types.js +4 -3
- package/node_modules/tar/dist/esm/unpack.d.ts +143 -89
- package/node_modules/tar/dist/esm/unpack.js +776 -719
- package/node_modules/tar/dist/esm/update.d.ts +11 -1
- package/node_modules/tar/dist/esm/update.js +35 -28
- package/node_modules/tar/dist/esm/warn.d.ts +27 -0
- package/node_modules/tar/dist/esm/warn.js +31 -0
- package/node_modules/tar/dist/esm/win32-path.d.ts +16 -0
- package/node_modules/tar/dist/esm/win32-path.js +60 -0
- package/node_modules/tar/dist/esm/write-entry.d.ts +64 -111
- package/node_modules/tar/dist/esm/write-entry.js +107 -633
- package/node_modules/tar/dist/esm/write-flag.d.ts +18 -0
- package/node_modules/tar/dist/esm/write-flag.js +25 -0
- package/node_modules/tar/package.json +68 -224
- package/package.json +2 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3TXEWHQX.js +0 -125
- package/dist/cli-bundle/chunks/chunk-JPJNJHQW.js +0 -2
- package/dist/cli-bundle/chunks/chunk-NVYDPNQP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SJWIPGZW.js +0 -113
- package/dist/cli-bundle/chunks/chunk-USBTXMKS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-VCXQ6A35.js +0 -3
- package/dist/cli-bundle/chunks/chunk-YPMNXG2C.js +0 -2
- package/dist/cli-bundle/chunks/item-revision-UAF6L47R.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-RJECL53Y.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2UUBS4BG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4ER3VMST.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-4YBMHMBJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HXM7K6VH.js +0 -100
- package/dist/cli-bundle/focused-chunks/chunk-NGHT2LNG.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-P55AZPFN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WAP3DF4B.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XR745UGE.js +0 -4
- package/dist/cli-bundle/focused-chunks/item-revision-J7EUGCHR.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-SLFAUONA.js +0 -2
- package/node_modules/@isaacs/fs-minipass/LICENSE +0 -15
- package/node_modules/@isaacs/fs-minipass/README.md +0 -71
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.d.ts +0 -118
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/index.js +0 -430
- package/node_modules/@isaacs/fs-minipass/dist/commonjs/package.json +0 -3
- package/node_modules/@isaacs/fs-minipass/dist/esm/index.d.ts +0 -118
- package/node_modules/@isaacs/fs-minipass/dist/esm/index.js +0 -420
- package/node_modules/@isaacs/fs-minipass/dist/esm/package.json +0 -3
- package/node_modules/@isaacs/fs-minipass/package.json +0 -72
- package/node_modules/chownr/LICENSE.md +0 -63
- package/node_modules/chownr/README.md +0 -3
- package/node_modules/chownr/dist/commonjs/index.d.ts +0 -3
- package/node_modules/chownr/dist/commonjs/index.js +0 -93
- package/node_modules/chownr/dist/commonjs/package.json +0 -3
- package/node_modules/chownr/dist/esm/index.d.ts +0 -3
- package/node_modules/chownr/dist/esm/index.js +0 -85
- package/node_modules/chownr/dist/esm/package.json +0 -3
- package/node_modules/chownr/package.json +0 -69
- package/node_modules/minipass/LICENSE.md +0 -55
- package/node_modules/minipass/README.md +0 -825
- package/node_modules/minipass/dist/commonjs/index.d.ts +0 -545
- package/node_modules/minipass/dist/commonjs/index.js +0 -1038
- package/node_modules/minipass/dist/commonjs/package.json +0 -3
- package/node_modules/minipass/dist/esm/index.d.ts +0 -545
- package/node_modules/minipass/dist/esm/index.js +0 -1020
- package/node_modules/minipass/dist/esm/package.json +0 -3
- package/node_modules/minipass/package.json +0 -77
- package/node_modules/minizlib/LICENSE +0 -26
- package/node_modules/minizlib/README.md +0 -64
- package/node_modules/minizlib/dist/commonjs/constants.d.ts +0 -2
- package/node_modules/minizlib/dist/commonjs/constants.js +0 -123
- package/node_modules/minizlib/dist/commonjs/index.d.ts +0 -99
- package/node_modules/minizlib/dist/commonjs/index.js +0 -416
- package/node_modules/minizlib/dist/commonjs/package.json +0 -3
- package/node_modules/minizlib/dist/esm/constants.d.ts +0 -2
- package/node_modules/minizlib/dist/esm/constants.js +0 -117
- package/node_modules/minizlib/dist/esm/index.d.ts +0 -99
- package/node_modules/minizlib/dist/esm/index.js +0 -363
- package/node_modules/minizlib/dist/esm/package.json +0 -3
- package/node_modules/minizlib/package.json +0 -80
- package/node_modules/tar/dist/commonjs/get-write-flag.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/get-write-flag.js +0 -32
- package/node_modules/tar/dist/commonjs/make-command.d.ts +0 -49
- package/node_modules/tar/dist/commonjs/make-command.js +0 -52
- package/node_modules/tar/dist/commonjs/normalize-windows-path.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/normalize-windows-path.js +0 -12
- package/node_modules/tar/dist/commonjs/parse.d.ts +0 -92
- package/node_modules/tar/dist/commonjs/parse.js +0 -655
- package/node_modules/tar/dist/commonjs/process-umask.d.ts +0 -2
- package/node_modules/tar/dist/commonjs/process-umask.js +0 -7
- package/node_modules/tar/dist/commonjs/warn-method.d.ts +0 -24
- package/node_modules/tar/dist/commonjs/warn-method.js +0 -31
- package/node_modules/tar/dist/esm/get-write-flag.d.ts +0 -2
- package/node_modules/tar/dist/esm/get-write-flag.js +0 -26
- package/node_modules/tar/dist/esm/make-command.d.ts +0 -49
- package/node_modules/tar/dist/esm/make-command.js +0 -48
- package/node_modules/tar/dist/esm/normalize-windows-path.d.ts +0 -2
- package/node_modules/tar/dist/esm/normalize-windows-path.js +0 -9
- package/node_modules/tar/dist/esm/parse.d.ts +0 -92
- package/node_modules/tar/dist/esm/parse.js +0 -651
- package/node_modules/tar/dist/esm/process-umask.d.ts +0 -2
- package/node_modules/tar/dist/esm/process-umask.js +0 -3
- package/node_modules/tar/dist/esm/warn-method.d.ts +0 -24
- package/node_modules/tar/dist/esm/warn-method.js +0 -27
- package/node_modules/yallist/LICENSE.md +0 -63
- package/node_modules/yallist/README.md +0 -205
- package/node_modules/yallist/dist/commonjs/index.d.ts +0 -39
- package/node_modules/yallist/dist/commonjs/index.js +0 -384
- package/node_modules/yallist/dist/commonjs/package.json +0 -3
- package/node_modules/yallist/dist/esm/index.d.ts +0 -39
- package/node_modules/yallist/dist/esm/index.js +0 -379
- package/node_modules/yallist/dist/esm/package.json +0 -3
- package/node_modules/yallist/package.json +0 -68
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import{a as
|
|
2
|
-
`),null,2)}async function
|
|
3
|
-
`)})}import{AsyncLocalStorage as
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function Ba(e,t){return t==="detailed"?bl(e):xl(e)}function U(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var kl={cal:"calendar",ctx:"context"};function Sl(e,t){return e.commands.find(n=>n.name()===t)??null}function El(e,t){let n=e;for(let o of t){let i=Sl(n,o);if(!i)return null;n=i}return n}function ro(e,t,n,o){let i=El(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",Ba(n,o))}function ao(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var _e={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","pm package list shows the packages installed in the selected scope; catalog shows what pm bundles.","External npm package discovery still belongs to npm search."]},"package inventory":{why:"Lists the packages installed in the selected scope (alias: pm package list) from manifests and saved state, without activating extension code, with the newer version the last pm package manage check observed.",examples:["pm package list","pm package list --global --fields name,version,update","pm package list pm-changelog"],tips:["update is null until pm package manage has checked the registry for that installed version; manage is the live check.","Use pm package catalog for the bundled first-party packages and pm package describe to map what a package registers."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension inventory":{why:"Compatibility view of the installed package inventory (alias: pm extension list); it reads manifests and saved state without activating extension code.",examples:["pm package list","pm package list --global --fields name,version,update"],tips:["Prefer pm package list in new user-facing workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --takeover-stale --message "Take over an abandoned claim"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","The refusal reports the holder's claim age, last activity and idle hours. --takeover-stale takes over only a claim idle for at least mutation_guard.stale_in_progress_hours (default 72), refuses an active one with stale_claim_takeover_refused, and records the previous holder and idle time in the claim's history entry.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of M){let n=_e[e];n&&(_e[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var $e={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Va=K.filter(e=>e.lifecycle==="deprecated");for(let e of Va){let t=_e[e.alias];_e[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[$e,...Object.values(_e)])e.examples=e.examples.map(t=>{for(let n of Va){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Al(e){let t=U(e??"");return t?kl[t]??t:""}function so(e){let t=Al(e);return t?_e[t]??$e:$e}function Ja(e,t){let n=so(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Wa(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Rl(){let e=K.filter(({lifecycle:n})=>n==="permanent"),t=K.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${Oi(n)})`)].join(`
|
|
6
|
-
`)}function
|
|
7
|
-
`,s=t.visibleCommands(e);for(let c of s)
|
|
8
|
-
`).map(i=>` ${i}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function
|
|
9
|
-
`)}var
|
|
1
|
+
import{a as La}from"./chunks/chunk-HZZLSBIJ.js";import"./chunks/chunk-5EFS7K7Y.js";import"./chunks/chunk-SLFRSZK6.js";import{a as zn,b as ca,f as la,g as Sa,h as Ea,i as Aa,j as Ra,k as Oa,l as Ta,m as Yn,o as Ia,p as $a,r as Pa,s as Xn}from"./chunks/chunk-OBPO6V7H.js";import{c as N,d as F,e as L,f as S,g as A,h as ta,m as fe,n as $t,o as na,p as oa}from"./chunks/chunk-MZZ4ZJ5Z.js";import{Wa as ka,f as Zr,k as Qr}from"./chunks/chunk-ROTEELDL.js";import"./chunks/chunk-G6TARHFK.js";import"./chunks/chunk-SY5C3U32.js";import{A as ga,B as ha,C as Mt,F as ya,G as _a,H as Q,I as wa,Wc as ba,Zb as xa,b as ae,ca as va,l as sa,q as Vn,r as Jn,s as ua,t as pa,u as fa,v as Kn,w as Nt,x as tt}from"./chunks/chunk-SDXCJZKB.js";import"./chunks/chunk-ZL6J6JYT.js";import"./chunks/chunk-X5D5YUHR.js";import"./chunks/chunk-4QA5O64H.js";import"./chunks/chunk-L2ZSSMYY.js";import"./chunks/chunk-GOEQXVOI.js";import{k as ea}from"./chunks/chunk-7V65VACG.js";import{d as Ca}from"./chunks/chunk-3HKPVOAN.js";import"./chunks/chunk-6H36ZHMI.js";import"./chunks/chunk-Q6K7HWZ7.js";import"./chunks/chunk-OGVSGXQX.js";import"./chunks/chunk-AA52P34H.js";import{Ka as ma,a as ia,b as ra,d as aa,ma as Pt,na as Lt,oa as Wn,pa as et,qa as R,ra as da,sa as Bn,wa as B}from"./chunks/chunk-C6WM6ZN4.js";import{B as Kr,C as Yr,D as Gn,E as Xr,a as Br,o as qn,q as Vr,v as Hn,x as Jr}from"./chunks/chunk-QDV7S2QS.js";import"./chunks/chunk-AHV3CSQG.js";import"./chunks/chunk-PZA7QECY.js";import{Ac as Dn,Bc as Mr,Cc as Ie,Fc as Fr,Jc as Dr,K as ji,Xb as In,bc as Er,ec as Ar,fc as Rr,hc as Or,id as Ze,lc as Tr,ld as jr,mb as Et,mc as Ir,nb as Sr,nc as $n,pc as $r,qc as ue,rc as Pn,rd as Ur,sc as Ln,tc as Nn,uc as Mn,vc as At,wc as Fn,wd as jn,xc as Pr,xd as qr,yc as Lr,yd as Hr,zc as Nr}from"./chunks/chunk-CBUC4X7Q.js";import{l as St,o as xr,p as br,t as Te,u as U,v as kr}from"./chunks/chunk-OXC5KBIQ.js";import"./chunks/chunk-3AZOATC2.js";import{Be as Z,Dg as mr,Ed as Wi,Eg as Ye,Fd as Bi,Gg as Xe,Hd as Vi,Hg as ur,Ib as Ct,Id as Ji,Jd as Ki,Kd as Yi,Ke as tr,Ld as Xi,Le as ie,Md as Zi,Mf as ar,Nf as sr,Pe as Rn,Q as Re,Qe as x,Qg as pr,R as Ve,Rg as fr,Sg as gr,T as Je,Tg as hr,Ug as re,Vg as yr,Wg as On,X as Ke,Xg as de,Yg as _r,Zg as xt,ag as cr,ah as Oe,ba as wn,bh as me,eh as wr,fh as bt,ga as vt,gd as xn,hd as bn,id as Gi,ja as vn,jd as zi,ke as Qi,kf as nr,ld as kn,lf as or,md as Sn,mf as ir,nd as En,nf as rr,oe as er,og as lr,oh as Tn,pd as An,ph as kt,qg as dr,qh as vr,r as Be,rh as Cr,xb as qi,yb as Hi}from"./chunks/chunk-NRQCBUYD.js";import{d as fn,g as le,i as Li,j as _t,m as gn,n as Ni,o as P,q as Mi,r as X}from"./chunks/chunk-GSLOAEY2.js";import"./chunks/chunk-WSEIEDEK.js";import{E as Gr,G as zr,H as Tt,I as Wr,K as pe,p as Rt,r as Qe,s as Ot,tb as It,ub as Un,vb as M}from"./chunks/chunk-A5ZEMOVR.js";import{G as Di,H as wt,I as J,Z as Ui,h as j,i as Ii,j as V,k as T,m as K,n as pn,o as q,p as $i,r as Fi,v as hn,x as _,y as yn,z as _n}from"./chunks/chunk-I4SPJQQI.js";import{a as Pi,da as Cn}from"./chunks/chunk-TE6FBDHP.js";import{A as g,B as yt,C as $,E as Y}from"./chunks/chunk-K672XXGQ.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as al}from"node:async_hooks";var $e=new al;function Na(e){let t=$e.getStore();return t===void 0?e:t!==null}function ge(e,t=`warning:${e}`){let n=$e.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):x(t)}function nt(e){let t=$e.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([a,s])=>s!==`warning:${a}`).map(([a,s])=>({code:a,message:s})),i=Reflect.get(e,"warning_details"),r={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),r}function Zn(e){if(!$e.getStore()?.size)return e;let{token_accounting:t,...n}=nt(JSON.parse(e));return JSON.stringify(t===void 0?n:Z(n,o=>`${JSON.stringify(o,null,2)}
|
|
2
|
+
`),null,2)}async function Ma(e,t){if(!e){await $e.run(null,t);return}let n=new Map;await $e.run(n,async()=>{await t(),n.size>0&&ie(`${JSON.stringify(nt({type:"warning"}))}
|
|
3
|
+
`)})}import{AsyncLocalStorage as sl}from"node:async_hooks";var Qn=new sl,Fa=new WeakMap;function cl(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:Re(e),outputArgs:t}}var Da=new WeakMap;function ll(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function eo(e,t){return t.some(n=>n.path!==e.path||n.args.length!==e.args.length||n.args.some((o,i)=>o!==e.args[i]))}async function to(e){if(e.expectHash===void 0)return;let t=qn(e.expectHash),n=e.commandPath.trim().toLowerCase();if(Gn(n,e.commandOptions),e.rewritten===!0)throw Hn();let o=Qn.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await Vr(e.pmRoot,t,ll(e.command,e.commandArgs));ir(o,e.pmRoot,i),Da.set(o,n),e.globalOptions!==void 0&&Fa.set(o,cl(e.globalOptions))}function no(e,t,n){let o=Qn.getStore(),i=o===void 0?void 0:Da.get(o);if(i!==void 0){if(eo(e,[t]))throw Hn();Gn(i,n)}}function ja(e,t){if(t!==void 0)throw qn(t),Xr(e)}function dl(e){for(let t of rr(e).unchecked)ge(Yr(t))}async function ml(e,t){return e.pmRoot===void 0?t:Jr(t,e.pmRoot,Fa.get(e))}async function Ua(e){let t=nr();try{await e(n=>Qn.run(t,()=>or(t,n)))}catch(n){throw await ml(t,n)}dl(t)}import{Command as vi,CommanderError as Ac}from"commander";function W(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function he(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return W(t)}function ee(e){let t=new Set,n=[];for(let o of e){let i=he(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}var oo=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Ft=new Set(["--full","--brief","--compact"]);function ul(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function Pe(e,t=A([...e])){let n=M(t),o=new Set([...ia,...ra,...aa].flatMap(s=>s.keys.map(c=>`--${c.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`)}`))),i=new Map([...pe,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,s.flag]))),r=new Map([...pe,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,ul(s,o)])));for(let s of oo)r.set(s,!0);for(let s of Ft)r.set(s,!1);let a=new Map;for(let s=0;s<e.length;s+=1){let c=e[s];if(c==="--")break;if(!c.startsWith("-"))continue;let d=c.split("=")[0];if(!r.has(d)&&!c.includes("="))return;let l=r.get(d)===!0&&!c.includes("=");a.set(s,{flag:i.get(d)??d,consumesValue:l}),l&&(s+=1)}return a}function pl(e){let t=Pe(e);return t===void 0?void 0:new Map([...t].map(([n,{flag:o}])=>[n,o]))}function qa(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),oo.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function fl(e,t){let n=t.find(i=>Ft.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Ft.has(i));return o.length===1?o[0]:n}function Ha(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let r=pl(e);if(!r)return i;let a;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let c=[...r].find(([d,l])=>l==="--fields")?.[0]??-1;if(c<0)return i;a=qa(e,r,new Set(["--fields"])),a.splice(c,0,"--fields",o[s+1])}else{let s=fl(r,o);if(s===void 0||![...r.values()].includes(s))return i;let c=new Set([...oo,...Ft].filter(d=>d!==s));a=qa(e,r,c)}return{...n,suggested_retry:_(a),suggested_retry_args:a}}var gl=3;function Dt(e){let t=S([...e]);if(t===void 0)return;let n=[];for(let o of F(e.slice(t))){if(o.startsWith("-")||n.length===gl)break;n.push(o)}for(let o=n.length;o>1;o-=1){let i=n.slice(0,o).join(" ");if(It(i))return i}return e[t]}var Ga=new Set(Ji);function hl(e){return e.includes("@")&&e.includes(":")}function yl(e){let t=ae(e??"",M(e));return new Set(t.filter(n=>n.takes_value).flatMap(n=>[n.flag,...n.aliases??[]]))}function za(e,t,n,o=[],i=()=>!1){if(t!==Vi)return n;let r=n===void 0?void 0:{...n,suggested_retry:void 0,suggested_retry_args:void 0},a=Dt(e),s=Pe(e,a);if(s===void 0||o===null||e.some(hl)||i())return r;let c=_l(e,s,yl(a));if(c===void 0||c.size===0)return r;let d=[...o,...e.filter((l,m)=>!c.has(m))];return{...n,suggested_retry:_(d),suggested_retry_args:d}}function _l(e,t,n){let o=new Set;for(let[r,{flag:a,consumesValue:s}]of t){if(!Ga.has(a))continue;let c=e[r-1];if(c!==void 0&&!c.includes("=")&&n.has(c)||s&&e[r+1]?.startsWith("-")===!0)return;o.add(r),s&&o.add(r+1)}return e.some((r,a)=>!o.has(a)&&Ga.has(r.split("=",1)[0]))?void 0:o}var wl=new Set(["normalized_args","suggested_retry_args","provided_fields","parsed_positionals","normalizedInvocationArgs","providedOptionFlags","suggestedRetryArgs"]),vl=new Set(["code","original_code","type","recovery_mode","option_scope","diagnostic_class"]),Wa=`URL credentials in this invocation were replaced with ${yn}; restore them before replaying any command shown here.`;function Cl(e){return`URL credentials in this invocation were replaced with ${yn}. Those in ${e} caused this refusal, so do not restore them: give ${e} a value without URL credentials, and restore any other redacted credentials before replaying.`}function ye(e){return e.map(_n)}function xl(e,t){return e==="producer"||t==="details"?"producer":e==="schema"&&t==="recovery"?"schema":"typed"}function bl(e,t,n){let o=J(e);o!==e&&(n.changed=!0);let i=o;for(let r=2;Object.hasOwn(t,i);r+=1)i=`${o} (${r})`;return i}function kl(e,t,n){let o=J(n?_n(e):e);return o!==e&&(t.changed=!0),o}function Sl(e,t,n){return e!=="schema"?!1:t==="urlCredentialsRejected"||vl.has(t)&&typeof n=="string"}function io(e,t,n,o){if(typeof e=="string"&&t.ownSteps.has(e))return e;if(typeof e=="string")return kl(e,t,n);if(typeof e!="object"||e===null)return e;let i=t.copies.get(e);if(i!==void 0)return i;if(Array.isArray(e)){let a=[];t.copies.set(e,a);for(let s of e)a.push(io(s,t,n,o));return a}let r={};t.copies.set(e,r);for(let[a,s]of Object.entries(e)){if(Sl(o,a,s)){r[a]=s;continue}let c=o==="producer"?bl(a,r,t):a;r[c]=io(s,t,n||wl.has(a),xl(o,a))}return r}function jt(e){let t=e.urlCredentialsRejected,n=t===void 0?Wa:Cl(t.source),o=new Set([Wa,n]),i={copies:new Map,changed:!1,ownSteps:o},r=io(e,i,!1,"schema");if(!i.changed&&!wt())return e;r.recovery&&(r.recovery={...r.recovery,suggested_retry:void 0,suggested_retry_args:void 0});let a=(r.nextSteps??[]).filter(s=>!o.has(s));return r.nextSteps=[n,...a],r}var El="project_schema_field_requires_declared_flag";function Al(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function Ba(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==El||n===void 0||i===void 0)return o;let r=Al(e).filter(({assignment:l})=>l.split("=",1)[0].trim()===n&&l.includes("="));if(r.length!==1)return o;let[a]=r,s=a.assignment.trim(),c=s.slice(s.indexOf("=")+1),d=[...e.slice(0,a.index),i,c,...e.slice(a.index+a.width)];return{...o,suggested_retry:_(d),suggested_retry_args:d}}var ro=sa;function Rl(e,t,n,o,i){let r=[],a=e.indexOf(n,t);if(a<0||e.slice(t,a).some(s=>s.startsWith("-")))return r;for(let s=a+1;s<e.length;s+=1){let c=e[s];if(c==="--")break;c===`${o}=${i}`?r.push({index:s,width:1}):c===o&&e[s+1]===i&&(r.push({index:s,width:2}),s+=1)}return r}function Va(e,t,n,o,i=[]){let r=o?.suggested_flags?.[0];if(t!==ro||n===void 0||r===void 0||o.suggested_retry_args===void 0)return o;let a={...o,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||i===null)return a;let c=o.suggested_retry_args,d=Rl(e,s,c[0],n,r);if(d.length!==1)return a;let{index:l,width:m}=d[0],u=[...e.slice(0,l),r,...e.slice(l+m)];if(!Ol(u,l,n,r,c))return a;let p=[...i,...u];return{...o,suggested_retry:_(p),suggested_retry_args:p}}function Ol(e,t,n,o,i){let r=i.lastIndexOf(o);return r<0||i.slice(r).some((a,s)=>e[t+s]!==a)?!1:!e.some((a,s)=>s!==t&&(a===n||a.startsWith(`${n}=`)))}var ao="close_validation_missing_fields";function Tl(e,t,n,o){let i=e.slice(t+1);if(!i.includes("--"))return[...e,...o];if(!i.some(r=>n.has(r.split("=",1)[0])))return[...e.slice(0,t+1),...o,...i]}function Il(e,t){let n=e.slice(0,e.length-2*t),o=n.length;for(;o>0&&n[o-1].startsWith("--expect-hash=");)o-=1;return n.slice(o)}function Ja(e,t,n,o=[]){let i=n?.missing;if(t!==ao||i===void 0||i.length===0)return n;let r=n.suggested_retry_args;if(r===void 0)return n;let a={...n,suggested_retry:void 0,suggested_retry_args:void 0},s=S([...e]);if(s===void 0||o===null)return a;let c=M(e[s].trim().toLowerCase()),d=i.map(f=>c.find(y=>y.flag===f||y.aliases?.includes(f)===!0));if(d.some(f=>f===void 0))return a;let l=new Set(d.flatMap(f=>[f.flag,...f.aliases??[]])),m=Il(r,i.length),u=Tl(e,s,l,[...i.flatMap(f=>[f,"<value>"]),...m]);if(u===void 0)return a;let p=[...o,...u];return{...n,suggested_retry:_(p),suggested_retry_args:p}}async function Ka(e,t){await qr(e,{ok:t.ok,error:t.error,result:me(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function Ya(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Qi({pmRoot:e.pmRoot,result:me()})}catch(o){t=o}let n=await U(e.pmRoot);if(await er({pmRoot:e.pmRoot,author:Ct(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}var Xa=new WeakMap;function Ut(e,t){Xa.set(e,t)}function _e(e){return Xa.get(e)}function Za(e){return e.length>0?[e[0]]:[]}function $l(e){let t=["","Intent:",` ${e.why}`],n=Za(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
|
|
4
|
+
`)}function Pl(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
|
|
5
|
+
`)}function Qa(e,t){return t==="detailed"?Pl(e):$l(e)}function H(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Ll={cal:"calendar",ctx:"context"};function Nl(e,t){return e.commands.find(n=>n.name()===t)??null}function Ml(e,t){let n=e;for(let o of t){let i=Nl(n,o);if(!i)return null;n=i}return n}function so(e,t,n,o){let i=Ml(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",Qa(n,o))}function co(e){return e.includes("--explain")?"detailed":"compact"}function se(e){return e.includes("--all")||e.includes("--explain")}var we={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package catalog --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","pm package list shows the packages installed in the selected scope; catalog shows what pm bundles.","External npm package discovery still belongs to npm search."]},"package inventory":{why:"Lists the packages installed in the selected scope (alias: pm package list) from manifests and saved state, without activating extension code, with the newer version the last pm package manage check observed.",examples:["pm package list","pm package list --global --fields name,version,update","pm package list pm-changelog"],tips:["update is null until pm package manage has checked the registry for that installed version; manage is the live check.","Use pm package catalog for the bundled first-party packages and pm package describe to map what a package registers."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension inventory":{why:"Compatibility view of the installed package inventory (alias: pm extension list); it reads manifests and saved state without activating extension code.",examples:["pm package list","pm package list --global --fields name,version,update"],tips:["Prefer pm package list in new user-facing workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --takeover-stale --message "Take over an abandoned claim"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","The refusal reports the holder's claim age, last activity and idle hours. --takeover-stale takes over only a claim idle for at least mutation_guard.stale_in_progress_hours (default 72), refuses an active one with stale_claim_takeover_refused, and records the previous holder and idle time in the claim's history entry.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of j){let n=we[e];n&&(we[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Le={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},es=K.filter(e=>e.lifecycle==="deprecated");for(let e of es){let t=we[e.alias];we[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Le,...Object.values(we)])e.examples=e.examples.map(t=>{for(let n of es){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Fl(e){let t=H(e??"");return t?Ll[t]??t:""}function lo(e){let t=Fl(e);return t?we[t]??Le:Le}function ts(e,t){let n=lo(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Za(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Dl(){let e=K.filter(({lifecycle:n})=>n==="permanent"),t=K.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${$i(n)})`)].join(`
|
|
6
|
+
`)}function jl(e,t,n,o){let i=new Set(ya);e.configureHelp({visibleCommands(a){let s=t.visibleCommands(a);return n?s.filter(c=>(_e(c)??Q(c.name()))!=="internal"):a!==e?s:s.filter(c=>o.has(c))},visibleOptions(a){let s=t.visibleOptions(a);return a!==e||n?s:s.filter(c=>i.has(c.flags))}});let r=e.options.filter(a=>a.long==="--output-cursor");for(let a of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(a.name())&&a.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...r]})}function Ul(e,t,n,o){let i=new Set(wa("core")),r=e.createHelp();r.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${r.formatHelp(e,r)}${o}
|
|
7
|
+
`,s=t.visibleCommands(e);for(let c of s)_e(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)_e(c)==="core"&&(n.add(c),_a(a()).within_budget||n.delete(c))}function ns(e,t=process.argv.slice(2)){let n=e.createHelp(),o=se(t),i=new Set;jl(e,n,o,i);let r=co(t),a=Qa(Le,r);e.addHelpText("after",a),o&&e.addHelpText("after",Dl()),Ul(e,n,i,a);for(let[l,m]of Object.entries(we))so(e,l,m,r);let s=H(L(t).commandPathTokens.join(" ")),c=Qe(s);if(c){so(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,Ot(c.accepted_flags)]},r);return}let d=Rt.filter(({parent:l})=>l===s);d.length>0&&so(e,s,{why:`Dispatches one declared positional action: ${d.map(({action:l})=>l).join("|")}.`,examples:d.map(({example:l})=>l),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},r)}function mo(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of j){if(t&&!j.some(d=>d.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(d=>d.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let d of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(l=>l.name()===d)??s.command(d).description(`Discover ${d} operations.`);let c=i[i.length-1];if(s.commands.some(d=>d.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(c),Ut(a,Q(o)),s.enablePositionalOptions(),s.addCommand(a)}}function Ht(e){let{title:t,...n}=e;Sn(n.why)&&delete n.why,kn(n.required)&&delete n.required;let o=En(n.examples);o.length>0?n.examples=o:delete n.examples;let i=An(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var ql=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Hl(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!ql.has(e.code)}function ds(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:ds(e.code)}}var Ne={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},os={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},is={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},qt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Gl={guide:Ne,shell:Ne,completion:Ne,"completion-statuses":Ne,"completion-tags":Ne,"completion-types":Ne,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:os,cal:os,reindex:is,"search-advanced":is,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":qt,"dedupe-audit":qt,"dedupe-merge":qt,normalize:qt};function zl(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Gl[t]}function fo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Wl(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function Bl(e){if(!Array.isArray(e))return;let t=e.map(n=>({source:typeof n?.source=="string"?n.source.trim():"",command:typeof n?.command=="string"?n.command.trim():"",reason:typeof n?.reason=="string"?n.reason.trim():""})).filter(n=>n.source.length>0&&n.command.length>0&&n.reason.length>0);return t.length>0?t:void 0}function uo(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function ms(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function te(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"||t==="allowed_values"){let i=ms(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=n.map(r=>({role:typeof r?.role=="string"?r.role.trim():"",value:typeof r?.value=="string"?r.value.trim():""})).filter(r=>r.role.length>0&&r.value.length>0);i.length>0&&(e.parsed_positionals=i);return}let o=Wl(n);o&&(e[t]=o)}function Vl(e,t){if(!Or(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:r,basis:a,reason:s}}var us=["retry_after_ms","waited_ms","owner_handoffs"];function Jl(e,t){for(let n of us)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function Kl(e,t){for(let n of us){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function xe(e){if(!e||typeof e!="object")return;let t={};Vl(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),uo(t,"attempted_command",e.attempted_command),te(t,"normalized_args",e.normalized_args),te(t,"parsed_positionals",e.parsed_positionals),te(t,"provided_fields",e.provided_fields),te(t,"missing",e.missing),te(t,"missing_required_fields",e.missing_required_fields),te(t,"suggested_flags",e.suggested_flags),te(t,"allowed_values",e.allowed_values),te(t,"candidate_commands",e.candidate_commands),typeof e.candidate_commands_total=="number"&&Number.isSafeInteger(e.candidate_commands_total)&&e.candidate_commands_total>=0&&(t.candidate_commands_total=e.candidate_commands_total),e.candidate_commands_truncated===!0&&(t.candidate_commands_truncated=!0),(e.option_scope==="declared_on_path"||e.option_scope==="declared_elsewhere"||e.option_scope==="declared_nowhere")&&(t.option_scope=e.option_scope),uo(t,"suggested_retry",e.suggested_retry),te(t,"suggested_retry_args",e.suggested_retry_args),Kl(t,e);let n=Bl(e.fallback_candidates);return n&&(t.fallback_candidates=n),uo(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function po(e,t,n){n&&e.push(` ${t}: ${n}`)}function ve(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}var go=8,Yl=12,ps=Number.POSITIVE_INFINITY;function Xl(e,t,n){let o=t!==void 0&&n===ps&&t.length<=Yl?t.length:Math.min(n,go),i=t?.slice(0,o).map(r=>/^[\p{L}\p{N}._:/@=-]+$/u.test(r)?r:JSON.stringify(r));ve(e,"allowed_values",i,", "),t&&t.length>o&&e.push(` allowed_values_omitted: ${t.length-o} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function Zl(e,t){let n=xe(e);if(!n)return[];let o=["Recovery bundle:"];if(n.token_budget){let i=n.token_budget;o.push(` requested_token_budget: ${i.requested_tokens}`,` feasible_token_budget: ${i.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${i.minimum_feasible_tokens??"not established"}`)}if(po(o,"suggested_retry",n.suggested_retry),po(o,"attempted_command",n.attempted_command),ve(o,"normalized_args",n.attempted_command?void 0:n.normalized_args," "),n.parsed_positionals&&n.parsed_positionals.length>0){o.push(" parsed_positionals:");for(let i of n.parsed_positionals)o.push(` - ${i.role}: ${i.value}`)}if(ve(o,"provided_fields",n.provided_fields,", "),ve(o,"missing",n.missing,", "),ve(o,"missing_required_fields",n.missing_required_fields,", "),ve(o,"suggested_flags",n.suggested_flags,", "),Xl(o,n.allowed_values,t),ve(o,"candidate_commands",n.candidate_commands,", "),typeof n.candidate_commands_total=="number"&&o.push(` candidate_commands_total: ${String(n.candidate_commands_total)}`),n.candidate_commands_truncated===!0&&o.push(" candidate_commands_truncated: true"),n.option_scope!==void 0&&o.push(` option_scope: ${n.option_scope}`),Jl(o,n),po(o,"next_best_command",n.next_best_command),n.fallback_candidates&&n.fallback_candidates.length>0){o.push(" fallback_candidates:");for(let i of n.fallback_candidates)o.push(` - ${i.source}: ${i.command} (${i.reason})`)}return o}var rs=120;function Ql(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>rs?`${n.slice(0,rs).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})${nd(e.claimActivity)}`}function ed(e){return e.history_unreadable===!0?"history unreadable":e.unproven_activity!==void 0?`idleness unproven: ${e.unproven_activity}`:e.last_activity_at===null?"no valid activity time":"idle time not measurable"}function td(e){return e.state!==void 0?e.state:e.history_unreadable===!0||e.unproven_activity!==void 0||!Number.isFinite(e.idle_hours)?"unknown":e.stale_policy.stale?"stale":"active"}function nd(e){if(e===void 0)return"";let t=`${e.stale_policy.setting}=${e.stale_policy.threshold_hours}`,n=td(e);if(n==="unknown"){let o=Number.isFinite(e.idle_hours)?`, last recorded activity ${e.idle_hours}h ago`:"";return`; activity unknown under ${t} (${ed(e)}${o})`}return`; idle ${e.idle_hours}h, ${n} under ${t}`}function od(e,t){let n=[`Error: ${e.title}`];e.code==="close_validation_missing_fields"&&e.recovery?.suggested_retry&&n.push(`Run: ${e.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!t||!kn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...fo("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=Ql(e);return o!==void 0&&n.push("",o),n}function id(e,t){let n=[];e.why&&!(t&&Sn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?En(e.examples):e.examples??[];o.length>0&&n.push("",...fo("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...fo("Verification errors:",i)),n.push(...rd(e)),n}function rd(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
|
|
8
|
+
`).map(i=>` ${i}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function ad(e,t={}){return fs(e,t,ps)}function fs(e,t,n){let o=t.lean===!0,i=[...od(e,o),...id(e,o||e.code==="close_validation_missing_fields")],r=e.code==="close_validation_missing_fields"&&e.recovery?{...e.recovery,suggested_retry:void 0}:e.recovery,a=Zl(o?An(r):r,n);return a.length>0&&(i.push(""),i.push(...a)),i.join(`
|
|
9
|
+
`)}var sd="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",cd=400,as=320;function ld(e){let t=xe(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=cd&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.allowed_values&&(n.allowed_values=t.allowed_values),t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function ss(e,t){if(e.code!=="close_validation_missing_fields"||!e.recovery?.suggested_retry||t.recovery?.suggested_retry)return t.nextSteps;let n=t.recovery?.next_best_command?["Run recovery.next_best_command with real evidence, then repeat the original close."]:[...t.nextSteps,"Retrieve the complete retry from SDK error.context.recovery.suggested_retry; replace placeholders with real evidence before executing it."];return Me(n,e.partialLegalDomainNotice)}function dd(e,t={}){let n=ad(e,t),o=bn("error").default_max_estimated_tokens_by_format.text,i=u=>xn(Buffer.byteLength(u,"utf8"))<=o;if(i(n))return n;let r={...e,why:void 0},a=Me(e.nextSteps?.slice(0,1)??[],e.partialLegalDomainNotice),s={...r,details:void 0,examples:e.examples?.slice(0,1),nextSteps:a,verificationErrors:e.verificationErrors?.slice(0,3)},c={...s,recovery:ld(e.recovery)};c.nextSteps=ss(e,c);let d=Array.from(e.happened),l={...c,examples:void 0,happened:d.length>as?`${d.slice(0,as).join("")}...`:e.happened},m={code:e.code,type:e.type,title:e.title,happened:l.happened,required:e.required,nextSteps:Me([],e.partialLegalDomainNotice)};m.nextSteps=ss(e,m);for(let[u,p]of[[r,go],[s,go],[c,3],[l,3],...e.partialLegalDomainNotice?[[m,3],[{...m,happened:e.title},3],[{...m,required:"Correct the producer metadata before relying on a complete legal domain."},3]]:[]]){let f=`${fs(u,t,p)}
|
|
10
10
|
|
|
11
|
-
${Xl}`;if(i(f))return f}return n}function td(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",t.claimActivity!==void 0&&(e.claim_activity=t.claimActivity),e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function cs(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),td(e,t),$l(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function nd(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return j([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i))}function od(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(r=>r===n||r.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function id(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=j(e.recovery?.normalized_args??[]),o=V(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=nd(e,i),a=od(e,i,r);return{surface:r??e.recovery?.missing?.[0]??Vn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function rd(e,t){let n=cs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:id(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function fo(e,t){let n=Ft(e),o=n.recovery,r=!!o?.suggested_retry||!!o?.suggested_retry_args?.length||!!o?.allowed_values?.length||!!o?.candidate_commands?.length||!!n.nextSteps?.length?"recovery_bundle":"error";return Ui(ad(rd(n,t),r),{diagnosticClass:r})}function ad(e,t){if(e.details===void 0)return e;let n=Cn(t).default_max_estimated_tokens_by_format.json;if(vn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:br.max_bytes}}}function go(e){return cs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function qt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function sd(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function ve(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function ts(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function cd(e){return Vn(e?.normalized_args)}function ld(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function dd(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let r of o){let a=n.findIndex(s=>s===r);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=i,_(s)}}}function md(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function ud(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function pd(e,t,n,o){if(t==="close_validation_missing_fields")return"Close is missing required evidence";let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?md(o):void 0)??e.title}function fd(e){let t=Sr(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var gd=400;function hd(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=gd&&t.push(o)}return t}function yd(e){let t=e?.allowed_values;if(t===void 0||Array.isArray(t)&&t.every(a=>typeof a=="string"))return;let n=Array.isArray(t)?t.filter(a=>typeof a=="string"):[],o=hd(n),i=o.join(", ")||"none shown",r=n.length>o.length?` (${n.length-o.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${i}${r}. Correct the producer metadata before relying on a complete domain.`}function _d(e,t,n){let o=Ce(t),i=o&&e?Ce({...e,...o}):o??e;if(!n)return i;let{allowed_values:r,...a}=i??{};return Object.keys(a).length>0?a:void 0}function ne(e,t,n){if(!n)return e;let o=qt(t),i=tt(n.code,e.code),r=tt(n.type,os(i)),a=ve(n.examples)??e.examples,s=ve(n.nextSteps)??e.nextSteps,c=yd(n.recovery),l=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,d=ve(n.verification_errors)??e.verificationErrors,m=_d(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:pd(e,i,n,o),happened:o.length>0?o:e.happened,required:tt(n.required,e.required),why:tt(n.why,e.why),examples:a,nextSteps:l,urlCredentialsRejected:n.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:c,verificationErrors:d,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:ud(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,claimActivity:n.claim_activity,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:m,...fd(n)}}function wd(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=$i(process.cwd(),i);return ne(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function vd(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ne(b({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Cd(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ne(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function xd(e,t,n){if(!t.includes("is locked"))return null;let o=is(n?.recovery?.normalized_args),i=o?_(o):void 0,r=ne(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(r.recovery={...r.recovery,suggested_retry:i,suggested_retry_args:[...o]}),r}function bd(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",c=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ne(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function kd(e,t,n){return t.startsWith("No update flags provided")?ne(b({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Sd(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=tt(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function Ed(e,t,n){if(!Sd(t,n))return null;let o=Ce(n?.recovery),i=cd(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??ld(t),s=Ce({...o,allowed_values:o?.allowed_values??a}),c=dd(o,a),l=c?[c,r]:[r,"pm contracts --command <command> --flags-only --json"],d=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ne(b({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:l,nextSteps:d,recovery:s}),e,n)}function ho(e,t){let n=qt(e),o=wd(e,n,t)??vd(e,n,t)??Cd(e,n,t)??xd(e,n,t)??bd(e,n,t)??kd(e,n,t)??Ed(e,n,t);return o||ne(b({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Ad(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function Rd(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Od(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function yo(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function q(e,t={}){let n=yo(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Od(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Ce({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Le(e,t){return!t||e.includes(t)?e:[...e,t]}var Td=new Set(["--add","--add-json","--remove"]),Id=new Set(["command","cmd","path"]);function $d(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Td.has(o))return o}}function Pd(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!Id.has(r))return;let a=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;a.push(d)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return _(c)}}function Ld(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Rd(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,c=yo(o?.providedOptionFlags),l=[r],d=Ad(t,r,n),m=s?Le(d,s):d,u=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],p=s?Le(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?Le(p,`Already provided options: ${c.join(", ")}`):p;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:q(o,{missing:l})})}function Nd(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:q(n,{missing:[i]})})}function Md(e,t,n){return b({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:q(t,{suggested_flags:n})})}var Fd={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Dd(e){let t=ve(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function jd(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:Ud(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,ds(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var ls=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function Ud(e,t){if(t===void 0||!ls.includes(e.split("=",1)[0]))return;let n=wa(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${va(n)}.`}function qd(e,t,n){let o=Ca(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...ls,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function ds(e){return/\s/u.test(e)}function Hd(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...j(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function Gd(e,t,n){if(ds(t))return Hd(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=qd(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(xa(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let r=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(r<0||i.includes("--")||!i[r]?.includes("=")&&r!==i.length-1&&i[r+1]?.startsWith("-")!==!0)return{};let a=j(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function zd(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=yo(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=Gd(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return Md(r,n,a);let l=Dd(i),d=jd(r,t,a,l,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${D(t)?.canonical??t} --help`:"pm --help --all"].filter(u=>typeof u=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Fd[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:q(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:l.otherCommands,candidate_commands_total:l.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:l.optionScope})})}function Wd(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:ts([t.installCommand,...n]),nextSteps:ts([r,...a]),recovery:q(i)})}function Bd(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=ve(t?.unknownCommandExamples),r=ve(t?.unknownCommandNextSteps),a=Ll(o),s=i??["pm --help"],c=r??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!d||!l.has(d))?Wd(o,a,s,c,t):b({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:q(t)})}function Vd(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ve(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${D(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:q(e,{allowed_values:o,suggested_retry:i})})}function Jd(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=$d(o);if(!i)return null;let r=Pd(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...r?[r]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:q(n,r?{suggested_retry:r}:{})})}var Kd=new Set(["comments","docs","files","learnings","notes","test"]);function Yd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Mi(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,r=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return b({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${r}.`,examples:[i??r],recovery:q(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function Xd(e){return[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)}function Zd(e){let t=_t()?void 0:e.retryArgs,n=process.platform==="win32"||Li(process.platform)==="cmd",o=t?.some(i=>Xd(i)||n&&fn(i,process.platform,"cmd")!==i)===!0;return{retryArgs:t,argvOnly:o,retry:t&&!o?_(t):void 0}}function Qd(e,t,n){let o=n?.linkedResourceValueList;if(!/too many arguments/i.test(e)||o===void 0)return null;let i=o.flags[0],r=o.flags.join(", "),{retryArgs:a,argvOnly:s,retry:c}=Zd(o),l=t!=="test"&&o.flags.includes("--add"),d=`pm ${t} ${o.itemId} ${i} <value> ${i} <value>`,m=o.extraValues.length;return b({code:"linked_resource_value_list",title:`Repeat ${i} once per value${l?" (or use --add-glob)":""}`,happened:`${m} more value${m===1?"":"s"} followed the value of ${r}. pm ${t} takes one value per occurrence, so they were read as extra positional arguments and nothing was changed.`,required:c?`Retry with one ${i} per value: ${c}`:s?`Retry with one ${i} per value by replaying recovery.suggested_retry_args (shown with --json): a value holds a control character, or needs cmd.exe quoting that a copied command cannot carry exactly.`:o.readsStdin?`Write one ${i} per value and pipe the same input again, because the command reads stdin: ${d}`:`Write one ${i} per value, and quote a value that contains spaces or commas so the shell passes it as one argument: ${d}`,why:`Each occurrence of a repeatable flag takes exactly one value, so an item id written after the flag (pm ${t} ${i} <value> <id>) stays unambiguous.`,examples:[c??d,...l?[`pm ${t} ${o.itemId} --add-glob "<pattern>"`]:[],`pm ${t} --help`],recovery:q(n,{suggested_retry:c,suggested_retry_args:a})})}function em(e,t,n){if(!/too many arguments/i.test(e)||!Kd.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>l===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:q(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var tm=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ns=new Set(["context","ctx"]);function nm(e,t,n){if(!/too many arguments/i.test(e)||!ns.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>ns.has(l)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(r)){if(l){l=!1;continue}let m=d.split("=")[0];if(tm.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:q(n,{suggested_retry:c})})}function _o(e,t,n,o){let i=qt(e),r=Ld(i,t,n,o)??Nd(i,t,o)??zd(i,t,o)??Bd(i,o)??Vd(o)??em(i,t,o)??Qd(i,t,o)??Jd(i,t,o)??Yd(i,t,o)??nm(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:q(o)})}function ms(e,t,n={}){let o=Ft(ho(e,t));return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
12
|
-
`):
|
|
11
|
+
${sd}`;if(i(f))return f}return n}function md(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",t.claimActivity!==void 0&&(e.claim_activity=t.claimActivity),e.item_id=t.itemId),t.currentRevision!==void 0&&(e.expected_revision=t.expectedRevision??null,e.current_revision=t.currentRevision,t.itemId!==void 0&&(e.item_id=t.itemId))}function gs(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),md(e,t),Hl(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function ud(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return F([r]).length>0&&!["--help","--no-changed-fields","--version"].includes(r)&&t.some(a=>a===r||a.startsWith(`${r}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(i=>i[0]).find(i=>n(i))}function pd(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(r=>r===n||r.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function fd(e){let t=F([...e]),n=V(t);return n?[n.alias,...t.slice(n.canonical_argv.length)]:t}function gd(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(r=>r.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(r=>r.missing_fields))],exit_code:t};let n=fd(e.recovery?.normalized_args??[]),o=ud(e,n),i=pd(e,n,o);return{surface:o??e.recovery?.missing?.[0]??Yn(n)??"command",...i!==void 0?{rejected_value:i}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function hd(e,t){let n=gs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:gd(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function ho(e,t){let n=jt(e),o=n.recovery,r=!!o?.suggested_retry||!!o?.suggested_retry_args?.length||!!o?.allowed_values?.length||!!o?.candidate_commands?.length||!!n.nextSteps?.length?"recovery_bundle":"error";return Gi(yd(hd(n,t),r),{diagnosticClass:r})}function yd(e,t){if(e.details===void 0)return e;let n=bn(t).default_max_estimated_tokens_by_format.json;if(xn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:Er.max_bytes}}}function yo(e){return gs({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Gt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function _d(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function Ce(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function cs(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function wd(e){return Yn(e?.normalized_args)}function vd(e){let t=e.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);return t?t[1].split(/[|,]/).map(n=>n.trim()).filter(n=>/^[A-Za-z0-9_.-]+$/.test(n)):[]}function Cd(e){if(e===void 0)return;let t=e.trim().replace(/\s+/gu," ").replace(/^ctx(?= |$)/u,"context").replace(/^(package|packages|extension) scaffold$/u,"$1 init"),n=T(t);return Ii.find(o=>o.alias===n)?.canonical??t}function xd(e,t,n){let o=n?.normalized_args;if(t===void 0||!Array.isArray(o))return{commandPath:void 0,refusedFlag:void 0};let i=Dt(o),r=hs(t,n);if(r!==void 0)return{commandPath:i,refusedFlag:r};let a=new Set(M(i).filter(l=>l.reservation_scope!=="inherited").flatMap(l=>[l.flag,...l.aliases??[]])),s=new Set([...Pe(o,i)?.keys()??[]].map(l=>o[l].split("=",1)[0])),c=e.replace(/"[^"]*"|'[^']*'/gu," "),d=new Set([...c.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(l=>l[0]).filter(l=>a.has(l)&&s.has(l)));return{commandPath:i,refusedFlag:d.size===1?[...d][0]:void 0}}function bd(e,t,n,o){let i=ae(e??"",M(e)).some(s=>(s.flag===t||s.aliases?.includes(t)===!0)&&s.takes_value),r=n[o+1],a=n[o+2];return i&&r!==void 0&&!r.startsWith("-")&&(a===void 0||a.startsWith("-"))}function kd(e,t,n){let o=Pe(e,t.commandPath);if(o===void 0)return;let i=[...o].filter(([m,u])=>e[m].split("=",1)[0]===n||u.flag===n);if(i.length!==1)return;let[r,a]=i[0],s=e[r].includes("=");if(!s&&!a.consumesValue&&!bd(t.commandPath,n,e,r))return;let c=e[r].split("=",1)[0],d=s?e[r].slice(c.length+1):e[r+1],l=[...o.values()].some(m=>m.flag==="--json");return d===void 0?void 0:{index:r,attached:s,spelling:c,value:d,jsonRequested:l}}function Sd(e,t){return!(e.value.startsWith("-")&&!e.attached)&&!/[=,:\n]/u.test(e.value)&&!t.includes(e.value)}function Ed(e,t,n){let o=e?.normalized_args,i=n.refusedFlag;if(!Array.isArray(o)||i===void 0||t.length===0)return;let r=kd(o,n,i);if(r===void 0||!Sd(r,t))return;let a=r.jsonRequested&&t.includes("json")?"json":t[0],s=[...o];return r.attached?s[r.index]=`${r.spelling}=${a}`:s[r.index+1]=a,_(s)}function Ad(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function ot(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function hs(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function Rd(e,t,n,o){if(t==="close_validation_missing_fields")return"Close is missing required evidence";let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?Ad(o):void 0)??e.title}function Od(e){let t=Rr(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var Td=400;function Id(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=Td&&t.push(o)}return t}function $d(e){let t=e?.allowed_values;if(t===void 0||Array.isArray(t)&&t.every(a=>typeof a=="string"))return;let n=Array.isArray(t)?t.filter(a=>typeof a=="string"):[],o=Id(n),i=o.join(", ")||"none shown",r=n.length>o.length?` (${n.length-o.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${i}${r}. Correct the producer metadata before relying on a complete domain.`}function Pd(e,t,n){let o=xe(t),i=o&&e?xe({...e,...o}):o??e;if(!n)return i;let{allowed_values:r,...a}=i??{};return Object.keys(a).length>0?a:void 0}function ne(e,t,n){if(!n)return e;let o=Gt(t),i=ot(n.code,e.code),r=ot(n.type,ds(i)),a=Ce(n.examples)??e.examples,s=Ce(n.nextSteps)??e.nextSteps,c=$d(n.recovery),d=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,l=Ce(n.verification_errors)??e.verificationErrors,m=Pd(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:Rd(e,i,n,o),happened:o.length>0?o:e.happened,required:ot(n.required,e.required),why:ot(n.why,e.why),examples:a,nextSteps:d,urlCredentialsRejected:n.url_credentials_rejected??e.urlCredentialsRejected,partialLegalDomainNotice:c,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:hs(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,claimActivity:n.claim_activity,expectedRevision:n.expected_revision,currentRevision:n.current_revision,availableDependencies:n.available_dependencies,recovery:m,...Od(n)}}function Ld(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],r=Ni(process.cwd(),i);return ne(b(r?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${r}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${r} <command>`,`PM_PATH=${r} pm <command>`],nextSteps:[`Re-run with "--pm-path ${r}" or export PM_PATH=${r}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Nd(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],r=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),a=r?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return ne(b({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:r?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Md(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ne(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Fd(e,t,n){if(!t.includes("is locked"))return null;let o=ms(n?.recovery?.normalized_args),i=o?_(o):void 0,r=ne(b({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(r.recovery={...r.recovery,suggested_retry:i,suggested_retry_args:[...o]}),r}function Dd(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let r=!!i,a=r?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",c=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return ne(b({code:"missing_required_option",title:r?"Missing required options":`Missing required option ${s}`,happened:t,required:r?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function jd(e,t,n){return t.startsWith("No update flags provided")?ne(b({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Ud(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=ot(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function qd(e,t,n){if(!Ud(t,n))return null;let o=xe(n?.recovery),i=wd(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??vd(t),s=xe({...o,allowed_values:o?.allowed_values??a}),c=xd(t,n,o),d=Ed(o,a,c),l=Cd(c.commandPath??i),m=d?[d,r]:[r,l===void 0?"pm contracts --command <command> --flags-only --json":_(["contracts","--command",l,"--flags-only","--json"])],u=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${r}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return ne(b({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:m,nextSteps:u,recovery:s}),e,n)}function _o(e,t){let n=Gt(e),o=Ld(e,n,t)??Nd(e,n,t)??Md(e,n,t)??Fd(e,n,t)??Dd(e,n,t)??jd(e,n,t)??qd(e,n,t);return o||ne(b({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Hd(e,t,n){return e==="create"&&t.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${n.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:e==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${e??"<command>"} --help`]}function Gd(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function zd(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function wo(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function G(e,t={}){let n=wo(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:zd(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return xe({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Me(e,t){return!t||e.includes(t)?e:[...e,t]}var Wd=new Set(["--add","--add-json","--remove"]),Bd=new Set(["command","cmd","path"]);function Vd(e){if(Array.isArray(e))for(let t of e){if(!t.startsWith("--"))continue;let n=t.indexOf("="),o=n>=0?t.slice(0,n):t;if(Wd.has(o))return o}}function Jd(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let r=e[o+1];if(typeof r!="string"||!Bd.has(r))return;let a=[];for(let d=o+2;d<e.length;d+=1){let l=e[d];if(l.startsWith("--")&&l.length>2)break;a.push(l)}if(a.length<2)return;let s=`${r}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return _(c)}}function Kd(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Gd(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,c=wo(o?.providedOptionFlags),d=[r],l=Hd(t,r,n),m=s?Me(l,s):l,u=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],p=s?Me(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?Me(p,`Already provided options: ${c.join(", ")}`):p;return b({code:"missing_required_option",title:`Missing required option ${r}`,happened:`Commander rejected the command because ${r} was not provided.`,required:`Pass ${r} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:G(o,{missing:d})})}function Yd(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return b({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:G(n,{missing:[i]})})}function Xd(e,t,n){return b({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:G(t,{suggested_flags:n})})}var Zd={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function Qd(e){let t=Ce(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function em(e,t,n,o,i){let r=o.otherCommands.slice(0,3),a=o.candidateTotal-r.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:tm(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,_s(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(c=>typeof c=="string")}var ys=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function tm(e,t){if(t===void 0||!ys.includes(e.split("=",1)[0]))return;let n=Ea(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${Aa(n)}.`}function nm(e,t,n){let o=Ra(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...ys,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function _s(e){return/\s/u.test(e)}function om(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...F(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function im(e,t,n){if(_s(t))return om(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=nm(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(Oa(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let r=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(r<0||i.includes("--")||!i[r]?.includes("=")&&r!==i.length-1&&i[r+1]?.startsWith("-")!==!0)return{};let a=F(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function rm(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=wo(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=im(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return Xd(r,n,a);let d=Qd(i),l=em(r,t,a,d,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(r.split("=",1)[0])&&l.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${q(t)?.canonical??t} --help`:"pm --help --all"].filter(u=>typeof u=="string");return b({code:"unknown_option",title:`Unknown option ${r}`,happened:`Commander does not recognize option ${r} for this command path.`,required:Zd[d.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:l,recovery:G(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:c,candidate_commands:d.otherCommands,candidate_commands_total:d.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:d.optionScope})})}function am(e,t,n,o,i){let r=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:cs([t.installCommand,...n]),nextSteps:cs([r,...a]),recovery:G(i)})}function sm(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=Ce(t?.unknownCommandExamples),r=Ce(t?.unknownCommandNextSteps),a=zl(o),s=i??["pm --help"],c=r??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),l=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!l||!d.has(l))?am(o,a,s,c,t):b({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:G(t)})}function cm(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=Ce(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return b({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${q(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:G(e,{allowed_values:o,suggested_retry:i})})}function lm(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Vd(o);if(!i)return null;let r=Jd(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...r?[r]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...r?[`Replay with the value re-joined into one argument: ${r}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:G(n,r?{suggested_retry:r}:{})})}var dm=new Set(["comments","docs","files","learnings","notes","test"]);function mm(e,t,n){if(!/too many arguments/i.test(e))return null;let o=ji(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,r=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return b({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${r}.`,examples:[i??r],recovery:G(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function um(e){return[...e].some(t=>t.charCodeAt(0)<32||t.charCodeAt(0)===127)}function pm(e){let t=wt()?void 0:e.retryArgs,n=process.platform==="win32"||Fi(process.platform)==="cmd",o=t?.some(i=>um(i)||n&&hn(i,process.platform,"cmd")!==i)===!0;return{retryArgs:t,argvOnly:o,retry:t&&!o?_(t):void 0}}function fm(e,t,n){let o=n?.linkedResourceValueList;if(!/too many arguments/i.test(e)||o===void 0)return null;let i=o.flags[0],r=o.flags.join(", "),{retryArgs:a,argvOnly:s,retry:c}=pm(o),d=t!=="test"&&o.flags.includes("--add"),l=`pm ${t} ${o.itemId} ${i} <value> ${i} <value>`,m=o.extraValues.length;return b({code:"linked_resource_value_list",title:`Repeat ${i} once per value${d?" (or use --add-glob)":""}`,happened:`${m} more value${m===1?"":"s"} followed the value of ${r}. pm ${t} takes one value per occurrence, so they were read as extra positional arguments and nothing was changed.`,required:c?`Retry with one ${i} per value: ${c}`:s?`Retry with one ${i} per value by replaying recovery.suggested_retry_args (shown with --json): a value holds a control character, or needs cmd.exe quoting that a copied command cannot carry exactly.`:o.readsStdin?`Write one ${i} per value and pipe the same input again, because the command reads stdin: ${l}`:`Write one ${i} per value, and quote a value that contains spaces or commas so the shell passes it as one argument: ${l}`,why:`Each occurrence of a repeatable flag takes exactly one value, so an item id written after the flag (pm ${t} ${i} <value> <id>) stays unambiguous.`,examples:[c??l,...d?[`pm ${t} ${o.itemId} --add-glob "<pattern>"`]:[],`pm ${t} --help`],recovery:G(n,{suggested_retry:c,suggested_retry_args:a})})}function gm(e,t,n){if(!/too many arguments/i.test(e)||!dm.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(d=>d===t),r=o[i+1],a=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(r?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:G(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var hm=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]),ls=new Set(["context","ctx"]);function ym(e,t,n){if(!/too many arguments/i.test(e)||!ls.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(d=>ls.has(d)),r=i===-1?1:i+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let l of o.slice(r)){if(d){d=!1;continue}let m=l.split("=")[0];if(hm.has(m)){d=!l.includes("=");continue}if(!l.startsWith("-")){s=l;break}}}if(!s)return null;let c=`pm get ${s}`;return b({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:G(n,{suggested_retry:c})})}function vo(e,t,n,o){let i=Gt(e),r=Kd(i,t,n,o)??Yd(i,t,o)??rm(i,t,o)??sm(i,o)??cm(o)??gm(i,t,o)??fm(i,t,o)??lm(i,t,o)??mm(i,t,o)??ym(i,t,o);return r||b({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:G(o)})}function ws(e,t,n={}){let o=jt(_o(e,t));return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
12
|
+
`):vs(o,n)}function vs(e,t){let n=jt(e),o=a=>zi(dd(n,a),n.required).output,i=o(t);if(t.lean!==!0)return i;let r=o({});return Buffer.byteLength(r,"utf8")<Buffer.byteLength(i,"utf8")?r:i}function Cs(e,t){return yo(_o(e,t))}function Co(e,t,n){return ho(_o(e,n),t)}function xs(e,t,n,o,i={}){let r=vo(e,t,n,o);return vs(r,i)}function xo(e,t,n,o){return yo(vo(e,t,n,o))}function zt(e,t,n,o,i){return ho(vo(e,t,n,i),o)}function bs(e,t){let n=ks(e);return ho(n,t)}function ks(e){let t=Gt(e);return _d(t)?b({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):b({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Ss(e){return yo(ks(e))}var it=Pi.join("|"),_m={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"},wm={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}},Es=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function vm(e,t){let n=wm[e];if(!n)return[];let o=W(t);for(let[i,r]of Object.entries(n))if(W(i)===o)return r;return[]}function bo(e,t,n){if(n.length===0)return e;let o=n.map(s=>({...s,name:J(s.name),error:J(s.error),...s.recovery_commands?{recovery_commands:s.recovery_commands.map(J)}:{}}));if(t){let s=o.find(m=>m.declared_command_match===!0),{token_accounting:c,...d}=JSON.parse(e),l={...d,...s?{extension_command_failure:{code:"extension_command_activation_failed",extension:s.name,layer:s.layer,error:s.error,recovery_commands:s.recovery_commands??[]}}:{},failed_extensions:o};return JSON.stringify(c===void 0?l:Z(l,m=>`${JSON.stringify(m,null,2)}
|
|
13
13
|
`),null,2)}let i=o.map(s=>`- ${s.layer}:${s.name}: ${s.error}`).join(`
|
|
14
14
|
`),r=o.find(s=>s.declared_command_match===!0);if(!r)return`${e}
|
|
15
15
|
Extension activation failures:
|
|
@@ -21,24 +21,24 @@ ${a}`:""}
|
|
|
21
21
|
|
|
22
22
|
${e}
|
|
23
23
|
Extension activation failures:
|
|
24
|
-
${i}`}function
|
|
25
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function
|
|
26
|
-
`):c,null,2)}async function
|
|
24
|
+
${i}`}function ko(e){return L(e).commandPathTokens[0]??A(e)??"<command>"}function Is(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=H(R(i)),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r),o.push(...i.commands)}for(let i of t.keys()){let r=H(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function As(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let r=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of i){let c=vn(s,o,r);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function Rs(e){return W(e).slice(2).replace(/-/g,"")}function So(e){return _(e)}function Cm(e){let t=q(e)?.canonical??pn[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=_m[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Os(e){let t=Ca(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function xm(e,t){let n=Os(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let r=new Set,a=i.source;if(a)for(let c of[a.name,a.package]){let d=Os(c??"");d.length>0&&r.add(d)}if(r.size===0)continue;[...r].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(i.command)}return[...new Set(o)].sort((i,r)=>i.localeCompare(r))}function be(e,t){let n=new Set,o=t??M(e);for(let i of o){i.flag.startsWith("--")&&n.add(W(i.flag));for(let r of i.aliases??[])r.startsWith("--")&&n.add(W(r))}return[...n].sort((i,r)=>i.localeCompare(r))}function bm(e,t){if(!e.startsWith("--"))return[];let n=Rs(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=Rs(r);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){i.push({flag:r,rank:0,distance:a.length-n.length});continue}let s=vn(n,a,o);s===null||s<=0||i.push({flag:r,rank:1,distance:s})}return i.sort((r,a)=>r.rank!==a.rank?r.rank-a.rank:r.distance!==a.distance?r.distance-a.distance:r.flag.localeCompare(a.flag)).map(r=>r.flag).slice(0,3)}var Wt,km=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function Sm(){if(Wt)return Wt;let e=new Map;for(let n of Be)if(!km.has(n))for(let o of be(n)){let i=e.get(o)??[];i.push(n),e.set(o,i)}let t=new Map;for(let n of Un())for(let o of be(n))e.has(o)||t.set(o,[...t.get(o)??[],n]);for(let[n,o]of t)e.set(n,o);return Wt=e,Wt}function Em(e,t){if(!e.startsWith("--"))return[];let n=Sm().get(W(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(be(o)),r=n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:be(a).filter(s=>i.has(s)).length})).sort((a,s)=>a.sharedFlagCount!==s.sharedFlagCount?s.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(s.command)).map(({command:a})=>a);return[...new Set([...Am(e,o),...r].map(a=>q(a)?.canonical??a))]}function Am(e,t){if(t===void 0)return[];let n=T(t).split(" ",1)[0].replace(/^packages$/u,"package"),o=W(e);return Un().filter(i=>i.split(" ",1)[0]===n&&be(i).includes(o))}function Rm(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let r=i.indexOf("="),a=r>=0?i.slice(0,r):i;if(W(a)!==W(t))continue;let s=[...e];return s[o]=r>=0?`${n}${i.slice(r)}`:n,s}}function Om(e){let t=new Set(e.commandPaths),n=r=>Math.min(As(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?As(r,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(r,a)=>{if(!Number.isFinite(a)||!t.has(r))return;let s=o.get(r);(s===void 0||a<s)&&o.set(r,a)};for(let r of e.commandPaths)i(r,n(r));for(let[r,a]of Object.entries(pn))r!=="read"&&i(a,n(r));return[...o.entries()].sort(([r,a],[s,c])=>a!==c?a-c:r.localeCompare(s)).map(([r])=>r)}function Tm(e){let t=q(e.normalizedUnknown),n=Pa(e.commandPaths,e.primaryToken),o=Om(e),i=xm(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return Xn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(r=>!e.normalizedUnknown.includes(" ")||r!==e.normalizedUnknown)}function Im(e,t,n){let[o,...i]=e.split(" ");if(n.includes(o)||q(o)!==void 0)return;let r=o.endsWith("s")?o.slice(0,-1):`${o}s`,a=q(r),s=a&&n.includes(a.canonical)?a.canonical:n.includes(r)?r:void 0;if(s===void 0)return;let c=s,d=["package","packages","extension"].includes(s)?[$t(Pm(t))??""].filter(l=>l.length>0):Lm(t,i.length);for(let l of[...i,...d]){let m=`${c} ${l}`,u=q(m);if(!n.includes(m)&&!(u!==void 0&&!u.hidden&&n.includes(u.canonical)))break;c=m}return c}function $m(e,t,n,o){let i=Im(e,t,n),r=$a(e,n)??i,a=o.length>0||i!==void 0,s=a?[]:Xn(Nm(n),n),c=[...new Set([...r?[r]:[],...o.length>0?o:s])].slice(0,3);return{misnestedPath:r,hasConcreteCandidates:a,suggestedPaths:c}}function Pm(e){let t=S([...e]);return t===void 0?[]:e.slice(t+1)}function Lm(e,t){let n=[],o=S([...e]);for(;o!==void 0;){let i=S(e.slice(o+1));o=i===void 0?void 0:o+1+i,o!==void 0&&n.push(e[o])}return n.slice(t)}function Nm(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Mm(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Fm(e,t,n){let o=S([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let r=S(t.slice(o+1));o=r===void 0?void 0:o+1+r}return e}function Ts(e,t){if(!e)return;let n=N([...t]);return[...Re(n),...e.split(" "),"--help"]}function Eo(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let r=Is(t,n),a=Fm(i[1],o,r),s=H(a);if(s.length===0||r.length===0)return;let c=Sa(s,r);if(c){let O=Ts("update",o),E=O.slice(0,-2);return{suggestedRetryCommand:_(O),suggestedRetryArgs:O,unknownCommandExamples:[_(O),...c.examples.map(k=>_([...E,...k]))],unknownCommandNextSteps:c.nextSteps}}let d=Cm(s);if(d&&!r.includes(d.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[d.installCommand,`pm ${d.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${d.packageAlias}" package. Install it with: ${d.installCommand}. Command after installation: pm ${d.canonicalPath}.`],suggestedRetryCommand:d.installCommand};let l=s.split(" ")[0],m=Tm({commandPaths:r,normalizedUnknown:s,primaryToken:l,extensionDescriptors:n}),{misnestedPath:u,hasConcreteCandidates:p,suggestedPaths:f}=$m(s,o,r,m),y=Ts(u,o),h=Mm(f,p),C=p?`Did you mean: ${f.join(", ")}?`:null;return{...y?{suggestedRetryCommand:_(y),suggestedRetryArgs:y}:{},unknownCommandExamples:y?[_(y),...h.slice(1)]:h,unknownCommandNextSteps:[...C?[C]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...C?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function Dm(e){return Array.from(new Set(e))}function jm(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
25
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Um(e){let t=e.length;for(;t>0;){let n=e[t-1];if(n!==","&&n!==":"&&n!==";")break;t-=1}return e.slice(0,t)}function qm(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(r=>r.trim().toLowerCase()===n))}function Fe(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=qm(n,i);if(!r){let a=n.registeredArguments;return a.length>0&&(n.commands.length===0||a[0]?.required===!0)&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=r}return!0}async function Hm(e,t,n,o){try{let i=P(process.cwd(),e.path);if(!await Y(X(i)))return{allowedTypes:it};let r=await U(i),a=e.noExtensions?void 0:de(),s=le(r,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),l=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&l!==void 0&&!l.startsWith("-"))try{c=(await Et(i,l,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):it,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:it}}}function Gm(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Dm([...vm(t,n[1]),...bm(n[1],be(t))]).filter(a=>Ta(n[1],a)):void 0,i=n?Em(n[1],t):[],r=n!==null&&be(t).includes(W(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:r?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function zm(e,t,n){if(!t||!n||n.length===0)return;let o=Rm(e,t[1],n[0]);return o?So(o):void 0}function Wm(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Um(jm(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=A(t);if(i)return Ia(t,i,[o])}function Bm(e,t){if(!/too many arguments/i.test(e))return;let n=S(t),o=V(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,r=t[i+1]?.trim().toLowerCase(),a=t[i+2]?.trim().toLowerCase();if(!r||!a)return;let s=`${r}-${a}`;if(!Es.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[...Es],suggestedRetryCommand:So(c)}}function Vm(e,t,n,o){let i=S(t),r=V(t.slice(i))?.alias??A(t);if(!/unknown option /i.test(e)||r===void 0)return r;let a=q(r)?.canonical??r;return Be.some(s=>s===r)||Is(n,o).includes(a)?r:void 0}async function rt(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",s=fe([...i]).argv,c=ye(s),d=N(s),l=Vm(a,c,t,n),m=So(c),u=ee(c),p=await Hm(d,a,c,l),f=p.allowedTypes,y=Eo(a,t,n,c),h=Gm(a,l),C=Bm(a,c),O=C?.suggestedRetryCommand??zm(c,h.match,h.suggestions)??Wm(a,c);return{message:a,commandName:l,allowedTypes:f,attemptedCommand:m,normalizedInvocationArgs:[...c],providedOptionFlags:u,unknownOptionSuggestions:h.suggestions,unknownOptionOtherCommands:h.otherCommands.length>0?h.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:h.otherCommands.length>0?h.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:h.otherCommands.length>12||void 0,unknownOptionScope:h.scope,suggestedRetryCommand:O,verifiedCollectionItemId:p.verifiedCollectionItemId,linkedResourceValueList:await Jm(a,l,t,c),...C,...y,...o}}async function Jm(e,t,n,o){if(!/too many arguments/i.test(e))return;let{resolveUsageValueListRecovery:i}=await import("./chunks/linked-resource-value-list-ZBIY4H23.js");return i(t,n,o)}async function Ao(e,t,n,o={},i=process.argv.slice(2)){let r=await rt(e,t,n,o,i),{message:a,commandName:s,allowedTypes:c,...d}=r,l=N(r.normalizedInvocationArgs).lean,m=xs(a,s,c,d,{lean:l}),u=await Cr("help_format",{message:m,command:s,allowed_types:c});return u.handled&&typeof u.result=="string"?u.result:m}async function Ro(e,t,n,o=!1,i={},r=process.argv.slice(2)){let a=await rt(e,t,n,i,r),s=zt(a.message,a.commandName,a.allowedTypes,g.USAGE,a),c=o?Ht(s):s,d=N(a.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(d?Z(c,l=>`${JSON.stringify(l,null,2)}
|
|
26
|
+
`):c,null,2)}async function $s(e,t,n,o){if(n)return null;let i=e.some(a=>a==="--for"||a.startsWith("--for=")),r=A(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as Km}from"commander";function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ls(e,t){let n=new Map;for(let o of e){let i=v(o.command);for(let r of t){if(r.layer!==o.layer||r.name!==o.name)continue;let a=v(r.command),s=a.split(" "),c=s.at(-1),d=s.slice(1).join(" "),l=d?`${s[0]}-${c} ${d}`:`${s[0]}-${c}`;if(c&&i===l){n.set(i,a);break}}}return n}function Oo(e,t,n,o){if(!t||!n)return;let i,r=0;for(let[s,c]of e.entries()){if(c!==t)continue;let d=e.slice(s);for(let[l,m]of o.entries()){let u=l.split(" ");u.length>r&&u.every((p,f)=>d[f]===p)&&(i=m,r=u.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return Ym(a).takesValue}function Vt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Bt(e){return typeof e=="boolean"?e:void 0}function Ym(e){let t=vt(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function Xm(e){let t=Je(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=To(e);return n?`${n} ${Io(e)}`:null}function Ns(e){let t=[...new Set(e.map(Xm).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
27
27
|
Extension-provided flags:
|
|
28
28
|
${t.join(`
|
|
29
|
-
`)}`}function
|
|
30
|
-
`)}function
|
|
29
|
+
`)}`}function Ms(e){let t=new Map;for(let i of e){let r=v(i.target_command);if(r.length===0)continue;let a=t.get(r)??[];a.push(...i.flags),t.set(r,a)}let n=[...t.entries()].sort(([i],[r])=>i.localeCompare(r)),o=new Map;for(let[i,r]of n){let a=Ns(r);a&&o.set(i,a)}return o}function Fs(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Ps(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function Zm(e){return Array.isArray(e)?e.map(t=>{let n=typeof t.name=="string"?t.name.trim():"";if(n.length===0)return null;let o={name:n,required:t.required===!0,variadic:t.variadic===!0};return typeof t.description=="string"&&t.description.trim().length>0&&(o.description=t.description.trim()),o}).filter(t=>t!==null):[]}function Qm(e){let t=new Map;for(let n of e){let o=v(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,r=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Fs(o,n.action),description:i,intent:r,examples:Ps(n.examples),failure_hints:Ps(n.failure_hints),arguments:Zm(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",...n.read_output===void 0?{}:{read_output_declared:!0},source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function eu(e){let t=new Map;for(let n of e){let o=v(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function tu(e,t,n){let o=new Set;for(let i of e){let r=v(i);r.length>0&&o.add(r)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function nu(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Ds(e,t,n,o=new Map){let i=Qm(t),r=eu(n),a=tu(e,i,r),s=new Map,c=[...a].sort((d,l)=>d.localeCompare(l));for(let d of c){let l=nu(d,i,o)??i.get(d),m=r.get(d)??(l?r.get(l.command):void 0)??[];if(l){s.set(d,{...l,command:d,flags:m});continue}s.set(d,{command:d,action:Fs(d,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function ou(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function js(e,t){for(let n of t.arguments)e.argument(ou(n),n.description??"Extension argument.")}function iu(e){if(Bt(e.visible)===!1)return null;let n=Je(e.long),o=Vt(e.short),i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=n&&n.startsWith("--")&&n.length>2?n:null,a=[i,r].filter(s=>s!==null);return a.length>0?a:null}function To(e){let t=iu(e);if(!t)return null;let{value_name:n,value_arity:o}=vt(e),r=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${r}`}function ru(e){return To(e)}function Io(e){let t=Vt(e.description)??"Extension-provided option.",n=[];Bt(e.required)===!0&&n.push("required"),Bt(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function Us(e,t){let n=Je(t.long),o=Vt(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function $o(e,t){for(let n of t){if(Us(e,n))continue;let o=ru(n);if(!o)continue;let i=Io(n),r=new Km(o,i);if(r.negate=!1,n.list!==!0){e.addOption(r);continue}e.addOption(r.argParser((a,s=[])=>[...Array.isArray(s)?s:[s],a??!0]))}}function Po(e,t){return Ns(t.filter(n=>!Us(e,n)))}function au(e){let t=To(e);if(!t)return null;let n=Je(e.long),o=Vt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=vt(e),s=Bt(e.required)===!0;return{flags:t,long:i,short:r,description:Io(e),takes_value:a.value_arity!=="none",value_required:a.value_arity==="required",value_name:a.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{},owner:"extension",...su(Nt(e))}}function su(e){return e===null?{}:{sdk_option:e}}function qs(e,t){return ae(e,t).map(n=>({flags:`${n.short===void 0?"":`${n.short}, `}${n.takes_value?`${n.flag} <${n.value_name}>`:n.flag}`,long:n.flag,short:n.short??null,description:n.description,takes_value:n.takes_value,value_required:n.value_required,value_name:n.takes_value?n.value_name:null,variadic:!1,required:!1,aliases:[...n.aliases??[]],alias_for:null,owner:"host"}))}function Lo(e){return qs(e.command,Tt({readOutput:e.read_output_declared===!0}))}function Hs(e,t){let n=t.flatMap(o=>[o.long,o.short,...o.aliases].filter(i=>typeof i=="string"));return qs(e,Wr(e,n,{expectHashAdmissible:Br(T(e))}))}function No(e){return["","Inherited host flags (delivered through context.global):",` ${Lo(e).map(n=>n.flags).join(" | ")}`,` Run pm contracts --command ${e.command} --flags-only --json for each flag's owner and sdk_option key.`].join(`
|
|
30
|
+
`)}function Gs(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=au(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function zs(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{},...o.owner===void 0?{}:{owner:o.owner},...o.sdk_option===void 0?{}:{sdk_option:o.sdk_option}}:o)}return[...n.values()]}function Ws(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
|
|
31
31
|
Extension command metadata:
|
|
32
32
|
${t.join(`
|
|
33
|
-
`)}`}function Lo(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function rt(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Lo(o).includes(n))??null}function oe(e,t){let n=e;for(let o of t){let i=rt(n,o);if(!i)return null;n=i}return n}var Bt=new WeakSet;function at(e){return Bt.has(e)}function Ms(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&M.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=rt(n,i);if(r){n=r;continue}let a=n.command(i);Bt.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Bm(e,t){let n=t.join(" "),o=M.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=rt(i,a);if(!s)return null;r.push(a);let c=s.commands.length>0||M.some(l=>l.canonical.startsWith(`${r.join(" ")} `));if(!Bt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function Vm(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Bm(e,r),s=oe(e,r),c=M.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bt.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let l=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${l}`}function Fs(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=Vm(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Ds(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import Me from"node:path";async function No(e,t={},n=[]){let o={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:pn,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let c=(r.effective??[]).find(u=>u.layer===s.layer&&u.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(U).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),d=n.map(U),m=l.some(u=>d.some(p=>p===u||p.startsWith(`${u} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function js(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await No(t,n,o),r={readSettings:F,loadExtensions:Je,activateExtensions:Ke,resolveImplicitPmRoot:pn,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(Me.resolve(a)===Me.resolve(t))return i;let[s,c]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[l,d]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(p=>p.activation?.commands??[])),u=[...new Set(d.loaded.flatMap(p=>p.activation?.commands??[]))].filter(p=>!m.has(p)).sort((p,f)=>p.localeCompare(f));if(u.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Me.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${Me.resolve(a)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${u.length} workspace command path(s): ${u.slice(0,8).join(", ")}${u.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${Me.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${Me.resolve(t)} install <package> --project".`})}catch{}return i}var Us={core:0,standard:1,full:2,internal:3};function qs(e,t,n=!0){let o=t.get(G(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,c)=>Us[c.tier]<Us[s]?c.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function Hs(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(G(o)!==o||!ze.some(i=>i===o)&&!Tt(o)&&!Xe(o)&&!Ne(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=oe(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function Jm(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Gs(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function Km(e){let t=new Map;for(let n of e){let o=n,i=Gs(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function Ym(e){return _(e)}function Xm(e){let t=e.options??[],n=Km(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=Gs(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),d=a.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,u=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),p=r.includes("<"),f=p||r.includes("["),y={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:f,value_required:p,value_name:Jm(r),variadic:i.variadic===!0,required:u,aliases:l,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function Zm(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Qm(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function eu(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(ye(r)??Q(r.name()))!=="internal").map(r=>{let a=U(A(r)),s=a,c=ye(r),l=qs(a,t,c!==void 0),d=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Lo(r),description:r.description().trim(),tier:l?.tier??c??Q(s),family:l?.family??Nt(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function tu(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function nu(e,t,n,o,i){let r=e!==void 0&&so(e)===$e,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ja(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:tu(n,a,o),intentSource:s}}function ou(e,t){return e===void 0?null:t?.tier??Q(e)}function iu(e,t){return e===void 0?null:t?.family??Nt(e)}function ru(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Hs(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function au(e,t,n,o,i=new Map,r=!1){if(!e){let s=Qm(t),c=eu(t,i,r),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...At.filter(({parent:d,action:m})=>d===n&&!l.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:Q(n.split(" ")[0]),family:Nt(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:l,value_kind:d,polymorphic:m})=>({name:s,required:c,variadic:l,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&a.has(s)||c.some(l=>a.has(l))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:l})=>{let d=l?`${s}...`:s;return c?`<${d}>`:`[${d}]`})].join(" ")}}function su(e,t){return t!==void 0&&at(e)?{inherited_options:$o(t)}:{}}function cu(e,t,n,o,i){let r=ao(n),a=ae(n),s=U(A(t)),c=U(o.join(" ")),l=c.length>s.length?c:s,d=Xe(l),m=d?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(G(u)):void 0,y=u?qs(u,i,ye(t)!==void 0):void 0,{narrative:h,intentSource:C}=nu(u,t.description().trim(),r,f,d!==void 0),R=Zm(Ls(Xm(t),Ps(f))),O=au(d,t,m,R,i,a),k=ru(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:ou(p,y),capability_family:iu(p,y),description:d?.description??t.description(),usage:O.usage,intent:d?.description??h.intent,intent_source:C,examples:d?[d.example]:h.examples,tips:d?[Rt(d.accepted_flags)]:h.tips,arguments:O.arguments,options:O.options,...su(t,f),subcommands:O.subcommands,has_subcommands:O.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function zs(e,t,n,o=t){let i=L(t);if(!i.json)return!1;let r=P(t);if(!r.requested)return!1;let a=Hs(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=he(t),c=`unknown command '${he(r.commandPathTokens).join(" ")}'`,l=ko(c,e,n,s),d=Ht(c,"help",nt,g.USAGE,{...l,attemptedCommand:Ym(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(d,u=>`${JSON.stringify(u,null,2)}
|
|
34
|
-
`):
|
|
35
|
-
`)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=
|
|
36
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
37
|
-
`)}function
|
|
38
|
-
`)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(y=>y==="--create-mode"||y.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],
|
|
39
|
-
`)}function Ws(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let i=rt(e,o);i&&i.addHelpText("after",pu(o,t,n))}function fu(e,t){let n=Ve(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function gu(e){return Ve(e.status)?.toLowerCase()??"pending"}function hu(e){return e.mandatory===!0}function yu(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function Js(e){let t=[];return e.forEach((n,o)=>{if(!hu(n.definition))return;let i=gu(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:fu(n.definition,o),status:i})}),t.sort(yu),t}function Bs(e){return Array.isArray(e)&&e.length>0}var _u=new Set(["create","beads import","todos import"]),wu=new Set(["restore","update","close","delete","append","claim","release"]),vu=new Set(["comments","notes","learnings"]),Cu=new Set(["files","docs","test"]),xu=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function Mo(e,t){let n=t.force===!0;return _u.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:wu.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:vu.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Cu.has(e)?{isMutation:Bs(t.add)||Bs(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function bu(e,t,n){if(Mo(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Nr(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>xu.has(i.trim().toLowerCase())):!1}function Vs(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function ku(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Ve(t[1])||i.push("source"),Ve(n.to)||i.push("--to"),i.length!==0)throw new I(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function Su(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Vs(n.status)!==Vs(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ce(i,le()),s=await St(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await xr(s,{schema:i.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||x(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function Fo(e,t,n,o,i){if(!bu(e,t,n)||(ku(e,t,n),!await Y(X(i))))return;let r=await Re(i);Ra(o.json===!0)||await Su(e,t,n,i,r.settings);let a=Lr({author:vt(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)fe(s)}function Ks(e,t,n){if(n.length===0)return;let o=Mo(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new I(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function Do(e,t,n,o){if(!Mo(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await Y(X(n)))return;let{settings:r,metadata:a,warnings:s}=await Re(n);for(let c of s)fe(c);if(!vr(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(wr(r),await Cr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=ce(r,le());await Mr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function jo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function De(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of jo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,G(i)]))]}function Uo(e,t){let n=v(e);if(n.length===0)return!1;let o=De(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Jt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...N(n.commands),...N(n.command_handlers),...N(n.command_overrides),...N(n.flag_commands),...N(n.parser_overrides),...Ys(n.preflight_ownership),...Ys(n.renderer_ownership)]:[]}function N(e){return e??[]}function Ys(e){return N(e).flatMap(t=>t.commands)}function st(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Xs=new Set(["hooks","parser","preflight","renderers"]),Zs=new Set(["commands","schema","services","importers"]),Eu=new Set(["reindex","search","search-advanced"]),Au=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function qo(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Eu.has(n??t)}function Ho(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function Kt(e){return v(e.commandPath??"")==="create"&&Ho(e,Au)}function Go(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Vt(e,t){return e.some(n=>Uo(n,t))||Kt(t)&&Go(e)}function zo(e){return[N(e.hooks).length,(e.preflight_overrides??0)-N(e.preflight_ownership).length,N(e.item_types).length,N(e.item_fields).length,N(e.relationship_kinds).length,N(e.service_overrides).length,N(e.assurance_providers).length,N(e.renderer_overrides).length-N(e.renderer_ownership).length].some(n=>n>0)}function Wo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Vt(n,t);let o=Jt(e);if(Vt(o,t)||st(e).has("search")&&qo(t.commandPath))return!0;if(e.contributions)return zo(e.contributions)}function Yt(e,t){let n=Wo(e,t);if(n!==void 0)return n;let o=st(e);return!!(Fe(o,Xs)||Fe(o,Zs))}function ct(e,t){return e.effective.length===0?!1:lt(t)!=="all"?e.effective.some(o=>Yt(o,t)):e.effective.some(o=>{let i=st(o);return Jt(o).length>0||Fe(i,Xs)||Fe(i,Zs)||i.has("search")})}function lt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=De(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Kt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Bo(e){return lt(e)==="all"?void 0:t=>Yt(t,e)}function je(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=j(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Vo(e){let t=e.args.map(String);if(v(A(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Xt=Symbol.for("pm.readOutputInvocationProvenance"),Ru=new Map(ue.filter(e=>e.reservation_scope==="root_only").map(e=>[Lt({long:e.flag}),e.flag]));function se(e,t){let n=Reflect.get(e,Xt);n!==void 0&&Reflect.set(t,Xt,n)}function Jo(e,t,n){let o=Gi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(ee(r.slice(2))),s=Hi.find(d=>d.command===o),c=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,Xt);Reflect.set(n,Xt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),se(n,e)}function Ou(e){let t=e.optsWithGlobals(),n=A(e);if(G(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of i.options){let a=r.attributeName(),s=i.getOptionValueSource(a)==="cli";if(s&&!e.options.some(c=>c.long===r.long))throw new I(`Unknown option '${r.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:r.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(a)!=="cli"){let c=i.getOptionValue(a);e.setOptionValueWithSource(a,c,"cli")}a in o?t[a]=o[a]:delete t[a]}return t}function Ko(e,t,n,o){Jo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Ki(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;se(o,e);let s=Ji(t);for(let l of a){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=r.length>0?r.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Pt(e,n)}function Ue(e,t,n=[],o){let r={...Ou(e)};se(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession,delete r.expectHash;let a=aa(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=zn(n),c=z(A(e)).map(u=>({long:u.flag,short:u.short,aliases:u.aliases})),l={...a};for(let u of s)r[u]!==void 0&&(l[u]=r[u]);Wn(l,[...c,...n],A(e),o);let d=la(a,ic(e),n),m=ra(r,n,d,A(e));return se(r,m),m}return r}function tc(e,t,n){let o=zn(t.map(({long:a})=>({long:a}))),i=[...Ru].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new I(`Unknown option '${r}' for extension command '${n}'. ${r} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:r,required:`Remove ${r}, or use it on the root command (pm --help ${r}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function dt(e,t,n){let o=Qe(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=Qe(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function Zt(e){return e.arguments??[]}function Qs(e){let t=Zt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Yo(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}var nc=Symbol("pm.commandOptionTokens"),ec=Symbol("pm.capturesOptionTokens");function oc(e){if(Reflect.get(e,ec)===!0)return;Reflect.set(e,ec,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,nc,[...n]),t(n))}function Tu(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function Iu(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function ic(e){let t=[];for(let o=e;o?.parent;o=o.parent)t.unshift(o);let n=[];for(let o of t){let i=Reflect.get(o,nc);if(i===void 0)continue;let r=Tu(o),a=[];for(let s=o;s;s=s.parent)a.push(s);n.push({tokens:i,optionOf:s=>r.get(s),includesLooseFlags:o===e,negativeNumbersAreValues:!a.some(s=>s.options.some(c=>c.short!==void 0&&/^-\d$/u.test(c.short))),...Iu(o)})}return n}function rc(e,t,n){t.length!==0&&ca(ic(e),t,n)}function Xo(e,t){let n=Zt(e),o=n.filter(c=>c.required).length,r=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new I(`Missing required argument for extension command '${e.command}'. Usage: ${Qs(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new I(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Qs(e)}${s}`,g.USAGE)}}function $u(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Qt(e,t){return{definitions:e,inheritedFlags:Ot({readOutput:t}).map(n=>n.flag)}}function Pu(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map($u);if(o.length===0)return;let{inheritedFlags:i}=Qt([],n);throw new I(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Lu(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Wn(t,n,e.command,Qt(n,o));return}Pu(t,e.command,o)}function Zo(e,t,n,o){e&&(Xo(e,t),Lu(e,n,o))}import{Command as ac}from"commander";var Nu=new Set(["--version","-V"]);function mt(e){let t;try{t=pe(e).argv}catch{return!1}let n=Kr(t),o=S(n);return o===void 0?!1:["package","packages","extension"].includes(n[o])&&["inventory","list"].includes(It(n.slice(o+1))??"")}function sc(e){if(j(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new ac().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of ue)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Mu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Qo=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),cc=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Fu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Du=new Set(["claim","close-task","pause-task","release","start-task","test"]),xe={setup:!0,listQuery:!0,mutation:!0,operation:!0},ju=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function ut(e){return e.some(t=>Nu.has(t))}function Uu(e,t){if(!M.some(o=>o.canonical_argv[0]===t))return;let n=new ac().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Te(t,z(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let r of[o.flag,o.short,...o.aliases??[]])r!==void 0&&n.option(`${r}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return xe;let i=V([t,...o.operands])?.alias;if(M.some(r=>r.alias===i))return{...xe,targetCommandName:i}}catch{return xe}}function ei(e){if(ut(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return xe;let t=E(e);if(!t)return xe;let n=t.trim().toLowerCase(),o=j(e),i=V(o)?.alias;if(M.some(a=>a.alias===i))return{...xe,targetCommandName:i};let r=Uu(o,n==="ctx"?"context":n);return r||(Mu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Qo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:cc.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Fu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:xe)}function ti(e){return e.length===0||P(e).requested||e.includes("--explain")&&E(e)===void 0}function ni(e,t){return mt(t)||ut(t)?!1:ae(t)||P(t).requested?!0:!!E(t)}function oi(e){if(ut(e))return!1;let t=E(e);return t?ju.has(t):!1}function qu(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),r=i?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${i}${l.slice(d)}`:i:l}):e.argv,a=We(r),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ii(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),i=o.length>0?o.join(" "):"the canonical flag",r=cc.has(t)||Du.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=qu({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new I(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:a,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}var Hu=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),Gu=new Set(["parse","preflight","execute","unknown"]),zu=new Set(["usage","validation","conflict","runtime","unknown"]);function be(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function ri(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function en(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function ai(e){if(!e)return;let t=e.trim().toLowerCase();if(Hu.has(t))return t}function si(e){if(!e)return;let t=e.trim().toLowerCase();if(Gu.has(t))return t}function ci(e){if(!e)return;let t=e.trim().toLowerCase();if(zu.has(t))return t}function li(e){let t=be(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(ri(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=en(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>yn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function di(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function mi(){let e=yn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=en(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=pa(o),r=be(e,"error_code","errorCode")??di(i,o),a=ci(be(e,"error_category","errorCategory"))??(i?void 0:ht(r)),s=i?void 0:li(e)??`command_exit_${o}`,c=ai(be(e,"command_resolution","commandResolution"))??Et({ok:i,errorCode:r,errorCategory:a}),l=si(be(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,command_resolution:c,resolution_stage:l}}var ui="PM_CLI_PACKAGE_ROOT",_c=Symbol("pm.deprecatedAliasInvocation"),on=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=on.get(t)??[];n.push(e),on.set(t,n)}for(let e of on.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Wu(){return or(import.meta.url,["../.."])}(typeof process.env[ui]!="string"||process.env[ui]?.trim().length===0)&&(process.env[ui]=Wu());var Se=null,H=null,rn=null;function Bu(e){Se=e}function Vu(e){T=e}var pt=null,ke=null,T=new Map,wi=250,Ju=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Ku=new Set(["1","true","yes","on"]),Yu=Ye(()=>import("./chunks/register-setup-6V6NQB5C.js")),Xu=Ye(()=>import("./chunks/register-list-query-DRA3CWHI.js")),Zu=Ye(()=>import("./chunks/register-mutation-WO74VLEQ.js")),Qu=Ye(()=>import("./chunks/register-operations-CRBKH7WN.js"));function nn(e){return _(e)}function wc(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>ge(o)??o))];return n.length>0?n:void 0}function ep(e,t,n,o){if(n?.suggested_retry||o===io||o===oo||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=ee(t),r=new Set(i.map(m=>ge(m)??m)),a=wc(e),s=t.find(m=>w.commands.some(u=>u.name()===m)),c=s?w.commands.find(m=>m.name()===s):void 0,l=new Set([...w.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(u=>ge(u)).filter(u=>u!==void 0))),d=a?.filter(m=>{let u=ge(m)??m;return r.has(u)?!1:l.has(u)||Ao(t,s,u,T)!==void 0});return d&&d.length>0?d:void 0}function tp(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?ge(i):void 0,a=e.find(u=>w.commands.some(p=>p.name()===u)),s=a?w.commands.find(u=>u.name()===a):void 0,c=r?s?.options.find(u=>u.flags.split(/[ ,|]+/).includes(r)):void 0,l=Ao(e,a,r,T),d=r?c?.isBoolean()===!0||l===!1?[r]:[r,"<value>"]:[],m=r?nn([...e,...d]):t;return m===t?void 0:m}function np(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!==void 0&&(o==="allowed_values"||i!==null)&&(n[o]=i)}return n}function op(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,...np(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function lc(e,t){return{...e,recovery:t}}function ip(e,t){if(t===void 0)return;let n=ja(e,t.code,t.field,Na(e,t.code,t.recovery)),o=rp(e),i=Ua(e,t.code,t.field,n,o),r=Fa(e,t.code,i,o,()=>Hr($(process.cwd(),L(e).path)));return qa(e,t.code,r,o)}var dc=" ";function rp(e){let t=e.map(i=>i===""?dc:/^--(?:pm-)?path=$/u.test(i)?`${i}${dc}`:i),n=L(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Ee({});return n!==void 0&&o.length>0?null:o}function vc(e,t,n){let o=We(t),i=j(o),r=S(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:kr(e);let l=ip(o,e),d=l&&(a==="history-redact"||a==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:nn(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:nn(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return lc(e,d);let m=nn(o),u=ee(o),p=ep(n,o,d,e?.code),f=tp(o,m,p,d),y=op({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:d});return lc(e,y)}async function ft(e){let t=H;H=null,await Ha(t,e);let n=Se;if(Se=null,!n){xt();return}let o=[],i=hr();try{await Ga({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await sr(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:de(),affected:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{xt()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${W(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${W(o)}`)}async function Cc(e,t){await Rr();let n=H,o=Se,i=n?.command??o?.commandName??e,r=n??On(o?.globalOptions??t),a=T.get(v(i))?.source;Nn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??He,extension:a})}function xc(e){return Ku.has((process.env[e]??"").trim().toLowerCase())}function bc(e){return xc("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Ju.has(Math.trunc(e))}async function an(e,t){return bc(e.exit_code)?(await Cc(e.command,t),Pr({...e,source_context:e.source_context??On(t).source_context}),!0):!1}async function kc(e){let t=J(me(e.error)),n=ys(t);e.bootstrapGlobal.json?x(JSON.stringify(et(gs(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Cc(e.attemptedCommand,e.bootstrapGlobal),Mn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,await ln(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to report error: ${me(r)}`)}try{await ft({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to run error hooks: ${me(r)}`)}try{await Oe()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${me(r)}`)}}var ap={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},pi=new Map;function fi(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Sc(e,t){return e.options.some(n=>n.long===t)}function Ec(e,t){return e.options.some(n=>n.short===t)}function gi(e,t,n,o){let i=t.trim();if(!i||!Fi(i))return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Ec(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,Gn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!Sc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,Gn);return}e.option(`${a} <value>`,r)}}async function Ac(e,t){let n=ap[e];if(!n)return[];let o=`${t}:${n}`,i=pi.get(o);if(i)return i;if(!await Y(X(t)))return pi.set(o,[]),[];let r=await F(t),s=(wn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:fi(c.type),value_type:fi(c.type)})));return pi.set(o,s),s}async function Rc(e,t){let n=L(t),o=$(process.cwd(),n.path);if(!await Y(X(o)))return;let i=ke?.key===xi(o)?ke.snapshot:null,r=i===null?await F(o):i.settings,a=wn(r.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=oe(e,c.path.split(" "));if(l)for(let d of a.command_to_fields.get(c.command)??[]){let m=d.description??"";gi(l,d.cli_flag,m,d.repeatable);for(let u of d.cli_aliases)gi(l,u,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function vi(e,t,n,o,i){let r=E(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await F(t),s=ce(a,o);Ws(e,s,n)}catch{}}function hi(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Oc(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ci(e){return e.some(t=>t==="--profile")}function xi(e){return`pm-root:${e}`}function yi(e){for(let t of e)t.startsWith("settings_read_")&&fe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Tc(e,t){e.profile&&(x(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&x(`profile:extensions activation_warnings=${W(t.activationWarnings)}`))}function sn(e,t,n){if(!e)return;let o=v(n.commandPath??"")||"<none>";x(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function cn(e,t=Re){let n=xi(e);if(ke?.key===n)return ke.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await cr({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return ke={key:n,snapshot:s},s}catch{return ke={key:n,snapshot:null},null}}async function Ge(e,t,n=F){let o=t?lt(t):"all",i=Oc(e,o);if(pt?.key===i)return pt.snapshot;try{let r=await n(e),a=await Je({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Bo(t):void 0}),s=await Ke({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(p=>v(p.command)))].filter(p=>p.length>0).sort((p,f)=>p.localeCompare(f)),l=Rs(s.registrations.flags),d=Es(s.commands.handlers,s.registrations.commands),m=Ts(c,s.registrations.commands,s.registrations.flags,d),u={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:r,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:p,module:f})=>({name:p,module:f}))};return pt={key:i,snapshot:u},u}catch{return pt={key:i,snapshot:null},null}}async function Ic(e){let t=Ze(e);if(t.noExtensions){let a=$(process.cwd(),t.path);return await Y(X(a))&&yi((await Re(a)).warnings),null}let n=$(process.cwd(),t.path),o=await cn(n);if(!o)return null;yi(o.settingsReadWarnings);let i={commandPath:A(e),commandArgs:Vo(e)};if(!ct(o.discovery,i))return sn(t.profile,o,i),null;let r=await Ge(n,i);return r?(Tc(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function bi(e){let t=await Ge(e);return t?new Map(t.commandDescriptors):T}async function sp(e,t){return!e.requested||t.noExtensions||Ne(w,e.commandPathTokens)?T:bi($(process.cwd(),t.path))}async function $c(e,t){return(await Vr({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function Pc(e,t,n){let o=t.author;return Br(e,ya.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Lc(e,t,n,o=[]){let i=A(e),r=Bn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=$(process.cwd(),n.path),l={args:[...r],path:n.path},d=await bt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&x(`profile:extensions parser_warnings=${W(d.warnings)}`),r=d.context.args,a=d.context.options,s=d.context.global,Qn(l,{args:r,path:s.path},a),Zo(T.get(v(i)),r,a,o),Ae(void 0),Ct({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await Rn({command:i,args:r,options:a,global:s,pm_root:c,sdk:Pc(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${W(m.warnings)}`),!m.handled)throw m.warnings.length>0?Or(i,m):new I(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Ae(m.result),m.result}var mc=Symbol("pm.wrappedActionHandler");function cp(e,t){let n=e[e.length-1];return n instanceof _i?n:t}function uc(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${W(n)}`)}function lp(e){let t=T.get(v(e.commandPath));if(!t||!Yo(e.activeRegistrations,e.commandPath))return;let n=Zt(t).length===0?sa(e.commandArgs):Bn(e.commandArgs,e.extensionFlagDefinitions);Xo(t,n)}function dp(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function ki(e,t,n){if(!at(e))return;let o=T.get(v(t))?.read_output_declared===!0;return Qt(n,o)}function Nc(e){let t=n=>{let o=n;if(oc(n),typeof o._actionHandler=="function"&&o[mc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=cp(a,n),c=Date.now();Hn(s);let l=Ze(s),d=G(A(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return $a(d,l.expectHash),await i.apply(this,a);let m=$(process.cwd(),l.path),u=s.args.map(String),p=le(),f=p?dt(p,d,u):[],y=await Ac(d,m),h=ki(s,d,f),C=Ue(s,u,[...f,...y],h);rc(s,f,d),T.has(v(d))&&delete C.author,h!==void 0&&tc(C,f,d);let R={args:[...u],path:l.path},O=await bt({command:d,args:u,options:C,global:l,pm_root:m});uc(l.profile,"parser_warnings",O.warnings),u=O.context.args,C=O.context.options,se(s,C),l=O.context.global,Qn(R,{args:u,path:l.path},C),lp({activeRegistrations:p,commandPath:d,commandArgs:u,extensionFlagDefinitions:f}),l=await oa(l),Pt(s,l),dp(s,a,u),$t(s,C),Ae(void 0),Ct({command:d,args:u,options:{...C},global:{...l},pm_root:m});let k=await Rn({command:d,args:u,options:C,global:l,pm_root:m,sdk:Pc(m,l,d)});if(uc(l.profile,"command_handler_warnings",k.warnings),k.handled){Ae(k.result),En(k.result,{...l,command:d,commandArgs:u,commandOptions:C,pmRoot:m}),l.profile&&x(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await i.apply(this,a)},o[mc]=!0}for(let i of n.commands)t(i)};t(e)}async function tn(e){T=new Map,re({overrides:[]}),e&&await vi(e.rootProgram,e.pmRoot,e.invocationArgv,rr(),e.settings)}function mp(e,t,n,o){if(t?.flags&&t.flags.length>0){To(e,t.flags);let i=Io(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&at(e)&&e.addHelpText("after",Po(t)),o&&e.addHelpText("after",o)}function up(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Po(n)),o&&e.addHelpText("after",o)}function Mc(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),l=c.length===0?"standard":c.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");Dt(r,l);for(let d of r.commands)i(d,[...a,d.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function Fc(e,t){let n=L(t),o=$(process.cwd(),n.path);if(n.noExtensions){await tn({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await cn(o),r=je(t);if(!i){await tn();return}if(!ct(i.discovery,r)){await tn({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),sn(Ci(t),i,r);return}let a=await Ge(o,r);if(!a){await tn({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),T=new Map(a.commandDescriptors),await vi(e,o,t,a.registrations,a.settings);let s=Fs(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Ds(a.activationWarnings,x,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(R=>R.length>0),u=a.commandDescriptors.get(d),p=oe(e,m),f=a.commandFlagHelp.get(d),y=u?Ns(u):null;if(p){mp(p,u,f,y);return}let h=Ms(e,m);u?.description&&h.description(u.description);let C=f;u&&(Is(h,u),u.flags.length>0&&(To(h,u.flags),C=Io(h,u.flags)??void 0)),up(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let O=R[R.length-1],k=O instanceof _i?O:h,gt=Ze(k),Kc=Date.now(),dn=dt(a.registrations,d,k.args.map(String)),Ai=Ue(k,k.args.map(String),dn,ki(k,d,dn)),Ri=await Lc(k,Ai,gt,dn);await ia(gt,Ri),En(Ri,{...gt,command:d,commandArgs:k.args.map(String),commandOptions:Ai,pmRoot:o}),gt.profile&&x(`profile:command=${d} took_ms=${Date.now()-Kc}`)})};for(let d of s)l(d);Mc(e,c,a.commandDescriptors)}var He=ir(import.meta.url,["../.."])??"0.0.0",w=qn(He);async function pc(e){if(!H)return;let t=Reflect.get(e,_c);typeof t=="string"&&await ha(t)}async function fc(e,t,n){let o=A(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function gc(e,t,n){!H||!await Tn(!0)||(Nn(e,t,n,{source_context:H.source_context,source_context_source:H.source_context_source}),Tr(e),rn=H)}async function ln(e,t,n){let o=rn;if(!o)return;rn=null;let i=!1;try{let r=await F(o.global_pm_root);i=r.telemetry.enabled&&r.telemetry.installation_id===o.installation_id}catch{}await Tn(i)?$r(e,t,n):Ir()}async function pp(e){let t=await Ic(e);return An(t?.registrations??null),t}function Dc(e,t){t&&mt(t)||(e.hook("preAction",async(n,o)=>{Se=null,H=null,rn=null,xt(),Hn(o);let i=o.optsWithGlobals(),r=Ze(o),a=G(A(o)),s=o.args.map(String),c={args:[...s],path:r.path},l=Ue(o,s),d={...r},m=$(process.cwd(),r.path),u=await pp(o);if(Vi(a,{...l,...Bi(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Ko(o,a,d,l),await fc(o,void 0,()=>Fr(a,d)),!u){Se=lr({commandName:a,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),H=await Fn({command:a,pm_version:He,args:s,options:l,global:d,pm_root:m}),await pc(e),await gc(a,s,l),await Do(a,l,m,hi()),await Fo(a,s,l,d,m),await Zn({command:o,commandPath:a,commandArgs:s,commandOptions:l,expectHash:r.expectHash,pmRoot:m,globalOptions:d});return}dr(u.hooks),mr(u.commands),ur(u.parsers),pr(u.preflight),re(u.services),fr(u.renderers),An(u.registrations);let p=dt(u.registrations,a,s);l=Ue(o,s,p,ki(o,a,p)),Ko(o,a,d,l);let f=await bt({command:a,args:s,options:l,global:d,pm_root:u.pmRoot});d.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${W(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),d=f.context.global;let y={args:[...s],path:d.path};$t(o,l);let h=await yr({command:a,args:s,options:l,global:d,pm_root:u.pmRoot,decision:hi()});d.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${W(h.warnings)}`),s=h.context.args,l=h.context.options,se(o,l),d=h.context.global,$t(o,l);let C=h.decision;await Do(a,l,u.pmRoot,C),await Fo(a,s,l,d,u.pmRoot),await Zn({command:o,commandPath:a,commandArgs:c.args,commandOptions:l,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:Xn(c,[y,{args:s,path:d.path}]),globalOptions:{...d,path:r.path,noExtensions:r.noExtensions}});let R=C.run_extension_migrations?await fc(o,[],()=>$c(u.registrations.migrations,u.pmRoot)):[];d.profile&&R.length>0&&x(`profile:extensions migration_warnings=${W(R)}`);let O=Js(u.registrations.migrations);Se={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:u.pmRoot,profileEnabled:!!d.profile,migrationBlockers:O},Ae(void 0),Ct({command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot}),H=await Fn({command:a,pm_version:He,args:s,options:l,global:d,pm_root:u.pmRoot}),await pc(e),await gc(a,s,l);let k=await ar(u.hooks,{command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot});d.profile&&k.length>0&&x(`profile:extensions hook_warnings=${W(k)}`),C.enforce_mandatory_migration_gate&&Ks(a,l,O)}),e.hook("postAction",async()=>{let n=mi();await ln(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await ft(n),await Oe()}))}Dc(w);var hc=Symbol("pmCliIdempotentTopLevelRegistration");function jc(e){let t=e;if(t[hc])return;t[hc]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new _i(r):n(o,...i)})}async function fp(e,t){if(jc(e),t.setup){let{registerSetupCommands:n}=await Yu();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Xu(),o=typeof t.targetCommandName=="string"&&Qo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Zu();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Qu();n(e)}}function qe(e){return e.rawInvocationArgv??e.invocationArgv}function gp(e){return async t=>{let n=ht(t.errorCode),o=Et({ok:!1,errorCode:t.errorCode,errorCategory:n});return await jr({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:He,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Uc(e){if(e.bootstrapGlobal.noExtensions||mt(e.invocationArgv))return;let t=je(e.invocationArgv),n=await cn(e.bootstrapPmRoot);if(n&&ct(n.discovery,t)){let o=await Ge(e.bootstrapPmRoot,t);qc(o);return}n&&sn(Ci(e.invocationArgv),n,t),re({overrides:[]})}function qc(e){if(!e){re({overrides:[]});return}re(e.services)}async function Si(e){await ln(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await ft({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Hc(){await ln(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await ft({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Gc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof I)&&(Pn(e.error)||!n))return!1;let o=J(me(e.error)),i=e.error instanceof I?e.error.exitCode:$n(t),r=e.error instanceof I||Ar(e.error)?e.error.context:void 0,a=vc(r,e.invocationArgv,o),s=ps(o,a),c=et(e.bootstrapGlobal.lean?Ut(wo(o,i,a)):wo(o,i,a)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Z(c,p=>`${JSON.stringify(p,null,2)}
|
|
40
|
-
`):c,null,2):
|
|
41
|
-
`):x(
|
|
42
|
-
`):x(y),p&&await
|
|
43
|
-
`):x(
|
|
33
|
+
`)}`}function Mo(e){let t=e;if(typeof t.aliases=="function")return t.aliases().map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);if(typeof t.alias=="function"){let n=t.alias();if(typeof n=="string"&&n.trim().length>0)return[n.trim().toLowerCase()]}return Array.isArray(t._aliases)?t._aliases.map(n=>n.trim().toLowerCase()).filter(n=>n.length>0):[]}function at(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Mo(o).includes(n))??null}function oe(e,t){let n=e;for(let o of t){let i=at(n,o);if(!i)return null;n=i}return n}var Jt=new WeakSet;function st(e){return Jt.has(e)}function Bs(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&j.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=at(n,i);if(r){n=r;continue}let a=n.command(i);Jt.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function cu(e,t){let n=t.join(" "),o=j.find(a=>n===a.canonical||n.startsWith(`${a.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,r=[];for(let a of t){let s=at(i,a);if(!s)return null;r.push(a);let c=s.commands.length>0||j.some(d=>d.canonical.startsWith(`${r.join(" ")} `));if(!Jt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function lu(e,t,n,o,i=!1){let r=t.split(" ").filter(l=>l.length>0),a=cu(e,r),s=oe(e,r),c=j.some(l=>l.canonical===t&&l.alias===o?.action&&!e.commands.some(m=>m.name()===l.alias)&&(s===null||Jt.has(s)));if(!a||a.core_path===t&&s!==null&&!n.has(t)&&!i||c&&!n.has(t))return null;let d=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${d}`}function Vs(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(r=>r.trim().length>0).sort((r,a)=>r.localeCompare(a)).filter(r=>{let a=lu(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Js(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}import De from"node:path";async function Fo(e,t={},n=[]){let o={readSettings:U,loadExtensions:Ye,activateExtensions:Xe,resolveImplicitPmRoot:gn,...t};try{let i=await o.readSettings(e),r=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(r);return[...r.failed,...a.failed].map(s=>{let c=(r.effective??[]).find(u=>u.layer===s.layer&&u.name===s.name),d=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(H).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),l=n.map(H),m=d.some(u=>l.some(p=>p===u||p.startsWith(`${u} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function Ks(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Fo(t,n,o),r={readSettings:U,loadExtensions:Ye,activateExtensions:Xe,resolveImplicitPmRoot:gn,...n};try{let a=r.resolveImplicitPmRoot(process.cwd());if(De.resolve(a)===De.resolve(t))return i;let[s,c]=await Promise.all([r.readSettings(t),r.readSettings(a)]),[d,l]=await Promise.all([r.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),r.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(p=>p.activation?.commands??[])),u=[...new Set(l.loaded.flatMap(p=>p.activation?.commands??[]))].filter(p=>!m.has(p)).sort((p,f)=>p.localeCompare(f));if(u.length===0)return i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${De.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${De.resolve(a)} cwd_extension_discovery_root=${l.roots.project}; the selected --pm-path runtime is missing ${u.length} workspace command path(s): ${u.slice(0,8).join(", ")}${u.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${De.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${De.resolve(t)} install <package> --project".`})}catch{}return i}var Ys={core:0,standard:1,full:2,internal:3};function Xs(e,t,n=!0){let o=t.get(T(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let r=i.reduce((s,c)=>Ys[c.tier]<Ys[s]?c.tier:s,"internal"),a=new Set(i.map(({family:s})=>s));return{tier:r,family:a.size===1?i[0].family:"extensions"}}function Zs(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(T(o)!==o||!Be.some(i=>i===o)&&!It(o)&&!Qe(o)&&!Fe(e,t))return null;for(let i=t.length-1;i>0;i-=1){let r=oe(e,t.slice(0,i));if(r)return r}return t.length===1?e:null}function du(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Qs(e){let t=e;if(typeof t.attributeName=="function"){let n=t.attributeName();return typeof n=="string"&&n.trim().length>0?n.trim():null}return typeof t.attributeName=="string"&&t.attributeName.trim().length>0?t.attributeName.trim():null}function mu(e){let t=new Map;for(let n of e){let o=n,i=Qs(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let r=t.get(i)??[];r.push(o.long.trim()),t.set(i,r)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,r)=>i.localeCompare(r)));return t}function uu(e){return _(e)}function pu(e){let t=e.options??[],n=mu(t);return t.map(o=>{let i=o,r=typeof i.flags=="string"?i.flags.trim():"",a=typeof i.description=="string"?i.description.trim():"",s=Qs(o),d=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),l=a.match(/^Alias for ([^ ]+)/i),m=l&&l[1]?l[1].trim():null,u=i.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),p=r.includes("<"),f=p||r.includes("["),y={flags:r,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:a,takes_value:f,value_required:p,value_name:du(r),variadic:i.variadic===!0,required:u,aliases:d,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function fu(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,r=t.get(i);if(!r)continue;let a=o.long,s=new Set([...r.aliases??[],a]);r.aliases=[...s].sort((c,d)=>c.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function gu(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let i=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",r=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:i.trim(),required:o.required===!0||r?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:r}})}function hu(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(r=>r.name()!=="help"||e.parent===null).filter(r=>!n||(_e(r)??Q(r.name()))!=="internal").map(r=>{let a=H(R(r)),s=a,c=_e(r),d=Xs(a,t,c!==void 0),l=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:Mo(r),description:r.description().trim(),tier:d?.tier??c??Q(s),family:d?.family??Mt(s),...l?{alias_for:l.canonical,alias_lifecycle:l.lifecycle,...l.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function yu(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function _u(e,t,n,o,i){let r=e!==void 0&&lo(e)===Le,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:ts(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:yu(n,a,o),intentSource:s}}function wu(e,t){return e===void 0?null:t?.tier??Q(e)}function vu(e,t){return e===void 0?null:t?.family??Mt(e)}function Cu(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Zs(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function xu(e,t,n,o,i=new Map,r=!1){if(!e){let s=gu(t),c=hu(t,i,r),d=new Set(c.map(({name:l})=>l));return{arguments:s,options:o,subcommands:[...c,...Rt.filter(({parent:l,action:m})=>l===n&&!d.has(m)).map(({action:l,description:m})=>({name:l,aliases:[],description:m,tier:Q(n.split(" ")[0]),family:Mt(n.split(" ")[0])}))].sort((l,m)=>l.name.localeCompare(m.name)),usage:[n,s.reduce((l,m)=>m.required?l.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):l,t.usage())].filter(l=>l.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:c,variadic:d,value_kind:l,polymorphic:m})=>({name:s,required:c,variadic:d,description:m?`Polymorphic ${l} value; inspect the action contract before mutation.`:`${l.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:c})=>s!==null&&a.has(s)||c.some(d=>a.has(d))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:c,variadic:d})=>{let l=d?`${s}...`:s;return c?`<${l}>`:`[${l}]`})].join(" ")}}function bu(e,t,n,o){return st(e)?t===void 0?{}:{inherited_options:Lo(t)}:n!==void 0&&zr(n)?{inherited_options:Hs(n,o)}:{}}function ku(e,t,n,o,i){let r=co(n),a=se(n),s=H(R(t)),c=H(o.join(" ")),d=c.length>s.length?c:s,l=Qe(d),m=l?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(T(u)):void 0,y=u?Xs(u,i,_e(t)!==void 0):void 0,{narrative:h,intentSource:C}=_u(u,t.description().trim(),r,f,l!==void 0),O=fu(zs(pu(t),Gs(f))),E=xu(l,t,m,O,i,a),k=Cu(e,t,a);return{format:"pm_help_v1",detail_mode:r,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:wu(p,y),capability_family:vu(p,y),description:l?.description??t.description(),usage:E.usage,intent:l?.description??h.intent,intent_source:C,examples:l?[l.example]:h.examples,tips:l?[Ot(l.accepted_flags)]:h.tips,arguments:E.arguments,options:E.options,...bu(t,f,u,E.options),subcommands:E.subcommands,has_subcommands:E.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function ec(e,t,n,o=t){let i=N(t);if(!i.json)return!1;let r=L(t);if(!r.requested)return!1;let a=Zs(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=ye(t),c=`unknown command '${ye(r.commandPathTokens).join(" ")}'`,d=Eo(c,e,n,s),l=zt(c,"help",it,g.USAGE,{...d,attemptedCommand:uu(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(l,u=>`${JSON.stringify(u,null,2)}
|
|
34
|
+
`):l;ie(`${JSON.stringify(m,null,2)}
|
|
35
|
+
`)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=ku(e,a,t,r.commandPathTokens,n),c=L(o).commandPathTokens;s.requested_path=c;let d=q(c.join(" "));d&&(s.resolved_path=d.canonical),a===e&&!se(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),tr(`${JSON.stringify(s,null,2)}
|
|
36
|
+
`)}return process.exitCode=g.SUCCESS,!0}function Su(e,t){let n=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${t.types.join("|")}`];return e==="create"&&n.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows."),n.join(`
|
|
37
|
+
`)}function Eu(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Au(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function Ru(e,t,n,o){let i=new Set(n),r=o.filter(c=>!i.has(c)),a=c=>c.length>0?c.map(d=>fn("create",d)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(xa).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function Ou(e,t,n){let o=oa(n);if(!o)return Su(e,t);let i=Li(o,t);if(!i){let y=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${y}`].join(`
|
|
38
|
+
`)}let r=n.indexOf("--"),a=r<0?n:n.slice(0,r),s=a.findIndex(y=>y==="--create-mode"||y.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&c?.toLowerCase()==="strict",l=Au(e,i),m=_t(i,e,l.progressive),u=_t(i,e,d?l.strict:l.progressive),p=y=>y.length>0?y.map(h=>fn(e,h)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${p(u.required)}`,` disabled: ${p(u.disabled)}`,` hidden: ${p(u.hidden)}`];if(e==="create"){let y=_t(i,e,l.strict);Ru(f,i,m.required,y.required)}return Eu(f,i),u.errors.length>0&&f.push(` config errors: ${u.errors.join("; ")}`),f.join(`
|
|
39
|
+
`)}function tc(e,t,n){let o=A(n);if(o!=="create"&&o!=="update")return;let i=at(e,o);i&&i.addHelpText("after",Ou(o,t,n))}function Tu(e,t){let n=Ke(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Iu(e){return Ke(e.status)?.toLowerCase()??"pending"}function $u(e){return e.mandatory===!0}function Pu(e,t){let n=e.layer.localeCompare(t.layer);if(n!==0)return n;let o=e.name.localeCompare(t.name);return o!==0?o:e.id.localeCompare(t.id)}function ic(e){let t=[];return e.forEach((n,o)=>{if(!$u(n.definition))return;let i=Iu(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:Tu(n.definition,o),status:i})}),t.sort(Pu),t}function nc(e){return Array.isArray(e)&&e.length>0}var Lu=new Set(["create","beads import","todos import"]),Nu=new Set(["restore","update","close","delete","append","claim","release"]),Mu=new Set(["comments","notes","learnings"]),Fu=new Set(["files","docs","test"]),Du=new Set(["activate","add","add-field","add-status","add-type","apply","compact","create","deactivate","delete","disable","edit","enable","import","infer","install","materialize","migrate","redact","remove","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type","repair","run","save","set","unset","update","upgrade"]);function Do(e,t){let n=t.force===!0;return Lu.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Nu.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Mu.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Fu.has(e)?{isMutation:nc(t.add)||nc(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function ju(e,t,n){if(Do(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Dr(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>Du.has(i.trim().toLowerCase())):!1}function oc(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Uu(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Ke(t[1])||i.push("source"),Ke(n.to)||i.push("--to"),i.length!==0)throw new $(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(r=>r.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function qu(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||oc(n.status)!==oc(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=le(i,de()),s=await Et(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await Sr(s,{schema:i.schema}),d=typeof n.assignee=="string"?n.assignee.trim():void 0;(d===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(d.toLowerCase())&&d)||x(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function jo(e,t,n,o,i){if(!ju(e,t,n)||(Uu(e,t,n),!await Y(X(i))))return;let r=await Te(i);Na(o.json===!0)||await qu(e,t,n,i,r.settings);let a=Fr({author:Ct(o.author,r.settings.author_default),payload:{command:e,args:t,options:n},settings:r.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)ge(s)}function rc(e,t,n){if(n.length===0)return;let o=Do(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),r=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new $(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function Uo(e,t,n,o){if(!Do(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await Y(X(n)))return;let{settings:r,metadata:a,warnings:s}=await Te(n);for(let c of s)ge(c);if(!br(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(xr(r),await kr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=le(r,de());await jr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function qo(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function Ue(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of qo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,T(i)]))]}function Ho(e,t){let n=v(e);if(n.length===0)return!1;let o=Ue(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Yt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...D(n.commands),...D(n.command_handlers),...D(n.command_overrides),...D(n.flag_commands),...D(n.parser_overrides),...ac(n.preflight_ownership),...ac(n.renderer_ownership)]:[]}function D(e){return e??[]}function ac(e){return D(e).flatMap(t=>t.commands)}function ct(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var sc=new Set(["hooks","parser","preflight","renderers"]),cc=new Set(["commands","schema","services","importers"]),Hu=new Set(["reindex","search","search-advanced"]),Gu=new Set(["--template"]);function je(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Go(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Hu.has(n??t)}function zo(e,t){for(let n of e.commandArgs??[]){if(!n.startsWith("--"))continue;let[o]=n.split("=",1);if(t.has(o))return!0}return!1}function Xt(e){return v(e.commandPath??"")==="create"&&zo(e,Gu)}function Wo(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Kt(e,t){return e.some(n=>Ho(n,t))||Xt(t)&&Wo(e)}function Bo(e){return[D(e.hooks).length,(e.preflight_overrides??0)-D(e.preflight_ownership).length,D(e.item_types).length,D(e.item_fields).length,D(e.relationship_kinds).length,D(e.service_overrides).length,D(e.assurance_providers).length,D(e.renderer_overrides).length-D(e.renderer_ownership).length].some(n=>n>0)}function Vo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Kt(n,t);let o=Yt(e);if(Kt(o,t)||ct(e).has("search")&&Go(t.commandPath))return!0;if(e.contributions)return Bo(e.contributions)}function Zt(e,t){let n=Vo(e,t);if(n!==void 0)return n;let o=ct(e);return!!(je(o,sc)||je(o,cc))}function lt(e,t){return e.effective.length===0?!1:dt(t)!=="all"?e.effective.some(o=>Zt(o,t)):e.effective.some(o=>{let i=ct(o);return Yt(o).length>0||je(i,sc)||je(i,cc)||i.has("search")})}function dt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=Ue(e).filter(i=>i.split(" ").every(r=>!r.startsWith("-"))).sort((i,r)=>r.length-i.length)[0]??v(e.commandPath??"");if(t.length===0)return"all";let n=Xt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Jo(e){return dt(e)==="all"?void 0:t=>Zt(t,e)}function qe(e){let t=L(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...r]=t.commandPathTokens;return{commandPath:i,commandArgs:r,allowCommandPrefixMatch:!0}}let n=F(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Ko(e){let t=e.args.map(String);if(v(R(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Qt=Symbol.for("pm.readOutputInvocationProvenance"),zu=new Map(pe.filter(e=>e.reservation_scope==="root_only").map(e=>[Nt({long:e.flag}),e.flag]));function ce(e,t){let n=Reflect.get(e,Qt);n!==void 0&&Reflect.set(t,Qt,n)}function Yo(e,t,n){let o=Bi(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let r=i.rawArgs,a=new Set(ee(r.slice(2))),s=Wi.find(l=>l.command===o),c=Object.values(s?.dimensions??{}).flatMap(l=>l.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,Qt);Reflect.set(n,Qt,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),ce(n,e)}function Wu(e){let t=e.optsWithGlobals(),n=R(e);if(T(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let r of i.options){let a=r.attributeName(),s=i.getOptionValueSource(a)==="cli";if(s&&!e.options.some(c=>c.long===r.long))throw new $(`Unknown option '${r.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:r.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(a)!=="cli"){let c=i.getOptionValue(a);e.setOptionValueWithSource(a,c,"cli")}a in o?t[a]=o[a]:delete t[a]}return t}function Xo(e,t,n,o){Yo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Zi(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;ce(o,e);let s=Xi(t);for(let d of a){let l=s.get(d),m=o[l];e.setOptionValueWithSource(l,m,"cli")}let c=r.length>0?r.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",c,"cli");Lt(e,n)}function He(e,t,n=[],o){let r={...Wu(e)};ce(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession,delete r.expectHash;let a=pa(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=Vn(n),c=M(R(e)).map(u=>({long:u.flag,short:u.short,aliases:u.aliases})),d={...a};for(let u of s)r[u]!==void 0&&(d[u]=r[u]);Jn(d,[...c,...n],R(e),o);let l=ha(a,fc(e),n),m=ua(r,n,l,R(e));return ce(r,m),m}return r}function mc(e,t,n){let o=Vn(t.map(({long:a})=>({long:a}))),i=[...zu].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new $(`Unknown option '${r}' for extension command '${n}'. ${r} is a root-only pm flag and this command does not declare it.`,g.USAGE,{code:"unknown_option",flag:r,required:`Remove ${r}, or use it on the root command (pm --help ${r}).`,nextSteps:[`Run pm contracts --command ${n} --flags-only --json to list the flags this command accepts.`]})}function mt(e,t,n){let o=tt(e,t),i=[t],r=[];for(let a of n){if(a.startsWith("-"))break;i.push(a);let s=tt(e,i.join(" "));s.length>0&&(r=s)}return r.length>0?r:o}function en(e){return e.arguments??[]}function lc(e){let t=en(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Zo(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}var uc=Symbol("pm.commandOptionTokens"),dc=Symbol("pm.capturesOptionTokens");function pc(e){if(Reflect.get(e,dc)===!0)return;Reflect.set(e,dc,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,uc,[...n]),t(n))}function Bu(e){let t=new Map;for(let n of e.options){let o={arity:n.required?"required":n.optional?"optional":"none",key:n.attributeName(),variadic:n.variadic};for(let i of[n.short,n.long])i&&t.set(i,o)}return t}function Vu(e){let t=Reflect.get(e,"_passThroughOptions")===!0;return!t&&Reflect.get(e,"_enablePositionalOptions")!==!0?{}:{stop:{atSubcommand:n=>e.commands.some(o=>o.name()===n||o.aliases().includes(n)),atFirstUnrecognized:t}}}function fc(e){let t=[];for(let o=e;o?.parent;o=o.parent)t.unshift(o);let n=[];for(let o of t){let i=Reflect.get(o,uc);if(i===void 0)continue;let r=Bu(o),a=[];for(let s=o;s;s=s.parent)a.push(s);n.push({tokens:i,optionOf:s=>r.get(s),includesLooseFlags:o===e,negativeNumbersAreValues:!a.some(s=>s.options.some(c=>c.short!==void 0&&/^-\d$/u.test(c.short))),...Vu(o)})}return n}function gc(e,t,n){t.length!==0&&ga(fc(e),t,n)}function Qo(e,t){let n=en(e),o=n.filter(c=>c.required).length,r=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new $(`Missing required argument for extension command '${e.command}'. Usage: ${lc(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new $(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${lc(e)}${s}`,g.USAGE)}}function Ju(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function tn(e,t){return{definitions:e,inheritedFlags:Tt({readOutput:t}).map(n=>n.flag)}}function Ku(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map(Ju);if(o.length===0)return;let{inheritedFlags:i}=tn([],n);throw new $(`Unknown option '${o.join(", ")}' for extension command '${t}'. This command declares no flags; it accepts only the host flags ${i.join(", ")}.`,g.USAGE,{code:"unknown_option",flag:o[0],required:`Remove ${o.join(", ")}, or ask the package to declare it with api.registerFlags.`,nextSteps:[`Run pm contracts --command ${t} --flags-only --json to list the flags this command accepts.`]})}function Yu(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Jn(t,n,e.command,tn(n,o));return}Ku(t,e.command,o)}function ei(e,t,n,o){e&&(Qo(e,t),Yu(e,n,o))}import{Command as hc}from"commander";var Xu=new Set(["--version","-V"]);function ut(e){let t;try{t=fe(e).argv}catch{return!1}let n=na(t),o=S(n);return o===void 0?!1:["package","packages","extension"].includes(n[o])&&["inventory","list"].includes($t(n.slice(o+1))??"")}function yc(e){if(F(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new hc().configureOutput({writeErr:()=>{}}).exitOverride(),o=new Set;for(let r of pe)for(let a of[r.flag,r.short,...r.aliases??[]]){if(a===void 0||o.has(a))continue;o.add(a);let s=r.value_name!==void 0||r.flag==="--pm-path";n.option(`${a}${s?" <value>":""}`)}try{n.parseOptions(e)}catch{}let i=n.opts();return{path:i.pmPath??i.path}}var Zu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ti=new Set(["activity","aggregate","context","ctx","events","get","graph","history","list","list-all","list-blocked","list-canceled","list-closed","list-draft","list-in-progress","list-open","search"]),_c=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),Qu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),ep=new Set(["claim","close-task","pause-task","release","start-task","test"]),ke={setup:!0,listQuery:!0,mutation:!0,operation:!0},tp=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function pt(e){return e.some(t=>Xu.has(t))}function np(e,t){if(!j.some(o=>o.canonical_argv[0]===t))return;let n=new hc().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of ae(t,M(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let r of[o.flag,o.short,...o.aliases??[]])r!==void 0&&n.option(`${r}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return ke;let i=V([t,...o.operands])?.alias;if(j.some(r=>r.alias===i))return{...ke,targetCommandName:i}}catch{return ke}}function ni(e){if(pt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||L(e).requested)return ke;let t=A(e);if(!t)return ke;let n=t.trim().toLowerCase(),o=F(e),i=V(o)?.alias;if(j.some(a=>a.alias===i))return{...ke,targetCommandName:i};let r=np(o,n==="ctx"?"context":n);return r||(Zu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ti.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:_c.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Qu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:ke)}function oi(e){return e.length===0||L(e).requested||e.includes("--explain")&&A(e)===void 0}function ii(e,t){return ut(t)||pt(t)?!1:se(t)||L(t).requested?!0:!!A(t)}function ri(e){if(pt(e))return!1;let t=A(e);return t?tp.has(t):!1}function op(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(d=>{let l=d.indexOf("=");return l>=0?d.slice(0,l):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),r=i?e.argv.map(d=>{let l=d.indexOf("=");return(l>=0?d.slice(0,l):d)===o?l>=0?`${i}${d.slice(l)}`:i:d}):e.argv,a=Ve(r),s=i&&n>=0?`${o}=[redacted]`:t,c=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ai(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),i=o.length>0?o.join(" "):"the canonical flag",r=_c.has(t)||ep.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=op({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new $(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:a,examples:[_(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:_(c.argv)}})}var ip=new Set(["success","nonexistent_command","invalid_option","missing_required_option","missing_required_argument","invalid_usage","validation_failed","health_findings","validation_findings","conflict","runtime_failed","unknown_failed"]),rp=new Set(["parse","preflight","execute","unknown"]),ap=new Set(["usage","validation","conflict","runtime","unknown"]);function Se(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function si(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function nn(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.trunc(o))}}function ci(e){if(!e)return;let t=e.trim().toLowerCase();if(ip.has(t))return t}function li(e){if(!e)return;let t=e.trim().toLowerCase();if(rp.has(t))return t}function di(e){if(!e)return;let t=e.trim().toLowerCase();if(ap.has(t))return t}function mi(e){let t=Se(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(si(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=nn(e,"failed");if(typeof i=="number"&&i>0)return`failed_runs:${i}`;let r=e?.run_results;if(Array.isArray(r)){let a=r.filter(s=>wn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function ui(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function pi(){let e=wn(me()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=nn(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=va(o),r=Se(e,"error_code","errorCode")??ui(i,o),a=di(Se(e,"error_category","errorCategory"))??(i?void 0:yt(r)),s=i?void 0:mi(e)??`command_exit_${o}`,c=ci(Se(e,"command_resolution","commandResolution"))??At({ok:i,errorCode:r,errorCategory:a}),d=li(Se(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:r,error_category:a,command_resolution:c,resolution_stage:d}}var fi="PM_CLI_PACKAGE_ROOT",Rc=Symbol("pm.deprecatedAliasInvocation"),an=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=an.get(t)??[];n.push(e),an.set(t,n)}for(let e of an.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function sp(){return ar(import.meta.url,["../.."])}(typeof process.env[fi]!="string"||process.env[fi]?.trim().length===0)&&(process.env[fi]=sp());var Ae=null,z=null,sn=null;function cp(e){Ae=e}function lp(e){I=e}var ft=null,Ee=null,I=new Map,Ci=250,dp=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),mp=new Set(["1","true","yes","on"]),up=Ze(()=>import("./chunks/register-setup-RW26X3GJ.js")),pp=Ze(()=>import("./chunks/register-list-query-7S5QWDTI.js")),fp=Ze(()=>import("./chunks/register-mutation-EK6DVIQK.js")),gp=Ze(()=>import("./chunks/register-operations-6MURXE4V.js"));function rn(e){return _(e)}function Oc(e){let t=e.match(/--[a-zA-Z0-9][a-zA-Z0-9_-]*/g);if(!t||t.length===0)return;let n=[...new Set(t.map(o=>he(o)??o))];return n.length>0?n:void 0}function hp(e,t,n,o){if(n?.suggested_retry||o===ao||o===ro||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let i=ee(t),r=new Set(i.map(m=>he(m)??m)),a=Oc(e),s=t.find(m=>w.commands.some(u=>u.name()===m)),c=s?w.commands.find(m=>m.name()===s):void 0,d=new Set([...w.options,...c?.options??[]].flatMap(m=>m.flags.split(/[ ,|]+/).map(u=>he(u)).filter(u=>u!==void 0))),l=a?.filter(m=>{let u=he(m)??m;return r.has(u)?!1:d.has(u)||Oo(t,s,u,I)!==void 0});return l&&l.length>0?l:void 0}function yp(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?he(i):void 0,a=e.find(u=>w.commands.some(p=>p.name()===u)),s=a?w.commands.find(u=>u.name()===a):void 0,c=r?s?.options.find(u=>u.flags.split(/[ ,|]+/).includes(r)):void 0,d=Oo(e,a,r,I),l=r?c?.isBoolean()===!0||d===!1?[r]:[r,"<value>"]:[],m=r?rn([...e,...l]):t;return m===t?void 0:m}function _p(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!==void 0&&(o==="allowed_values"||i!==null)&&(n[o]=i)}return n}function wp(e){let t=e.existingRecovery;return{attempted_command:t?.attempted_command??e.attemptedCommand,normalized_args:t?.normalized_args??[...e.invocationArgv],provided_fields:t?.provided_fields??(e.providedFields.length>0?e.providedFields:void 0),missing:t?.missing??e.inferredMissing,..._p(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function wc(e,t){return{...e,recovery:t}}function vp(e,t){if(t===void 0)return;let n=Ba(e,t.code,t.field,Ha(e,t.code,t.recovery)),o=Cp(e),i=Va(e,t.code,t.field,n,o),r=za(e,t.code,i,o,()=>Kr(P(process.cwd(),N(e).path)));return Ja(e,t.code,r,o)}var vc=" ";function Cp(e){let t=e.map(i=>i===""?vc:/^--(?:pm-)?path=$/u.test(i)?`${i}${vc}`:i),n=N(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Re({});return n!==void 0&&o.length>0?null:o}function Tc(e,t,n){let o=Ve(t),i=F(o),r=S(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:Ar(e);let d=vp(o,e),l=d&&(a==="history-redact"||a==="history"&&s==="redact")?{...d,...d.attempted_command?{attempted_command:rn(o)}:{},...d.normalized_args?{normalized_args:[...o]}:{},...d.suggested_retry?{suggested_retry:rn(o)}:{},...d.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:d;if(l?.recovery_mode==="compact"&&!c)return wc(e,l);let m=rn(o),u=ee(o),p=hp(n,o,l,e?.code),f=yp(o,m,p,l),y=wp({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:l});return wc(e,y)}async function gt(e){let t=z;z=null,await Ka(t,e);let n=Ae;if(Ae=null,!n){bt();return}let o=[],i=wr();try{await Ya({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(r=>r.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await dr(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:me(),affected:i}))}catch(r){o=[`afterCommand hooks failed: ${r instanceof Error?r.message:String(r)}`]}finally{bt()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${B(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${B(o)}`)}async function Ic(e,t){await Ir();let n=z,o=Ae,i=n?.command??o?.commandName??e,r=n??In(o?.globalOptions??t),a=I.get(v(i))?.source;Fn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??ze,extension:a})}function $c(e){return mp.has((process.env[e]??"").trim().toLowerCase())}function Pc(e){return $c("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!dp.has(Math.trunc(e))}async function cn(e,t){return Pc(e.exit_code)?(await Ic(e.command,t),Mr({...e,source_context:e.source_context??In(t).source_context}),!0):!1}async function Lc(e){let t=J(ue(e.error)),n=Ss(t);e.bootstrapGlobal.json?x(JSON.stringify(nt(bs(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Ic(e.attemptedCommand,e.bootstrapGlobal),Dn(e.error);let r=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=r.errorCategory,i=r.commandResolution,await mn(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to report error: ${ue(r)}`)}try{await gt({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(r){e.bootstrapGlobal.json||x(`Failed to run error hooks: ${ue(r)}`)}try{await Ie()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${ue(r)}`)}}var xp={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},gi=new Map;function hi(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Nc(e,t){return e.options.some(n=>n.long===t)}function Mc(e,t){return e.options.some(n=>n.short===t)}function yi(e,t,n,o){let i=t.trim();if(!i||!Ui(i))return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Mc(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,Bn);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!Nc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,Bn);return}e.option(`${a} <value>`,r)}}async function Fc(e,t){let n=xp[e];if(!n)return[];let o=`${t}:${n}`,i=gi.get(o);if(i)return i;if(!await Y(X(t)))return gi.set(o,[]),[];let r=await U(t),s=(Cn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(l=>({long:`--${l}`,type:hi(c.type),value_type:hi(c.type)})));return gi.set(o,s),s}async function Dc(e,t){let n=N(t),o=P(process.cwd(),n.path);if(!await Y(X(o)))return;let i=Ee?.key===ki(o)?Ee.snapshot:null,r=i===null?await U(o):i.settings,a=Cn(r.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let d=oe(e,c.path.split(" "));if(d)for(let l of a.command_to_fields.get(c.command)??[]){let m=l.description??"";yi(d,l.cli_flag,m,l.repeatable);for(let u of l.cli_aliases)yi(d,u,`Alias for --${l.cli_flag}`,l.repeatable)}}}async function xi(e,t,n,o,i){let r=A(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await U(t),s=le(a,o);tc(e,s,n)}catch{}}function _i(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function jc(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function bi(e){return e.some(t=>t==="--profile")}function ki(e){return`pm-root:${e}`}function wi(e){for(let t of e)t.startsWith("settings_read_")&&ge(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Uc(e,t){e.profile&&(x(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&x(`profile:extensions activation_warnings=${B(t.activationWarnings)}`))}function ln(e,t,n){if(!e)return;let o=v(n.commandPath??"")||"<none>";x(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function dn(e,t=Te){let n=ki(e);if(Ee?.key===n)return Ee.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await mr({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return Ee={key:n,snapshot:s},s}catch{return Ee={key:n,snapshot:null},null}}async function We(e,t,n=U){let o=t?dt(t):"all",i=jc(e,o);if(ft?.key===i)return ft.snapshot;try{let r=await n(e),a=await Ye({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Jo(t):void 0}),s=await Xe({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(p=>v(p.command)))].filter(p=>p.length>0).sort((p,f)=>p.localeCompare(f)),d=Ms(s.registrations.flags),l=Ls(s.commands.handlers,s.registrations.commands),m=Ds(c,s.registrations.commands,s.registrations.flags,l),u={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:r,commandHandlers:c,commandFlagHelp:d,commandDescriptors:m,commandAliases:l,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:p,module:f})=>({name:p,module:f}))};return ft={key:i,snapshot:u},u}catch{return ft={key:i,snapshot:null},null}}async function qc(e){let t=et(e);if(t.noExtensions){let a=P(process.cwd(),t.path);return await Y(X(a))&&wi((await Te(a)).warnings),null}let n=P(process.cwd(),t.path),o=await dn(n);if(!o)return null;wi(o.settingsReadWarnings);let i={commandPath:R(e),commandArgs:Ko(e)};if(!lt(o.discovery,i))return ln(t.profile,o,i),null;let r=await We(n,i);return r?(Uc(t,r),{hooks:r.hooks,commands:r.commands,parsers:r.parsers,preflight:r.preflight,services:r.services,renderers:r.renderers,registrations:r.registrations,pmRoot:n}):null}async function Si(e){let t=await We(e);return t?new Map(t.commandDescriptors):I}async function bp(e,t){return!e.requested||t.noExtensions||Fe(w,e.commandPathTokens)?I:Si(P(process.cwd(),t.path))}async function Hc(e,t){return(await ea({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function Gc(e,t,n){let o=t.author;return Qr(e,ka.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function zc(e,t,n,o=[]){let i=R(e),r=Kn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=P(process.cwd(),n.path),d={args:[...r],path:n.path},l=await kt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&l.warnings.length>0&&x(`profile:extensions parser_warnings=${B(l.warnings)}`),r=l.context.args,a=l.context.options,s=l.context.global,no(d,{args:r,path:s.path},a),ei(I.get(v(i)),r,a,o),Oe(void 0),xt({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await Tn({command:i,args:r,options:a,global:s,pm_root:c,sdk:Gc(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${B(m.warnings)}`),!m.handled)throw m.warnings.length>0?$r(i,m):new $(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Oe(m.result),m.result}var Cc=Symbol("pm.wrappedActionHandler");function kp(e,t){let n=e[e.length-1];return n instanceof vi?n:t}function xc(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${B(n)}`)}function Sp(e){let t=I.get(v(e.commandPath));if(!t||!Zo(e.activeRegistrations,e.commandPath))return;let n=en(t).length===0?fa(e.commandArgs):Kn(e.commandArgs,e.extensionFlagDefinitions);Qo(t,n)}function Ep(e,t,n){e.args=[...n],"_processArguments"in e&&typeof e._processArguments=="function"&&e._processArguments(),t.length>0&&Array.isArray(t[0])&&(t[0]=[...e.processedArgs])}function Ei(e,t,n){if(!st(e))return;let o=I.get(v(t))?.read_output_declared===!0;return tn(n,o)}function Wc(e){let t=n=>{let o=n;if(pc(n),typeof o._actionHandler=="function"&&o[Cc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=kp(a,n),c=Date.now();Wn(s);let d=et(s),l=T(R(s));if(Gr.has(l))return ja(l,d.expectHash),await i.apply(this,a);let m=P(process.cwd(),d.path),u=s.args.map(String),p=de(),f=p?mt(p,l,u):[],y=await Fc(l,m),h=Ei(s,l,f),C=He(s,u,[...f,...y],h);gc(s,f,l),I.has(v(l))&&delete C.author,h!==void 0&&mc(C,f,l);let O={args:[...u],path:d.path},E=await kt({command:l,args:u,options:C,global:d,pm_root:m});xc(d.profile,"parser_warnings",E.warnings),u=E.context.args,C=E.context.options,ce(s,C),d=E.context.global,no(O,{args:u,path:d.path},C),Sp({activeRegistrations:p,commandPath:l,commandArgs:u,extensionFlagDefinitions:f}),d=await da(d),Lt(s,d),Ep(s,a,u),Pt(s,C),Oe(void 0),xt({command:l,args:u,options:{...C},global:{...d},pm_root:m});let k=await Tn({command:l,args:u,options:C,global:d,pm_root:m,sdk:Gc(m,d,l)});if(xc(d.profile,"command_handler_warnings",k.warnings),k.handled){Oe(k.result),Rn(k.result,{...d,command:l,commandArgs:u,commandOptions:C,pmRoot:m}),d.profile&&x(`profile:command=${l} took_ms=${Date.now()-c}`);return}return await i.apply(this,a)},o[Cc]=!0}for(let i of n.commands)t(i)};t(e)}async function on(e){I=new Map,re({overrides:[]}),e&&await xi(e.rootProgram,e.pmRoot,e.invocationArgv,cr(),e.settings)}function Ap(e,t,n,o){if(t?.flags&&t.flags.length>0){$o(e,t.flags);let i=Po(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&st(e)&&e.addHelpText("after",No(t)),o&&e.addHelpText("after",o)}function Rp(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",No(n)),o&&e.addHelpText("after",o)}function Bc(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(r,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([l])=>l===s||l.startsWith(`${s} `)).map(([,l])=>l),d=c.length===0?"standard":c.reduce((l,m)=>o[m.tier]<o[l]?m.tier:l,"internal");Ut(r,d);for(let l of r.commands)i(l,[...a,l.name()])};for(let r of e.commands)t.has(r.name())||i(r,[r.name()])}async function Vc(e,t){let n=N(t),o=P(process.cwd(),n.path);if(n.noExtensions){await on({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await dn(o),r=qe(t);if(!i){await on();return}if(!lt(i.discovery,r)){await on({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),ln(bi(t),i,r);return}let a=await We(o,r);if(!a){await on({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),I=new Map(a.commandDescriptors),await xi(e,o,t,a.registrations,a.settings);let s=Vs(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,l=>Js(a.activationWarnings,x,l)),c=new Set(e.commands.map(l=>l.name())),d=l=>{let m=l.split(" ").filter(O=>O.length>0),u=a.commandDescriptors.get(l),p=oe(e,m),f=a.commandFlagHelp.get(l),y=u?Ws(u):null;if(p){Ap(p,u,f,y);return}let h=Bs(e,m);u?.description&&h.description(u.description);let C=f;u&&(js(h,u),u.flags.length>0&&($o(h,u.flags),C=Po(h,u.flags)??void 0)),Rp(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...O)=>{let E=O[O.length-1],k=E instanceof vi?E:h,ht=et(k),rl=Date.now(),un=mt(a.registrations,l,k.args.map(String)),Oi=He(k,k.args.map(String),un,Ei(k,l,un)),Ti=await zc(k,Oi,ht,un);await ma(ht,Ti),Rn(Ti,{...ht,command:l,commandArgs:k.args.map(String),commandOptions:Oi,pmRoot:o}),ht.profile&&x(`profile:command=${l} took_ms=${Date.now()-rl}`)})};for(let l of s)d(l);Bc(e,c,a.commandDescriptors)}var ze=sr(import.meta.url,["../.."])??"0.0.0",w=zn(ze);async function bc(e){if(!z)return;let t=Reflect.get(e,Rc);typeof t=="string"&&await ba(t)}async function kc(e,t,n){let o=R(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function Sc(e,t,n){!z||!await $n(!0)||(Fn(e,t,n,{source_context:z.source_context,source_context_source:z.source_context_source}),Pr(e),sn=z)}async function mn(e,t,n){let o=sn;if(!o)return;sn=null;let i=!1;try{let r=await U(o.global_pm_root);i=r.telemetry.enabled&&r.telemetry.installation_id===o.installation_id}catch{}await $n(i)?Nr(e,t,n):Lr()}async function Op(e){let t=await qc(e);return On(t?.registrations??null),t}function Jc(e,t){t&&ut(t)||(e.hook("preAction",async(n,o)=>{Ae=null,z=null,sn=null,bt(),Wn(o);let i=o.optsWithGlobals(),r=et(o),a=T(R(o)),s=o.args.map(String),c={args:[...s],path:r.path},d=He(o,s),l={...r},m=P(process.cwd(),r.path),u=await Op(o);if(Yi(a,{...d,...Ki(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Xo(o,a,l,d),await kc(o,void 0,()=>Ur(a,l)),!u){Ae=ur({commandName:a,commandArgs:s,commandOptions:d,globalOptions:l,pmRoot:m}),z=await jn({command:a,pm_version:ze,args:s,options:d,global:l,pm_root:m}),await bc(e),await Sc(a,s,d),await Uo(a,d,m,_i()),await jo(a,s,d,l,m),await to({command:o,commandPath:a,commandArgs:s,commandOptions:d,expectHash:r.expectHash,pmRoot:m,globalOptions:l});return}pr(u.hooks),fr(u.commands),gr(u.parsers),hr(u.preflight),re(u.services),yr(u.renderers),On(u.registrations);let p=mt(u.registrations,a,s);d=He(o,s,p,Ei(o,a,p)),Xo(o,a,l,d);let f=await kt({command:a,args:s,options:d,global:l,pm_root:u.pmRoot});l.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${B(f.warnings)}`),s=f.context.args,d=f.context.options,ce(o,d),l=f.context.global;let y={args:[...s],path:l.path};Pt(o,d);let h=await vr({command:a,args:s,options:d,global:l,pm_root:u.pmRoot,decision:_i()});l.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${B(h.warnings)}`),s=h.context.args,d=h.context.options,ce(o,d),l=h.context.global,Pt(o,d);let C=h.decision;await Uo(a,d,u.pmRoot,C),await jo(a,s,d,l,u.pmRoot),await to({command:o,commandPath:a,commandArgs:c.args,commandOptions:d,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:eo(c,[y,{args:s,path:l.path}]),globalOptions:{...l,path:r.path,noExtensions:r.noExtensions}});let O=C.run_extension_migrations?await kc(o,[],()=>Hc(u.registrations.migrations,u.pmRoot)):[];l.profile&&O.length>0&&x(`profile:extensions migration_warnings=${B(O)}`);let E=ic(u.registrations.migrations);Ae={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...d},globalOptions:{...l},pmRoot:u.pmRoot,profileEnabled:!!l.profile,migrationBlockers:E},Oe(void 0),xt({command:a,args:s,options:{...d},global:{...l},pm_root:u.pmRoot}),z=await jn({command:a,pm_version:ze,args:s,options:d,global:l,pm_root:u.pmRoot}),await bc(e),await Sc(a,s,d);let k=await lr(u.hooks,{command:a,args:s,options:{...d},global:{...l},pm_root:u.pmRoot});l.profile&&k.length>0&&x(`profile:extensions hook_warnings=${B(k)}`),C.enforce_mandatory_migration_gate&&rc(a,d,E)}),e.hook("postAction",async()=>{let n=pi();await mn(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await gt(n),await Ie()}))}Jc(w);var Ec=Symbol("pmCliIdempotentTopLevelRegistration");function Kc(e){let t=e;if(t[Ec])return;t[Ec]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let r=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===r||a.aliases().includes(r))?new vi(r):n(o,...i)})}async function Tp(e,t){if(Kc(e),t.setup){let{registerSetupCommands:n}=await up();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await pp(),o=typeof t.targetCommandName=="string"&&ti.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await fp();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await gp();n(e)}}function Ge(e){return e.rawInvocationArgv??e.invocationArgv}function Ip(e){return async t=>{let n=yt(t.errorCode),o=At({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Hr({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:ze,pm_root:e.bootstrapPmRoot,error_code:t.errorCode,error_message:t.errorMessage,exit_code:t.exitCode,error_category:n,command_resolution:o,resolution_stage:t.resolutionStage}),{errorCategory:n,commandResolution:o}}}async function Yc(e){if(e.bootstrapGlobal.noExtensions||ut(e.invocationArgv))return;let t=qe(e.invocationArgv),n=await dn(e.bootstrapPmRoot);if(n&<(n.discovery,t)){let o=await We(e.bootstrapPmRoot,t);Xc(o);return}n&&ln(bi(e.invocationArgv),n,t),re({overrides:[]})}function Xc(e){if(!e){re({overrides:[]});return}re(e.services)}async function Ai(e){await mn(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await gt({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Zc(){await mn(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await gt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Qc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof $)&&(Nn(e.error)||!n))return!1;let o=J(ue(e.error)),i=e.error instanceof $?e.error.exitCode:Ln(t),r=e.error instanceof $||Tr(e.error)?e.error.context:void 0,a=Tc(r,e.invocationArgv,o),s=Cs(o,a),c=nt(e.bootstrapGlobal.lean?Ht(Co(o,i,a)):Co(o,i,a)),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Z(c,p=>`${JSON.stringify(p,null,2)}
|
|
40
|
+
`):c,null,2):ws(o,a,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?ie(`${d}
|
|
41
|
+
`):x(d);let{errorCategory:l,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),u=await cn({command:e.attemptedCommand,error_code:s.code,error_category:l,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:z?.source_context},e.bootstrapGlobal);return await Ai({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:l,commandResolution:m,resolutionStage:"execute"}),u&&(Dn(Mn(e.error,o)),await Ie(Ci)),process.exitCode=i,!0}async function el(e,t){let n=L(e.invocationArgv).commandPathTokens.join(" ")||ko(e.invocationArgv),o=T(n),i=`unknown command '${n}'`,r=P(process.cwd(),e.bootstrapGlobal.path),a=e.bootstrapGlobal.noExtensions?I:await Si(r),s=qe(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await Fo(r,{},Ue(s)),d=await rt({message:i},w,a,{failedExtensions:c},Ge(e)),l=xo(d.message,d.commandName,d.allowedTypes,{unknownCommandExamples:d.unknownCommandExamples,unknownCommandNextSteps:d.unknownCommandNextSteps,attemptedCommand:d.attemptedCommand,normalizedInvocationArgs:d.normalizedInvocationArgs,providedOptionFlags:d.providedOptionFlags,unknownOptionSuggestions:d.unknownOptionSuggestions,suggestedRetryCommand:d.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:u}=await e.emitTelemetryCommandError({command:o,errorCode:l.code,errorMessage:l.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await cn({command:o,error_code:l.code,error_category:m,exit_code:g.USAGE,error_message:l.detail,command_resolution:u,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await Ro({message:i},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:c},Ge(e)):await Ao({message:i},w,a,{failedExtensions:c},Ge(e)),y=bo(f,e.jsonErrors,c);await Ai({errorMessage:i,exitCode:g.USAGE,classificationCode:l.code,errorCategory:m,commandResolution:u,resolutionStage:"parse"}),e.jsonErrors?ie(`${Zn(y)}
|
|
42
|
+
`):x(y),p&&await Ie(Ci),process.exitCode=g.USAGE}async function tl(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=L(e.invocationArgv);return i.requested&&!Fe(w,i.commandPathTokens)?(await el(e,t),!0):(await Zc(),!0)}async function nl(e,t){let n=await rt(e.error,w,I,{},Ge(e)),o=xo(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:r}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await cn({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:r,resolution_stage:"parse",source_context:z?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await Ro(e.error,w,I,e.bootstrapGlobal.lean===!0,{},Ge(e)):await Ao(e.error,w,I,{},Ge(e)),c=await Ks(o.code,e.bootstrapPmRoot,{},Ue(qe(e.invocationArgv))),d=bo(s,e.jsonErrors,c);await Ai({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?ie(`${Zn(d)}
|
|
43
|
+
`):x(d),a&&await Ie(Ci),process.exitCode=g.USAGE}function ol(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return typeof t=="string"&&(t==="commander.version"||t.startsWith("commander."))?!0:String(e.message??"").includes("(outputHelp)")}async function il(e){let t=e.error.code,n=String(e.error.message??"");if(!await tl(e,t,n)){if(t==="commander.version"){await Zc();return}await nl(e,t)}}async function Ri(e){let t=N(e.invocationArgv),n=P(process.cwd(),t.path),o=ye(e.invocationArgv),i={error:e.error,invocationArgv:o,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:A(o)??"<unknown>",emitTelemetryCommandError:Ip({invocationArgv:o,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Yc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Qc(i,Pn(e.error))){if(ol(e.error)){await il(i);return}await Lc({error:e.error,attemptedCommand:i.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:i.emitTelemetryCommandError})}}function $p(e,t,n){let o=n.requested?n.commandPathTokens:F(t),i=V(o);if(i&&!oe(e,[...i.canonical_argv]))throw new Ac(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function Pp(e,t){let n=S(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=S(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=an.get(t[n]),i=t.slice(n).filter(a=>!["--global","--project","--local"].includes(a)),r=o?.find(a=>a.alias.split(" ").every((s,c)=>i[c]===s));r?.lifecycle==="deprecated"&&Reflect.set(e,Rc,r.alias)}function Lp(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Np(e,t){w=zn(ze),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(R(a))&&a.optsWithGlobals().dryRun===!0}),Jc(w,e),ft=null,Ee=null,I=new Map,_r();let n=[...e],o,i;try{let r=fe(e);n=r.argv,La(r.trace),Pp(w,e);let a=Lp(n),s=n.length===0,c=N(n);if(c.authorMissingValue)throw new $("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=ca(c.author),ai(r),i=ta(n);let d=ni(n);await Tp(w,d),mo(w,!0),ii(w,n)?await Vc(w,n):(I=new Map,re({overrides:[]})),ri(n)&&await Dc(w,n),mo(w);let m=L(n);$p(w,n,m),oi(n)&&ns(w,n),Wc(w);let u=await bp(m,c);if(await ec(w,n,u,e))return;if(m.requested&&!Fe(w,m.commandPathTokens))throw new Ac(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||se(n)&&A(n)===void 0){w.outputHelp();return}if(ut(n)){await w.parseAsync(a);return}let f=P(process.cwd(),c.path),y=await U(f),h=await $s(n,f,c.noExtensions,We);await Ua(C=>Zr({pmRoot:f,packages:h?.contextIntentPackages},()=>qi({env:{...process.env,PM_PATH:f},argv:a,cwd:process.cwd()},()=>Hi(y.agent_identity.harness_signals,()=>C(()=>w.parseAsync(a)),{probesEnabled:y.agent_identity?.probes_enabled}))))}catch(r){await Ri({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function fy(e=process.argv.slice(2)){let t=e;try{t=fe(e).argv}catch{}await Di([...e,...t],()=>Mp(e,t))}async function Mp(e,t){let n=yc(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=()=>Ma(N(t).json,async()=>{try{await la(process.env,()=>Np(e,o))}catch(a){await Ri({error:a,invocationArgv:[...e]})}});if(n!==void 0){let a=P(process.cwd(),N(t).path),s=P(process.cwd(),n.path),c=Mi(process.cwd());await St(a,()=>St(s,()=>St(c,r,i),i),i)}else await r()}var gy={activationCommandMatchesProbe:Ho,applyDynamicExtensionRootHelpVisibility:Bc,bootstrapProfileEnabled:bi,buildBootstrapActivationProbe:qe,buildPostActionTelemetryOutcome:pi,buildPmCliRecoveryContext:Tc,buildRuntimeExtensionDiscoverySnapshotCacheKey:ki,buildRuntimeExtensionActivationScope:dt,buildRuntimeExtensionSnapshotCacheKey:jc,buildRuntimeExtensionFilterForProbe:Jo,addRuntimeFieldOption:yi,collectActivationCommandCandidates:Ue,collectExtensionFlagDefinitionsForCommand:tt,collectExtensionFlagDefinitionsForInvocation:mt,collectLeadingCommandArgs:qo,collectParsedActivationCommandArgs:Ko,collectRuntimeFieldLooseFlagDefinitionsForCommand:Fc,commandHasLongOption:Nc,commandHasShortOption:Mc,commandPathNeedsSearchExtensions:Go,commandPathNeedsTemplateExtensions:Xt,describeUnknownError:ue,defaultPreflightDecision:_i,discoveryNeedsActivationForProbe:lt,emitExtensionProfile:Uc,emitExtensionSkippedProfile:ln,emitSettingsReadWarnings:wi,ensureIdempotentTopLevelCommandRegistration:Kc,enforceExplicitRetryForFlagTypos:ai,envFlagEnabled:$c,executeRegisteredRuntimeMigrations:Hc,extractCommandScopedOptions:He,extensionActivationCommands:Yt,extensionCapabilities:ct,extensionNeedsActivationForProbe:Zt,extensionProvidesTemplatesRuntime:Wo,hasAnyCapability:je,hasGlobalExtensionContributions:Bo,handleGenericRunPmCliError:Lc,handleRunPmCliCommanderError:il,handleRunPmCliError:Ri,handleRunPmCliHelpDisplayError:tl,handleRunPmCliKnownError:Qc,handleRunPmCliCommanderUsageError:nl,handleUnknownHelpCommandError:el,inferMissingFieldsFromErrorMessage:Oc,inferPostActionErrorCode:ui,inferPostActionFailureMessage:mi,invocationRequestsVersion:pt,isCommanderError:Nn,loadRuntimeExtensionCommandDescriptorsForRecovery:Si,loadRuntimeExtensionDiscoverySnapshot:dn,loadRuntimeExtensionSnapshot:We,maybeLoadRuntimeExtensions:qc,maybeAttachCreateUpdatePolicyHelpText:xi,maybeLogHandledCliErrorToSentry:cn,matchesStaticExtensionCommand:Kt,normalizeTelemetryCommandResolution:ci,normalizeTelemetryErrorCategory:di,normalizeTelemetryResolutionStage:li,normalizeThrownExitCode:Ln,probeUsesAnyFlag:zo,prepareExtensionServicesForRunPmCliError:Yc,readRecordBoolean:si,readRecordNumber:nn,readRecordString:Se,recordCliReadOutputInvocationProvenance:Yo,registerDynamicExtensionCommandPaths:Vc,registerRuntimeSchemaFieldFlags:Dc,resolveCoreCommandRegistrationSelection:ni,resolveStaticExtensionActivationDecision:Vo,resolveUnknownHelpToken:ko,readThrownExitCode:Pn,runAndClearAfterCommandHooks:gt,runRequiredExtensionCommand:zc,shouldAttachRichHelpTextForInvocation:oi,shouldLogHandledErrorToSentry:Pc,shouldRegisterDynamicExtensionPaths:ii,shouldRegisterRuntimeSchemaFlags:ri,shouldHandleRunPmCliCommanderError:ol,setActiveExtensionHookContextForTest:cp,setActiveRuntimeExtensionCommandDescriptorsForTest:lp,setRecoveredExtensionServices:Xc,toLooseFieldDefinitionType:hi,isImporterOrExporterCommandPath:Zo,validateDynamicExtensionCommandInvocation:ei,wrapProgramActionsForExtensionHandlers:Wc,wrapThrownErrorForSentry:Mn};export{gy as _testOnly,fy as runPmCli};
|
|
44
44
|
//# sourceMappingURL=main.js.map
|