@unbrained/pm-cli 2026.11.23 → 2026.11.25
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/error-guidance.js +5 -5
- package/dist/cli/main.js +5 -5
- package/dist/cli/register-annotations.js +1 -1
- package/dist/cli/runtime/invocation-options.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-4FZH5BTV.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-YYT3MIRF.js → chunk-6OIHST4I.js} +1 -1
- package/dist/cli-bundle/chunks/chunk-7EPYCU7U.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-AEOHUSUI.js → chunk-BVJMVU4Z.js} +68 -68
- package/dist/cli-bundle/chunks/{chunk-2UQU7HRR.js → chunk-C4KIZQHW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-CNUFU454.js +113 -0
- package/dist/cli-bundle/chunks/chunk-CONBVY2O.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-BSRIVYTM.js → chunk-CZEMEPPQ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-DF6A7C32.js +2 -0
- package/dist/cli-bundle/chunks/chunk-FHLOGAGA.js +8 -0
- package/dist/cli-bundle/chunks/chunk-FVY7U3SU.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-F2Z6XLZB.js → chunk-GBVF2ZB3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GZI7ZAB7.js +2 -0
- package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-K34FR5CO.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-D6PDUKUG.js → chunk-KHFUHGL3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-L6VS7F3R.js +2 -0
- package/dist/cli-bundle/chunks/chunk-LOX3VY4T.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-H7JEXRIN.js → chunk-LPW7S5KA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5DUP4AZA.js → chunk-MGJMQSN4.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OS5W4ZG2.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-O7JHS64G.js → chunk-OWK2JL4I.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-SCIPT7WF.js +2 -0
- package/dist/cli-bundle/chunks/chunk-SX76UGEY.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-CFWLQFJM.js → chunk-VA4T37Q4.js} +50 -51
- package/dist/cli-bundle/chunks/chunk-WQOEVGLQ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XHCIOLJP.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-J2PDAVBC.js → chunk-XKWJONAO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-YIGBEY7K.js +2 -0
- package/dist/cli-bundle/chunks/chunk-ZBOQEZ2H.js +33 -0
- package/dist/cli-bundle/chunks/chunk-ZLICQPRG.js +3 -0
- package/dist/cli-bundle/chunks/field-option-collisions-QE65APSD.js +2 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-BPYKN5Q7.js → indexed-receipt-blobs-H3MMNXXG.js} +2 -2
- package/dist/cli-bundle/{focused-chunks/item-revision-YDACCDVY.js → chunks/item-revision-INDHJV6X.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-LCKK4XXB.js +2 -0
- package/dist/cli-bundle/chunks/mutation-actor-KU7BMLUN.js +2 -0
- package/dist/cli-bundle/chunks/mutation-admission-3OMCTQD4.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-L4IBU64P.js → register-list-query-3GV3LBOT.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-GZLF47SX.js +21 -0
- package/dist/cli-bundle/chunks/register-operations-PBJZGCAL.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-ZLJEF6NZ.js +2 -0
- package/dist/cli-bundle/chunks/runtime-schema-Y4SHTEXL.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-6MR32OOC.js → settlement-hook-ESAAEBRM.js} +2 -2
- package/dist/cli-bundle/chunks/stage-3WIZBD4N.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3Y5PTQ2F.js +27 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Y2ESLKCF.js → chunk-4LQL4EO6.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-RIE3SJSE.js → chunk-4SX2BN4V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZHWPCVQL.js → chunk-5RBC4WSE.js} +39 -39
- package/dist/cli-bundle/focused-chunks/chunk-7SSGTGZO.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-A4R57E4K.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-BOIMP2AR.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-BYQK5DGH.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-C3FEDTSD.js +44 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAOKVKWW.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-JOKRDFMQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MB56Y4M6.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-A6VEMCRR.js → chunk-NGFDPEP7.js} +1 -1
- package/dist/cli-bundle/focused-chunks/chunk-OCKKIECS.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-PKX2EHE3.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXC2EO3E.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-TQIKDFOD.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-TRL4JDWX.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-IROZDIDX.js → chunk-UWWAVXG4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VMYVN36N.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-VU2PH4PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-WL2R7T5G.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-WVA5KOXF.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QQIIMMFU.js → chunk-X4EWD6TL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XKLBTDJ7.js +100 -0
- package/dist/cli-bundle/focused-chunks/chunk-YYEWIKNI.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-ZLRRII55.js +2 -0
- package/dist/cli-bundle/focused-chunks/field-option-collisions-5ROXGUME.js +2 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-EGEJMG3G.js → indexed-receipt-blobs-PG2VJ3MB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-revision-KYMSQVZE.js +2 -0
- package/dist/cli-bundle/focused-chunks/item-transaction-I4HLVHEJ.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-actor-GGOQKAE6.js +2 -0
- package/dist/cli-bundle/focused-chunks/mutation-admission-OS36ZCMH.js +2 -0
- package/dist/cli-bundle/focused-chunks/runtime-schema-YXPYDD2C.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-FMLGKG7J.js → settlement-hook-4MGRERCT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-4ZFWJUKO.js +2 -0
- package/dist/cli-bundle/main.js +26 -26
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +4 -4
- 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 +63 -63
- 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 +12 -12
- package/dist/core/profile/profile-lint.d.ts +1 -1
- package/dist/core/profile/profile-lint.js +1 -1
- package/dist/core/schema/fields-file.js +2 -2
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/schema/runtime-schema.d.ts +2 -0
- package/dist/core/schema/runtime-schema.js +1 -1
- package/dist/core/shared/command-line.d.ts +54 -4
- package/dist/core/shared/command-line.js +1 -1
- package/dist/core/shared/errors.d.ts +9 -0
- package/dist/core/shared/secret-rules.js +5 -5
- package/dist/core/shared/url-credentials.d.ts +16 -3
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/core/store/item-store.d.ts +26 -4
- package/dist/core/store/item-store.js +1 -1
- package/dist/sdk/command-line.d.ts +1 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/extension/command-options.d.ts +26 -1
- package/dist/sdk/extension/command-options.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +21 -1
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/ownership-source.d.ts +15 -1
- package/dist/sdk/ownership-source.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-contracts.d.ts +11 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
- package/dist/sdk/schema/field-flag-spelling.js +2 -0
- package/dist/sdk/schema/field-option-collisions.js +1 -1
- package/docs/AGENT_GUIDE.md +2 -2
- package/docs/COMMANDS.md +1 -1
- package/docs/CONFIGURATION.md +1 -0
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MUTATION_INTEGRITY.md +97 -8
- package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
- package/docs/SDK.md +60 -4
- package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +17 -4
- package/marketplace.json +1 -1
- package/package.json +1 -1
- 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-5WZZ5XEN.js +0 -3
- package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +0 -31
- package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +0 -2
- package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +0 -2
- package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +0 -33
- package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +0 -115
- package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +0 -2
- package/dist/cli-bundle/chunks/chunk-OPJF254V.js +0 -9
- package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +0 -2
- package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +0 -2
- package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +0 -125
- package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +0 -8
- package/dist/cli-bundle/chunks/item-revision-FMD4KWBB.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +0 -2
- package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +0 -2
- package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +0 -21
- package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +0 -2
- package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +0 -13
- package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +0 -27
- package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +0 -102
- package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +0 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +0 -2
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 ja(e,t){return t==="detailed"?fl(e):pl(e)}function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var gl={cal:"calendar",ctx:"context"};function hl(e,t){return e.commands.find(n=>n.name()===t)??null}function yl(e,t){let n=e;for(let o of t){let i=hl(n,o);if(!i)return null;n=i}return n}function no(e,t,n,o){let i=yl(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",ja(n,o))}function oo(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var ye={"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 list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"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 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 L){let n=ye[e];n&&(ye[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Ie={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."]},Ua=K.filter(e=>e.lifecycle==="deprecated");for(let e of Ua){let t=ye[e.alias];ye[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Ie,...Object.values(ye)])e.examples=e.examples.map(t=>{for(let n of Ua){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function _l(e){let t=j(e??"");return t?gl[t]??t:""}function io(e){let t=_l(e);return t?ye[t]??Ie:Ie}function qa(e,t){let n=io(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Da(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function wl(){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(" ")} (${Si(n)})`)].join(`
|
|
6
|
-
`)}function
|
|
7
|
-
`,s=t.visibleCommands(e);for(let c of s)he(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)he(c)==="core"&&(n.add(c),
|
|
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 xa}from"./chunks/chunk-HZZLSBIJ.js";import"./chunks/chunk-SLFRSZK6.js";import{A as zn,C as wa,D as va,F as Ca,G as Wn,a as Dn,d as $,e as D,f as P,g as N,h as S,i as zr,n as Xe,o as Wr,p as Yr,t as Xr,u as pa,v as fa,w as ga,x as ha,y as ya,z as _a}from"./chunks/chunk-GZI7ZAB7.js";import{Wa as ua,f as qr,k as Hr}from"./chunks/chunk-BVJMVU4Z.js";import{A as oa,B as ia,C as $t,F as ra,G as aa,H as Q,I as sa,Qc as da,Rd as ma,b as Oe,ca,l as Kr,r as qn,s as Hn,t as ea,u as ta,v as na,w as Gn,x as Pt,y as Qe}from"./chunks/chunk-OS5W4ZG2.js";import"./chunks/chunk-MGJMQSN4.js";import"./chunks/chunk-L6VS7F3R.js";import"./chunks/chunk-ZLICQPRG.js";import{ea as la,k as Gr}from"./chunks/chunk-VA4T37Q4.js";import"./chunks/chunk-CZEMEPPQ.js";import"./chunks/chunk-KHFUHGL3.js";import"./chunks/chunk-AA52P34H.js";import"./chunks/chunk-LPW7S5KA.js";import"./chunks/chunk-ZBOQEZ2H.js";import"./chunks/chunk-6H36ZHMI.js";import"./chunks/chunk-WQOEVGLQ.js";import{Ka as Qr,a as Br,b as Vr,d as Jr,ma as Tt,na as It,oa as jn,pa as Ze,qa as E,ra as Zr,sa as Un,wa as z}from"./chunks/chunk-7EPYCU7U.js";import{A as Dr,B as jr,C as Fn,D as Ur,n as Mn,p as Lr,u as Ln,w as Fr}from"./chunks/chunk-DF6A7C32.js";import"./chunks/chunk-CONBVY2O.js";import"./chunks/chunk-PZA7QECY.js";import{$b as En,Ac as Pn,Ad as Nn,Bc as Er,Bd as Nr,Cc as Ar,Cd as Mr,Dc as Rr,Ec as $n,Fc as Or,Gc as Re,Jc as Tr,K as Pi,Nc as Ir,fc as wr,ic as vr,jc as Cr,lc as xr,md as Ke,pc as br,pd as Pr,qb as kt,qc as kr,rb as _r,rc as An,tc as Sr,uc as me,vc as Rn,vd as $r,wc as On,xc as Tn,yc as In,zc as St}from"./chunks/chunk-FVY7U3SU.js";import{n as bt,q as gr,r as hr,u as Ae,v as F,w as yr}from"./chunks/chunk-C4KIZQHW.js";import{$ as mn,$d as xn,Af as x,Ah as re,Bh as dr,Ca as Be,Ch as kn,Dh as le,Eh as mr,Fh as vt,Ia as fn,Ih as Ee,Jh as de,Mg as tr,Mh as ur,Na as _t,Nh as Ct,Qa as gn,S as dn,Sd as yn,Td as _n,Ud as Li,V as ce,Vd as Fi,We as Bi,Wf as Ki,Wg as nr,Wh as Sn,X as Ai,Xd as wn,Xf as Yi,Xh as xt,Y as yt,Yd as vn,Yf as Xi,Yg as or,Yh as pr,Zd as Cn,Zf as Zi,Zh as fr,_e as Vi,aa as Ri,ba as I,cc as Ni,da as Oi,dc as Mi,ea as X,jh as ir,kh as Ve,lf as Z,mh as Je,nc as wt,nh as rr,oe as Di,pe as ji,r as Ge,re as Ui,se as qi,te as Hi,ue as Gi,uf as Ji,va as Se,ve as zi,vf as ie,wa as ze,we as Wi,wg as Qi,wh as ar,xg as er,xh as sr,ya as We,yh as cr,zf as bn,zh as lr}from"./chunks/chunk-CNUFU454.js";import"./chunks/chunk-K34FR5CO.js";import{E as Rt,F as ue,lb as Ot,mb as H,p as Et,r as Ye,s as At}from"./chunks/chunk-4FZH5BTV.js";import{G as Ti,H as Ii,I as J,Y as $i,h as L,j as B,k as q,m as K,n as ln,o as V,p as Si,x as _,y as un,z as pn}from"./chunks/chunk-XHCIOLJP.js";import{Q as hn,a as Ei}from"./chunks/chunk-SX76UGEY.js";import{A as g,B as ht,C as T,E as Y}from"./chunks/chunk-6OIHST4I.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as zc}from"node:async_hooks";var Te=new zc;function ba(e){let t=Te.getStore();return t===void 0?e:t!==null}function pe(e,t=`warning:${e}`){let n=Te.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):x(t)}function et(e){let t=Te.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 Bn(e){if(!Te.getStore()?.size)return e;let{token_accounting:t,...n}=et(JSON.parse(e));return JSON.stringify(t===void 0?n:Z(n,o=>`${JSON.stringify(o,null,2)}
|
|
2
|
+
`),null,2)}async function ka(e,t){if(!e){await Te.run(null,t);return}let n=new Map;await Te.run(n,async()=>{await t(),n.size>0&&ie(`${JSON.stringify(et({type:"warning"}))}
|
|
3
|
+
`)})}import{AsyncLocalStorage as Wc}from"node:async_hooks";var Vn=new Wc,Sa=new WeakMap;function Bc(e){let t=e.outputFormat!==void 0?["--output-format",e.outputFormat]:e.json===!0?["--json"]:[];return{scopeArgs:Se(e),outputArgs:t}}var Ea=new WeakMap;function Vc(e,t){let n=e.registeredArguments.findIndex(o=>o.name()==="id");if(!(n===-1||e.name()==="plan"&&t[0]==="create"))return t[n]}function Jn(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 Kn(e){if(e.expectHash===void 0)return;let t=Mn(e.expectHash),n=e.commandPath.trim().toLowerCase();if(Fn(n,e.commandOptions),e.rewritten===!0)throw Ln();let o=Vn.getStore();if(o===void 0)throw new TypeError("--expect-hash was parsed outside an invocation revision scope");let i=await Lr(e.pmRoot,t,Vc(e.command,e.commandArgs));Xi(o,e.pmRoot,i),Ea.set(o,n),e.globalOptions!==void 0&&Sa.set(o,Bc(e.globalOptions))}function Yn(e,t,n){let o=Vn.getStore(),i=o===void 0?void 0:Ea.get(o);if(i!==void 0){if(Jn(e,[t]))throw Ln();Fn(i,n)}}function Aa(e,t){if(t!==void 0)throw Mn(t),Ur(e)}function Jc(e){for(let t of Zi(e).unchecked)pe(jr(t))}async function Kc(e,t){return e.pmRoot===void 0?t:Fr(t,e.pmRoot,Sa.get(e))}async function Ra(e){let t=Ki();try{await e(n=>Vn.run(t,()=>Yi(t,n)))}catch(n){throw await Kc(t,n)}Jc(t)}import{Command as fi,CommanderError as mc}from"commander";function W(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function fe(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=fe(o);i&&(t.has(i)||n.push(i),t.add(i))}return n}var Xn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Nt=new Set(["--full","--brief","--compact"]);function Yc(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 Zn(e,t=S([...e])){let n=H(t),o=new Set([...Br,...Vr,...Jr].flatMap(s=>s.keys.map(c=>`--${c.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),i=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,s.flag]))),r=new Map([...ue,...n].flatMap(s=>[s.flag,...s.aliases??[]].map(c=>[c,Yc(s,o)])));for(let s of Xn)r.set(s,!0);for(let s of Nt)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 l=c.split("=")[0];if(!r.has(l)&&!c.includes("="))return;let d=r.get(l)===!0&&!c.includes("=");a.set(s,{flag:i.get(l)??l,consumesValue:d}),d&&(s+=1)}return a}function Xc(e){let t=Zn(e);return t===void 0?void 0:new Map([...t].map(([n,{flag:o}])=>[n,o]))}function Oa(e,t,n){let o=new Set;for(let[i,r]of t)n.has(r)&&(o.add(i),Xn.has(r)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,r)=>!o.has(r))}function Zc(e,t){let n=t.find(i=>Nt.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>Nt.has(i));return o.length===1?o[0]:n}function Ta(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=Xc(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(([l,d])=>d==="--fields")?.[0]??-1;if(c<0)return i;a=Oa(e,r,new Set(["--fields"])),a.splice(c,0,"--fields",o[s+1])}else{let s=Zc(r,o);if(s===void 0||![...r.values()].includes(s))return i;let c=new Set([...Xn,...Nt].filter(l=>l!==s));a=Oa(e,r,c)}return{...n,suggested_retry:_(a),suggested_retry_args:a}}var Ia=new Set(qi);function Qc(e){return e.includes("@")&&e.includes(":")}function el(e){let t=N([...e]);if(t===void 0)return;let n=e[t+1],o=n===void 0||n.startsWith("-")?void 0:`${e[t]} ${n}`;return o!==void 0&&Ot(o)?o:e[t]}function tl(e){let t=Oe(e??"",H(e));return new Set(t.filter(n=>n.takes_value).flatMap(n=>[n.flag,...n.aliases??[]]))}function Pa(e,t,n,o=[],i=()=>!1){if(t!==Ui)return n;let r=n===void 0?void 0:{...n,suggested_retry:void 0,suggested_retry_args:void 0},a=el(e),s=Zn(e,a);if(s===void 0||o===null||e.some(Qc)||i())return r;let c=nl(e,s,tl(a));if(c===void 0||c.size===0)return r;let l=[...o,...e.filter((d,m)=>!c.has(m))];return{...n,suggested_retry:_(l),suggested_retry_args:l}}function nl(e,t,n){let o=new Set;for(let[r,{flag:a,consumesValue:s}]of t){if(!Ia.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)&&Ia.has(r.split("=",1)[0]))?void 0:o}var ol=new Set(["normalized_args","suggested_retry_args","provided_fields","parsed_positionals","normalizedInvocationArgs","providedOptionFlags","suggestedRetryArgs"]),il=new Set(["code","original_code","type","recovery_mode","option_scope","diagnostic_class"]),$a=`URL credentials in this invocation were replaced with ${un}; restore them before replaying any command shown here.`;function rl(e){return`URL credentials in this invocation were replaced with ${un}. 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 ge(e){return e.map(pn)}function al(e,t){return e==="producer"||t==="details"?"producer":e==="schema"&&t==="recovery"?"schema":"typed"}function sl(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 cl(e,t,n){let o=J(n?pn(e):e);return o!==e&&(t.changed=!0),o}function ll(e,t,n){return e!=="schema"?!1:t==="urlCredentialsRejected"||il.has(t)&&typeof n=="string"}function Qn(e,t,n,o){if(typeof e=="string"&&t.ownSteps.has(e))return e;if(typeof e=="string")return cl(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(Qn(s,t,n,o));return a}let r={};t.copies.set(e,r);for(let[a,s]of Object.entries(e)){if(ll(o,a,s)){r[a]=s;continue}let c=o==="producer"?sl(a,r,t):a;r[c]=Qn(s,t,n||ol.has(a),al(o,a))}return r}function Mt(e){let t=e.urlCredentialsRejected,n=t===void 0?$a:rl(t.source),o=new Set([$a,n]),i={copies:new Map,changed:!1,ownSteps:o},r=Qn(e,i,!1,"schema");if(!i.changed&&!Ii())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 dl="project_schema_field_requires_declared_flag";function ml(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 Na(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==dl||n===void 0||i===void 0)return o;let r=ml(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(r.length!==1)return o;let[a]=r,s=a.assignment.trim(),c=s.slice(s.indexOf("=")+1),l=[...e.slice(0,a.index),i,c,...e.slice(a.index+a.width)];return{...o,suggested_retry:_(l),suggested_retry_args:l}}var eo=Kr;function ul(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 Ma(e,t,n,o,i=[]){let r=o?.suggested_flags?.[0];if(t!==eo||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=N([...e]);if(s===void 0||i===null)return a;let c=o.suggested_retry_args,l=ul(e,s,c[0],n,r);if(l.length!==1)return a;let{index:d,width:m}=l[0],u=[...e.slice(0,d),r,...e.slice(d+m)];if(!pl(u,d,n,r,c))return a;let p=[...i,...u];return{...o,suggested_retry:_(p),suggested_retry_args:p}}function pl(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 to="close_validation_missing_fields";function fl(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 gl(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 La(e,t,n,o=[]){let i=n?.missing;if(t!==to||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=N([...e]);if(s===void 0||o===null)return a;let c=H(e[s].trim().toLowerCase()),l=i.map(f=>c.find(y=>y.flag===f||y.aliases?.includes(f)===!0));if(l.some(f=>f===void 0))return a;let d=new Set(l.flatMap(f=>[f.flag,...f.aliases??[]])),m=gl(r,i.length),u=fl(e,s,d,[...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 Fa(e,t){await Nr(e,{ok:t.ok,error:t.error,result:de(),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 Da(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await Bi({pmRoot:e.pmRoot,result:de()})}catch(o){t=o}let n=await F(e.pmRoot);if(await Vi({pmRoot:e.pmRoot,author:wt(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}var ja=new WeakMap;function Lt(e,t){ja.set(e,t)}function he(e){return ja.get(e)}function Ua(e){return e.length>0?[e[0]]:[]}function hl(e){let t=["","Intent:",` ${e.why}`],n=Ua(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 yl(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"?yl(e):hl(e)}function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var _l={cal:"calendar",ctx:"context"};function wl(e,t){return e.commands.find(n=>n.name()===t)??null}function vl(e,t){let n=e;for(let o of t){let i=wl(n,o);if(!i)return null;n=i}return n}function no(e,t,n,o){let i=vl(e,t.split(" ").filter(r=>r.length>0));i&&i.addHelpText("after",qa(n,o))}function oo(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var ye={"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 list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"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 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 L){let n=ye[e];n&&(ye[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Ie={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."]},Ha=K.filter(e=>e.lifecycle==="deprecated");for(let e of Ha){let t=ye[e.alias];ye[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Ie,...Object.values(ye)])e.examples=e.examples.map(t=>{for(let n of Ha){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Cl(e){let t=j(e??"");return t?_l[t]??t:""}function io(e){let t=Cl(e);return t?ye[t]??Ie:Ie}function Ga(e,t){let n=io(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Ua(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function xl(){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(" ")} (${Si(n)})`)].join(`
|
|
6
|
+
`)}function bl(e,t,n,o){let i=new Set(ra);e.configureHelp({visibleCommands(a){let s=t.visibleCommands(a);return n?s.filter(c=>(he(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 kl(e,t,n,o){let i=new Set(sa("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)he(c)===void 0&&(c.name()==="help"||i.has(c.name()))&&n.add(c);for(let c of s)he(c)==="core"&&(n.add(c),aa(a()).within_budget||n.delete(c))}function za(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ae(t),i=new Set;bl(e,n,o,i);let r=oo(t),a=qa(Ie,r);e.addHelpText("after",a),o&&e.addHelpText("after",xl()),kl(e,n,i,a);for(let[d,m]of Object.entries(ye))no(e,d,m,r);let s=j(P(t).commandPathTokens.join(" ")),c=Ye(s);if(c){no(e,c.parent,{why:c.description,examples:[c.example],tips:[`Action path: pm ${c.command}`,At(c.accepted_flags)]},r);return}let l=Et.filter(({parent:d})=>d===s);l.length>0&&no(e,s,{why:`Dispatches one declared positional action: ${l.map(({action:d})=>d).join("|")}.`,examples:l.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <action> --help --json.`]},r)}function ro(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 L){if(t&&!L.some(l=>l.canonical.startsWith(`${o} `)))continue;let r=e.commands.findIndex(l=>l.name()===n);if(r<0)continue;let a=e.commands[r],s=e;for(let l of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===l)??s.command(l).description(`Discover ${l} operations.`);let c=i[i.length-1];if(s.commands.some(l=>l.name()===c))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(r,1),a.name(c),Lt(a,Q(o)),s.enablePositionalOptions(),s.addCommand(a)}}function Dt(e){let{title:t,...n}=e;vn(n.why)&&delete n.why,wn(n.required)&&delete n.required;let o=Cn(n.examples);o.length>0?n.examples=o:delete n.examples;let i=xn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var Sl=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function El(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Sl.has(e.code)}function Za(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:Za(e.code)}}var Pe={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Wa={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ba={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Ft={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Al={guide:Pe,shell:Pe,completion:Pe,"completion-statuses":Pe,"completion-tags":Pe,"completion-types":Pe,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Wa,cal:Wa,reindex:Ba,"search-advanced":Ba,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Ft,"dedupe-audit":Ft,"dedupe-merge":Ft,normalize:Ft};function Rl(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Al[t]}function co(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ol(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 Tl(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 ao(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Qa(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=Qa(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=Ol(n);o&&(e[t]=o)}function Il(e,t){if(!xr(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 es=["retry_after_ms","waited_ms","owner_handoffs"];function Pl(e,t){for(let n of es)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function $l(e,t){for(let n of es){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function ve(e){if(!e||typeof e!="object")return;let t={};Il(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),ao(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),ao(t,"suggested_retry",e.suggested_retry),te(t,"suggested_retry_args",e.suggested_retry_args),$l(t,e);let n=Tl(e.fallback_candidates);return n&&(t.fallback_candidates=n),ao(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function so(e,t,n){n&&e.push(` ${t}: ${n}`)}function _e(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Nl(e,t,n){let o=t?.slice(0,n).map(i=>/^[\p{L}\p{N}._:/@=-]+$/u.test(i)?i:JSON.stringify(i));_e(e,"allowed_values",o,", "),t&&t.length>n&&e.push(` allowed_values_omitted: ${t.length-n} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function Ml(e,t){let n=ve(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(so(o,"suggested_retry",n.suggested_retry),so(o,"attempted_command",n.attempted_command),_e(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(_e(o,"provided_fields",n.provided_fields,", "),_e(o,"missing",n.missing,", "),_e(o,"missing_required_fields",n.missing_required_fields,", "),_e(o,"suggested_flags",n.suggested_flags,", "),Nl(o,n.allowed_values,t),_e(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}`),Pl(o,n),so(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 Va=120;function Ll(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>Va?`${n.slice(0,Va).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})${jl(e.claimActivity)}`}function Fl(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 Dl(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 jl(e){if(e===void 0)return"";let t=`${e.stale_policy.setting}=${e.stale_policy.threshold_hours}`,n=Dl(e);if(n==="unknown"){let o=Number.isFinite(e.idle_hours)?`, last recorded activity ${e.idle_hours}h ago`:"";return`; activity unknown under ${t} (${Fl(e)}${o})`}return`; idle ${e.idle_hours}h, ${n} under ${t}`}function Ul(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||!wn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...co("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=Ll(e);return o!==void 0&&n.push("",o),n}function ql(e,t){let n=[];e.why&&!(t&&vn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?Cn(e.examples):e.examples??[];o.length>0&&n.push("",...co("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...co("Verification errors:",i)),n.push(...Hl(e)),n}function Hl(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 Gl(e,t={}){return ts(e,t,8)}function ts(e,t,n){let o=t.lean===!0,i=[...Ul(e,o),...ql(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=Ml(o?xn(r):r,n);return a.length>0&&(i.push(""),i.push(...a)),i.join(`
|
|
9
|
+
`)}var zl="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",Wl=400,Ja=320;function Bl(e){let t=ve(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=Wl&&(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 Ka(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 $e(n,e.partialLegalDomainNotice)}function Vl(e,t={}){let n=Gl(e,t),o=_n("error").default_max_estimated_tokens_by_format.text,i=u=>yn(Buffer.byteLength(u,"utf8"))<=o;if(i(n))return n;let r={...e,why:void 0},a=$e(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:Bl(e.recovery)};c.nextSteps=Ka(e,c);let l=Array.from(e.happened),d={...c,examples:void 0,happened:l.length>Ja?`${l.slice(0,Ja).join("")}...`:e.happened},m={code:e.code,type:e.type,title:e.title,happened:d.happened,required:e.required,nextSteps:$e([],e.partialLegalDomainNotice)};m.nextSteps=Ka(e,m);for(let[u,p]of[[r,8],[s,8],[c,3],[d,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=`${ts(u,t,p)}
|
|
10
10
|
|
|
11
|
-
${Dl}`;if(i(f))return f}return n}function Hl(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 es(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),Hl(e,t),bl(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 Gl(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return D([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 zl(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 Wl(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=D(e.recovery?.normalized_args??[]),o=B(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=Gl(e,i),a=zl(e,i,r);return{surface:r??e.recovery?.missing?.[0]??zn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Bl(e,t){let n=es({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Wl(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 lo(e,t){let n=Mt(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 Mi(Vl(Bl(n,t),r),{diagnosticClass:r})}function Vl(e,t){if(e.details===void 0)return e;let n=_n(t).default_max_estimated_tokens_by_format.json;if(yn(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:yr.max_bytes}}}function mo(e){return es({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function jt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Jl(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 we(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 Ja(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Kl(e){return zn(e?.normalized_args)}function Yl(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 Xl(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 Zl(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 Ql(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 ed(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?Zl(o):void 0)??e.title}function td(e){let t=wr(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var nd=400;function od(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=nd&&t.push(o)}return t}function id(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=od(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 rd(e,t,n){let o=ve(t),i=o&&e?ve({...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=jt(t),i=tt(n.code,e.code),r=tt(n.type,Ya(i)),a=we(n.examples)??e.examples,s=we(n.nextSteps)??e.nextSteps,c=id(n.recovery),l=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,d=we(n.verification_errors)??e.verificationErrors,m=rd(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:ed(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:Ql(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,...td(n)}}function ad(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=Ri(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 sd(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 ld(e,t,n){if(!t.includes("is locked"))return null;let o=Xa(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 md(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=tt(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function pd(e,t,n){if(!ud(t,n))return null;let o=ve(n?.recovery),i=Kl(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??Yl(t),s=ve({...o,allowed_values:o?.allowed_values??a}),c=Xl(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 uo(e,t){let n=jt(e),o=ad(e,n,t)??sd(e,n,t)??cd(e,n,t)??ld(e,n,t)??dd(e,n,t)??md(e,n,t)??pd(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 fd(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 hd(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function po(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=po(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:hd(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return ve({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function $e(e,t){return!t||e.includes(t)?e:[...e,t]}var yd=new Set(["--add","--add-json","--remove"]),_d=new Set(["command","cmd","path"]);function wd(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(yd.has(o))return o}}function vd(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"||!_d.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 Cd(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=po(o?.providedOptionFlags),l=[r],d=fd(t,r,n),m=s?$e(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?$e(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?$e(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:l})})}function xd(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 bd(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 kd={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 Sd(e){let t=we(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Ed(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:Ad(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,ns(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 ts=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function Ad(e,t){if(t===void 0||!ts.includes(e.split("=",1)[0]))return;let n=ua(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${pa(n)}.`}function Rd(e,t,n){let o=fa(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...ts,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function ns(e){return/\s/u.test(e)}function Od(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=[...D(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function Td(e,t,n){if(ns(t))return Od(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=Rd(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(ga(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=D(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function Id(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=po(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=Td(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return bd(r,n,a);let l=Sd(i),d=Ed(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 ${V(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:kd[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:G(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 Pd(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:Ja([t.installCommand,...n]),nextSteps:Ja([r,...a]),recovery:G(i)})}function $d(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=we(t?.unknownCommandExamples),r=we(t?.unknownCommandNextSteps),a=Sl(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))?Pd(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 Nd(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=we(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 ${V(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 Md(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=wd(o);if(!i)return null;let r=vd(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 Ld=new Set(["comments","docs","files","learnings","notes","test"]);function Fd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Pi(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 Dd(e,t,n){if(!/too many arguments/i.test(e)||!Ld.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:G(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var jd=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"]),Ka=new Set(["context","ctx"]);function Ud(e,t,n){if(!/too many arguments/i.test(e)||!Ka.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>Ka.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(jd.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:G(n,{suggested_retry:c})})}function fo(e,t,n,o){let i=jt(e),r=Cd(i,t,n,o)??xd(i,t,o)??Id(i,t,o)??$d(i,o)??Nd(o)??Dd(i,t,o)??Md(i,t,o)??Fd(i,t,o)??Ud(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 os(e,t,n={}){let o=Mt(uo(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
|
+
${zl}`;if(i(f))return f}return n}function Jl(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 ns(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),Jl(e,t),El(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 Kl(e,t){if(e.flag)return e.flag;let n=i=>{let r=i.split("=",1)[0];return D([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 Yl(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 Xl(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=D(e.recovery?.normalized_args??[]),o=B(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,r=Kl(e,i),a=Yl(e,i,r);return{surface:r??e.recovery?.missing?.[0]??zn(i)??"command",...a!==void 0?{rejected_value:a}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Zl(e,t){let n=ns({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Xl(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 lo(e,t){let n=Mt(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 Li(Ql(Zl(n,t),r),{diagnosticClass:r})}function Ql(e,t){if(e.details===void 0)return e;let n=_n(t).default_max_estimated_tokens_by_format.json;if(yn(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:wr.max_bytes}}}function mo(e){return ns({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function jt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function ed(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 we(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 Ya(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function td(e){return zn(e?.normalized_args)}function nd(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 od(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 id(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 rd(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 ad(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?id(o):void 0)??e.title}function sd(e){let t=Cr(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}var cd=400;function ld(e){let t=[];for(let n of e.slice(0,8)){let o=JSON.stringify(n);Buffer.byteLength([...t,o].join(", "),"utf8")<=cd&&t.push(o)}return t}function dd(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=ld(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 md(e,t,n){let o=ve(t),i=o&&e?ve({...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=jt(t),i=tt(n.code,e.code),r=tt(n.type,Za(i)),a=we(n.examples)??e.examples,s=we(n.nextSteps)??e.nextSteps,c=dd(n.recovery),l=c?[...s?.slice(0,1)??[],c,...s?.slice(1)??[]]:s,d=we(n.verification_errors)??e.verificationErrors,m=md(e.recovery,n.recovery,c!==void 0);return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:r,title:ad(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:rd(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,...sd(n)}}function ud(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=Ri(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 pd(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 fd(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 gd(e,t,n){if(!t.includes("is locked"))return null;let o=Qa(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 hd(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 yd(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 _d(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 wd(e,t,n){if(!_d(t,n))return null;let o=ve(n?.recovery),i=td(o),r=i?`pm ${i} --help`:"pm <command> --help",a=n?.recovery?.allowed_values!==void 0?[]:n?.allowed??nd(t),s=ve({...o,allowed_values:o?.allowed_values??a}),c=od(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 uo(e,t){let n=jt(e),o=ud(e,n,t)??pd(e,n,t)??fd(e,n,t)??gd(e,n,t)??hd(e,n,t)??yd(e,n,t)??wd(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 vd(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 Cd(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function xd(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function po(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=po(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:xd(o),r=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return ve({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:r,suggested_retry_args:e?.suggestedRetryArgs,...t})}function $e(e,t){return!t||e.includes(t)?e:[...e,t]}var bd=new Set(["--add","--add-json","--remove"]),kd=new Set(["command","cmd","path"]);function Sd(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(bd.has(o))return o}}function Ed(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"||!kd.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 Ad(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let r=Cd(i[1]),a=r.startsWith("--type"),s=o?.suggestedRetryCommand,c=po(o?.providedOptionFlags),l=[r],d=vd(t,r,n),m=s?$e(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?$e(u,`Replay with preserved arguments: ${s}`):u,f=c&&c.length>0?$e(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:l})})}function Rd(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 Od(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 Td={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 Id(e){let t=we(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Pd(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:$d(e,t),r.length?`${e} is accepted by ${r.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,is(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 os=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function $d(e,t){if(t===void 0||!os.includes(e.split("=",1)[0]))return;let n=fa(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${ga(n)}.`}function Nd(e,t,n){let o=ha(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...os,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function is(e){return/\s/u.test(e)}function Md(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=[...D(e.filter((i,r)=>r!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function Ld(e,t,n){if(is(t))return Md(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=Nd(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(ya(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=D(i.filter((s,c)=>c!==r));return{retryCommand:_(a),suggestedRetryArgs:a}}function Fd(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},r=o[1],a=po(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:c}=Ld(i,r,t);if(t==="update"&&(r==="--file"||r==="--doc"))return Od(r,n,a);let l=Id(i),d=Pd(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 ${V(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:Td[l.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:r,value:r,examples:m,nextSteps:d,recovery:G(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 Dd(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:Ya([t.installCommand,...n]),nextSteps:Ya([r,...a]),recovery:G(i)})}function jd(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=we(t?.unknownCommandExamples),r=we(t?.unknownCommandNextSteps),a=Rl(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))?Dd(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 Ud(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=we(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 ${V(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 qd(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=Sd(o);if(!i)return null;let r=Ed(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 Hd=new Set(["comments","docs","files","learnings","notes","test"]);function Gd(e,t,n){if(!/too many arguments/i.test(e))return null;let o=Pi(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 zd(e,t,n){if(!/too many arguments/i.test(e)||!Hd.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:G(n,{parsed_positionals:[{role:"transposed_subcommand",value:r},{role:"item_id",value:s}],suggested_retry:c})})}var Wd=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"]),Xa=new Set(["context","ctx"]);function Bd(e,t,n){if(!/too many arguments/i.test(e)||!Xa.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(l=>Xa.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(Wd.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:G(n,{suggested_retry:c})})}function fo(e,t,n,o){let i=jt(e),r=Ad(i,t,n,o)??Rd(i,t,o)??Fd(i,t,o)??jd(i,o)??Ud(o)??zd(i,t,o)??qd(i,t,o)??Gd(i,t,o)??Bd(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 rs(e,t,n={}){let o=Mt(uo(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
|
+
`):as(o,n)}function as(e,t){let n=Mt(e),o=a=>Fi(Vl(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 ss(e,t){return mo(uo(e,t))}function go(e,t,n){return lo(uo(e,n),t)}function cs(e,t,n,o,i={}){let r=fo(e,t,n,o);return as(r,i)}function ho(e,t,n,o){return mo(fo(e,t,n,o))}function Ut(e,t,n,o,i){return lo(fo(e,t,n,i),o)}function ls(e,t){let n=ds(e);return lo(n,t)}function ds(e){let t=jt(e);return ed(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 ms(e){return mo(ds(e))}var nt=Ei.join("|"),Vd={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"},Jd={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"]}},us=["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 Kd(e,t){let n=Jd[e];if(!n)return[];let o=W(t);for(let[i,r]of Object.entries(n))if(W(i)===o)return r;return[]}function yo(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,...l}=JSON.parse(e),d={...l,...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?d:Z(d,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 _o(e){return P(e).commandPathTokens[0]??S(e)??"<command>"}function
|
|
25
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function
|
|
26
|
-
`):c,null,2)}async function
|
|
24
|
+
${i}`}function _o(e){return P(e).commandPathTokens[0]??S(e)??"<command>"}function ys(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let r=j(E(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=j(i),a=r.split(" ").some(s=>s.startsWith("_"));r.length>0&&!a&&n.add(r)}return[...n].sort((i,r)=>i.localeCompare(r))}function ps(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=gn(s,o,r);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function fs(e){return W(e).slice(2).replace(/-/g,"")}function wo(e){return _(e)}function Yd(e){let t=V(e)?.canonical??ln[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=Vd[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function gs(e){let t=la(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Xd(e,t){let n=gs(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 l=gs(c??"");l.length>0&&r.add(l)}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 ot(e,t){let n=new Set,o=t??H(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 Zd(e,t){if(!e.startsWith("--"))return[];let n=fs(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let r of t){let a=fs(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=gn(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 qt,Qd=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 em(){if(qt)return qt;let e=new Map;for(let t of Ge)if(!Qd.has(t))for(let n of ot(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return qt=e,qt}function tm(e,t){if(!e.startsWith("--"))return[];let n=em().get(W(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(ot(o));return[...new Set(n.filter(r=>r!==o).map(r=>({command:r,sharedFlagCount:ot(r).filter(a=>i.has(a)).length})).sort((r,a)=>r.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-r.sharedFlagCount:r.command.localeCompare(a.command)).map(({command:r})=>V(r)?.canonical??r))]}function nm(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(ps(r,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?ps(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(ln))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 im(e){let t=V(e.normalizedUnknown),n=Ca(e.commandPaths,e.primaryToken),o=om(e),i=Xd(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return Wn([...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 rm(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function am(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 sm(e,t,n){let o=N([...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=N(t.slice(o+1));o=r===void 0?void 0:o+1+r}return e}function hs(e,t){if(!e)return;let n=$([...t]);return[...Se(n),...e.split(" "),"--help"]}function vo(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let r=ys(t,n),a=sm(i[1],o,r),s=j(a);if(s.length===0||r.length===0)return;let c=pa(s,r);if(c){let A=hs("update",o),R=A.slice(0,-2);return{suggestedRetryCommand:_(A),suggestedRetryArgs:A,unknownCommandExamples:[_(A),...c.examples.map(k=>_([...R,...k]))],unknownCommandNextSteps:c.nextSteps}}let l=Yd(s);if(l&&!r.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let d=s.split(" ")[0],m=im({commandPaths:r,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),u=rm(r),p=va(s,r),f=hs(p,o),y=[...new Set([...p?[p]:[],...m.length>0?m:Wn(u,r)])].slice(0,3),h=am(y,m.length>0),C=m.length>0?`Did you mean: ${y.join(", ")}?`:null;return{...f?{suggestedRetryCommand:_(f),suggestedRetryArgs:f}:{},unknownCommandExamples:f?[_(f),...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 cm(e){return Array.from(new Set(e))}function lm(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 dm(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 mm(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 Ne(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let r=mm(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 um(e,t,n,o){try{let i=I(process.cwd(),e.path);if(!await Y(X(i)))return{allowedTypes:nt};let r=await F(i),a=e.noExtensions?void 0:le(),s=ce(r,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await kt(i,d,r.id_prefix,r.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):nt,pmRoot:i,settings:r,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:nt}}}function pm(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?cm([...Kd(t,n[1]),...Zd(n[1],ot(t))]).filter(a=>_a(n[1],a)):void 0,i=n?tm(n[1],t):[],r=n!==null&&ot(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 fm(e,t,n){if(!t||!n||n.length===0)return;let o=nm(e,t[1],n[0]);return o?wo(o):void 0}function gm(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?dm(lm(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=S(t);if(i)return wa(t,i,[o])}function hm(e,t){if(!/too many arguments/i.test(e))return;let n=N(t),o=B(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(!us.includes(s))return;let c=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${r} ${a}`,unknownSubcommandAllowedValues:[...us],suggestedRetryCommand:wo(c)}}function ym(e,t,n,o){let i=N(t),r=B(t.slice(i))?.alias??S(t);if(!/unknown option /i.test(e)||r===void 0)return r;let a=V(r)?.canonical??r;return Ge.some(s=>s===r)||ys(n,o).includes(a)?r:void 0}async function it(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",s=Xe([...i]).argv,c=ge(s),l=$(s),d=ym(a,c,t,n),m=wo(c),u=ee(c),p=await um(l,a,c,d),f=p.allowedTypes,y=vo(a,t,n,c),h=pm(a,d),C=hm(a,c),A=C?.suggestedRetryCommand??fm(c,h.match,h.suggestions)??gm(a,c);return{message:a,commandName:d,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:A,verifiedCollectionItemId:p.verifiedCollectionItemId,...C,...y,...o}}async function Co(e,t,n,o={},i=process.argv.slice(2)){let r=await it(e,t,n,o,i),{message:a,commandName:s,allowedTypes:c,...l}=r,d=$(r.normalizedInvocationArgs).lean,m=cs(a,s,c,l,{lean:d}),u=await fr("help_format",{message:m,command:s,allowed_types:c});return u.handled&&typeof u.result=="string"?u.result:m}async function xo(e,t,n,o=!1,i={},r=process.argv.slice(2)){let a=await it(e,t,n,i,r),s=Ut(a.message,a.commandName,a.allowedTypes,g.USAGE,a),c=o?Dt(s):s,l=$(a.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(l?Z(c,d=>`${JSON.stringify(d,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=S(e)==="contracts"&&e.includes("--full");return i||r?await o(t):null}import{Option as _m}from"commander";function v(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function vs(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),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&i===d){n.set(i,a);break}}}return n}function bo(e,t,n,o){if(!t||!n)return;let i,r=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let u=d.split(" ");u.length>r&&u.every((p,f)=>l[f]===p)&&(i=m,r=u.length)}}let a=i?.flags.find(s=>s.long===n||s.short===n);if(a)return wm(a).takesValue}function Gt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ht(e){return typeof e=="boolean"?e:void 0}function wm(e){let t=_t(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function vm(e){let t=We(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=ko(e);return n?`${n} ${So(e)}`:null}function Cs(e){let t=[...new Set(e.map(vm).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 xs(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=Cs(r);a&&o.set(i,a)}return o}function bs(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function ws(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 Cm(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 xm(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:bs(o,n.action),description:i,intent:r,examples:ws(n.examples),failure_hints:ws(n.failure_hints),arguments:Cm(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 bm(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 km(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 Sm(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function ks(e,t,n,o=new Map){let i=xm(t),r=bm(n),a=km(e,i,r),s=new Map,c=[...a].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=Sm(l,i,o)??i.get(l),m=r.get(l)??(d?r.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:bs(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Em(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Ss(e,t){for(let n of t.arguments)e.argument(Em(n),n.description??"Extension argument.")}function Am(e){if(Ht(e.visible)===!1)return null;let n=We(e.long),o=Gt(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 ko(e){let t=Am(e);if(!t)return null;let{value_name:n,value_arity:o}=_t(e),r=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${r}`}function Rm(e){return ko(e)}function So(e){let t=Gt(e.description)??"Extension-provided option.",n=[];Ht(e.required)===!0&&n.push("required"),Ht(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 Es(e,t){let n=We(t.long),o=Gt(t.short);return e.options.some(i=>{let r=i;return n!==null&&r.long===n||o!==null&&r.short===o})}function Eo(e,t){for(let n of t){if(Es(e,n))continue;let o=Rm(n);if(!o)continue;let i=So(n),r=new _m(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 Ao(e,t){return Cs(t.filter(n=>!Es(e,n)))}function Om(e){let t=ko(e);if(!t)return null;let n=We(e.long),o=Gt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=_t(e),s=Ht(e.required)===!0;return{flags:t,long:i,short:r,description:So(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",...Tm(Pt(e))}}function Tm(e){return e===null?{}:{sdk_option:e}}function Ro(e){return Oe(e.command,Rt({readOutput:e.read_output_declared===!0})).map(t=>({flags:t.takes_value?`${t.flag} <${t.value_name}>`:t.flag,long:t.flag,short:null,description:t.description,takes_value:t.takes_value,value_required:t.value_required,value_name:t.takes_value?t.value_name:null,variadic:!1,required:!1,aliases:[...t.aliases??[]],alias_for:null,owner:"host"}))}function Oo(e){return["","Inherited host flags (delivered through context.global):",` ${Ro(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 As(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=Om(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function Rs(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 Os(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 To(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:To(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 zt=new WeakSet;function at(e){return zt.has(e)}function Rs(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&&L.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=rt(n,i);if(r){n=r;continue}let a=n.command(i);zt.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 Sm(e,t){let n=t.join(" "),o=L.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||L.some(l=>l.canonical.startsWith(`${r.join(" ")} `));if(!zt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function Em(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Sm(e,r),s=oe(e,r),c=L.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||zt.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 Os(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=Em(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Ts(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 Io(e,t={},n=[]){let o={readSettings:F,loadExtensions:Ve,activateExtensions:Je,resolveImplicitPmRoot:mn,...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(j).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),d=n.map(j),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 Is(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Io(t,n,o),r={readSettings:F,loadExtensions:Ve,activateExtensions:Je,resolveImplicitPmRoot:mn,...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 Ps={core:0,standard:1,full:2,internal:3};function $s(e,t,n=!0){let o=t.get(q(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)=>Ps[c.tier]<Ps[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 Ns(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(q(o)!==o||!Ge.some(i=>i===o)&&!Ot(o)&&!Ye(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 Am(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Ms(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 Rm(e){let t=new Map;for(let n of e){let o=n,i=Ms(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 Om(e){return _(e)}function Tm(e){let t=e.options??[],n=Rm(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=Ms(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:Am(r),variadic:i.variadic===!0,required:u,aliases:l,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function Im(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 Pm(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 $m(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||(he(r)??Q(r.name()))!=="internal").map(r=>{let a=j(E(r)),s=a,c=he(r),l=$s(a,t,c!==void 0),d=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:To(r),description:r.description().trim(),tier:l?.tier??c??Q(s),family:l?.family??$t(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function Nm(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 Mm(e,t,n,o,i){let r=e!==void 0&&io(e)===Ie,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:qa(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Nm(n,a,o),intentSource:s}}function Lm(e,t){return e===void 0?null:t?.tier??Q(e)}function Fm(e,t){return e===void 0?null:t?.family??$t(e)}function Dm(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Ns(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function jm(e,t,n,o,i=new Map,r=!1){if(!e){let s=Pm(t),c=$m(t,i,r),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...Et.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:$t(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 Um(e,t){return t!==void 0&&at(e)?{inherited_options:Ro(t)}:{}}function qm(e,t,n,o,i){let r=oo(n),a=ae(n),s=j(E(t)),c=j(o.join(" ")),l=c.length>s.length?c:s,d=Ye(l),m=d?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(q(u)):void 0,y=u?$s(u,i,he(t)!==void 0):void 0,{narrative:h,intentSource:C}=Mm(u,t.description().trim(),r,f,d!==void 0),A=Im(Es(Tm(t),Ss(f))),R=jm(d,t,m,A,i,a),k=Dm(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:Lm(p,y),capability_family:Fm(p,y),description:d?.description??t.description(),usage:R.usage,intent:d?.description??h.intent,intent_source:C,examples:d?[d.example]:h.examples,tips:d?[At(d.accepted_flags)]:h.tips,arguments:R.arguments,options:R.options,...Um(t,f),subcommands:R.subcommands,has_subcommands:R.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function Ls(e,t,n,o=t){let i=$(t);if(!i.json)return!1;let r=P(t);if(!r.requested)return!1;let a=Ns(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=ge(t),c=`unknown command '${ge(r.commandPathTokens).join(" ")}'`,l=vo(c,e,n,s),d=Ut(c,"help",nt,g.USAGE,{...l,attemptedCommand:Om(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(d,u=>`${JSON.stringify(u,null,2)}
|
|
33
|
+
`)}`}function To(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:To(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 zt=new WeakSet;function at(e){return zt.has(e)}function Ts(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&&L.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let r=rt(n,i);if(r){n=r;continue}let a=n.command(i);zt.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 Im(e,t){let n=t.join(" "),o=L.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||L.some(l=>l.canonical.startsWith(`${r.join(" ")} `));if(!zt.has(s)&&(r.length===t.length||!c))return{core_path:r.join(" "),extension_path:t.join(" ")};i=s}return null}function Pm(e,t,n,o,i=!1){let r=t.split(" ").filter(d=>d.length>0),a=Im(e,r),s=oe(e,r),c=L.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||zt.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 Is(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=Pm(e,r,o,n.get(r),t.includes(r));return a?(i(a),!o.has(r)&&oe(e,r.split(" "))!==null):!0})}function Ps(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 Io(e,t={},n=[]){let o={readSettings:F,loadExtensions:Ve,activateExtensions:Je,resolveImplicitPmRoot:mn,...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(j).filter((u,p,f)=>u.length>0&&f.indexOf(u)===p).sort((u,p)=>u.localeCompare(p)),d=n.map(j),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 $s(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await Io(t,n,o),r={readSettings:F,loadExtensions:Ve,activateExtensions:Je,resolveImplicitPmRoot:mn,...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 Ns={core:0,standard:1,full:2,internal:3};function Ms(e,t,n=!0){let o=t.get(q(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)=>Ns[c.tier]<Ns[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 Ls(e,t){if(t.length===0)return e;let n=oe(e,t);if(n)return n;let o=t.join(" ");if(q(o)!==o||!Ge.some(i=>i===o)&&!Ot(o)&&!Ye(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 $m(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Fs(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 Nm(e){let t=new Map;for(let n of e){let o=n,i=Fs(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 Mm(e){return _(e)}function Lm(e){let t=e.options??[],n=Nm(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=Fs(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:$m(r),variadic:i.variadic===!0,required:u,aliases:l,alias_for:m};return i.defaultValue!==void 0&&(y.default_value=i.defaultValue),y})}function Fm(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 Dm(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 jm(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||(he(r)??Q(r.name()))!=="internal").map(r=>{let a=j(E(r)),s=a,c=he(r),l=Ms(a,t,c!==void 0),d=K.find(({alias:m})=>m===a);return{name:r.name().trim(),aliases:To(r),description:r.description().trim(),tier:l?.tier??c??Q(s),family:l?.family??$t(s),...d?{alias_for:d.canonical,alias_lifecycle:d.lifecycle,...d.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((r,a)=>r.name.localeCompare(a.name))}function Um(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 qm(e,t,n,o,i){let r=e!==void 0&&io(e)===Ie,a=r?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ga(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":r?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Um(n,a,o),intentSource:s}}function Hm(e,t){return e===void 0?null:t?.tier??Q(e)}function Gm(e,t){return e===void 0?null:t?.family??$t(e)}function zm(e,t,n){if(!(t!==e||!n))return K.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Ls(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Wm(e,t,n,o,i=new Map,r=!1){if(!e){let s=Dm(t),c=jm(t,i,r),l=new Set(c.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...c,...Et.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:$t(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 Bm(e,t){return t!==void 0&&at(e)?{inherited_options:Ro(t)}:{}}function Vm(e,t,n,o,i){let r=oo(n),a=ae(n),s=j(E(t)),c=j(o.join(" ")),l=c.length>s.length?c:s,d=Ye(l),m=d?.command??s,u=m.length>0?m:void 0,p=u,f=u?i.get(q(u)):void 0,y=u?Ms(u,i,he(t)!==void 0):void 0,{narrative:h,intentSource:C}=qm(u,t.description().trim(),r,f,d!==void 0),A=Fm(Rs(Lm(t),As(f))),R=Wm(d,t,m,A,i,a),k=zm(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:Hm(p,y),capability_family:Gm(p,y),description:d?.description??t.description(),usage:R.usage,intent:d?.description??h.intent,intent_source:C,examples:d?[d.example]:h.examples,tips:d?[At(d.accepted_flags)]:h.tips,arguments:R.arguments,options:R.options,...Bm(t,f),subcommands:R.subcommands,has_subcommands:R.subcommands.length>0,...k===void 0?{}:{command_aliases:k}}}async function Ds(e,t,n,o=t){let i=$(t);if(!i.json)return!1;let r=P(t);if(!r.requested)return!1;let a=Ls(e,r.commandPathTokens);if(!a){if(!i.quiet){let s=ge(t),c=`unknown command '${ge(r.commandPathTokens).join(" ")}'`,l=vo(c,e,n,s),d=Ut(c,"help",nt,g.USAGE,{...l,attemptedCommand:Mm(s),normalizedInvocationArgs:[...s],providedOptionFlags:ee(s)}),m=i.tokenAccounting?Z(d,u=>`${JSON.stringify(u,null,2)}
|
|
34
34
|
`):d;ie(`${JSON.stringify(m,null,2)}
|
|
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],l=e==="create"&&c?.toLowerCase()==="strict",d=
|
|
39
|
-
`)}function Fs(e,t,n){let o=S(n);if(o!=="create"&&o!=="update")return;let i=rt(e,o);i&&i.addHelpText("after",Bm(o,t,n))}function Vm(e,t){let n=Be(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Jm(e){return Be(e.status)?.toLowerCase()??"pending"}function Km(e){return e.mandatory===!0}function Ym(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 Us(e){let t=[];return e.forEach((n,o)=>{if(!Km(n.definition))return;let i=Jm(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:Vm(n.definition,o),status:i})}),t.sort(Ym),t}function Ds(e){return Array.isArray(e)&&e.length>0}var Xm=new Set(["create","beads import","todos import"]),Zm=new Set(["restore","update","close","delete","append","claim","release"]),Qm=new Set(["comments","notes","learnings"]),eu=new Set(["files","docs","test"]),tu=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 Po(e,t){let n=t.force===!0;return Xm.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Zm.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Qm.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:eu.has(e)?{isMutation:Ds(t.add)||Ds(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function nu(e,t,n){if(Po(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Or(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>tu.has(i.trim().toLowerCase())):!1}function js(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function ou(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(Be(t[1])||i.push("source"),Be(n.to)||i.push("--to"),i.length!==0)throw new T(`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 iu(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||js(n.status)!==js(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ce(i,le()),s=await kt(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await hr(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 $o(e,t,n,o,i){if(!nu(e,t,n)||(ou(e,t,n),!await Y(X(i))))return;let r=await Ae(i);Ca(o.json===!0)||await iu(e,t,n,i,r.settings);let a=Rr({author:wt(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)pe(s)}function qs(e,t,n){if(n.length===0)return;let o=Po(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 T(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function No(e,t,n,o){if(!Po(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 Ae(n);for(let c of s)pe(c);if(!fr(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(pr(r),await gr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=ce(r,le());await Tr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function Mo(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 Fe(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 Mo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,q(i)]))]}function Lo(e,t){let n=v(e);if(n.length===0)return!1;let o=Fe(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 Bt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...M(n.commands),...M(n.command_handlers),...M(n.command_overrides),...M(n.flag_commands),...M(n.parser_overrides),...Hs(n.preflight_ownership),...Hs(n.renderer_ownership)]:[]}function M(e){return e??[]}function Hs(e){return M(e).flatMap(t=>t.commands)}function st(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Gs=new Set(["hooks","parser","preflight","renderers"]),zs=new Set(["commands","schema","services","importers"]),ru=new Set(["reindex","search","search-advanced"]),au=new Set(["--template"]);function Le(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Fo(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return ru.has(n??t)}function Do(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 Vt(e){return v(e.commandPath??"")==="create"&&Do(e,au)}function jo(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Wt(e,t){return e.some(n=>Lo(n,t))||Vt(t)&&jo(e)}function Uo(e){return[M(e.hooks).length,(e.preflight_overrides??0)-M(e.preflight_ownership).length,M(e.item_types).length,M(e.item_fields).length,M(e.relationship_kinds).length,M(e.service_overrides).length,M(e.assurance_providers).length,M(e.renderer_overrides).length-M(e.renderer_ownership).length].some(n=>n>0)}function qo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Wt(n,t);let o=Bt(e);if(Wt(o,t)||st(e).has("search")&&Fo(t.commandPath))return!0;if(e.contributions)return Uo(e.contributions)}function Jt(e,t){let n=qo(e,t);if(n!==void 0)return n;let o=st(e);return!!(Le(o,Gs)||Le(o,zs))}function ct(e,t){return e.effective.length===0?!1:lt(t)!=="all"?e.effective.some(o=>Jt(o,t)):e.effective.some(o=>{let i=st(o);return Bt(o).length>0||Le(i,Gs)||Le(i,zs)||i.has("search")})}function lt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=Fe(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=Vt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Ho(e){return lt(e)==="all"?void 0:t=>Jt(t,e)}function De(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=D(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 Go(e){let t=e.args.map(String);if(v(E(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Kt=Symbol.for("pm.readOutputInvocationProvenance"),su=new Map(ue.filter(e=>e.reservation_scope==="root_only").map(e=>[Pt({long:e.flag}),e.flag]));function se(e,t){let n=Reflect.get(e,Kt);n!==void 0&&Reflect.set(t,Kt,n)}function zo(e,t,n){let o=Di(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=Fi.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,Kt);Reflect.set(n,Kt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),se(n,e)}function cu(e){let t=e.optsWithGlobals(),n=E(e);if(q(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 T(`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 Wo(e,t,n,o){zo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Gi(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=Hi(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");It(e,n)}function je(e,t,n=[],o){let r={...cu(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=ea(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=qn(n),c=H(E(e)).map(m=>({long:m.flag,short:m.short,aliases:m.aliases})),l={...a};for(let m of s)r[m]!==void 0&&(l[m]=r[m]);Hn(l,[...c,...n],E(e),o);let d=Qr(r,n,a,E(e));return se(r,d),d}return r}function Vs(e,t,n){let o=qn(t.map(({long:a})=>({long:a}))),i=[...su].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new T(`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 Yt(e){return e.arguments??[]}function Ws(e){let t=Yt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Bo(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 Js=Symbol("pm.commandOptionTokens"),Bs=Symbol("pm.capturesOptionTokens");function Ks(e){if(Reflect.get(e,Bs)===!0)return;Reflect.set(e,Bs,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,Js,[...n]),t(n))}function lu(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 du(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 Ys(e,t,n){if(t.length===0)return;let o=[];for(let r=e;r?.parent;r=r.parent)o.unshift(r);let i=[];for(let r of o){let a=Reflect.get(r,Js);if(a===void 0)continue;let s=lu(r),c=[];for(let l=r;l;l=l.parent)c.push(l);i.push({tokens:a,optionOf:l=>s.get(l),includesLooseFlags:r===e,negativeNumbersAreValues:!c.some(l=>l.options.some(d=>d.short!==void 0&&/^-\d$/u.test(d.short))),...du(r)})}na(i,t,n)}function Vo(e,t){let n=Yt(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 T(`Missing required argument for extension command '${e.command}'. Usage: ${Ws(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new T(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Ws(e)}${s}`,g.USAGE)}}function mu(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Xt(e,t){return{definitions:e,inheritedFlags:Rt({readOutput:t}).map(n=>n.flag)}}function uu(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map(mu);if(o.length===0)return;let{inheritedFlags:i}=Xt([],n);throw new T(`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 pu(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Hn(t,n,e.command,Xt(n,o));return}uu(t,e.command,o)}function Jo(e,t,n,o){e&&(Vo(e,t),pu(e,n,o))}import{Command as Xs}from"commander";var fu=new Set(["--version","-V"]);function mt(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Zs(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new Xs().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 gu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ko=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"]),Qs=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"]),hu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),yu=new Set(["claim","close-task","pause-task","release","start-task","test"]),Ce={setup:!0,listQuery:!0,mutation:!0,operation:!0},_u=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=>fu.has(t))}function wu(e,t){if(!L.some(o=>o.canonical_argv[0]===t))return;let n=new Xs().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Oe(t,H(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 Ce;let i=B([t,...o.operands])?.alias;if(L.some(r=>r.alias===i))return{...Ce,targetCommandName:i}}catch{return Ce}}function Yo(e){if(ut(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return Ce;let t=S(e);if(!t)return Ce;let n=t.trim().toLowerCase(),o=D(e),i=B(o)?.alias;if(L.some(a=>a.alias===i))return{...Ce,targetCommandName:i};let r=wu(o,n==="ctx"?"context":n);return r||(gu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ko.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Qs.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:hu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:Ce)}function Xo(e){return e.length===0||P(e).requested||e.includes("--explain")&&S(e)===void 0}function Zo(e,t){return mt(t)||ut(t)?!1:ae(t)||P(t).requested?!0:!!S(t)}function Qo(e){if(ut(e))return!1;let t=S(e);return t?_u.has(t):!1}function vu(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=ze(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 ei(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=Qs.has(t)||yu.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=vu({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new T(`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 Cu=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"]),xu=new Set(["parse","preflight","execute","unknown"]),bu=new Set(["usage","validation","conflict","runtime","unknown"]);function xe(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 ti(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Zt(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 ni(e){if(!e)return;let t=e.trim().toLowerCase();if(Cu.has(t))return t}function oi(e){if(!e)return;let t=e.trim().toLowerCase();if(xu.has(t))return t}function ii(e){if(!e)return;let t=e.trim().toLowerCase();if(bu.has(t))return t}function ri(e){let t=xe(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(ti(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=Zt(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=>fn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function ai(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 si(){let e=fn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Zt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=aa(o),r=xe(e,"error_code","errorCode")??ai(i,o),a=ii(xe(e,"error_category","errorCategory"))??(i?void 0:ht(r)),s=i?void 0:ri(e)??`command_exit_${o}`,c=ni(xe(e,"command_resolution","commandResolution"))??St({ok:i,errorCode:r,errorCategory:a}),l=oi(xe(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 ci="PM_CLI_PACKAGE_ROOT",lc=Symbol("pm.deprecatedAliasInvocation"),tn=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=tn.get(t)??[];n.push(e),tn.set(t,n)}for(let e of tn.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function ku(){return Xi(import.meta.url,["../.."])}(typeof process.env[ci]!="string"||process.env[ci]?.trim().length===0)&&(process.env[ci]=ku());var ke=null,U=null,nn=null;function Su(e){ke=e}function Eu(e){O=e}var pt=null,be=null,O=new Map,gi=250,Au=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Ru=new Set(["1","true","yes","on"]),Ou=Ke(()=>import("./chunks/register-setup-C44SIXEH.js")),Tu=Ke(()=>import("./chunks/register-list-query-L4IBU64P.js")),Iu=Ke(()=>import("./chunks/register-mutation-6NUOPHZ3.js")),Pu=Ke(()=>import("./chunks/register-operations-JGYVORNN.js"));function en(e){return _(e)}function dc(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=>fe(o)??o))];return n.length>0?n:void 0}function $u(e,t,n,o){if(n?.suggested_retry||o===to||o===eo||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=>fe(m)??m)),a=dc(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=>fe(u)).filter(u=>u!==void 0))),d=a?.filter(m=>{let u=fe(m)??m;return r.has(u)?!1:l.has(u)||bo(t,s,u,O)!==void 0});return d&&d.length>0?d:void 0}function Nu(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?fe(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=bo(e,a,r,O),d=r?c?.isBoolean()===!0||l===!1?[r]:[r,"<value>"]:[],m=r?en([...e,...d]):t;return m===t?void 0:m}function Mu(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 Lu(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,...Mu(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function ec(e,t){return{...e,recovery:t}}function Fu(e,t){if(t===void 0)return;let n=Pa(e,t.code,t.field,Ra(e,t.code,t.recovery)),o=Du(e),i=$a(e,t.code,t.field,n,o),r=Ta(e,t.code,i,o,()=>Lr(I(process.cwd(),$(e).path)));return Na(e,t.code,r,o)}var tc=" ";function Du(e){let t=e.map(i=>i===""?tc:/^--(?:pm-)?path=$/u.test(i)?`${i}${tc}`:i),n=$(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Se({});return n!==void 0&&o.length>0?null:o}function mc(e,t,n){let o=ze(t),i=D(o),r=N(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:_r(e);let l=Fu(o,e),d=l&&(a==="history-redact"||a==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:en(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:en(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return ec(e,d);let m=en(o),u=ee(o),p=$u(n,o,d,e?.code),f=Nu(o,m,p,d),y=Lu({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:d});return ec(e,y)}async function ft(e){let t=U;U=null,await Ma(t,e);let n=ke;if(ke=null,!n){Ct();return}let o=[],i=dr();try{await La({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 tr(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{Ct()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${z(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${z(o)}`)}async function uc(e,t){await xr();let n=U,o=ke,i=n?.command??o?.commandName??e,r=n??En(o?.globalOptions??t),a=O.get(v(i))?.source;Pn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??qe,extension:a})}function pc(e){return Ru.has((process.env[e]??"").trim().toLowerCase())}function fc(e){return pc("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Au.has(Math.trunc(e))}async function on(e,t){return fc(e.exit_code)?(await uc(e.command,t),Ar({...e,source_context:e.source_context??En(t).source_context}),!0):!1}async function gc(e){let t=J(me(e.error)),n=ls(t);e.bootstrapGlobal.json?x(JSON.stringify(et(ss(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await uc(e.attemptedCommand,e.bootstrapGlobal),$n(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 sn(!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 Re()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${me(r)}`)}}var ju={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"},li=new Map;function di(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function hc(e,t){return e.options.some(n=>n.long===t)}function yc(e,t){return e.options.some(n=>n.short===t)}function mi(e,t,n,o){let i=t.trim();if(!i)return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(yc(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,Un);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!hc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,Un);return}e.option(`${a} <value>`,r)}}async function _c(e,t){let n=ju[e];if(!n)return[];let o=`${t}:${n}`,i=li.get(o);if(i)return i;if(!await Y(X(t)))return li.set(o,[]),[];let r=await F(t),s=(hn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:di(c.type),value_type:di(c.type)})));return li.set(o,s),s}async function wc(e,t){let n=$(t),o=I(process.cwd(),n.path);if(!await Y(X(o)))return;let i=be?.key===_i(o)?be.snapshot:null,r=i===null?await F(o):i.settings,a=hn(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??"";mi(l,d.cli_flag,m,d.repeatable);for(let u of d.cli_aliases)mi(l,u,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function hi(e,t,n,o,i){let r=S(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await F(t),s=ce(a,o);Fs(e,s,n)}catch{}}function ui(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function vc(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function yi(e){return e.some(t=>t==="--profile")}function _i(e){return`pm-root:${e}`}function pi(e){for(let t of e)t.startsWith("settings_read_")&&pe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Cc(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=${z(t.activationWarnings)}`))}function rn(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 an(e,t=Ae){let n=_i(e);if(be?.key===n)return be.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await nr({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return be={key:n,snapshot:s},s}catch{return be={key:n,snapshot:null},null}}async function He(e,t,n=F){let o=t?lt(t):"all",i=vc(e,o);if(pt?.key===i)return pt.snapshot;try{let r=await n(e),a=await Ve({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Ho(t):void 0}),s=await Je({...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=vs(s.registrations.flags),d=_s(s.commands.handlers,s.registrations.commands),m=xs(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 xc(e){let t=Ze(e);if(t.noExtensions){let a=I(process.cwd(),t.path);return await Y(X(a))&&pi((await Ae(a)).warnings),null}let n=I(process.cwd(),t.path),o=await an(n);if(!o)return null;pi(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:Go(e)};if(!ct(o.discovery,i))return rn(t.profile,o,i),null;let r=await He(n,i);return r?(Cc(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 wi(e){let t=await He(e);return t?new Map(t.commandDescriptors):O}async function Uu(e,t){return!e.requested||t.noExtensions||Ne(w,e.commandPathTokens)?O:wi(I(process.cwd(),t.path))}async function bc(e,t){return(await qr({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 kc(e,t,n){let o=t.author;return Ur(e,da.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Sc(e,t,n,o=[]){let i=E(e),r=Gn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=I(process.cwd(),n.path),l={args:[...r],path:n.path},d=await xt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&x(`profile:extensions parser_warnings=${z(d.warnings)}`),r=d.context.args,a=d.context.options,s=d.context.global,Yn(l,{args:r,path:s.path},a),Jo(O.get(v(i)),r,a,o),Ee(void 0),vt({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await Sn({command:i,args:r,options:a,global:s,pm_root:c,sdk:kc(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${z(m.warnings)}`),!m.handled)throw m.warnings.length>0?br(i,m):new T(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Ee(m.result),m.result}var nc=Symbol("pm.wrappedActionHandler");function qu(e,t){let n=e[e.length-1];return n instanceof fi?n:t}function oc(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${z(n)}`)}function Hu(e){let t=O.get(v(e.commandPath));if(!t||!Bo(e.activeRegistrations,e.commandPath))return;let n=Yt(t).length===0?ta(e.commandArgs):Gn(e.commandArgs,e.extensionFlagDefinitions);Vo(t,n)}function Gu(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 vi(e,t,n){if(!at(e))return;let o=O.get(v(t))?.read_output_declared===!0;return Xt(n,o)}function Ec(e){let t=n=>{let o=n;if(Ks(n),typeof o._actionHandler=="function"&&o[nc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=qu(a,n),c=Date.now();jn(s);let l=Ze(s),d=q(E(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return Sa(d,l.expectHash),await i.apply(this,a);let m=I(process.cwd(),l.path),u=s.args.map(String),p=le(),f=p?dt(p,d,u):[],y=await _c(d,m),h=vi(s,d,f),C=je(s,u,[...f,...y],h);Ys(s,f,d),O.has(v(d))&&delete C.author,h!==void 0&&Vs(C,f,d);let A={args:[...u],path:l.path},R=await xt({command:d,args:u,options:C,global:l,pm_root:m});oc(l.profile,"parser_warnings",R.warnings),u=R.context.args,C=R.context.options,se(s,C),l=R.context.global,Yn(A,{args:u,path:l.path},C),Hu({activeRegistrations:p,commandPath:d,commandArgs:u,extensionFlagDefinitions:f}),l=await Jr(l),It(s,l),Gu(s,a,u),Tt(s,C),Ee(void 0),vt({command:d,args:u,options:{...C},global:{...l},pm_root:m});let k=await Sn({command:d,args:u,options:C,global:l,pm_root:m,sdk:kc(m,l,d)});if(oc(l.profile,"command_handler_warnings",k.warnings),k.handled){Ee(k.result),bn(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[nc]=!0}for(let i of n.commands)t(i)};t(e)}async function Qt(e){O=new Map,re({overrides:[]}),e&&await hi(e.rootProgram,e.pmRoot,e.invocationArgv,Qi(),e.settings)}function zu(e,t,n,o){if(t?.flags&&t.flags.length>0){Eo(e,t.flags);let i=Ao(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&at(e)&&e.addHelpText("after",Oo(t)),o&&e.addHelpText("after",o)}function Wu(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Oo(n)),o&&e.addHelpText("after",o)}function Ac(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");Lt(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 Rc(e,t){let n=$(t),o=I(process.cwd(),n.path);if(n.noExtensions){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await an(o),r=De(t);if(!i){await Qt();return}if(!ct(i.discovery,r)){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),rn(yi(t),i,r);return}let a=await He(o,r);if(!a){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),O=new Map(a.commandDescriptors),await hi(e,o,t,a.registrations,a.settings);let s=Os(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Ts(a.activationWarnings,x,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(A=>A.length>0),u=a.commandDescriptors.get(d),p=oe(e,m),f=a.commandFlagHelp.get(d),y=u?As(u):null;if(p){zu(p,u,f,y);return}let h=Rs(e,m);u?.description&&h.description(u.description);let C=f;u&&(bs(h,u),u.flags.length>0&&(Eo(h,u.flags),C=Ao(h,u.flags)??void 0)),Wu(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{let R=A[A.length-1],k=R instanceof fi?R:h,gt=Ze(k),Uc=Date.now(),cn=dt(a.registrations,d,k.args.map(String)),bi=je(k,k.args.map(String),cn,vi(k,d,cn)),ki=await Sc(k,bi,gt,cn);await Kr(gt,ki),bn(ki,{...gt,command:d,commandArgs:k.args.map(String),commandOptions:bi,pmRoot:o}),gt.profile&&x(`profile:command=${d} took_ms=${Date.now()-Uc}`)})};for(let d of s)l(d);Ac(e,c,a.commandDescriptors)}var qe=Zi(import.meta.url,["../.."])??"0.0.0",w=Dn(qe);async function ic(e){if(!U)return;let t=Reflect.get(e,lc);typeof t=="string"&&await la(t)}async function rc(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function ac(e,t,n){!U||!await An(!0)||(Pn(e,t,n,{source_context:U.source_context,source_context_source:U.source_context_source}),kr(e),nn=U)}async function sn(e,t,n){let o=nn;if(!o)return;nn=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 An(i)?Er(e,t,n):Sr()}async function Bu(e){let t=await xc(e);return kn(t?.registrations??null),t}function Oc(e,t){t&&mt(t)||(e.hook("preAction",async(n,o)=>{ke=null,U=null,nn=null,Ct(),jn(o);let i=o.optsWithGlobals(),r=Ze(o),a=q(E(o)),s=o.args.map(String),c={args:[...s],path:r.path},l=je(o,s),d={...r},m=I(process.cwd(),r.path),u=await Bu(o);if(qi(a,{...l,...Yr(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Wo(o,a,d,l),await rc(o,void 0,()=>Ir(a,d)),!u){ke=or({commandName:a,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),U=await Nn({command:a,pm_version:qe,args:s,options:l,global:d,pm_root:m}),await ic(e),await ac(a,s,l),await No(a,l,m,ui()),await $o(a,s,l,d,m),await Kn({command:o,commandPath:a,commandArgs:s,commandOptions:l,expectHash:r.expectHash,pmRoot:m,globalOptions:d});return}ir(u.hooks),rr(u.commands),ar(u.parsers),sr(u.preflight),re(u.services),cr(u.renderers),kn(u.registrations);let p=dt(u.registrations,a,s);l=je(o,s,p,vi(o,a,p)),Wo(o,a,d,l);let f=await xt({command:a,args:s,options:l,global:d,pm_root:u.pmRoot});d.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${z(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),d=f.context.global;let y={args:[...s],path:d.path};Tt(o,l);let h=await mr({command:a,args:s,options:l,global:d,pm_root:u.pmRoot,decision:ui()});d.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${z(h.warnings)}`),s=h.context.args,l=h.context.options,se(o,l),d=h.context.global,Tt(o,l);let C=h.decision;await No(a,l,u.pmRoot,C),await $o(a,s,l,d,u.pmRoot),await Kn({command:o,commandPath:a,commandArgs:c.args,commandOptions:l,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:Jn(c,[y,{args:s,path:d.path}]),globalOptions:{...d,path:r.path,noExtensions:r.noExtensions}});let A=C.run_extension_migrations?await rc(o,[],()=>bc(u.registrations.migrations,u.pmRoot)):[];d.profile&&A.length>0&&x(`profile:extensions migration_warnings=${z(A)}`);let R=Us(u.registrations.migrations);ke={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:u.pmRoot,profileEnabled:!!d.profile,migrationBlockers:R},Ee(void 0),vt({command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot}),U=await Nn({command:a,pm_version:qe,args:s,options:l,global:d,pm_root:u.pmRoot}),await ic(e),await ac(a,s,l);let k=await er(u.hooks,{command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot});d.profile&&k.length>0&&x(`profile:extensions hook_warnings=${z(k)}`),C.enforce_mandatory_migration_gate&&qs(a,l,R)}),e.hook("postAction",async()=>{let n=si();await sn(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 Re()}))}Oc(w);var sc=Symbol("pmCliIdempotentTopLevelRegistration");function Tc(e){let t=e;if(t[sc])return;t[sc]=!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 fi(r):n(o,...i)})}async function Vu(e,t){if(Tc(e),t.setup){let{registerSetupCommands:n}=await Ou();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Tu(),o=typeof t.targetCommandName=="string"&&Ko.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Iu();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Pu();n(e)}}function Ue(e){return e.rawInvocationArgv??e.invocationArgv}function Ju(e){return async t=>{let n=ht(t.errorCode),o=St({ok:!1,errorCode:t.errorCode,errorCategory:n});return await $r({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:qe,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 Ic(e){if(e.bootstrapGlobal.noExtensions||mt(e.invocationArgv))return;let t=De(e.invocationArgv),n=await an(e.bootstrapPmRoot);if(n&&ct(n.discovery,t)){let o=await He(e.bootstrapPmRoot,t);Pc(o);return}n&&rn(yi(e.invocationArgv),n,t),re({overrides:[]})}function Pc(e){if(!e){re({overrides:[]});return}re(e.services)}async function Ci(e){await sn(!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 $c(){await sn(!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 Nc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof T)&&(Tn(e.error)||!n))return!1;let o=J(me(e.error)),i=e.error instanceof T?e.error.exitCode:On(t),r=e.error instanceof T||Cr(e.error)?e.error.context:void 0,a=mc(r,e.invocationArgv,o),s=rs(o,a),c=et(e.bootstrapGlobal.lean?Dt(go(o,i,a)):go(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(l);let{errorCategory:d,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 on({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context},e.bootstrapGlobal);return await Ci({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),u&&($n(In(e.error,o)),await Re(gi)),process.exitCode=i,!0}async function
|
|
42
|
-
`):x(y),p&&await Re(gi),process.exitCode=g.USAGE}async function
|
|
43
|
-
`):x(l),a&&await Re(gi),process.exitCode=g.USAGE}function
|
|
35
|
+
`)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=Vm(e,a,t,r.commandPathTokens,n),c=P(o).commandPathTokens;s.requested_path=c;let l=V(c.join(" "));l&&(s.resolved_path=l.canonical),a===e&&!ae(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Ji(`${JSON.stringify(s,null,2)}
|
|
36
|
+
`)}return process.exitCode=g.SUCCESS,!0}function Jm(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 Km(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 Ym(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 Xm(e,t,n,o){let i=new Set(n),r=o.filter(c=>!i.has(c)),a=c=>c.length>0?c.map(l=>dn("create",l)).join(", "):"none";e.push(` required in strict mode: ${a(r)}`);let s=r.map(da).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 Zm(e,t,n){let o=Wr(n);if(!o)return Jm(e,t);let i=Ai(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],l=e==="create"&&c?.toLowerCase()==="strict",d=Ym(e,i),m=yt(i,e,d.progressive),u=yt(i,e,l?d.strict:d.progressive),p=y=>y.length>0?y.map(h=>dn(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=yt(i,e,d.strict);Xm(f,i,m.required,y.required)}return Km(f,i),u.errors.length>0&&f.push(` config errors: ${u.errors.join("; ")}`),f.join(`
|
|
39
|
+
`)}function js(e,t,n){let o=S(n);if(o!=="create"&&o!=="update")return;let i=rt(e,o);i&&i.addHelpText("after",Zm(o,t,n))}function Qm(e,t){let n=Be(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function eu(e){return Be(e.status)?.toLowerCase()??"pending"}function tu(e){return e.mandatory===!0}function nu(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 Hs(e){let t=[];return e.forEach((n,o)=>{if(!tu(n.definition))return;let i=eu(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:Qm(n.definition,o),status:i})}),t.sort(nu),t}function Us(e){return Array.isArray(e)&&e.length>0}var ou=new Set(["create","beads import","todos import"]),iu=new Set(["restore","update","close","delete","append","claim","release"]),ru=new Set(["comments","notes","learnings"]),au=new Set(["files","docs","test"]),su=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 Po(e,t){let n=t.force===!0;return ou.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:iu.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:ru.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:au.has(e)?{isMutation:Us(t.add)||Us(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function cu(e,t,n){if(Po(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Ir(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>su.has(i.trim().toLowerCase())):!1}function qs(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function lu(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(Be(t[1])||i.push("source"),Be(n.to)||i.push("--to"),i.length!==0)throw new T(`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 du(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||qs(n.status)!==qs(i.schema.workflow.in_progress_status))return;let r=t[0];if(!r)return;let a=ce(i,le()),s=await kt(o,r,i.id_prefix,i.item_format,a.type_to_folder);if(!s)return;let c=await _r(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 $o(e,t,n,o,i){if(!cu(e,t,n)||(lu(e,t,n),!await Y(X(i))))return;let r=await Ae(i);ba(o.json===!0)||await du(e,t,n,i,r.settings);let a=Tr({author:wt(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)pe(s)}function Gs(e,t,n){if(n.length===0)return;let o=Po(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 T(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${r}`,g.CONFLICT)}async function No(e,t,n,o){if(!Po(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 Ae(n);for(let c of s)pe(c);if(!hr(r)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(gr(r),await yr(n,r,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let c=ce(r,le());await Pr(n,r.item_format,"item_format:pre_mutation_sync",c.type_to_folder,r.schema)}}function Mo(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 Fe(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 Mo(e.commandArgs))o.push(...i.split(" ").filter(r=>r.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,q(i)]))]}function Lo(e,t){let n=v(e);if(n.length===0)return!1;let o=Fe(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 Bt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...M(n.commands),...M(n.command_handlers),...M(n.command_overrides),...M(n.flag_commands),...M(n.parser_overrides),...zs(n.preflight_ownership),...zs(n.renderer_ownership)]:[]}function M(e){return e??[]}function zs(e){return M(e).flatMap(t=>t.commands)}function st(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Ws=new Set(["hooks","parser","preflight","renderers"]),Bs=new Set(["commands","schema","services","importers"]),mu=new Set(["reindex","search","search-advanced"]),uu=new Set(["--template"]);function Le(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Fo(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return mu.has(n??t)}function Do(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 Vt(e){return v(e.commandPath??"")==="create"&&Do(e,uu)}function jo(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Wt(e,t){return e.some(n=>Lo(n,t))||Vt(t)&&jo(e)}function Uo(e){return[M(e.hooks).length,(e.preflight_overrides??0)-M(e.preflight_ownership).length,M(e.item_types).length,M(e.item_fields).length,M(e.relationship_kinds).length,M(e.service_overrides).length,M(e.assurance_providers).length,M(e.renderer_overrides).length-M(e.renderer_ownership).length].some(n=>n>0)}function qo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Wt(n,t);let o=Bt(e);if(Wt(o,t)||st(e).has("search")&&Fo(t.commandPath))return!0;if(e.contributions)return Uo(e.contributions)}function Jt(e,t){let n=qo(e,t);if(n!==void 0)return n;let o=st(e);return!!(Le(o,Ws)||Le(o,Bs))}function ct(e,t){return e.effective.length===0?!1:lt(t)!=="all"?e.effective.some(o=>Jt(o,t)):e.effective.some(o=>{let i=st(o);return Bt(o).length>0||Le(i,Ws)||Le(i,Bs)||i.has("search")})}function lt(e){if(v(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=Fe(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=Vt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Ho(e){return lt(e)==="all"?void 0:t=>Jt(t,e)}function De(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=D(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 Go(e){let t=e.args.map(String);if(v(E(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}var Kt=Symbol.for("pm.readOutputInvocationProvenance"),pu=new Map(ue.filter(e=>e.reservation_scope==="root_only").map(e=>[Pt({long:e.flag}),e.flag]));function se(e,t){let n=Reflect.get(e,Kt);n!==void 0&&Reflect.set(t,Kt,n)}function zo(e,t,n){let o=ji(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=Di.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,Kt);Reflect.set(n,Kt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),se(n,e)}function fu(e){let t=e.optsWithGlobals(),n=E(e);if(q(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 T(`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 Wo(e,t,n,o){zo(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:r,modes:a}=Wi(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=zi(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");It(e,n)}function je(e,t,n=[],o){let r={...fu(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=ta(t);for(let[s,c]of Object.entries(a))r[s]===void 0&&(r[s]=c);if(n.length>0){let s=qn(n),c=H(E(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]);Hn(l,[...c,...n],E(e),o);let d=ia(a,Zs(e),n),m=ea(r,n,d,E(e));return se(r,m),m}return r}function Ks(e,t,n){let o=qn(t.map(({long:a})=>({long:a}))),i=[...pu].find(([a])=>e[a]!==void 0&&!o.has(a));if(i===void 0)return;let r=i[1];throw new T(`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 Yt(e){return e.arguments??[]}function Vs(e){let t=Yt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Bo(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 Ys=Symbol("pm.commandOptionTokens"),Js=Symbol("pm.capturesOptionTokens");function Xs(e){if(Reflect.get(e,Js)===!0)return;Reflect.set(e,Js,!0);let t=e.parseOptions.bind(e);e.parseOptions=n=>(Reflect.set(e,Ys,[...n]),t(n))}function gu(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 hu(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 Zs(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,Ys);if(i===void 0)continue;let r=gu(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))),...hu(o)})}return n}function Qs(e,t,n){t.length!==0&&oa(Zs(e),t,n)}function Vo(e,t){let n=Yt(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 T(`Missing required argument for extension command '${e.command}'. Usage: ${Vs(e)}${s}`,g.USAGE);if(t.length>r){let c=t.slice(r).join(" ");throw new T(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Vs(e)}${s}`,g.USAGE)}}function yu(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Xt(e,t){return{definitions:e,inheritedFlags:Rt({readOutput:t}).map(n=>n.flag)}}function _u(e,t,n){let o=Object.keys(e).filter(r=>e[r]!==void 0).sort().map(yu);if(o.length===0)return;let{inheritedFlags:i}=Xt([],n);throw new T(`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 wu(e,t,n){let o=e.read_output_declared===!0;if(n.length>0){Hn(t,n,e.command,Xt(n,o));return}_u(t,e.command,o)}function Jo(e,t,n,o){e&&(Vo(e,t),wu(e,n,o))}import{Command as ec}from"commander";var vu=new Set(["--version","-V"]);function mt(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function tc(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let n=new ec().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 Cu=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ko=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"]),nc=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"]),xu=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),bu=new Set(["claim","close-task","pause-task","release","start-task","test"]),Ce={setup:!0,listQuery:!0,mutation:!0,operation:!0},ku=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=>vu.has(t))}function Su(e,t){if(!L.some(o=>o.canonical_argv[0]===t))return;let n=new ec().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of Oe(t,H(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 Ce;let i=B([t,...o.operands])?.alias;if(L.some(r=>r.alias===i))return{...Ce,targetCommandName:i}}catch{return Ce}}function Yo(e){if(ut(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return Ce;let t=S(e);if(!t)return Ce;let n=t.trim().toLowerCase(),o=D(e),i=B(o)?.alias;if(L.some(a=>a.alias===i))return{...Ce,targetCommandName:i};let r=Su(o,n==="ctx"?"context":n);return r||(Cu.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ko.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:nc.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:xu.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:Ce)}function Xo(e){return e.length===0||P(e).requested||e.includes("--explain")&&S(e)===void 0}function Zo(e,t){return mt(t)||ut(t)?!1:ae(t)||P(t).requested?!0:!!S(t)}function Qo(e){if(ut(e))return!1;let t=S(e);return t?ku.has(t):!1}function Eu(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=ze(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 ei(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=nc.has(t)||bu.has(t),a=r?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=r?"mutating option":"option",c=Eu({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new T(`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 Au=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"]),Ru=new Set(["parse","preflight","execute","unknown"]),Ou=new Set(["usage","validation","conflict","runtime","unknown"]);function xe(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 ti(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Zt(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 ni(e){if(!e)return;let t=e.trim().toLowerCase();if(Au.has(t))return t}function oi(e){if(!e)return;let t=e.trim().toLowerCase();if(Ru.has(t))return t}function ii(e){if(!e)return;let t=e.trim().toLowerCase();if(Ou.has(t))return t}function ri(e){let t=xe(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(ti(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let i=Zt(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=>fn(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function ai(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 si(){let e=fn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Zt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=ca(o),r=xe(e,"error_code","errorCode")??ai(i,o),a=ii(xe(e,"error_category","errorCategory"))??(i?void 0:ht(r)),s=i?void 0:ri(e)??`command_exit_${o}`,c=ni(xe(e,"command_resolution","commandResolution"))??St({ok:i,errorCode:r,errorCategory:a}),l=oi(xe(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 ci="PM_CLI_PACKAGE_ROOT",uc=Symbol("pm.deprecatedAliasInvocation"),tn=new Map;for(let e of K){let t=e.alias.split(" ")[0],n=tn.get(t)??[];n.push(e),tn.set(t,n)}for(let e of tn.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function Tu(){return Qi(import.meta.url,["../.."])}(typeof process.env[ci]!="string"||process.env[ci]?.trim().length===0)&&(process.env[ci]=Tu());var ke=null,U=null,nn=null;function Iu(e){ke=e}function Pu(e){O=e}var pt=null,be=null,O=new Map,gi=250,$u=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Nu=new Set(["1","true","yes","on"]),Mu=Ke(()=>import("./chunks/register-setup-ZLJEF6NZ.js")),Lu=Ke(()=>import("./chunks/register-list-query-3GV3LBOT.js")),Fu=Ke(()=>import("./chunks/register-mutation-GZLF47SX.js")),Du=Ke(()=>import("./chunks/register-operations-PBJZGCAL.js"));function en(e){return _(e)}function pc(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=>fe(o)??o))];return n.length>0?n:void 0}function ju(e,t,n,o){if(n?.suggested_retry||o===to||o===eo||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=>fe(m)??m)),a=pc(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=>fe(u)).filter(u=>u!==void 0))),d=a?.filter(m=>{let u=fe(m)??m;return r.has(u)?!1:l.has(u)||bo(t,s,u,O)!==void 0});return d&&d.length>0?d:void 0}function Uu(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],r=i?fe(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=bo(e,a,r,O),d=r?c?.isBoolean()===!0||l===!1?[r]:[r,"<value>"]:[],m=r?en([...e,...d]):t;return m===t?void 0:m}function qu(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 Hu(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,...qu(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function oc(e,t){return{...e,recovery:t}}function Gu(e,t){if(t===void 0)return;let n=Na(e,t.code,t.field,Ta(e,t.code,t.recovery)),o=zu(e),i=Ma(e,t.code,t.field,n,o),r=Pa(e,t.code,i,o,()=>Dr(I(process.cwd(),$(e).path)));return La(e,t.code,r,o)}var ic=" ";function zu(e){let t=e.map(i=>i===""?ic:/^--(?:pm-)?path=$/u.test(i)?`${i}${ic}`:i),n=$(t).path;if(n!==void 0&&n.trim()!=="")return[];let o=Se({});return n!==void 0&&o.length>0?null:o}function fc(e,t,n){let o=ze(t),i=D(o),r=N(i),[a,s]=r===void 0?[]:i.slice(r,r+2),c=o.includes("--explain");e=e===void 0?void 0:vr(e);let l=Gu(o,e),d=l&&(a==="history-redact"||a==="history"&&s==="redact")?{...l,...l.attempted_command?{attempted_command:en(o)}:{},...l.normalized_args?{normalized_args:[...o]}:{},...l.suggested_retry?{suggested_retry:en(o)}:{},...l.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:l;if(d?.recovery_mode==="compact"&&!c)return oc(e,d);let m=en(o),u=ee(o),p=ju(n,o,d,e?.code),f=Uu(o,m,p,d),y=Hu({invocationArgv:o,attemptedCommand:m,providedFields:u,inferredMissing:p,suggestedRetry:f,existingRecovery:d});return oc(e,y)}async function ft(e){let t=U;U=null,await Fa(t,e);let n=ke;if(ke=null,!n){Ct();return}let o=[],i=ur();try{await Da({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 or(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{Ct()}!n.globalOptions.json&&o.length>0&&x(`[pm] warning: afterCommand hook_warnings=${z(o)}`),n.profileEnabled&&o.length>0&&x(`profile:extensions hook_warnings=${z(o)}`)}async function gc(e,t){await kr();let n=U,o=ke,i=n?.command??o?.commandName??e,r=n??En(o?.globalOptions??t),a=O.get(v(i))?.source;Pn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:r.source_context,source_context_source:r.source_context_source,pm_version:n?.pm_version??qe,extension:a})}function hc(e){return Nu.has((process.env[e]??"").trim().toLowerCase())}function yc(e){return hc("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!$u.has(Math.trunc(e))}async function on(e,t){return yc(e.exit_code)?(await gc(e.command,t),Or({...e,source_context:e.source_context??En(t).source_context}),!0):!1}async function _c(e){let t=J(me(e.error)),n=ms(t);e.bootstrapGlobal.json?x(JSON.stringify(et(ls(t,g.GENERIC_FAILURE)),null,2)):x(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await gc(e.attemptedCommand,e.bootstrapGlobal),$n(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 sn(!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 Re()}catch(r){e.bootstrapGlobal.json||x(`Failed to flush error reporting: ${me(r)}`)}}var Wu={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"},li=new Map;function di(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function wc(e,t){return e.options.some(n=>n.long===t)}function vc(e,t){return e.options.some(n=>n.short===t)}function mi(e,t,n,o){let i=t.trim();if(!i||!$i(i))return;let r=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(vc(e,i))return;if(o){e.option(`${i} <value>`,`${r} (repeatable)`,Un);return}e.option(`${i} <value>`,r);return}let a=i.startsWith("--")?i:`--${i}`;if(!wc(e,a)){if(o){e.option(`${a} <value>`,`${r} (repeatable)`,Un);return}e.option(`${a} <value>`,r)}}async function Cc(e,t){let n=Wu[e];if(!n)return[];let o=`${t}:${n}`,i=li.get(o);if(i)return i;if(!await Y(X(t)))return li.set(o,[]),[];let r=await F(t),s=(hn(r.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:di(c.type),value_type:di(c.type)})));return li.set(o,s),s}async function xc(e,t){let n=$(t),o=I(process.cwd(),n.path);if(!await Y(X(o)))return;let i=be?.key===_i(o)?be.snapshot:null,r=i===null?await F(o):i.settings,a=hn(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??"";mi(l,d.cli_flag,m,d.repeatable);for(let u of d.cli_aliases)mi(l,u,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function hi(e,t,n,o,i){let r=S(n);if(!(r!=="create"&&r!=="update"))try{let a=i??await F(t),s=ce(a,o);js(e,s,n)}catch{}}function ui(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function bc(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function yi(e){return e.some(t=>t==="--profile")}function _i(e){return`pm-root:${e}`}function pi(e){for(let t of e)t.startsWith("settings_read_")&&pe(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function kc(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=${z(t.activationWarnings)}`))}function rn(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 an(e,t=Ae){let n=_i(e);if(be?.key===n)return be.snapshot;try{let o=Date.now(),{settings:i,warnings:r}=await t(e),a=await ir({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...r]};return be={key:n,snapshot:s},s}catch{return be={key:n,snapshot:null},null}}async function He(e,t,n=F){let o=t?lt(t):"all",i=bc(e,o);if(pt?.key===i)return pt.snapshot;try{let r=await n(e),a=await Ve({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Ho(t):void 0}),s=await Je({...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=xs(s.registrations.flags),d=vs(s.commands.handlers,s.registrations.commands),m=ks(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 Sc(e){let t=Ze(e);if(t.noExtensions){let a=I(process.cwd(),t.path);return await Y(X(a))&&pi((await Ae(a)).warnings),null}let n=I(process.cwd(),t.path),o=await an(n);if(!o)return null;pi(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:Go(e)};if(!ct(o.discovery,i))return rn(t.profile,o,i),null;let r=await He(n,i);return r?(kc(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 wi(e){let t=await He(e);return t?new Map(t.commandDescriptors):O}async function Bu(e,t){return!e.requested||t.noExtensions||Ne(w,e.commandPathTokens)?O:wi(I(process.cwd(),t.path))}async function Ec(e,t){return(await Gr({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 Ac(e,t,n){let o=t.author;return Hr(e,ua.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function Rc(e,t,n,o=[]){let i=E(e),r=Gn(e.args.map(String),o),a={...t};delete a.author;let s={...n},c=I(process.cwd(),n.path),l={args:[...r],path:n.path},d=await xt({command:i,args:r,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&x(`profile:extensions parser_warnings=${z(d.warnings)}`),r=d.context.args,a=d.context.options,s=d.context.global,Yn(l,{args:r,path:s.path},a),Jo(O.get(v(i)),r,a,o),Ee(void 0),vt({command:i,args:r,options:{...a},global:{...s},pm_root:c});let m=await Sn({command:i,args:r,options:a,global:s,pm_root:c,sdk:Ac(c,s,i)});if(s.profile&&m.warnings.length>0&&x(`profile:extensions command_handler_warnings=${z(m.warnings)}`),!m.handled)throw m.warnings.length>0?Sr(i,m):new T(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return m.exitCode!==void 0&&(process.exitCode=m.exitCode),Ee(m.result),m.result}var rc=Symbol("pm.wrappedActionHandler");function Vu(e,t){let n=e[e.length-1];return n instanceof fi?n:t}function ac(e,t,n){e&&n.length>0&&x(`profile:extensions ${t}=${z(n)}`)}function Ju(e){let t=O.get(v(e.commandPath));if(!t||!Bo(e.activeRegistrations,e.commandPath))return;let n=Yt(t).length===0?na(e.commandArgs):Gn(e.commandArgs,e.extensionFlagDefinitions);Vo(t,n)}function Ku(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 vi(e,t,n){if(!at(e))return;let o=O.get(v(t))?.read_output_declared===!0;return Xt(n,o)}function Oc(e){let t=n=>{let o=n;if(Xs(n),typeof o._actionHandler=="function"&&o[rc]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let s=Vu(a,n),c=Date.now();jn(s);let l=Ze(s),d=q(E(s));if(["package inventory","packages inventory","extension inventory"].includes(d))return Aa(d,l.expectHash),await i.apply(this,a);let m=I(process.cwd(),l.path),u=s.args.map(String),p=le(),f=p?dt(p,d,u):[],y=await Cc(d,m),h=vi(s,d,f),C=je(s,u,[...f,...y],h);Qs(s,f,d),O.has(v(d))&&delete C.author,h!==void 0&&Ks(C,f,d);let A={args:[...u],path:l.path},R=await xt({command:d,args:u,options:C,global:l,pm_root:m});ac(l.profile,"parser_warnings",R.warnings),u=R.context.args,C=R.context.options,se(s,C),l=R.context.global,Yn(A,{args:u,path:l.path},C),Ju({activeRegistrations:p,commandPath:d,commandArgs:u,extensionFlagDefinitions:f}),l=await Zr(l),It(s,l),Ku(s,a,u),Tt(s,C),Ee(void 0),vt({command:d,args:u,options:{...C},global:{...l},pm_root:m});let k=await Sn({command:d,args:u,options:C,global:l,pm_root:m,sdk:Ac(m,l,d)});if(ac(l.profile,"command_handler_warnings",k.warnings),k.handled){Ee(k.result),bn(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[rc]=!0}for(let i of n.commands)t(i)};t(e)}async function Qt(e){O=new Map,re({overrides:[]}),e&&await hi(e.rootProgram,e.pmRoot,e.invocationArgv,tr(),e.settings)}function Yu(e,t,n,o){if(t?.flags&&t.flags.length>0){Eo(e,t.flags);let i=Ao(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);t&&at(e)&&e.addHelpText("after",Oo(t)),o&&e.addHelpText("after",o)}function Xu(e,t,n,o){t&&e.addHelpText("after",t),n&&e.addHelpText("after",Oo(n)),o&&e.addHelpText("after",o)}function Tc(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");Lt(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 Ic(e,t){let n=$(t),o=I(process.cwd(),n.path);if(n.noExtensions){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await an(o),r=De(t);if(!i){await Qt();return}if(!ct(i.discovery,r)){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),rn(yi(t),i,r);return}let a=await He(o,r);if(!a){await Qt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}re(a.services),O=new Map(a.commandDescriptors),await hi(e,o,t,a.registrations,a.settings);let s=Is(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,d=>Ps(a.activationWarnings,x,d)),c=new Set(e.commands.map(d=>d.name())),l=d=>{let m=d.split(" ").filter(A=>A.length>0),u=a.commandDescriptors.get(d),p=oe(e,m),f=a.commandFlagHelp.get(d),y=u?Os(u):null;if(p){Yu(p,u,f,y);return}let h=Ts(e,m);u?.description&&h.description(u.description);let C=f;u&&(Ss(h,u),u.flags.length>0&&(Eo(h,u.flags),C=Ao(h,u.flags)??void 0)),Xu(h,C,u,y),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...A)=>{let R=A[A.length-1],k=R instanceof fi?R:h,gt=Ze(k),Gc=Date.now(),cn=dt(a.registrations,d,k.args.map(String)),bi=je(k,k.args.map(String),cn,vi(k,d,cn)),ki=await Rc(k,bi,gt,cn);await Qr(gt,ki),bn(ki,{...gt,command:d,commandArgs:k.args.map(String),commandOptions:bi,pmRoot:o}),gt.profile&&x(`profile:command=${d} took_ms=${Date.now()-Gc}`)})};for(let d of s)l(d);Tc(e,c,a.commandDescriptors)}var qe=er(import.meta.url,["../.."])??"0.0.0",w=Dn(qe);async function sc(e){if(!U)return;let t=Reflect.get(e,uc);typeof t=="string"&&await ma(t)}async function cc(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function lc(e,t,n){!U||!await An(!0)||(Pn(e,t,n,{source_context:U.source_context,source_context_source:U.source_context_source}),Er(e),nn=U)}async function sn(e,t,n){let o=nn;if(!o)return;nn=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 An(i)?Rr(e,t,n):Ar()}async function Zu(e){let t=await Sc(e);return kn(t?.registrations??null),t}function Pc(e,t){t&&mt(t)||(e.hook("preAction",async(n,o)=>{ke=null,U=null,nn=null,Ct(),jn(o);let i=o.optsWithGlobals(),r=Ze(o),a=q(E(o)),s=o.args.map(String),c={args:[...s],path:r.path},l=je(o,s),d={...r},m=I(process.cwd(),r.path),u=await Zu(o);if(Gi(a,{...l,...Hi(a,o.processedArgs),outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Wo(o,a,d,l),await cc(o,void 0,()=>$r(a,d)),!u){ke=rr({commandName:a,commandArgs:s,commandOptions:l,globalOptions:d,pmRoot:m}),U=await Nn({command:a,pm_version:qe,args:s,options:l,global:d,pm_root:m}),await sc(e),await lc(a,s,l),await No(a,l,m,ui()),await $o(a,s,l,d,m),await Kn({command:o,commandPath:a,commandArgs:s,commandOptions:l,expectHash:r.expectHash,pmRoot:m,globalOptions:d});return}ar(u.hooks),sr(u.commands),cr(u.parsers),lr(u.preflight),re(u.services),dr(u.renderers),kn(u.registrations);let p=dt(u.registrations,a,s);l=je(o,s,p,vi(o,a,p)),Wo(o,a,d,l);let f=await xt({command:a,args:s,options:l,global:d,pm_root:u.pmRoot});d.profile&&f.warnings.length>0&&x(`profile:extensions parser_warnings=${z(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),d=f.context.global;let y={args:[...s],path:d.path};Tt(o,l);let h=await pr({command:a,args:s,options:l,global:d,pm_root:u.pmRoot,decision:ui()});d.profile&&h.warnings.length>0&&x(`profile:extensions preflight_warnings=${z(h.warnings)}`),s=h.context.args,l=h.context.options,se(o,l),d=h.context.global,Tt(o,l);let C=h.decision;await No(a,l,u.pmRoot,C),await $o(a,s,l,d,u.pmRoot),await Kn({command:o,commandPath:a,commandArgs:c.args,commandOptions:l,expectHash:r.expectHash,pmRoot:u.pmRoot,rewritten:Jn(c,[y,{args:s,path:d.path}]),globalOptions:{...d,path:r.path,noExtensions:r.noExtensions}});let A=C.run_extension_migrations?await cc(o,[],()=>Ec(u.registrations.migrations,u.pmRoot)):[];d.profile&&A.length>0&&x(`profile:extensions migration_warnings=${z(A)}`);let R=Hs(u.registrations.migrations);ke={hooks:u.hooks,commandName:a,commandArgs:s,commandOptions:{...l},globalOptions:{...d},pmRoot:u.pmRoot,profileEnabled:!!d.profile,migrationBlockers:R},Ee(void 0),vt({command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot}),U=await Nn({command:a,pm_version:qe,args:s,options:l,global:d,pm_root:u.pmRoot}),await sc(e),await lc(a,s,l);let k=await nr(u.hooks,{command:a,args:s,options:{...l},global:{...d},pm_root:u.pmRoot});d.profile&&k.length>0&&x(`profile:extensions hook_warnings=${z(k)}`),C.enforce_mandatory_migration_gate&&Gs(a,l,R)}),e.hook("postAction",async()=>{let n=si();await sn(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 Re()}))}Pc(w);var dc=Symbol("pmCliIdempotentTopLevelRegistration");function $c(e){let t=e;if(t[dc])return;t[dc]=!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 fi(r):n(o,...i)})}async function Qu(e,t){if($c(e),t.setup){let{registerSetupCommands:n}=await Mu();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Lu(),o=typeof t.targetCommandName=="string"&&Ko.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Fu();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Du();n(e)}}function Ue(e){return e.rawInvocationArgv??e.invocationArgv}function ep(e){return async t=>{let n=ht(t.errorCode),o=St({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Mr({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:qe,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 Nc(e){if(e.bootstrapGlobal.noExtensions||mt(e.invocationArgv))return;let t=De(e.invocationArgv),n=await an(e.bootstrapPmRoot);if(n&&ct(n.discovery,t)){let o=await He(e.bootstrapPmRoot,t);Mc(o);return}n&&rn(yi(e.invocationArgv),n,t),re({overrides:[]})}function Mc(e){if(!e){re({overrides:[]});return}re(e.services)}async function Ci(e){await sn(!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 Lc(){await sn(!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 Fc(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof T)&&(Tn(e.error)||!n))return!1;let o=J(me(e.error)),i=e.error instanceof T?e.error.exitCode:On(t),r=e.error instanceof T||br(e.error)?e.error.context:void 0,a=fc(r,e.invocationArgv,o),s=ss(o,a),c=et(e.bootstrapGlobal.lean?Dt(go(o,i,a)):go(o,i,a)),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Z(c,p=>`${JSON.stringify(p,null,2)}
|
|
40
|
+
`):c,null,2):rs(o,a,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?ie(`${l}
|
|
41
|
+
`):x(l);let{errorCategory:d,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 on({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context},e.bootstrapGlobal);return await Ci({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),u&&($n(In(e.error,o)),await Re(gi)),process.exitCode=i,!0}async function Dc(e,t){let n=P(e.invocationArgv).commandPathTokens.join(" ")||_o(e.invocationArgv),o=q(n),i=`unknown command '${n}'`,r=I(process.cwd(),e.bootstrapGlobal.path),a=e.bootstrapGlobal.noExtensions?O:await wi(r),s=De(e.invocationArgv),c=e.bootstrapGlobal.noExtensions?[]:await Io(r,{},Fe(s)),l=await it({message:i},w,a,{failedExtensions:c},Ue(e)),d=ho(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:c}),{errorCategory:m,commandResolution:u}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await on({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:u,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await xo({message:i},w,a,e.bootstrapGlobal.lean===!0,{failedExtensions:c},Ue(e)):await Co({message:i},w,a,{failedExtensions:c},Ue(e)),y=yo(f,e.jsonErrors,c);await Ci({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:u,resolutionStage:"parse"}),e.jsonErrors?ie(`${Bn(y)}
|
|
42
|
+
`):x(y),p&&await Re(gi),process.exitCode=g.USAGE}async function jc(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let i=P(e.invocationArgv);return i.requested&&!Ne(w,i.commandPathTokens)?(await Dc(e,t),!0):(await Lc(),!0)}async function Uc(e,t){let n=await it(e.error,w,O,{},Ue(e)),o=ho(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 on({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:U?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await xo(e.error,w,O,e.bootstrapGlobal.lean===!0,{},Ue(e)):await Co(e.error,w,O,{},Ue(e)),c=await $s(o.code,e.bootstrapPmRoot,{},Fe(De(e.invocationArgv))),l=yo(s,e.jsonErrors,c);await Ci({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:r,resolutionStage:"parse"}),e.jsonErrors?ie(`${Bn(l)}
|
|
43
|
+
`):x(l),a&&await Re(gi),process.exitCode=g.USAGE}function qc(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 Hc(e){let t=e.error.code,n=String(e.error.message??"");if(!await jc(e,t,n)){if(t==="commander.version"){await Lc();return}await Uc(e,t)}}async function xi(e){let t=$(e.invocationArgv),n=I(process.cwd(),t.path),o=ge(e.invocationArgv),i={error:e.error,invocationArgv:o,rawInvocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:S(o)??"<unknown>",emitTelemetryCommandError:ep({invocationArgv:o,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Nc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Fc(i,Rn(e.error))){if(qc(e.error)){await Hc(i);return}await _c({error:e.error,attemptedCommand:i.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:i.emitTelemetryCommandError})}}function tp(e,t,n){let o=n.requested?n.commandPathTokens:D(t),i=B(o);if(i&&!oe(e,[...i.canonical_argv]))throw new mc(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function np(e,t){let n=N(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let a=N(t.slice(n+1));if(a===void 0)return;n+=a+1}let o=tn.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,uc,r.alias)}function op(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function ip(e,t){w=Dn(qe),w.hook("preAction",(r,a)=>{t.configurationOnly=["item mutate","item complete"].includes(E(a))&&a.optsWithGlobals().dryRun===!0}),Pc(w,e),pt=null,be=null,O=new Map,mr();let n=[...e],o,i;try{let r=Xe(e);n=r.argv,xa(r.trace),np(w,e);let a=op(n),s=n.length===0,c=$(n);if(c.authorMissingValue)throw new T("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Yr(c.author),ei(r),i=zr(n);let l=Yo(n);await Qu(w,l),ro(w,!0),Zo(w,n)?await Ic(w,n):(O=new Map,re({overrides:[]})),Qo(n)&&await xc(w,n),ro(w);let m=P(n);tp(w,n,m),Xo(n)&&za(w,n),Oc(w);let u=await Bu(m,c);if(await Ds(w,n,u,e))return;if(m.requested&&!Ne(w,m.commandPathTokens))throw new mc(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ae(n)&&S(n)===void 0){w.outputHelp();return}if(mt(n)){await w.parseAsync(a);return}let f=I(process.cwd(),c.path),y=await F(f),h=await _s(n,f,c.noExtensions,He);await Ra(C=>qr({pmRoot:f,packages:h?.contextIntentPackages},()=>Ni({env:{...process.env,PM_PATH:f},argv:a,cwd:process.cwd()},()=>Mi(y.agent_identity.harness_signals,()=>C(()=>w.parseAsync(a)),{probesEnabled:y.agent_identity?.probes_enabled}))))}catch(r){await xi({error:r,invocationArgv:n})}finally{i?.(),o?.()}}async function Rh(e=process.argv.slice(2)){let t=e;try{t=Xe(e).argv}catch{}await Ti([...e,...t],()=>rp(e,t))}async function rp(e,t){let n=tc(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,r=()=>ka($(t).json,async()=>{try{await Xr(process.env,()=>ip(e,o))}catch(a){await xi({error:a,invocationArgv:[...e]})}});if(n!==void 0){let a=I(process.cwd(),$(t).path),s=I(process.cwd(),n.path),c=Oi(process.cwd());await bt(a,()=>bt(s,()=>bt(c,r,i),i),i)}else await r()}var Oh={activationCommandMatchesProbe:Lo,applyDynamicExtensionRootHelpVisibility:Tc,bootstrapProfileEnabled:yi,buildBootstrapActivationProbe:De,buildPostActionTelemetryOutcome:si,buildPmCliRecoveryContext:fc,buildRuntimeExtensionDiscoverySnapshotCacheKey:_i,buildRuntimeExtensionActivationScope:lt,buildRuntimeExtensionSnapshotCacheKey:bc,buildRuntimeExtensionFilterForProbe:Ho,addRuntimeFieldOption:mi,collectActivationCommandCandidates:Fe,collectExtensionFlagDefinitionsForCommand:Qe,collectExtensionFlagDefinitionsForInvocation:dt,collectLeadingCommandArgs:Mo,collectParsedActivationCommandArgs:Go,collectRuntimeFieldLooseFlagDefinitionsForCommand:Cc,commandHasLongOption:wc,commandHasShortOption:vc,commandPathNeedsSearchExtensions:Fo,commandPathNeedsTemplateExtensions:Vt,describeUnknownError:me,defaultPreflightDecision:ui,discoveryNeedsActivationForProbe:ct,emitExtensionProfile:kc,emitExtensionSkippedProfile:rn,emitSettingsReadWarnings:pi,ensureIdempotentTopLevelCommandRegistration:$c,enforceExplicitRetryForFlagTypos:ei,envFlagEnabled:hc,executeRegisteredRuntimeMigrations:Ec,extractCommandScopedOptions:je,extensionActivationCommands:Bt,extensionCapabilities:st,extensionNeedsActivationForProbe:Jt,extensionProvidesTemplatesRuntime:jo,hasAnyCapability:Le,hasGlobalExtensionContributions:Uo,handleGenericRunPmCliError:_c,handleRunPmCliCommanderError:Hc,handleRunPmCliError:xi,handleRunPmCliHelpDisplayError:jc,handleRunPmCliKnownError:Fc,handleRunPmCliCommanderUsageError:Uc,handleUnknownHelpCommandError:Dc,inferMissingFieldsFromErrorMessage:pc,inferPostActionErrorCode:ai,inferPostActionFailureMessage:ri,invocationRequestsVersion:ut,isCommanderError:Tn,loadRuntimeExtensionCommandDescriptorsForRecovery:wi,loadRuntimeExtensionDiscoverySnapshot:an,loadRuntimeExtensionSnapshot:He,maybeLoadRuntimeExtensions:Sc,maybeAttachCreateUpdatePolicyHelpText:hi,maybeLogHandledCliErrorToSentry:on,matchesStaticExtensionCommand:Wt,normalizeTelemetryCommandResolution:ni,normalizeTelemetryErrorCategory:ii,normalizeTelemetryResolutionStage:oi,normalizeThrownExitCode:On,probeUsesAnyFlag:Do,prepareExtensionServicesForRunPmCliError:Nc,readRecordBoolean:ti,readRecordNumber:Zt,readRecordString:xe,recordCliReadOutputInvocationProvenance:zo,registerDynamicExtensionCommandPaths:Ic,registerRuntimeSchemaFieldFlags:xc,resolveCoreCommandRegistrationSelection:Yo,resolveStaticExtensionActivationDecision:qo,resolveUnknownHelpToken:_o,readThrownExitCode:Rn,runAndClearAfterCommandHooks:ft,runRequiredExtensionCommand:Rc,shouldAttachRichHelpTextForInvocation:Xo,shouldLogHandledErrorToSentry:yc,shouldRegisterDynamicExtensionPaths:Zo,shouldRegisterRuntimeSchemaFlags:Qo,shouldHandleRunPmCliCommanderError:qc,setActiveExtensionHookContextForTest:Iu,setActiveRuntimeExtensionCommandDescriptorsForTest:Pu,setRecoveredExtensionServices:Mc,toLooseFieldDefinitionType:di,isImporterOrExporterCommandPath:Bo,validateDynamicExtensionCommandInvocation:Jo,wrapProgramActionsForExtensionHandlers:Oc,wrapThrownErrorForSentry:In};export{Oh as _testOnly,Rh as runPmCli};
|
|
44
44
|
//# sourceMappingURL=main.js.map
|