@unbrained/pm-cli 2026.8.22 → 2026.8.24
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 +2 -2
- package/CHANGELOG.md +42 -1
- package/dist/cli/description-stdin.js +5 -4
- package/dist/cli/error-guidance.d.ts +13 -0
- package/dist/cli/error-guidance.js +62 -6
- package/dist/cli/extension-command-help.d.ts +5 -0
- package/dist/cli/extension-command-help.js +6 -2
- package/dist/cli/help-content.d.ts +5 -0
- package/dist/cli/help-content.js +56 -3
- package/dist/cli/help-json-payload.d.ts +5 -2
- package/dist/cli/help-json-payload.js +57 -17
- package/dist/cli/main.d.ts +3 -0
- package/dist/cli/main.js +39 -5
- package/dist/cli/register-annotations.js +5 -5
- package/dist/cli/register-mutation.js +77 -31
- package/dist/cli/register-operations.d.ts +73 -0
- package/dist/cli/register-operations.js +39 -14
- package/dist/cli/register-setup.js +3 -3
- package/dist/cli/schema-registration-helpers.d.ts +8 -1
- package/dist/cli/schema-registration-helpers.js +14 -5
- package/dist/cli-bundle/bundle-manifest.json +155 -155
- package/dist/cli-bundle/chunks/chunk-AGUL3HUT.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-WG4STC36.js → chunk-DJNJBWAQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MYYI3ZOA.js → chunk-I5Q7QSZX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IW72J5FW.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-BWX4SK46.js → chunk-L22NP5MA.js} +66 -66
- package/dist/cli-bundle/chunks/chunk-MKE6MD2K.js +36 -0
- package/dist/cli-bundle/chunks/{chunk-MZTZQTMS.js → chunk-NXBFO63A.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TEQDR5KI.js +202 -0
- package/dist/cli-bundle/chunks/chunk-X7WWQDYQ.js +2 -0
- package/dist/cli-bundle/chunks/chunk-YOLLRCLY.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-U6GQ4VMV.js → chunk-ZAVCS2GH.js} +4 -4
- package/dist/cli-bundle/chunks/{register-list-query-HZKBQNWW.js → register-list-query-37A4P6O4.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-TBJDHYIT.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-WRZNEBUM.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-QK4OTOXN.js → register-setup-H4PDLACD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GMYPD4FX.js → chunk-4WP7LNE3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-6MUTDXMP.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-6Z24ZMU3.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2ARQGDDW.js → chunk-BFA6KKCI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CWCN5RLO.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-FCTT4CZU.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-GJR6YEMR.js +156 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2POVTNLY.js → chunk-IMWTYKII.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-D6RBZEJJ.js → chunk-IZNRRCU3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PMGJUFNQ.js → chunk-MNPECIRL.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-A2BC5PQL.js → chunk-O4ZXNJMT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Q63PSLO4.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QBP5FSBX.js +4 -0
- package/dist/cli-bundle/focused-chunks/{chunk-R6SR45XU.js → chunk-QV5UP27O.js} +48 -47
- package/dist/cli-bundle/focused-chunks/chunk-RASVBJX5.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E2EWYPY6.js → chunk-RPRLENVA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TOFVXBWA.js +19 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6S2MO3Q3.js → chunk-WZLSSGEU.js} +2 -2
- package/dist/cli-bundle/main.js +18 -17
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +41 -41
- 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 +33 -32
- 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 +6 -5
- package/dist/core/config/nested-settings.js +8 -2
- package/dist/core/config/positional-value.d.ts +1 -1
- package/dist/core/config/positional-value.js +5 -2
- package/dist/core/extensions/command-metadata-contract.d.ts +10 -0
- package/dist/core/extensions/command-metadata-contract.js +23 -0
- package/dist/core/extensions/command-visibility-tier.js +12 -2
- package/dist/core/extensions/extension-types.d.ts +6 -0
- package/dist/core/extensions/extension-types.js +2 -2
- package/dist/core/extensions/loader.js +4 -3
- package/dist/core/history/history.js +3 -3
- package/dist/core/io/body-file.js +7 -2
- package/dist/core/io/bulk-ids-input.d.ts +24 -0
- package/dist/core/io/bulk-ids-input.js +113 -0
- package/dist/core/item/item-format.js +66 -12
- package/dist/core/item/parse.d.ts +22 -2
- package/dist/core/item/parse.js +97 -4
- package/dist/core/reproducibility/context.d.ts +4 -0
- package/dist/core/reproducibility/context.js +14 -8
- package/dist/core/shared/author.d.ts +55 -1
- package/dist/core/shared/author.js +333 -16
- package/dist/core/shared/constants.js +3 -2
- package/dist/core/store/settings-validator.d.ts +1 -0
- package/dist/core/store/settings-validator.js +6 -3
- package/dist/core/store/settings.js +5 -2
- package/dist/mcp/server.d.ts +4 -3
- package/dist/mcp/server.js +44 -16
- package/dist/sdk/agent/identity-config.d.ts +63 -0
- package/dist/sdk/agent/identity-config.js +107 -0
- package/dist/sdk/agent/refusal-closure-census.d.ts +66 -0
- package/dist/sdk/agent/refusal-closure-census.js +144 -0
- package/dist/sdk/agent/refusal-corpus-contracts.d.ts +76 -0
- package/dist/sdk/agent/refusal-corpus-contracts.js +194 -0
- package/dist/sdk/agent-capability-contracts.d.ts +34 -1
- package/dist/sdk/agent-capability-contracts.js +104 -6
- package/dist/sdk/annotations.d.ts +2 -0
- package/dist/sdk/annotations.js +25 -7
- package/dist/sdk/cli-contracts/agent-output-contracts.js +6 -4
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +4 -0
- package/dist/sdk/cli-contracts/enum-contracts.js +9 -2
- package/dist/sdk/cli-contracts/flag-contracts.js +9 -2
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +4 -4
- package/dist/sdk/cli-contracts/registration-helpers.js +5 -2
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +58 -2
- package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +14 -3
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +4 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.js +2 -2
- package/dist/sdk/cli-contracts.d.ts +3 -3
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/comments.js +15 -7
- package/dist/sdk/config.d.ts +6 -1
- package/dist/sdk/config.js +119 -14
- package/dist/sdk/context-intent-contracts.js +4 -2
- package/dist/sdk/core-governance.d.ts +1 -1
- package/dist/sdk/core-governance.js +3 -3
- package/dist/sdk/extension/scaffold.js +11 -5
- package/dist/sdk/flag-invocation-contracts.d.ts +2 -0
- package/dist/sdk/flag-invocation-contracts.js +30 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +83 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +87 -2
- package/dist/sdk/governance/assurance-action.js +30 -10
- package/dist/sdk/governance/validate.d.ts +2 -2
- package/dist/sdk/governance/validate.js +39 -14
- package/dist/sdk/guide-topics.d.ts +0 -5
- package/dist/sdk/guide-topics.js +28 -2
- package/dist/sdk/history-compact.d.ts +2 -1
- package/dist/sdk/history-compact.js +24 -5
- package/dist/sdk/history-mcp.js +11 -10
- package/dist/sdk/index.d.ts +8 -2
- package/dist/sdk/index.js +9 -3
- package/dist/sdk/item-transaction.js +19 -12
- package/dist/sdk/lifecycle/append.js +4 -4
- package/dist/sdk/lifecycle/close-many.js +16 -7
- package/dist/sdk/lifecycle/create.js +33 -22
- package/dist/sdk/lifecycle/plan.js +24 -6
- package/dist/sdk/lifecycle/update-many.js +15 -8
- package/dist/sdk/lifecycle/update.d.ts +2 -0
- package/dist/sdk/lifecycle/update.js +37 -25
- package/dist/sdk/merge/three-way.js +105 -26
- package/dist/sdk/read-output-budget.d.ts +21 -0
- package/dist/sdk/read-output-budget.js +39 -2
- package/dist/sdk/read-output-contracts.d.ts +5 -3
- package/dist/sdk/read-output-contracts.js +20 -12
- package/dist/sdk/reproducibility/process.d.ts +19 -0
- package/dist/sdk/reproducibility/process.js +88 -0
- package/dist/sdk/runtime-extended-actions.js +5 -3
- package/dist/sdk/runtime-input.d.ts +4 -0
- package/dist/sdk/runtime-input.js +98 -23
- package/dist/sdk/runtime-primitives.d.ts +3 -2
- package/dist/sdk/runtime-primitives.js +5 -4
- package/dist/sdk/runtime.js +11 -23
- package/dist/sdk/scheduling-shortcuts.js +5 -3
- package/dist/sdk/structured-mutations.js +10 -3
- package/dist/sdk/test/batch.d.ts +6 -0
- package/dist/sdk/test/batch.js +15 -3
- package/dist/sdk/test/entry.d.ts +1 -1
- package/dist/sdk/test/entry.js +3 -2
- package/dist/sdk/test/execution.d.ts +28 -3
- package/dist/sdk/test/execution.js +193 -34
- package/dist/sdk/test/parsers.d.ts +6 -0
- package/dist/sdk/test/parsers.js +21 -2
- package/dist/sdk/test/trust.d.ts +33 -0
- package/dist/sdk/test/trust.js +207 -0
- package/dist/sdk/workspace-contracts.d.ts +3 -0
- package/dist/sdk/workspace-contracts.js +3 -2
- package/dist/types.d.ts +23 -0
- package/dist/types.js +2 -2
- package/docs/AGENT_PROVENANCE_ADR.md +41 -5
- package/docs/CONFIGURATION.md +4 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +19 -2
- package/docs/MERGE_SAFETY.md +15 -1
- package/docs/README.md +2 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +11 -1
- package/docs/RELEASING.md +40 -21
- package/docs/REPRODUCIBLE_WORKSPACES.md +42 -8
- package/docs/SCRIPTING.md +62 -3
- package/docs/SDK.md +17 -0
- package/docs/SDK_AGENT_SESSION_CONTEXT.md +6 -4
- package/docs/SDK_EVIDENCE_TRACEABILITY.md +1 -1
- package/docs/TESTING.md +75 -8
- package/docs/agent-task-token-baseline.json +2 -2
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +17 -0
- package/docs/generated/AGENT_COMMAND_SURFACE.md +1 -1
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +355 -0
- package/marketplace.json +2 -2
- package/package.json +2 -2
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/README.md +9 -11
- package/packages/pm-command-kit/extensions/command-kit/index.ts +3 -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/extensions/guide-shell/index.ts +10 -0
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/generate-agent-capability-surfaces.mjs +27 -1
- package/sdk/public-surface.json +642 -28
- package/dist/cli-bundle/chunks/chunk-EMWDM5FI.js +0 -13
- package/dist/cli-bundle/chunks/chunk-HYG6LRL4.js +0 -200
- package/dist/cli-bundle/chunks/chunk-QI2CT3IX.js +0 -2
- package/dist/cli-bundle/chunks/chunk-SMWXHMVB.js +0 -35
- package/dist/cli-bundle/chunks/chunk-VMMIL3SI.js +0 -2
- package/dist/cli-bundle/chunks/chunk-YBPJAOQQ.js +0 -3
- package/dist/cli-bundle/chunks/register-mutation-HTKEEGRD.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-6EMRWJJY.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2AZT5WXZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3LKU6PTJ.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-5SHSBMX2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-C4S4A4JJ.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-L5LDSRO2.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-MB37AYN6.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-MCOR37QK.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PH2OXXVZ.js +0 -18
- package/dist/cli-bundle/focused-chunks/chunk-WZE4LIPW.js +0 -8
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,29 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function or(e,t){return t==="detailed"?Ci(e):vi(e)}function $(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var ki={cal:"calendar",ctx:"context"};function Ei(e,t){return e.commands.find(n=>n.name()===t)??null}function Si(e,t){let n=e;for(let o of t){let r=Ei(n,o);if(!r)return null;n=r}return n}function Gt(e,t,n,o){let r=Si(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",or(n,o))}function Bt(e){return e.includes("--explain")?"detailed":"compact"}var rr={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 install ./my-package --project","pm 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 extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension 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 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 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 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 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 extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --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 extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension 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 extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension 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 extension catalog --project","pm extension 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 install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm 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 upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm 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."]},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-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-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-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-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 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?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","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 "All acceptance criteria met" --message "Close after verification"','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 --message "Claim for implementation"','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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","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 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task 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."]}},Wt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-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."]};function Ai(e){let t=$(e??"");return t?ki[t]??t:""}function Ti(e){let t=Ai(e);return t?rr[t]??Wt:Wt}function ar(e,t){let n=Ti(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:nr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function ir(e,t=process.argv.slice(2)){let n=Bt(t);e.addHelpText("after",or(Wt,n));for(let[i,s]of Object.entries(rr))Gt(e,i,s,n);let o=$(P(t).commandPathTokens.join(" ")),r=we(o);if(r){Gt(e,r.parent,{why:r.description,examples:[r.example],tips:[`Action path: pm ${r.command}`,We(r.accepted_flags)]},n);return}let a=Ge.filter(({parent:i})=>i===o);a.length>0&&Gt(e,o,{why:`Dispatches one declared positional action: ${a.map(({action:i})=>i).join("|")}.`,examples:a.map(({example:i})=>i),tips:[`Inspect one action directly with pm ${o} <action> --help --json.`]},n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function sr(e,t){await To(e,{ok:t.ok,error:t.error,result:fe(),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 cr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await R(e.pmRoot);await Do({pmRoot:e.pmRoot,author:Ue(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function M(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function X(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return M(t)}function V(e){let t=new Set,n=[];for(let o of e){let r=X(o);r&&(t.has(r)||n.push(r),t.add(r))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="72da6986-67d5-5adf-8e63-4f654d9ec7dd")}catch{}})();function tt(e){let{why:t,title:n,...o}=e;return o}var Oi=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ri(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Oi.has(e.code)}function ur(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:ur(e.code)}}var re={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},lr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},dr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Ze={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ii={guide:re,shell:re,completion:re,"completion-statuses":re,"completion-tags":re,"completion-types":re,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:lr,cal:lr,reindex:dr,"search-advanced":dr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Ze,"dedupe-audit":Ze,"dedupe-merge":Ze,normalize:Ze};function $i(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ii[t]}function Vt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Pi(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 Ni(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 Kt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function z(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Pi(n);o&&(e[t]=o)}function nt(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Kt(t,"attempted_command",e.attempted_command),z(t,"normalized_args",e.normalized_args),z(t,"parsed_positionals",e.parsed_positionals),z(t,"provided_fields",e.provided_fields),z(t,"missing",e.missing),z(t,"missing_required_fields",e.missing_required_fields),z(t,"suggested_flags",e.suggested_flags),z(t,"allowed_values",e.allowed_values),z(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),Kt(t,"suggested_retry",e.suggested_retry),z(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Ni(e.fallback_candidates);return n&&(t.fallback_candidates=n),Kt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Yt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Fi(e){let t=nt(e);if(!t)return[];let n=["Recovery bundle:"];if(Yt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),Yt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Yt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function fr(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Vt("Next steps:",e.nextSteps))),t.push("","What happened:",` ${e.happened}`),e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Vt("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Vt("Verification errors:",e.verificationErrors)));let n=Fi(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
5
|
-
`)}function gr(e,t){return Ri(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 Xt(e,t){return gr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t},e)}function Qt(e){return gr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function ot(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Mi(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 Z(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 mr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Di(e){return Wo(e?.normalized_args)}function Li(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 Ui(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,O(s)}}}function ji(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function et(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function H(e,t,n){if(!n)return e;let o=ot(t),r=et(n.code,e.code),a=et(n.type,ur(r)),i=Z(n.examples)??e.examples,s=Z(n.nextSteps)??e.nextSteps,c=Z(n.verification_errors)??e.verificationErrors,l=e.code==="command_failed"&&n.code?ji(o):void 0,d=nt(n.recovery)??e.recovery;return{...e,code:r,type:a,title:l??e.title,happened:o.length>0?o:e.happened,required:et(n.required,e.required),why:et(n.why,e.why),examples:i,nextSteps:s,verificationErrors:c,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:d}}function qi(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 r=o[1],a=Vn(process.cwd(),r);return H(x(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,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 ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{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 zi(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return H(x({code:"item_not_found",title:"Item ID not found",happened:i,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:a?["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 Hi(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:H(x({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 Gi(e,t,n){return t.includes("is locked")?H(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function Wi(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return H(x({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"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 Bi(e,t,n){return t.startsWith("No update flags provided")?H(x({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 Vi(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=nt(n?.recovery),r=Di(o),a=r?`pm ${r} --help`:"pm <command> --help",i=Li(t),s=Ui(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return H(x({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:c,nextSteps:l}),e,n)}function Zt(e,t){let n=ot(e),o=qi(e,n,t)??zi(e,n,t)??Hi(e,n,t)??Gi(e,n,t)??Wi(e,n,t)??Bi(e,n,t)??Vi(e,n,t);return o||H(x({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 Ki(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 Yi(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ji(e){if(!(!Array.isArray(e)||e.length===0))return O(e)}function en(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 D(e,t={}){let n=en(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ji(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return nt({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Jt(e,t){return!t||e.includes(t)?e:[...e,t]}var Xi=new Set(["--add","--add-json","--remove"]),Qi=new Set(["command","cmd","path"]);function Zi(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(Xi.has(o))return o}}function es(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 r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Qi.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return O(c)}}function ts(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=Yi(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=en(o?.providedOptionFlags),l=[a],d=Ki(t,a,n),m=s?Jt(d,s):d,p=i?[`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.`],u=s?Jt(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Jt(u,`Already provided options: ${c.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--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:D(o,{missing:l})})}function ns(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:D(n,{missing:[r]})})}function os(e,t,n){return x({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:D(t,{suggested_flags:n})})}var rs={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 as(e){let t=Z(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function is(e,t,n,o,r){let a=o.otherCommands.slice(0,3),i=o.candidateTotal-a.length,s=i>0?` and ${String(i)} 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,a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,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,r?`Replay with suggested correction: ${r}`:void 0].filter(c=>typeof c=="string")}function ss(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},a=o[1],i=en(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(a==="--file"||a==="--doc"))return os(a,n,i);let c=as(r),l=is(a,t,i,c,s),d=[s,`pm ${t??"<command>"} --help`].filter(m=>typeof m=="string");return x({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:rs[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",examples:d,nextSteps:l,recovery:D(n,{suggested_flags:i.length>0?i:void 0,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function cs(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({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:mr([t.installCommand,...n]),nextSteps:mr([a,...i]),recovery:D(r)})}function ls(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=Z(t?.unknownCommandExamples),a=Z(t?.unknownCommandNextSteps),i=$i(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?cs(o,i,s,c,t):x({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:D(t)})}function ds(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=Z(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${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:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:D(e,{allowed_values:o,suggested_retry:r})})}function ms(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Zi(o);if(!r)return null;let a=es(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} 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:[...a?[a]:[],'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:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:D(n,a?{suggested_retry:a}:{})})}var ps=new Set(["comments","docs","files","learnings","notes","test"]);function us(e,t,n){if(!/too many arguments/i.test(e)||!ps.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>l===t),a=o[r+1],i=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!i||i.startsWith("-")||!s||s.toLowerCase()!==i.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return x({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:D(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var fs=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"]),pr=new Set(["context","ctx"]);function gs(e,t,n){if(!/too many arguments/i.test(e)||!pr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>pr.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(fs.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return x({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:D(n,{suggested_retry:c})})}function tn(e,t,n,o){let r=ot(e),a=ts(r,t,n,o)??ns(r,t,o)??ss(r,t,o)??ls(r,o)??ds(o)??us(r,t,o)??ms(r,t,o)??gs(r,t,o);return a||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:D(o)})}function hr(e,t){let n=Zt(e,t);return St(fr(n),n.required).output}function yr(e,t){return Qt(Zt(e,t))}function nn(e,t,n){return ze(Xt(Zt(e,n),t))}function wr(e,t,n,o){let r=tn(e,t,n,o);return St(fr(r),r.required).output}function on(e,t,n,o){return Qt(tn(e,t,n,o))}function rt(e,t,n,o,r){return ze(Xt(tn(e,t,n,r),o))}function _r(e,t){let n=br(e);return ze(Xt(n,t))}function br(e){let t=ot(e);return Mi(t)?x({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."]}):x({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 xr(e){return Qt(br(e))}import{Option as hs}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Cr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=_(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function rn(e,t,n,o){if(!t||!n)return;let r,a=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 p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return at(i).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function G(e){return typeof e=="boolean"?e:void 0}function at(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||G(e.required)===!0||G(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function ys(e){if(G(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=A(e.value_name),i=a?` <${a}>`:"",s=A(e.description)??"Extension-provided option.",c=[];G(e.required)===!0&&c.push("required"),G(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function kr(e){let t=[...new Set(e.map(ys).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
2
|
+
import{A as Zo,B as jt,D as er,d as $o,g as q,h as Vo,i as N,j as Ko,k as S,l as Jo,q as Qe,r as Yo,s as Xo,u as Qo,v as Y,w as Mt,x as Dt,y as Lt,z as Ut}from"./chunks/chunk-X7WWQDYQ.js";import{A as Fo,eb as Bo,f as No}from"./chunks/chunk-L22NP5MA.js";import"./chunks/chunk-AGUL3HUT.js";import"./chunks/chunk-DJNJBWAQ.js";import{Mb as qo,Oc as Ye,Rc as zo,Sc as Go,Tc as Xe,Uc as Wo,lc as Ho}from"./chunks/chunk-MKE6MD2K.js";import{Da as Uo,ma as Lo}from"./chunks/chunk-ZAVCS2GH.js";import{Fb as jo}from"./chunks/chunk-YOLLRCLY.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as Hn,$h as vo,$i as Tt,$m as Do,Ac as ao,Ag as _o,Bc as Ue,Bd as Et,Bg as bo,Bm as Je,C as g,Cc as oe,Cj as Oo,Cm as Pt,D as _t,Dc as he,Dg as At,Dm as Nt,E as v,Ee as R,Eg as w,Em as xe,Fe as ze,Fm as $,G as ue,Gc as so,Gm as Mo,Hc as je,Hj as $t,Hm as Ft,Ij as Ro,Jj as Io,K as bt,Kb as Jn,La as vt,Nc as kt,Nm as M,Oa as K,Oc as qe,Pc as co,Qa as Vn,Qc as lo,Ra as Le,Rb as Yn,Tb as Xn,Tf as uo,Ua as Ct,Uf as St,Va as Kn,Wa as E,Yh as xo,Za as j,Zh as re,_h as I,_i as ko,aa as zn,aj as Ot,ba as xt,bj as Rt,c as U,cj as ye,dj as It,ej as Eo,fc as Qn,fg as fo,fj as we,gc as fe,gg as go,hg as ho,ia as Gn,ic as ge,ig as yo,ij as So,ja as Wn,jc as Zn,jf as po,jg as wo,jj as Ao,la as Bn,lm as Po,mm as Ke,oe as mo,qi as We,ri as Co,rk as Be,sc as eo,sf as Ge,tc as to,tk as be,uc as no,uk as Ve,vc as oo,wc as B,we as He,wj as _e,xc as ro,yc as io,zc as J,zj as To}from"./chunks/chunk-TEQDR5KI.js";import{Command as Tn}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var Ca=new Set(["__proto__","prototype","constructor"]),tr=Symbol("looseOptionOccurrences");function ve(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function ka(e,t,n){let o=e[t];if(o===void 0){e[t]=n;return}if(Array.isArray(o)){o.push(n),e[t]=o;return}e[t]=[o,n]}function qt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:r,value:i}:{consumed:1,key:r,value:!0}}function Ze(e){return Ca.has(e)}function nr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Hn(t)}function Ce(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=ve(n.slice(2));r.length>0&&!Ze(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=ve(o.slice(1));r.length>0&&!Ze(r)&&t.push(r)}return[...new Set(t)]}function or(e){let t=new Set;for(let n of e)for(let o of Ce(n))t.add(o);return t}function Ea(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=ve(t.slice(2));if(n.length>0&&!Ze(n))return n}return Ce(e)[0]??null}function Sa(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")&&t.length>2)return t;let n=typeof e.short=="string"?e.short.trim():"";return n.startsWith("-")&&!n.startsWith("--")&&n.length>1?n:null}function Ht(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,i=[],a=[];for(let s of t){let c=Ce(s),d=Sa(s);d!==null&&a.push(d);for(let l of c)o.add(l),s.enabled===!1&&r.set(l,d);s.required===!0&&s.enabled!==!1&&c.length>0&&i.push({keys:c,label:d})}for(let s of Object.keys(e)){if(!o.has(s)){let d=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${d}`,g.USAGE)}let c=r.get(s);if(c)throw new v(`Option '${c}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of i)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function Aa(e){return typeof e=="string"||e==null?e:String(e)}function Ta(e){if(typeof e=="number")return e;if(typeof e=="string"&&e.trim().length>0){let t=Number(e);return Number.isFinite(t)?t:e}return e}function Oa(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true"||t==="1")return!0;if(t==="false"||t==="0")return!1}return e}var Ra={string:Aa,number:Ta,boolean:Oa};function et(e,t){return Array.isArray(e)?e.map(n=>et(n,t)):Ra[t](e)}function rr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):zn(e);return t?o.map(r=>et(r,t)):o}function Ia(e,t,n,o){return n?rr(e,t,o):t?et(e,t):e}function $a(e,t,n){let o=e[tr];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(i=>r.has(i.key)).map(i=>i.value)}function ir(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,i]of Object.entries(e))o[r]=i;for(let r of t){let i=Ea(r);if(!i)continue;let a=r.list===!0,s=Ce(r);for(let l of s)if(!(l===i||!Object.hasOwn(o,l))){if(Object.hasOwn(o,i)){if(!a){delete o[l];continue}let m=o[i],p=o[l];o[i]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[l];continue}o[i]=o[l],delete o[l]}let c=nr(r),d=r.repeatable===!0;if(!Object.hasOwn(o,i)){r.default!==void 0&&(o[i]=Ia(r.default,c,a,d));continue}if(a){o[i]=rr($a(n,s,o[i]),c,d);continue}c&&(o[i]=et(o[i],c))}return o}function ar(e){let t=Object.create(null),n=[];Object.defineProperty(t,tr,{value:n});let o=0;for(;o<e.length;){let r=qt(e,o);if(!r){o+=1;continue}let i=ve(r.key);if(i.length===0||Ze(i)){o+=r.consumed;continue}ka(t,i,r.value),n.push({...r,key:i}),o+=r.consumed}return t}function sr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=qt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function zt(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=nr(a);for(let c of Ce(a))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],i=0;for(;i<e.length;){if(e[i]==="--"){r.push(...e.slice(i+1));break}let a=qt(e,i);if(a){let s=ve(a.key);if(n.has(s)){let c=e[i],d=o.has(s)&&!c.includes("=")?1:a.consumed;i+=d;continue}}r.push(e[i]),i+=1}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0186e30-9c25-5539-b778-1ef2ee21764a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5ea35d21-cfe6-5138-9fdb-413083719924")}catch{}})();var cr=new WeakMap;function lr(e,t){cr.set(e,t)}function ke(e){return cr.get(e)}function dr(e){return e.length>0?[e[0]]:[]}function Pa(e){let t=["","Intent:",` ${e.why}`],n=dr(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(`
|
|
3
|
+
`)}function Na(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(`
|
|
4
|
+
`)}function mr(e,t){return t==="detailed"?Na(e):Pa(e)}function P(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Fa={cal:"calendar",ctx:"context"};function Ma(e,t){return e.commands.find(n=>n.name()===t)??null}function Da(e,t){let n=e;for(let o of t){let r=Ma(n,o);if(!r)return null;n=r}return n}function Gt(e,t,n,o){let r=Da(e,t.split(" ").filter(i=>i.length>0));r&&r.addHelpText("after",mr(n,o))}function Bt(e){return e.includes("--explain")?"detailed":"compact"}var pr={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 install ./my-package --project","pm 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 extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension 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 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 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 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 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 extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --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 extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension 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 extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension 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 extension catalog --project","pm extension 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 install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm 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 upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm 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."]},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-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-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-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-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 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?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","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 "All acceptance criteria met" --message "Close after verification"','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 --message "Claim for implementation"','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 takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","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 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task 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."]}},Wt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-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."]};function La(e){let t=P(e??"");return t?Fa[t]??t:""}function Ua(e){let t=La(e);return t?pr[t]??Wt:Wt}function ur(e,t){let n=Ua(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:dr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function fr(e,t=process.argv.slice(2)){let n=e.createHelp(),o=new Set(Wo("core")),r=new Set(zo),i=new Set;e.configureHelp({visibleCommands(f){let h=n.visibleCommands(f);return f!==e?h:h.filter(y=>i.has(y))},visibleOptions(f){let h=n.visibleOptions(f);return f===e?h.filter(y=>r.has(y.flags)):h}});let a=Bt(t),s=mr(Wt,a);e.addHelpText("after",s);let c=e.createHelp();c.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let d=()=>`${c.formatHelp(e,c)}${s}
|
|
5
|
+
`,l=n.visibleCommands(e);for(let f of l)ke(f)===void 0&&(f.name()==="help"||o.has(f.name()))&&i.add(f);for(let f of l)ke(f)==="core"&&(i.add(f),Go(d()).within_budget||i.delete(f));for(let[f,h]of Object.entries(pr))Gt(e,f,h,a);let m=P(N(t).commandPathTokens.join(" ")),p=be(m);if(p){Gt(e,p.parent,{why:p.description,examples:[p.example],tips:[`Action path: pm ${p.command}`,Ve(p.accepted_flags)]},a);return}let u=Be.filter(({parent:f})=>f===m);u.length>0&&Gt(e,m,{why:`Dispatches one declared positional action: ${u.map(({action:f})=>f).join("|")}.`,examples:u.map(({example:f})=>f),tips:[`Inspect one action directly with pm ${m} <action> --help --json.`]},a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function gr(e,t){await Ro(e,{ok:t.ok,error:t.error,result:he(),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 hr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await I(e.pmRoot);await jo({pmRoot:e.pmRoot,author:He(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function D(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function X(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return D(t)}function V(e){let t=new Set,n=[];for(let o of e){let r=X(o);r&&(t.has(r)||n.push(r),t.add(r))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4bdb7fcf-dd74-57bc-8a0e-07539095462e")}catch{}})();function ot(e){let{why:t,title:n,...o}=e;return o}var ja=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function qa(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!ja.has(e.code)}function xr(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:xr(e.code)}}var ie={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},yr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},wr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},tt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ha={guide:ie,shell:ie,completion:ie,"completion-statuses":ie,"completion-tags":ie,"completion-types":ie,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:yr,cal:yr,reindex:wr,"search-advanced":wr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":tt,"dedupe-audit":tt,"dedupe-merge":tt,normalize:tt};function za(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ha[t]}function Vt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ga(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 Wa(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 Kt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function H(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(i=>({role:typeof i?.role=="string"?i.role.trim():"",value:typeof i?.value=="string"?i.value.trim():""})).filter(i=>i.role.length>0&&i.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Ga(n);o&&(e[t]=o)}function ae(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Kt(t,"attempted_command",e.attempted_command),H(t,"normalized_args",e.normalized_args),H(t,"parsed_positionals",e.parsed_positionals),H(t,"provided_fields",e.provided_fields),H(t,"missing",e.missing),H(t,"missing_required_fields",e.missing_required_fields),H(t,"suggested_flags",e.suggested_flags),H(t,"allowed_values",e.allowed_values),H(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),Kt(t,"suggested_retry",e.suggested_retry),H(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Wa(e.fallback_candidates);return n&&(t.fallback_candidates=n),Kt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Jt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Ba(e){let t=ae(e);if(!t)return[];let n=["Recovery bundle:"];if(Jt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),t.option_scope!==void 0&&n.push(` option_scope: ${t.option_scope}`),Jt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Jt(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function vr(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Vt("Next steps:",e.nextSteps))),t.push("","What happened:",` ${e.happened}`),e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Vt("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Vt("Verification errors:",e.verificationErrors)));let n=Ba(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
6
|
+
`)}function Cr(e,t){return qa(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 Va(e,t){return e.flag?e.flag:e.recovery?.provided_fields?.find(n=>n!=="--json"&&n!=="--quiet"&&t.includes(n))}function Ka(e,t,n){if(e.value!==void 0)return e.value;if(n)return t[t.indexOf(n)+1];let o=e.recovery?.allowed_values;if(o?.length)return t.find((r,i)=>i>0&&!r.startsWith("-")&&!o.includes(r))}function Ja(e,t){let n=e.recovery?.normalized_args??[],o=Va(e,n),r=Ka(e,n,o);return{surface:o??e.recovery?.missing?.[0]??kr(e.recovery)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Ya(e,t){return Cr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Ja(e,t)},e)}function Xt(e,t){let n=e.recovery,o=!!n?.suggested_retry||!!n?.suggested_retry_args?.length||!!n?.allowed_values?.length||!!n?.candidate_commands?.length||!!e.nextSteps?.length;return uo(Ya(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Qt(e){return Cr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Xa(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 Z(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 _r(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function kr(e){return Xo(e?.normalized_args)}function Qa(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 Za(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let i of o){let a=n.findIndex(s=>s===i);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=r,R(s)}}}function es(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function nt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function z(e,t,n){if(!n)return e;let o=rt(t),r=nt(n.code,e.code),i=nt(n.type,xr(r)),a=Z(n.examples)??e.examples,s=Z(n.nextSteps)??e.nextSteps,c=Z(n.verification_errors)??e.verificationErrors,d=e.code==="command_failed"&&n.code?es(o):void 0,l=ae(n.recovery),m=l&&e.recovery?ae({...e.recovery,...l}):l??e.recovery;return{...e,code:r,type:i,title:d??e.title,happened:o.length>0?o:e.happened,required:nt(n.required,e.required),why:nt(n.why,e.why),examples:a,nextSteps:s,verificationErrors:c,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:m}}function ts(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 r=o[1],i=Kn(process.cwd(),r);return z(x(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${i}.`,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 ${i} <command>`,`PM_PATH=${i} pm <command>`],nextSteps:[`Re-run with "--pm-path ${i}" or export PM_PATH=${i}.`]}:{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 ns(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=i?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return z(x({code:"item_not_found",title:"Item ID not found",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:i?["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 os(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:z(x({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 rs(e,t,n){return t.includes("is locked")?z(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function is(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let i=!!r,a=i?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 z(x({code:"missing_required_option",title:i?"Missing required options":`Missing required option ${s}`,happened:t,required:i?"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 as(e,t,n){return t.startsWith("No update flags provided")?z(x({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 ss(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=ae(n?.recovery),r=kr(o),i=r?`pm ${r} --help`:"pm <command> --help",a=Qa(t),s=ae({...o,allowed_values:o?.allowed_values??a}),c=Za(o,a),d=c?[c,i]:[i,"pm contracts --command <command> --flags-only --json"],l=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return z(x({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:d,nextSteps:l,recovery:s}),e,n)}function Zt(e,t){let n=rt(e),o=ts(e,n,t)??ns(e,n,t)??os(e,n,t)??rs(e,n,t)??is(e,n,t)??as(e,n,t)??ss(e,n,t);return o||z(x({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 cs(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 ls(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function ds(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function en(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 L(e,t={}){let n=en(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:ds(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return ae({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:i,...t})}function Yt(e,t){return!t||e.includes(t)?e:[...e,t]}var ms=new Set(["--add","--add-json","--remove"]),ps=new Set(["command","cmd","path"]);function us(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(ms.has(o))return o}}function fs(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 r=e[o];if(r!=="--add"&&r!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!ps.has(i))return;let a=[];for(let d=o+2;d<e.length;d+=1){let l=e[d];if(l.startsWith("--")&&l.length>2)break;a.push(l)}if(a.length<2)return;let s=`${i}=${a.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return R(c)}}function gs(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let i=ls(r[1]),a=i.startsWith("--type"),s=o?.suggestedRetryCommand,c=en(o?.providedOptionFlags),d=[i],l=cs(t,i,n),m=s?Yt(l,s):l,p=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.`],u=s?Yt(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Yt(u,`Already provided options: ${c.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${i}`,happened:`Commander rejected the command because ${i} was not provided.`,required:`Pass ${i} 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:L(o,{missing:d})})}function hs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function ys(e,t,n){return x({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:L(t,{suggested_flags:n})})}var ws={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 _s(e){let t=Z(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function bs(e,t,n,o,r){let i=o.otherCommands.slice(0,3),a=o.candidateTotal-i.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.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,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,r?`Replay with suggested correction: ${r}`:void 0].filter(c=>typeof c=="string")}function xs(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},i=o[1],a=en(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(i==="--file"||i==="--doc"))return ys(i,n,a);let c=_s(r),d=bs(i,t,a,c,s),l=[s,`pm ${t??"<command>"} --help`].filter(m=>typeof m=="string");return x({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:ws[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",examples:l,nextSteps:d,recovery:L(n,{suggested_flags:a.length>0?a:void 0,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function vs(e,t,n,o,r){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({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:_r([t.installCommand,...n]),nextSteps:_r([i,...a]),recovery:L(r)})}function Cs(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=Z(t?.unknownCommandExamples),i=Z(t?.unknownCommandNextSteps),a=za(o),s=r??["pm --help"],c=i??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),l=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!l||!d.has(l))?vs(o,a,s,c,t):x({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:L(t)})}function ks(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=Z(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${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:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function Es(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=us(o);if(!r)return null;let i=fs(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} 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:[...i?[i]:[],'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:[...i?[`Replay with the value re-joined into one argument: ${i}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,i?{suggested_retry:i}:{})})}var Ss=new Set(["comments","docs","files","learnings","notes","test"]);function As(e,t,n){if(!/too many arguments/i.test(e)||!Ss.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>d===t),i=o[r+1],a=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return x({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:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:c})})}var Ts=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"]),br=new Set(["context","ctx"]);function Os(e,t,n){if(!/too many arguments/i.test(e)||!br.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>br.has(d)),i=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let l of o.slice(i)){if(d){d=!1;continue}let m=l.split("=")[0];if(Ts.has(m)){d=!l.includes("=");continue}if(!l.startsWith("-")){s=l;break}}}if(!s)return null;let c=`pm get ${s}`;return x({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:L(n,{suggested_retry:c})})}function tn(e,t,n,o){let r=rt(e),i=gs(r,t,n,o)??hs(r,t,o)??xs(r,t,o)??Cs(r,o)??ks(o)??As(r,t,o)??Es(r,t,o)??Os(r,t,o);return i||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function Er(e,t){let n=Zt(e,t);return St(vr(n),n.required).output}function Sr(e,t){return Qt(Zt(e,t))}function nn(e,t,n){return Xt(Zt(e,n),t)}function Ar(e,t,n,o){let r=tn(e,t,n,o);return St(vr(r),r.required).output}function on(e,t,n,o){return Qt(tn(e,t,n,o))}function it(e,t,n,o,r){return Xt(tn(e,t,n,r),o)}function Tr(e,t){let n=Or(e);return Xt(n,t)}function Or(e){let t=rt(e);return Xa(t)?x({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."]}):x({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 Rr(e){return Qt(Or(e))}import{Option as Rs}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99d39b7c-ec26-5c95-85c0-ac28112a6fe6")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function $r(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let a=_(i.command),s=a.split(" "),c=s.at(-1),d=s.slice(1).join(" "),l=d?`${s[0]}-${c} ${d}`:`${s[0]}-${c}`;if(c&&r===l){n.set(r,a);break}}}return n}function rn(e,t,n,o){if(!t||!n)return;let r,i=0;for(let[s,c]of e.entries()){if(c!==t)continue;let d=e.slice(s);for(let[l,m]of o.entries()){let p=l.split(" ");p.length>i&&p.every((u,f)=>d[f]===u)&&(r=m,i=p.length)}}let a=r?.flags.find(s=>s.long===n||s.short===n);if(a)return at(a).takesValue}function T(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function G(e){return typeof e=="boolean"?e:void 0}function at(e){let t=T(e.value_type)??T(e.type),n=T(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||G(e.required)===!0||G(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Is(e){if(G(e.visible)===!1)return null;let n=T(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",i=T(e.value_name),a=i?` <${i}>`:"",s=T(e.description)??"Extension-provided option.",c=[];G(e.required)===!0&&c.push("required"),G(e.enabled)===!1&&c.push("disabled");let d=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${a} ${s}${d}`}function Pr(e){let t=[...new Set(e.map(Is).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
6
7
|
Extension-provided flags:
|
|
7
8
|
${t.join(`
|
|
8
|
-
`)}`}function
|
|
9
|
+
`)}`}function Nr(e){let t=new Map;for(let r of e){let i=_(r.target_command);if(i.length===0)continue;let a=t.get(i)??[];a.push(...r.flags),t.set(i,a)}let n=[...t.entries()].sort(([r],[i])=>r.localeCompare(i)),o=new Map;for(let[r,i]of n){let a=Pr(i);a&&o.set(r,a)}return o}function Fr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Ir(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function $s(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 Ps(e){let t=new Map;for(let n of e){let o=_(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,i=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Fr(o,n.action),description:r,intent:i,examples:Ir(n.examples),failure_hints:Ir(n.failure_hints),arguments:$s(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function Ns(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function Fs(e,t,n){let o=new Set;for(let r of e){let i=_(r);i.length>0&&o.add(i)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function Ms(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Mr(e,t,n,o=new Map){let r=Ps(t),i=Ns(n),a=Fs(e,r,i),s=new Map,c=[...a].sort((d,l)=>d.localeCompare(l));for(let d of c){let l=Ms(d,r,o)??r.get(d),m=i.get(d)??(l?i.get(l.command):void 0)??[];if(l){s.set(d,{...l,command:d,flags:m});continue}s.set(d,{command:d,action:Fr(d,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Ds(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Dr(e,t){for(let n of t.arguments)e.argument(Ds(n),n.description??"Extension argument.")}function Lr(e){if(G(e.visible)===!1)return null;let n=T(e.long),o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,i=n&&n.startsWith("--")&&n.length>2?n:null,a=[r,i].filter(s=>s!==null);return a.length>0?a:null}function Ls(e){let t=Lr(e);if(!t)return null;let{valueName:n}=at(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Us(e){let t=Lr(e);if(!t)return null;let{valueName:n}=at(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Ur(e){let t=T(e.description)??"Extension-provided option.",n=[];G(e.required)===!0&&n.push("required"),G(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function jr(e,t){let n=T(t.long),o=T(t.short);return e.options.some(r=>{let i=r;return n!==null&&i.long===n||o!==null&&i.short===o})}function an(e,t){for(let n of t){if(jr(e,n))continue;let o=Us(n);if(!o)continue;let r=Ur(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Rs(o,r).argParser((i,a=[])=>[...Array.isArray(a)?a:[a],i]))}}function sn(e,t){return Pr(t.filter(n=>!jr(e,n)))}function js(e){let t=Ls(e);if(!t)return null;let n=T(e.long),o=T(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=at(e),c=G(e.required)===!0;return{flags:t,long:r,short:i,description:Ur(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function qr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=js(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function Hr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function zr(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:`
|
|
9
10
|
Extension command metadata:
|
|
10
11
|
${t.join(`
|
|
11
|
-
`)}`}function cn(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
|
|
12
|
-
`),r=n.find(
|
|
12
|
+
`)}`}function cn(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 Ee(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:cn(o).includes(n))??null}function se(e,t){let n=e;for(let o of t){let r=Ee(n,o);if(!r)return null;n=r}return n}var Gr=new WeakSet;function Wr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],i=Ee(n,r);if(i){n=i;continue}let a=n.command(r);Gr.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 qs(e,t){let n=e,o=[];for(let r of t){let i=Ee(n,r);if(!i)return null;if(o.push(r),!Gr.has(i))return{core_path:o.join(" "),extension_path:t.join(" ")};n=i}return null}function Hs(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),i=qs(e,r);if(!i||i.core_path===t&&!n.has(t))return null;let a=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${i.extension_path}:core_owner=pm-cli:${i.core_path}:extension_owner=${a}`}function Br(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,a)=>i.localeCompare(a)).filter(i=>{let a=Hs(e,i,o,n.get(i));return a?(r(a),!1):!0})}function Vr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function zs(e,t){let n=ue(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Gs(e){return ue(e.status)?.toLowerCase()??"pending"}function Ws(e){return e.mandatory===!0}function Bs(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 Yr(e){let t=[];return e.forEach((n,o)=>{if(!Ws(n.definition))return;let r=Gs(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:zs(n.definition,o),status:r})}),t.sort(Bs),t}function Kr(e){return Array.isArray(e)&&e.length>0}var Vs=new Set(["create","beads import","todos import"]),Ks=new Set(["restore","update","close","delete","append","claim","release"]),Js=new Set(["comments","notes","learnings"]),Ys=new Set(["files","docs","test"]),Xs=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 ln(e,t){let n=t.force===!0;return Vs.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Ks.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Js.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Ys.has(e)?{isMutation:Kr(t.add)||Kr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Qs(e,t,n){if(ln(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Ao(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>Xs.has(r.trim().toLowerCase())):!1}function Jr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Zs(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(ue(t[1])||r.push("source"),ue(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:r.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:r,suggested_flags:r.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function ec(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Jr(n.status)!==Jr(r.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let a=K(r,J()),s=await We(o,i,r.id_prefix,r.item_format,a.type_to_folder);if(!s)return;let c=await Co(s,{schema:r.schema}),d=typeof n.assignee=="string"?n.assignee.trim():void 0;(d===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(d.toLowerCase())&&d)||w(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function dn(e,t,n,o,r){if(!Qs(e,t,n)||(Zs(e,t,n),!await U(j(r))))return;let i=await re(r);o.json!==!0&&await ec(e,t,n,r,i.settings);let a=So({author:He(o.author,i.settings.author_default),payload:{command:e,args:t,options:n},settings:i.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)w(`warning:${s}`)}function Xr(e,t,n){if(n.length===0)return;let o=ln(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${i}`,g.CONFLICT)}async function mn(e,t,n,o){if(!ln(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await U(j(n)))return;let{settings:i,metadata:a,warnings:s}=await re(n);for(let c of s)w(`warning:${c}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(xo(i),await vo(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=K(i,J());await To(n,i.item_format,"item_format:pre_mutation_sync",c.type_to_folder,i.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48877bbb-17bf-5a78-91fa-19a2f2f4c2be")}catch{}})();var Se=Bn.join("|"),tc={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"},nc={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"]}},Qr=["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 oc(e,t){let n=nc[e];if(!n)return[];let o=D(t);for(let[r,i]of Object.entries(n))if(D(r)===o)return i;return[]}function pn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(a=>`- ${a.layer}:${a.name}: ${a.error}`).join(`
|
|
13
|
+
`),r=n.find(a=>a.declared_command_match===!0);if(!r)return`${e}
|
|
13
14
|
Extension activation failures:
|
|
14
|
-
${o}`;let
|
|
15
|
+
${o}`;let i=(r.recovery_commands??[]).map(a=>`- ${a}`).join(`
|
|
15
16
|
`);return`Extension command unavailable: ${r.layer}:${r.name}
|
|
16
|
-
${r.error}${
|
|
17
|
+
${r.error}${i.length>0?`
|
|
17
18
|
Recovery:
|
|
18
|
-
${
|
|
19
|
+
${i}`:""}
|
|
19
20
|
|
|
20
21
|
${e}
|
|
21
22
|
Extension activation failures:
|
|
22
|
-
${o}`}function un(e){return
|
|
23
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function oc(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 rc(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(a=>a.trim().toLowerCase()===n))}function Kr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=rc(n,r);if(!a)return o;o=!0,n=a}return o}async function ac(e,t,n,o){try{let r=k(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Ce};let a=await R(r),i=e.noExtensions?void 0:Y(),s=K(a,i),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 He(r,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ce,pmRoot:r,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ce}}}function ic(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Vr([...Hs(t,n[1]),...Vs(n[1],ke(t))]):void 0,r=n?Js(n[1],t):[],a=n!==null&&ke(t).includes(M(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:a?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function sc(e,t,n){if(!t||!n||n.length===0)return;let o=Xs(e,t[1],n[0]);return o?fn(o):void 0}function cc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?oc(nc(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=E(t);if(r)return Bo(t,r,[o])}function lc(e,t){if(!/too many arguments/i.test(e)||E(t)!=="schema")return;let n=zo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let a=`${o}-${r}`;if(!Hr.includes(a))return;let i=[...t.slice(0,n+1),a,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Hr],suggestedRetryCommand:fn(i)}}async function Ee(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=Je(process.argv.slice(2)).argv,s=q(i),c=E(i),l=fn(i),d=V(i),m=await ac(s,a,i,c),p=m.allowedTypes,u=gn(a,t,n),f=ic(a,c),h=lc(a,i),w=h?.suggestedRetryCommand??sc(i,f.match,f.suggestions)??cc(a,i);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:w,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function hn(e,t,n,o={}){let r=await Ee(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:L,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:yt,verifiedCollectionItemId:Pe,failedExtensions:Ne}=r,de=wr(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownOptionScope:v,unknownSubcommandPath:L,unknownSubcommandToken:W,unknownSubcommandAllowedValues:te,suggestedRetryCommand:yt,verifiedCollectionItemId:Pe,failedExtensions:Ne}),wt=await co("help_format",{message:de,command:i,allowed_types:s});return wt.handled&&typeof wt.result=="string"?wt.result:de}async function yn(e,t,n,o=!1,r={}){let a=await Ee(e,t,n,r),i=rt(a.message,a.commandName,a.allowedTypes,g.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:a.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:a.unknownOptionOtherCommandsTruncated,unknownOptionScope:a.unknownOptionScope,unknownSubcommandPath:a.unknownSubcommandPath,unknownSubcommandToken:a.unknownSubcommandToken,unknownSubcommandAllowedValues:a.unknownSubcommandAllowedValues,suggestedRetryCommand:a.suggestedRetryCommand,verifiedCollectionItemId:a.verifiedCollectionItemId,failedExtensions:a.failedExtensions});return JSON.stringify(o?tt(i):i,null,2)}import ie from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function wn(e,t={},n=[]){let o={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:Ct,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map($).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map($),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));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(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function Yr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await wn(t,n,o),a={readSettings:R,loadExtensions:pe,activateExtensions:ue,resolveImplicitPmRoot:Ct,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(ie.resolve(i)===ie.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ie.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${ie.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${ie.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${ie.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="abdb8d3e-8c1b-511e-b25b-220d5a40ae3f")}catch{}})();function dc(e,t){if(t.length===0)return e;let n=ae(e,t);if(n)return n;let o=t.join(" ");if(!qe.some(r=>r===o)&&!Ro(o)&&!we(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ae(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function mc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Jr(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 pc(e){let t=new Map;for(let n of e){let o=n,r=Jr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function uc(e){return O(e)}function fc(e){let t=e.options??[],n=pc(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Jr(o),l=(s?n.get(s)??[]:[]).filter(w=>w!==r.long).map(w=>w.trim()).filter(w=>w.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),f=u||a.includes("["),h={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:f,value_required:u,value_name:mc(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function gc(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 r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function hc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:a}})}function yc(e){return e.createHelp().visibleCommands(e).filter(t=>t.name()!=="help"||e.parent===null).map(t=>{let n=$(I(t)).split(" ")[0];return{name:t.name().trim(),aliases:cn(t),description:t.description().trim(),tier:Ye(n),family:Ke(n)}}).sort((t,n)=>t.name.localeCompare(n.name))}function wc(e,t,n){if(!n)return t;let o=n.examples??[],r=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"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function _c(e,t,n,o){if(!e){let a=hc(t),i=yc(t),s=new Set(i.map(({name:c})=>c));return{arguments:a,options:o,subcommands:[...i,...Ge.filter(({parent:c,action:l})=>c===n&&!s.has(l)).map(({action:c,description:l})=>({name:c,aliases:[],description:l,tier:Ye(n.split(" ")[0]),family:Ke(n.split(" ")[0])}))].sort((c,l)=>c.name.localeCompare(l.name)),usage:[n,a.reduce((c,l)=>l.required?c.replace(`[${l.name}${l.variadic?"...":""}]`,`<${l.name}${l.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:a,required:i,variadic:s,value_kind:c,polymorphic:l})=>({name:a,required:i,variadic:s,description:l?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:a,aliases:i})=>a!==null&&r.has(a)||i.some(s=>r.has(s))),subcommands:[],usage:[e.command,...e.slots.map(({name:a,required:i,variadic:s})=>{let c=s?`${a}...`:a;return i?`<${c}>`:`[${c}]`})].join(" ")}}function bc(e,t,n,o,r){let a=Bt(n),i=$(I(t)),s=$(o.join(" ")),c=s.length>i.length?s:i,l=we(c),d=l?.command??c,m=d.length>0?d:void 0,p=m?.split(" ")[0],u=ar(m,a),f=m?r.get(m):void 0,h=wc(a,u,f),w=gc(Pr(fc(t),$r(f))),v=_c(l,t,d,w);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:d.length>0?d:e.name(),visibility_tier:p===void 0?null:Ye(p),capability_family:p===void 0?null:Ke(p),description:l?.description??t.description(),usage:v.usage,intent:l?.description??h.intent,examples:l?[l.example]:h.examples,tips:l?[We(l.accepted_flags)]:h.tips,arguments:v.arguments,options:v.options,subcommands:v.subcommands,has_subcommands:v.subcommands.length>0}}async function Xr(e,t,n){let o=q(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let a=dc(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=gn(i,e,n),c=rt(i,"help",Ce,g.USAGE,{...s,attemptedCommand:uc(t),normalizedInvocationArgs:[...t],providedOptionFlags:V(t)});y(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let i=bc(e,a,t,r.commandPathTokens,n);wo(`${JSON.stringify(i,null,2)}
|
|
24
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
25
|
-
`)}function
|
|
26
|
-
`)}let
|
|
27
|
-
`)}function Qr(e,t,n){let o=E(n);if(o!=="create"&&o!=="update")return;let r=ve(e,o);r&&r.addHelpText("after",Ec(o,t,n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function Zr(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=E(e)==="contracts"&&e.includes("--full");return r||a?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a349bce-a08d-5ff6-870a-3ec38843b512")}catch{}})();var _n="PM_CLI_PACKAGE_ROOT",lt=Symbol.for("pm.readOutputInvocationProvenance");function On(e,t){let n=Reflect.get(e,lt);n!==void 0&&Reflect.set(t,lt,n)}function ia(e,t,n){let o=uo(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let a=r.rawArgs,i=new Set(V(a.slice(2))),s=po.find(d=>d.command===o),c=Object.values(s.dimensions).flatMap(d=>d.legacy_aliases.flatMap(m=>i.has(m.flag)?[m.flag]:[])),l=Reflect.get(n,lt);Reflect.set(n,lt,{canonical_include_modes:l?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),On(n,e)}function Sc(){return Hn(import.meta.url,["../.."])}(typeof process.env[_n]!="string"||process.env[_n]?.trim().length===0)&&(process.env[_n]=Sc());var ce=null,N=null;function Ac(e){ce=e}function Tc(e){T=e}var Oc=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"]),Rc=new Set(["parse","preflight","execute","unknown"]),Ic=new Set(["usage","validation","conflict","runtime","unknown"]),Se=null,ee=null,T=new Map,Rn=250,$c=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Pc=new Set(["1","true","yes","on"]),Nc=ye(()=>import("./chunks/register-setup-QK4OTOXN.js")),Fc=ye(()=>import("./chunks/register-list-query-HZKBQNWW.js")),Mc=ye(()=>import("./chunks/register-mutation-HTKEEGRD.js")),Dc=ye(()=>import("./chunks/register-operations-6EMRWJJY.js"));function ct(e){return O(e)}function sa(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=>X(o)??o))];return n.length>0?n:void 0}function Lc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=V(t),r=new Set(o.map(d=>X(d)??d)),a=sa(e),i=t.find(d=>b.commands.some(m=>m.name()===d)),s=i?b.commands.find(d=>d.name()===i):void 0,c=new Set([...b.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>X(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=X(d)??d;return r.has(m)?!1:c.has(m)||rn(t,i,m,T)!==void 0});return l&&l.length>0?l:void 0}function Uc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?X(r):void 0,i=e.find(p=>b.commands.some(u=>u.name()===p)),s=i?b.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=rn(e,i,a,T),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?ct([...e,...d]):t;return m===t?void 0:m}function jc(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 r=e[o];r!=null&&(n[o]=r)}return n}function qc(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,...jc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function ca(e,t,n){let o=je(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:ct(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:ct(o)}:{},...a.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=ct(o),c=V(o),l=Lc(n,o,i),d=Uc(o,s,l,i),m=qc({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function se(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function la(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function In(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 da(e){if(!e)return;let t=e.trim().toLowerCase();if(Oc.has(t))return t}function ma(e){if(!e)return;let t=e.trim().toLowerCase();if(Rc.has(t))return t}function pa(e){if(!e)return;let t=e.trim().toLowerCase();if(Ic.has(t))return t}function ua(e){let t=se(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(la(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=In(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>bt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function fa(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 ga(){let e=bt(fe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=In(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=Lo(o),a=se(e,"error_code","errorCode")??fa(r,o),i=pa(se(e,"error_category","errorCategory"))??(r?void 0:_t(a)),s=r?void 0:ua(e)??`command_exit_${o}`,c=da(se(e,"command_resolution","commandResolution"))??Tt({ok:r,errorCode:a,errorCategory:i}),l=ma(se(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Re(e){let t=N;N=null,await sr(t,e);let n=ce;if(ce=null,!n){De();return}let o=[],r=io();try{await cr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Jn(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:fe(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{De()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${F(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${F(o)}`)}async function ha(){await vo()}function ya(e){return Pc.has((process.env[e]??"").trim().toLowerCase())}function wa(e){return ya("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!$c.has(Math.trunc(e))}async function dt(e){return wa(e.exit_code)?(await ha(),Co(e),!0):!1}async function _a(e){let t=J(e.error),n=xr(t);e.bootstrapGlobal.json?y(JSON.stringify(_r(t,g.GENERIC_FAILURE),null,2)):y(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await ha(),It(e.error);let a=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=a.errorCategory,r=a.commandResolution,ge(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to report error: ${J(a)}`)}try{await Re({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${J(a)}`)}try{await he()}catch(a){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${J(a)}`)}}function ea(e,t,n,o){ia(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:a,modes:i}=ho(t,r,o);if(i.length===0)return;On(o,e);let s=go(t);for(let l of i){let d=s.get(l),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let c=a.length>0?a.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");Pt(e,n)}function Ae(e,t,n=[]){let r={...e.optsWithGlobals()};On(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;let a=er(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=Xo(n),s=Be(I(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return zt(c,[...s,...n],I(e)),Zo(r,n,a)}return r}function vn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function mt(e,t,n){let o=vn(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=vn(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function $n(e){return e.arguments??[]}function ta(e){let t=$n(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function ba(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function xa(e,t){let n=$n(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new C(`Missing required argument for extension command '${e.command}'. Usage: ${ta(e)}${s}`,g.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new C(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${ta(e)}${s}`,g.USAGE)}}function zc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Hc(e,t,n){if(n.length>0){zt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new C(`Unknown option '${o.map(zc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function va(e,t,n,o){e&&(xa(e,t),Hc(e,n,o))}var Gc={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"},bn=new Map;function Cn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Ca(e,t){return e.options.some(n=>n.long===t)}function ka(e,t){return e.options.some(n=>n.short===t)}function kn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(ka(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,Ft);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!Ca(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,Ft);return}e.option(`${i} <value>`,a)}}async function Ea(e,t){let n=Gc[e];if(!n)return[];let o=`${t}:${n}`,r=bn.get(o);if(r)return r;if(!await U(j(t)))return bn.set(o,[]),[];let a=await R(t),s=(Et(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:Cn(c.type),value_type:Cn(c.type)})));return bn.set(o,s),s}async function Sa(e,t){let n=q(t),o=k(process.cwd(),n.path);if(!await U(j(o)))return;let r=ee?.key===Fn(o)?ee.snapshot:null,a=r===null?await R(o):r.settings,i=Et(a.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=ae(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";kn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)kn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function Pn(e,t,n,o,r){let a=E(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await R(t),s=K(i,o);Qr(e,s,n)}catch{}}function En(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Aa(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Nn(e){return e.some(t=>t==="--profile")}function Fn(e){return`pm-root:${e}`}function Ta(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ie(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of Ta(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function Oa(e,t){let n=_(e);if(n.length===0)return!1;let o=Ie(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function Mn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...na(n.preflight_ownership),...na(n.renderer_ownership)]:[]}function S(e){return e??[]}function na(e){return S(e).flatMap(t=>t.commands)}function pt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Ra=new Set(["hooks","parser","preflight","renderers"]),Ia=new Set(["commands","schema","services","importers"]),Wc=new Set(["reindex","search","search-advanced"]),Bc=new Set(["--template"]);function Te(e,t){for(let n of t)if(e.has(n))return!0;return!1}function $a(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Wc.has(n??t)}function Pa(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 Dn(e){return _(e.commandPath??"")==="create"&&Pa(e,Bc)}function Na(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Sn(e,t){return e.some(n=>Oa(n,t))||Dn(t)&&Na(e)}function Fa(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Ma(e,t){let n=e.activation?.commands??[];if(n.length>0)return Sn(n,t);let o=Mn(e);if(Sn(o,t)||pt(e).has("search")&&$a(t.commandPath))return!0;if(e.contributions)return Fa(e.contributions)}function Ln(e,t){let n=Ma(e,t);if(n!==void 0)return n;let o=pt(e);return!!(Te(o,Ra)||Te(o,Ia))}function ut(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Ln(o,t)):e.effective.some(o=>{let r=pt(o);return Mn(o).length>0||Te(r,Ra)||Te(r,Ia)||r.has("search")})}function Un(e){let t=Ie(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=Dn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Da(e){return Un(e)==="all"?void 0:t=>Ln(t,e)}function $e(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=qo(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function La(e){let t=e.args.map(String);if(_(I(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function An(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Ua(e,t){e.profile&&(y(`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&&y(`profile:extensions activation_warnings=${F(t.activationWarnings)}`))}function ft(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function gt(e,t=oe){let n=Fn(e);if(ee?.key===n)return ee.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Xn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return ee={key:n,snapshot:s},s}catch{return ee={key:n,snapshot:null},null}}async function le(e,t,n=R){let o=t?Un(t):"all",r=Aa(e,o);if(Se?.key===r)return Se.snapshot;try{let a=await n(e),i=await pe({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Da(t):void 0}),s=await ue({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=Er(s.registrations.flags),d=Cr(s.commands.handlers,s.registrations.commands),m=Ar(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Se={key:r,snapshot:p},p}catch{return Se={key:r,snapshot:null},null}}async function ja(e){let t=_e(e);if(t.noExtensions){let i=k(process.cwd(),t.path);return await U(j(i))&&An((await oe(i)).warnings),null}let n=k(process.cwd(),t.path),o=await gt(n);if(!o)return null;An(o.settingsReadWarnings);let r={commandPath:I(e),commandArgs:La(e)};if(!ut(o.discovery,r))return ft(t.profile,o,r),null;let a=await le(n,r);return a?(Ua(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function qa(e){let t=await le(e);return t?new Map(t.commandDescriptors):T}async function za(e,t){return(await Mo({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 Ha(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Io(e,jo.forActiveExtensionHost({pmRoot:e,author:n}))}async function Ga(e,t,n,o=[]){let r=I(e),a=Ht(e.args.map(String),o),i={...t},s={...n},c=k(process.cwd(),n.path),l=await Le({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&y(`profile:extensions parser_warnings=${F(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,va(T.get(_(r)),a,i,o),ne(void 0),Me({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await kt({command:r,args:a,options:i,global:s,pm_root:c,sdk:Ha(c,s)});if(s.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${F(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new C(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new C(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ne(d.result),d.result}var oa=Symbol("pm.wrappedActionHandler");function Vc(e,t){let n=e[e.length-1];return n instanceof Tn?n:t}function ra(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${F(n)}`)}function Kc(e){let t=T.get(_(e.commandPath));if(!t||!ba(e.activeRegistrations,e.commandPath))return;let n=$n(t).length===0?tr(e.commandArgs):Ht(e.commandArgs,e.extensionFlagDefinitions);xa(t,n)}function Yc(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 Wa(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[oa]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=Vc(i,n),c=Date.now();Nt(s);let l=_e(s),d=I(s),m=k(process.cwd(),l.path),p=s.args.map(String),u=Y(),f=u?mt(u,d,p):[],h=await Ea(d,m),w=Ae(s,p,[...f,...h]),v=await Le({command:d,args:p,options:w,global:l,pm_root:m});ra(l.profile,"parser_warnings",v.warnings),p=v.context.args,w=v.context.options,l=v.context.global,Kc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:f}),l=await Po(l),Pt(s,l),Yc(s,i,p),Ve(s,w),ne(void 0),Me({command:d,args:p,options:{...w},global:{...l},pm_root:m});let L=await kt({command:d,args:p,options:w,global:l,pm_root:m,sdk:Ha(m,l)});if(ra(l.profile,"command_handler_warnings",L.warnings),L.handled){ne(L.result),At(L.result,{...l,command:d,commandArgs:p,commandOptions:w,pmRoot:m}),l.profile&&y(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[oa]=!0}for(let r of n.commands)t(r)};t(e)}async function st(e){T=new Map,B({overrides:[]}),e&&await Pn(e.rootProgram,e.pmRoot,e.invocationArgv,Kn(),e.settings)}function Jc(e,t,n,o){if(t?.flags&&t.flags.length>0){an(e,t.flags);let r=sn(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function Ba(e,t){let n=q(t),o=k(process.cwd(),n.path);if(n.noExtensions){await st({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await gt(o),a=$e(t);if(!r){await st();return}if(!ut(r.discovery,a)){await st({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),ft(Nn(t),r,a);return}let i=await le(o,a);if(!i){await st({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}B(i.services),T=new Map(i.commandDescriptors),await Pn(e,o,t,i.registrations,i.settings);let s=Dr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>Lr(i.activationWarnings,y,l)),c=l=>{let d=l.split(" ").filter(v=>v.length>0),m=i.commandDescriptors.get(l),p=ae(e,d),u=i.commandFlagHelp.get(l),f=m?Nr(m):null;if(p){Jc(p,m,u,f);return}let h=Mr(e,d);m?.description&&h.description(m.description);let w=u;m&&(Tr(h,m),m.flags.length>0&&(an(h,m.flags),w=sn(h,m.flags)??void 0)),w&&h.addHelpText("after",w),f&&h.addHelpText("after",f),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...v)=>{let L=v[v.length-1],W=L instanceof Tn?L:h,te=_e(W),yt=Date.now(),Pe=mt(i.registrations,l,W.args.map(String)),Ne=Ae(W,W.args.map(String),Pe),de=await Ga(W,Ne,te,Pe);await No(te,de),At(de,{...te,command:l,commandArgs:W.args.map(String),commandOptions:Ne,pmRoot:o}),te.profile&&y(`profile:command=${l} took_ms=${Date.now()-yt}`)})};for(let l of s)c(l)}var Oe=Gn(import.meta.url,["../.."])??"0.0.0",b=jt(Oe);function Va(e){e.hook("preAction",async(t,n)=>{ce=null,N=null,De(),Nt(n);let o=n.optsWithGlobals(),r=_e(n),a=I(n),i=n.args.map(String),s=Ae(n,i),c={...r};fo(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),ea(n,a,c,s),await Ao(a,c);let l=k(process.cwd(),r.path),d=await ja(n);if(!d){ce=Qn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),N=await $t({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:l}),Ot(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),Rt(a),await mn(a,s,l,En()),await dn(a,i,s,c,l);return}Zn(d.hooks),eo(d.commands),to(d.parsers),no(d.preflight),B(d.services),oo(d.renderers),ro(d.registrations);let m=mt(d.registrations,a,i);s=Ae(n,i,m),ea(n,a,c,s);let p=await Le({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${F(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,Ve(n,s);let u=await so({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:En()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${F(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,Ve(n,s);let f=u.decision;await mn(a,s,d.pmRoot,f),await dn(a,i,s,c,d.pmRoot);let h=f.run_extension_migrations?await za(d.registrations.migrations,d.pmRoot):[];c.profile&&h.length>0&&y(`profile:extensions migration_warnings=${F(h)}`);let w=qr(d.registrations.migrations);ce={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:w},ne(void 0),Me({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),N=await $t({command:a,pm_version:Oe,args:i,options:s,global:c,pm_root:d.pmRoot}),Ot(a,i,s,{source_context:N?.source_context,source_context_source:N?.source_context_source}),Rt(a);let v=await Yn(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&v.length>0&&y(`profile:extensions hook_warnings=${F(v)}`),f.enforce_mandatory_migration_gate&&zr(a,s,w)}),e.hook("postAction",async()=>{let t=ga();ge(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Re(t)})}Va(b);var Xc=new Set(["--version","-V"]),Qc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ka=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"]),Ya=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Zc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),el=new Set(["claim","close-task","pause-task","release","start-task","test"]),xn={setup:!0,listQuery:!0,mutation:!0,operation:!0},tl=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 ht(e){return e.some(t=>Xc.has(t))}function Ja(e){if(ht(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return xn;let t=E(e);if(!t)return xn;let n=t.trim().toLowerCase();return Qc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ka.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Ya.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Zc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:xn}function Xa(e){return e.length===0||P(e).requested}var aa=Symbol("pmCliIdempotentTopLevelRegistration");function Qa(e){let t=e;if(t[aa])return;t[aa]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new Tn(a):n(o,...r)})}async function nl(e,t){if(Qa(e),t.setup){let{registerSetupCommands:n}=await Nc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Fc(),o=typeof t.targetCommandName=="string"&&Ka.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Mc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Dc();n(e)}}function Za(e,t){return ht(t)?!1:P(t).requested?!0:!!E(t)}function ei(e){if(ht(e))return!1;let t=E(e);return t?tl.has(t):!1}function ol(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=je(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function ti(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),r=o.length>0?o.join(" "):"the canonical flag",a=Ya.has(t)||el.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=ol({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new C(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:i,examples:[O(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:O(c.argv)}})}function rl(e){return async t=>{let n=_t(t.errorCode),o=Tt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Oo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Oe,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 ni(e){if(e.bootstrapGlobal.noExtensions)return;let t=$e(e.invocationArgv),n=await gt(e.bootstrapPmRoot);if(n&&ut(n.discovery,t)){let o=await le(e.bootstrapPmRoot,t);oi(o);return}n&&ft(Nn(e.invocationArgv),n,t),B({overrides:[]})}function oi(e){if(!e){B({overrides:[]});return}B(e.services)}async function jn(e){ge(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Re({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 ri(){ge(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Re({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function ai(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof C)&&(Lt(e.error)||!n))return!1;let o=J(e.error),r=e.error instanceof C?e.error.exitCode:Dt(t),a=e.error instanceof C?e.error.context:void 0,i=ca(a,e.invocationArgv,o),s=yr(o,i),c=e.bootstrapGlobal.lean?tt(nn(o,r,i)):nn(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?yo(c,u=>`${JSON.stringify(u,null,2)}
|
|
28
|
-
`):c,null,2):
|
|
23
|
+
${o}`}function un(e){return N(e).commandPathTokens[0]??S(e)??"<command>"}function rc(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let i=P($(r)),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i),o.push(...r.commands)}for(let r of t.keys()){let i=P(r),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i)}return[...n].sort((r,i)=>r.localeCompare(i))}function Zr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of r){let c=xt(s,o,i);c!==null&&(a=Math.min(a,c))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function ei(e){return D(e).slice(2).replace(/-/g,"")}function fn(e){return R(e)}function ic(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=tc[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function ti(e){let t=Lo(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function ac(e,t){let n=ti(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let i=new Set,a=r.source;if(a)for(let c of[a.name,a.package]){let d=ti(c??"");d.length>0&&i.add(d)}if(i.size===0)continue;[...i].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function Ae(e,t){let n=new Set,o=t??Ke(e);for(let r of o){r.flag.startsWith("--")&&n.add(D(r.flag));for(let i of r.aliases??[])i.startsWith("--")&&n.add(D(i))}return[...n].sort((r,i)=>r.localeCompare(i))}function sc(e,t){if(!e.startsWith("--"))return[];let n=ei(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let i of t){let a=ei(i);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){r.push({flag:i,rank:0,distance:a.length-n.length});continue}let s=xt(n,a,o);s===null||s<=0||r.push({flag:i,rank:1,distance:s})}return r.sort((i,a)=>i.rank!==a.rank?i.rank-a.rank:i.distance!==a.distance?i.distance-a.distance:i.flag.localeCompare(a.flag)).map(i=>i.flag).slice(0,3)}var st,cc=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 lc(){if(st)return st;let e=new Map;for(let t of Ge)if(!cc.has(t))for(let n of Ae(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return st=e,st}function dc(e,t){if(!e.startsWith("--"))return[];let n=lc().get(D(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set(Ae(o));return n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:Ae(i).filter(a=>r.has(a)).length})).sort((i,a)=>i.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(a.command)).map(({command:i})=>i)}function mc(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let i=r.indexOf("="),a=i>=0?r.slice(0,i):r;if(D(a)!==D(t))continue;let s=[...e];return s[o]=i>=0?`${n}${r.slice(i)}`:n,s}}function pc(e){let t=new Set(e.commandPaths),n=i=>Math.min(Zr(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Zr(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(i,a)=>{if(!Number.isFinite(a)||!t.has(i))return;let s=o.get(i);(s===void 0||a<s)&&o.set(i,a)};for(let i of e.commandPaths)r(i,n(i));for(let[i,a]of Object.entries(po))i!=="read"&&r(a,n(i));return[...o.entries()].sort(([i,a],[s,c])=>a!==c?a-c:i.localeCompare(s)).map(([i])=>i)}function uc(e){let t=er(e.commandPaths,e.primaryToken),n=pc(e),o=ac(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return ni([...t,...n,...o])}function fc(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function gc(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function gn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=P(o[1]);if(r.length===0)return;let i=rc(t,n);if(i.length===0)return;let a=r.split(" ")[0],s=uc({commandPaths:i,normalizedUnknown:r,primaryToken:a,extensionDescriptors:n}),c=fc(i),d=(s.length>0?s:c).slice(0,3),l=gc(d,s.length>0),m=ic(r),p=s.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:l,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function ni(e){return Array.from(new Set(e))}function hc(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
24
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function yc(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 wc(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(i=>i.trim().toLowerCase()===n))}function oi(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let i=wc(n,r);if(!i)return o;o=!0,n=i}return o}async function _c(e,t,n,o){try{let r=E(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Se};let i=await I(r),a=e.noExtensions?void 0:J(),s=K(i,a),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),l=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&l!==void 0&&!l.startsWith("-"))try{c=(await We(r,l,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Se,pmRoot:r,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Se}}}function bc(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?ni([...oc(t,n[1]),...sc(n[1],Ae(t))]):void 0,r=n?dc(n[1],t):[],i=n!==null&&Ae(t).includes(D(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:i?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function xc(e,t,n){if(!t||!n||n.length===0)return;let o=mc(e,t[1],n[0]);return o?fn(o):void 0}function vc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?yc(hc(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=S(t);if(r)return Qo(t,r,[o])}function Cc(e,t){if(!/too many arguments/i.test(e)||S(t)!=="schema")return;let n=Ko(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let i=`${o}-${r}`;if(!Qr.includes(i))return;let a=[...t.slice(0,n+1),i,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Qr],suggestedRetryCommand:fn(a)}}async function Te(e,t,n,o={}){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=Qe(process.argv.slice(2)).argv,s=q(a),c=S(a),d=fn(a),l=V(a),m=await _c(s,i,a,c),p=m.allowedTypes,u=gn(i,t,n),f=bc(i,c),h=Cc(i,a),y=h?.suggestedRetryCommand??xc(a,f.match,f.suggestions)??vc(i,a);return{message:i,commandName:c,allowedTypes:p,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:l,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,unknownOptionScope:f.scope,suggestedRetryCommand:y,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function hn(e,t,n,o={}){let r=await Te(e,t,n,o),{message:i,commandName:a,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:d,attemptedCommand:l,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:k,unknownSubcommandPath:C,unknownSubcommandToken:Me,unknownSubcommandAllowedValues:W,suggestedRetryCommand:te,verifiedCollectionItemId:wt,failedExtensions:De}=r,pe=Ar(i,a,s,{unknownCommandExamples:c,unknownCommandNextSteps:d,attemptedCommand:l,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:y,unknownOptionScope:k,unknownSubcommandPath:C,unknownSubcommandToken:Me,unknownSubcommandAllowedValues:W,suggestedRetryCommand:te,verifiedCollectionItemId:wt,failedExtensions:De}),ne=await lo("help_format",{message:pe,command:a,allowed_types:s});return ne.handled&&typeof ne.result=="string"?ne.result:pe}async function yn(e,t,n,o=!1,r={}){let i=await Te(e,t,n,r),a=it(i.message,i.commandName,i.allowedTypes,g.USAGE,{unknownCommandExamples:i.unknownCommandExamples,unknownCommandNextSteps:i.unknownCommandNextSteps,attemptedCommand:i.attemptedCommand,normalizedInvocationArgs:i.normalizedInvocationArgs,providedOptionFlags:i.providedOptionFlags,unknownOptionSuggestions:i.unknownOptionSuggestions,unknownOptionOtherCommands:i.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:i.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:i.unknownOptionOtherCommandsTruncated,unknownOptionScope:i.unknownOptionScope,unknownSubcommandPath:i.unknownSubcommandPath,unknownSubcommandToken:i.unknownSubcommandToken,unknownSubcommandAllowedValues:i.unknownSubcommandAllowedValues,suggestedRetryCommand:i.suggestedRetryCommand,verifiedCollectionItemId:i.verifiedCollectionItemId,failedExtensions:i.failedExtensions});return JSON.stringify(o?ot(a):a,null,2)}import ce from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function wn(e,t={},n=[]){let o={readSettings:I,loadExtensions:fe,activateExtensions:ge,resolveImplicitPmRoot:Ct,...t};try{let r=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(i);return[...i.failed,...a.failed].map(s=>{let c=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),d=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(P).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),l=n.map(P),m=d.some(p=>l.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function ri(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await wn(t,n,o),i={readSettings:I,loadExtensions:fe,activateExtensions:ge,resolveImplicitPmRoot:Ct,...n};try{let a=i.resolveImplicitPmRoot(process.cwd());if(ce.resolve(a)===ce.resolve(t))return r;let[s,c]=await Promise.all([i.readSettings(t),i.readSettings(a)]),[d,l]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:a,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(l.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ce.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${ce.resolve(a)} cwd_extension_discovery_root=${l.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${ce.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${ce.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26c3efa6-b820-5370-b0ab-65b08bc007ec")}catch{}})();var ii={core:0,standard:1,full:2,internal:3};function ai(e,t,n=!0){let o=t.get(e);if(o)return o;if(!n)return;let r=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(r.length===0)return;let i=r.reduce((s,c)=>ii[c.tier]<ii[s]?c.tier:s,"internal"),a=new Set(r.map(({family:s})=>s));return{tier:i,family:a.size===1?r[0].family:"extensions"}}function kc(e,t){if(t.length===0)return e;let n=se(e,t);if(n)return n;let o=t.join(" ");if(!Ge.some(r=>r===o)&&!Po(o)&&!be(o))return null;for(let r=t.length-1;r>0;r-=1){let i=se(e,t.slice(0,r));if(i)return i}return t.length===1?e:null}function Ec(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function si(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 Sc(e){let t=new Map;for(let n of e){let o=n,r=si(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(r)??[];i.push(o.long.trim()),t.set(r,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,i)=>r.localeCompare(i)));return t}function Ac(e){return R(e)}function Tc(e){let t=e.options??[],n=Sc(t);return t.map(o=>{let r=o,i=typeof r.flags=="string"?r.flags.trim():"",a=typeof r.description=="string"?r.description.trim():"",s=si(o),d=(s?n.get(s)??[]:[]).filter(y=>y!==r.long).map(y=>y.trim()).filter(y=>y.length>0),l=a.match(/^Alias for ([^ ]+)/i),m=l&&l[1]?l[1].trim():null,p=r.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=i.includes("<"),f=u||i.includes("["),h={flags:i,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:a,takes_value:f,value_required:u,value_name:Ec(i),variadic:r.variadic===!0,required:p,aliases:d,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function Oc(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 r=o.alias_for,i=t.get(r);if(!i)continue;let a=o.long,s=new Set([...i.aliases??[],a]);i.aliases=[...s].sort((c,d)=>c.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Rc(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",i=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:i}})}function Ic(e,t=new Map){return e.createHelp().visibleCommands(e).filter(n=>n.name()!=="help"||e.parent===null).map(n=>{let o=P($(n)),r=o.split(" ")[0],i=ai(o,t,ke(n)!==void 0);return{name:n.name().trim(),aliases:cn(n),description:n.description().trim(),tier:i?.tier??Xe(r),family:i?.family??Ye(r)}}).sort((n,o)=>n.name.localeCompare(o.name))}function $c(e,t,n){if(!n)return t;let o=n.examples??[],r=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"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function Pc(e,t){return e===void 0?null:t?.tier??Xe(e)}function Nc(e,t){return e===void 0?null:t?.family??Ye(e)}function Fc(e,t,n,o,r=new Map){if(!e){let a=Rc(t),s=Ic(t,r),c=new Set(s.map(({name:d})=>d));return{arguments:a,options:o,subcommands:[...s,...Be.filter(({parent:d,action:l})=>d===n&&!c.has(l)).map(({action:d,description:l})=>({name:d,aliases:[],description:l,tier:Xe(n.split(" ")[0]),family:Ye(n.split(" ")[0])}))].sort((d,l)=>d.name.localeCompare(l.name)),usage:[n,a.reduce((d,l)=>l.required?d.replace(`[${l.name}${l.variadic?"...":""}]`,`<${l.name}${l.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let i=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:a,required:s,variadic:c,value_kind:d,polymorphic:l})=>({name:a,required:s,variadic:c,description:l?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:a,aliases:s})=>a!==null&&i.has(a)||s.some(c=>i.has(c))),subcommands:[],usage:[e.command,...e.slots.map(({name:a,required:s,variadic:c})=>{let d=c?`${a}...`:a;return s?`<${d}>`:`[${d}]`})].join(" ")}}function Mc(e,t,n,o,r){let i=Bt(n),a=P($(t)),s=P(o.join(" ")),c=s.length>a.length?s:a,d=be(c),l=d?.command??c,m=l.length>0?l:void 0,p=m?.split(" ")[0],u=ur(m,i),f=m?r.get(m):void 0,h=m?ai(m,r,ke(t)!==void 0):void 0,y=$c(i,u,f),k=Oc(Hr(Tc(t),qr(f))),C=Fc(d,t,l,k,r);return{format:"pm_help_v1",detail_mode:i,root_command:e.name(),requested_path:o,resolved_path:l.length>0?l:e.name(),visibility_tier:Pc(p,h),capability_family:Nc(p,h),description:d?.description??t.description(),usage:C.usage,intent:d?.description??y.intent,examples:d?[d.example]:y.examples,tips:d?[Ve(d.accepted_flags)]:y.tips,arguments:C.arguments,options:C.options,subcommands:C.subcommands,has_subcommands:C.subcommands.length>0}}async function ci(e,t,n){let o=q(t);if(!o.json)return!1;let r=N(t);if(!r.requested)return!1;let i=kc(e,r.commandPathTokens);if(!i){if(!o.quiet){let a=`unknown command '${r.commandPathTokens.join(" ")}'`,s=gn(a,e,n),c=it(a,"help",Se,g.USAGE,{...s,attemptedCommand:Ac(t),normalizedInvocationArgs:[...t],providedOptionFlags:V(t)});w(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let a=Mc(e,i,t,r.commandPathTokens,n);bo(`${JSON.stringify(a,null,2)}
|
|
25
|
+
`)}return process.exitCode=g.SUCCESS,!0}function Dc(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(`
|
|
26
|
+
`)}function Lc(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)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Uc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let r of[...t.required_create_fields,...t.required_create_repeatables])o.add(r);return{progressive:n,strict:o}}function jc(e,t,n,o){let r=new Set(n),i=o.filter(c=>!r.has(c)),a=c=>c.length>0?c.map(d=>vt("create",d)).join(", "):"none";e.push(` required in strict mode: ${a(i)}`);let s=i.map(Ho).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 qc(e,t,n){let o=Yo(n);if(!o)return Dc(e,t);let r=Vn(o,t);if(!r){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
|
|
27
|
+
`)}let i=n.indexOf("--"),a=i<0?n:n.slice(0,i),s=a.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&c?.toLowerCase()==="strict",l=Uc(e,r),m=Le(r,e,l.progressive),p=Le(r,e,d?l.strict:l.progressive),u=h=>h.length>0?h.map(y=>vt(e,y)).join(", "):"none",f=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=Le(r,e,l.strict);jc(f,r,m.required,h.required)}return Lc(f,r),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
|
|
28
|
+
`)}function li(e,t,n){let o=S(n);if(o!=="create"&&o!=="update")return;let r=Ee(e,o);r&&r.addHelpText("after",qc(o,t,n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function di(e,t,n,o){if(n)return null;let r=e.some(a=>a==="--for"||a.startsWith("--for=")),i=S(e)==="contracts"&&e.includes("--full");return r||i?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ffd55bde-cc30-529f-a6f9-ec43abe4efba")}catch{}})();var _n="PM_CLI_PACKAGE_ROOT",dt=Symbol.for("pm.readOutputInvocationProvenance");function On(e,t){let n=Reflect.get(e,dt);n!==void 0&&Reflect.set(t,dt,n)}function yi(e,t,n){let o=go(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let i=r.rawArgs,a=new Set(V(i.slice(2))),s=fo.find(l=>l.command===o),c=Object.values(s.dimensions).flatMap(l=>l.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,dt);Reflect.set(n,dt,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:c,cli_invocation_observed:!0}),On(n,e)}function Hc(){return Gn(import.meta.url,["../.."])}(typeof process.env[_n]!="string"||process.env[_n]?.trim().length===0)&&(process.env[_n]=Hc());var de=null,F=null;function zc(e){de=e}function Gc(e){O=e}var Wc=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"]),Bc=new Set(["parse","preflight","execute","unknown"]),Vc=new Set(["usage","validation","conflict","runtime","unknown"]),Oe=null,ee=null,O=new Map,Rn=250,Kc=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Jc=new Set(["1","true","yes","on"]),Yc=_e(()=>import("./chunks/register-setup-H4PDLACD.js")),Xc=_e(()=>import("./chunks/register-list-query-37A4P6O4.js")),Qc=_e(()=>import("./chunks/register-mutation-TBJDHYIT.js")),Zc=_e(()=>import("./chunks/register-operations-WRZNEBUM.js"));function lt(e){return R(e)}function wi(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=>X(o)??o))];return n.length>0?n:void 0}function el(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=V(t),r=new Set(o.map(l=>X(l)??l)),i=wi(e),a=t.find(l=>b.commands.some(m=>m.name()===l)),s=a?b.commands.find(l=>l.name()===a):void 0,c=new Set([...b.options,...s?.options??[]].flatMap(l=>l.flags.split(/[ ,|]+/).map(m=>X(m)).filter(m=>m!==void 0))),d=i?.filter(l=>{let m=X(l)??l;return r.has(m)?!1:c.has(m)||rn(t,a,m,O)!==void 0});return d&&d.length>0?d:void 0}function tl(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],i=r?X(r):void 0,a=e.find(p=>b.commands.some(u=>u.name()===p)),s=a?b.commands.find(p=>p.name()===a):void 0,c=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,d=rn(e,a,i,O),l=i?c?.isBoolean()===!0||d===!1?[i]:[i,"<value>"]:[],m=i?lt([...e,...l]):t;return m===t?void 0:m}function nl(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 r=e[o];r!=null&&(n[o]=r)}return n}function ol(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,...nl(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function _i(e,t,n){let o=ze(t),r=o.includes("--explain"),i=e?.recovery,a=i&&o.includes("history-redact")?{...i,...i.attempted_command?{attempted_command:lt(o)}:{},...i.normalized_args?{normalized_args:[...o]}:{},...i.suggested_retry?{suggested_retry:lt(o)}:{},...i.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:i;if(a?.recovery_mode==="compact"&&!r)return{...e,recovery:a};let s=lt(o),c=V(o),d=el(n,o,a),l=tl(o,s,d,a),m=ol({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:d,suggestedRetry:l,existingRecovery:a});return{...e,recovery:m}}function le(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function bi(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function In(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 xi(e){if(!e)return;let t=e.trim().toLowerCase();if(Wc.has(t))return t}function vi(e){if(!e)return;let t=e.trim().toLowerCase();if(Bc.has(t))return t}function Ci(e){if(!e)return;let t=e.trim().toLowerCase();if(Vc.has(t))return t}function ki(e){let t=le(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(bi(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=In(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(s=>bt(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Ei(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=bt(he()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=In(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=qo(o),i=le(e,"error_code","errorCode")??Ei(r,o),a=Ci(le(e,"error_category","errorCategory"))??(r?void 0:_t(i)),s=r?void 0:ki(e)??`command_exit_${o}`,c=xi(le(e,"command_resolution","commandResolution"))??Tt({ok:r,errorCode:i,errorCategory:a}),d=vi(le(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:i,error_category:a,command_resolution:c,resolution_stage:d}}async function Pe(e){let t=F;F=null,await gr(t,e);let n=de;if(de=null,!n){je();return}let o=[],r=so();try{await hr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Xn(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:he(),affected:r}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{je()}!n.globalOptions.json&&o.length>0&&w(`[pm] warning: afterCommand hook_warnings=${M(o)}`),n.profileEnabled&&o.length>0&&w(`profile:extensions hook_warnings=${M(o)}`)}async function Ai(){await ko()}function Ti(e){return Jc.has((process.env[e]??"").trim().toLowerCase())}function Oi(e){return Ti("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Kc.has(Math.trunc(e))}async function mt(e){return Oi(e.exit_code)?(await Ai(),Eo(e),!0):!1}async function Ri(e){let t=Y(e.error),n=Rr(t);e.bootstrapGlobal.json?w(JSON.stringify(Tr(t,g.GENERIC_FAILURE),null,2)):w(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Ai(),It(e.error);let i=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=i.errorCategory,r=i.commandResolution,ye(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||w(`Failed to report error: ${Y(i)}`)}try{await Pe({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||w(`Failed to run error hooks: ${Y(i)}`)}try{await we()}catch(i){e.bootstrapGlobal.json||w(`Failed to flush error reporting: ${Y(i)}`)}}function mi(e,t,n,o){yi(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:i,modes:a}=wo(t,r,o);if(a.length===0)return;On(o,e);let s=yo(t);for(let d of a){let l=s.get(d),m=o[l];e.setOptionValueWithSource(l,m,"cli")}let c=i.length>0?i.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",c,"cli");Pt(e,n)}function Re(e,t,n=[]){let r={...e.optsWithGlobals()};On(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;let i=ar(t);for(let[a,s]of Object.entries(i))r[a]===void 0&&(r[a]=s);if(n.length>0){let a=or(n),s=Ke($(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),c={...i};for(let d of a)r[d]!==void 0&&(c[d]=r[d]);return Ht(c,[...s,...n],$(e)),ir(r,n,i)}return r}function vn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function pt(e,t,n){let o=vn(e,t),r=[t],i=[];for(let a of n){if(a.startsWith("-"))break;r.push(a);let s=vn(e,r.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function $n(e){return e.arguments??[]}function pi(e){let t=$n(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Ii(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function $i(e,t){let n=$n(e),o=n.filter(c=>c.required).length,i=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 v(`Missing required argument for extension command '${e.command}'. Usage: ${pi(e)}${s}`,g.USAGE);if(t.length>i){let c=t.slice(i).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${pi(e)}${s}`,g.USAGE)}}function rl(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function il(e,t,n){if(n.length>0){Ht(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(rl).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function Pi(e,t,n,o){e&&($i(e,t),il(e,n,o))}var al={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"},bn=new Map;function Cn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Ni(e,t){return e.options.some(n=>n.long===t)}function Fi(e,t){return e.options.some(n=>n.short===t)}function kn(e,t,n,o){let r=t.trim();if(!r)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Fi(e,r))return;if(o){e.option(`${r} <value>`,`${i} (repeatable)`,Ft);return}e.option(`${r} <value>`,i);return}let a=r.startsWith("--")?r:`--${r}`;if(!Ni(e,a)){if(o){e.option(`${a} <value>`,`${i} (repeatable)`,Ft);return}e.option(`${a} <value>`,i)}}async function Mi(e,t){let n=al[e];if(!n)return[];let o=`${t}:${n}`,r=bn.get(o);if(r)return r;if(!await U(j(t)))return bn.set(o,[]),[];let i=await I(t),s=(Et(i.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(l=>({long:`--${l}`,type:Cn(c.type),value_type:Cn(c.type)})));return bn.set(o,s),s}async function Di(e,t){let n=q(t),o=E(process.cwd(),n.path);if(!await U(j(o)))return;let r=ee?.key===Fn(o)?ee.snapshot:null,i=r===null?await I(o):r.settings,a=Et(i.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let d=se(e,c.path.split(" "));if(d)for(let l of a.command_to_fields.get(c.command)??[]){let m=l.description??"";kn(d,l.cli_flag,m,l.repeatable);for(let p of l.cli_aliases)kn(d,p,`Alias for --${l.cli_flag}`,l.repeatable)}}}async function Pn(e,t,n,o,r){let i=S(n);if(!(i!=="create"&&i!=="update"))try{let a=r??await I(t),s=K(a,o);li(e,s,n)}catch{}}function En(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Li(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Nn(e){return e.some(t=>t==="--profile")}function Fn(e){return`pm-root:${e}`}function Ui(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ne(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of Ui(e.commandArgs))o.push(...r.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n)]}function ji(e,t){let n=_(e);if(n.length===0)return!1;let o=Ne(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function Mn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...A(n.commands),...A(n.command_handlers),...A(n.command_overrides),...A(n.flag_commands),...A(n.parser_overrides),...ui(n.preflight_ownership),...ui(n.renderer_ownership)]:[]}function A(e){return e??[]}function ui(e){return A(e).flatMap(t=>t.commands)}function ut(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var qi=new Set(["hooks","parser","preflight","renderers"]),Hi=new Set(["commands","schema","services","importers"]),sl=new Set(["reindex","search","search-advanced"]),cl=new Set(["--template"]);function Ie(e,t){for(let n of t)if(e.has(n))return!0;return!1}function zi(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return sl.has(n??t)}function Gi(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 Dn(e){return _(e.commandPath??"")==="create"&&Gi(e,cl)}function Wi(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Sn(e,t){return e.some(n=>ji(n,t))||Dn(t)&&Wi(e)}function Bi(e){return[A(e.hooks).length,(e.preflight_overrides??0)-A(e.preflight_ownership).length,A(e.item_types).length,A(e.item_fields).length,A(e.relationship_kinds).length,A(e.service_overrides).length,A(e.assurance_providers).length,A(e.renderer_overrides).length-A(e.renderer_ownership).length].some(n=>n>0)}function Vi(e,t){let n=e.activation?.commands??[];if(n.length>0)return Sn(n,t);let o=Mn(e);if(Sn(o,t)||ut(e).has("search")&&zi(t.commandPath))return!0;if(e.contributions)return Bi(e.contributions)}function Ln(e,t){let n=Vi(e,t);if(n!==void 0)return n;let o=ut(e);return!!(Ie(o,qi)||Ie(o,Hi))}function ft(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Ln(o,t)):e.effective.some(o=>{let r=ut(o);return Mn(o).length>0||Ie(r,qi)||Ie(r,Hi)||r.has("search")})}function Un(e){let t=Ne(e).filter(r=>r.split(" ").every(i=>!i.startsWith("-"))).sort((r,i)=>i.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=Dn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Ki(e){return Un(e)==="all"?void 0:t=>Ln(t,e)}function Fe(e){let t=N(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...i]=t.commandPathTokens;return{commandPath:r,commandArgs:i,allowCommandPrefixMatch:!0}}let n=Vo(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Ji(e){let t=e.args.map(String);if(_($(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function An(e){for(let t of e)t.startsWith("settings_read_")&&w(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Yi(e,t){e.profile&&(w(`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&&w(`profile:extensions activation_warnings=${M(t.activationWarnings)}`))}function gt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";w(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function ht(e,t=re){let n=Fn(e);if(ee?.key===n)return ee.snapshot;try{let o=Date.now(),{settings:r,warnings:i}=await t(e),a=await Qn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return ee={key:n,snapshot:s},s}catch{return ee={key:n,snapshot:null},null}}async function me(e,t,n=I){let o=t?Un(t):"all",r=Li(e,o);if(Oe?.key===r)return Oe.snapshot;try{let i=await n(e),a=await fe({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Ki(t):void 0}),s=await ge({...a,loaded:a.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),d=Nr(s.registrations.flags),l=$r(s.commands.handlers,s.registrations.commands),m=Mr(c,s.registrations.commands,s.registrations.flags,l),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:i,commandHandlers:c,commandFlagHelp:d,commandDescriptors:m,commandAliases:l,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Oe={key:r,snapshot:p},p}catch{return Oe={key:r,snapshot:null},null}}async function Xi(e){let t=xe(e);if(t.noExtensions){let a=E(process.cwd(),t.path);return await U(j(a))&&An((await re(a)).warnings),null}let n=E(process.cwd(),t.path),o=await ht(n);if(!o)return null;An(o.settingsReadWarnings);let r={commandPath:$(e),commandArgs:Ji(e)};if(!ft(o.discovery,r))return gt(t.profile,o,r),null;let i=await me(n,r);return i?(Yi(t,i),{hooks:i.hooks,commands:i.commands,parsers:i.parsers,preflight:i.preflight,services:i.services,renderers:i.renderers,registrations:i.registrations,pmRoot:n}):null}async function Qi(e){let t=await me(e);return t?new Map(t.commandDescriptors):O}async function Zi(e,t){return(await Uo({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 ea(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return No(e,Bo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ta(e,t,n,o=[]){let r=$(e),i=zt(e.args.map(String),o),a={...t},s={...n},c=E(process.cwd(),n.path),d=await qe({command:r,args:i,options:a,global:s,pm_root:c});n.profile&&d.warnings.length>0&&w(`profile:extensions parser_warnings=${M(d.warnings)}`),i=d.context.args,a=d.context.options,s=d.context.global,Pi(O.get(_(r)),i,a,o),oe(void 0),Ue({command:r,args:i,options:{...a},global:{...s},pm_root:c});let l=await kt({command:r,args:i,options:a,global:s,pm_root:c,sdk:ea(c,s)});if(s.profile&&l.warnings.length>0&&w(`profile:extensions command_handler_warnings=${M(l.warnings)}`),!l.handled){if(l.warnings.length>0){let m=l.warnings[0],p=l.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:l.errorCode??"command_failed",nextSteps:l.remediation?[l.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return l.exitCode!==void 0&&(process.exitCode=l.exitCode),oe(l.result),l.result}var fi=Symbol("pm.wrappedActionHandler");function ll(e,t){let n=e[e.length-1];return n instanceof Tn?n:t}function gi(e,t,n){e&&n.length>0&&w(`profile:extensions ${t}=${M(n)}`)}function dl(e){let t=O.get(_(e.commandPath));if(!t||!Ii(e.activeRegistrations,e.commandPath))return;let n=$n(t).length===0?sr(e.commandArgs):zt(e.commandArgs,e.extensionFlagDefinitions);$i(t,n)}function ml(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 na(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[fi]!==!0){let r=o._actionHandler;o._actionHandler=async function(...a){let s=ll(a,n),c=Date.now();Nt(s);let d=xe(s),l=$(s),m=E(process.cwd(),d.path),p=s.args.map(String),u=J(),f=u?pt(u,l,p):[],h=await Mi(l,m),y=Re(s,p,[...f,...h]),k=await qe({command:l,args:p,options:y,global:d,pm_root:m});gi(d.profile,"parser_warnings",k.warnings),p=k.context.args,y=k.context.options,d=k.context.global,dl({activeRegistrations:u,commandPath:l,commandArgs:p,extensionFlagDefinitions:f}),d=await Mo(d),Pt(s,d),ml(s,a,p),Je(s,y),oe(void 0),Ue({command:l,args:p,options:{...y},global:{...d},pm_root:m});let C=await kt({command:l,args:p,options:y,global:d,pm_root:m,sdk:ea(m,d)});if(gi(d.profile,"command_handler_warnings",C.warnings),C.handled){oe(C.result),At(C.result,{...d,command:l,commandArgs:p,commandOptions:y,pmRoot:m}),d.profile&&w(`profile:command=${l} took_ms=${Date.now()-c}`);return}return await r.apply(this,a)},o[fi]=!0}for(let r of n.commands)t(r)};t(e)}async function ct(e){O=new Map,B({overrides:[]}),e&&await Pn(e.rootProgram,e.pmRoot,e.invocationArgv,Jn(),e.settings)}function pl(e,t,n,o){if(t?.flags&&t.flags.length>0){an(e,t.flags);let r=sn(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function oa(e,t,n){let o={core:0,standard:1,full:2,internal:3},r=(i,a)=>{let s=a.join(" "),c=[...n.entries()].filter(([l])=>l===s||l.startsWith(`${s} `)).map(([,l])=>l),d=c.length===0?"standard":c.reduce((l,m)=>o[m.tier]<o[l]?m.tier:l,"internal");lr(i,d);for(let l of i.commands)r(l,[...a,l.name()])};for(let i of e.commands)t.has(i.name())||r(i,[i.name()])}async function ra(e,t){let n=q(t),o=E(process.cwd(),n.path);if(n.noExtensions){await ct({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await ht(o),i=Fe(t);if(!r){await ct();return}if(!ft(r.discovery,i)){await ct({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),gt(Nn(t),r,i);return}let a=await me(o,i);if(!a){await ct({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}B(a.services),O=new Map(a.commandDescriptors),await Pn(e,o,t,a.registrations,a.settings);let s=Br(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,l=>Vr(a.activationWarnings,w,l)),c=new Set(e.commands.map(l=>l.name())),d=l=>{let m=l.split(" ").filter(C=>C.length>0),p=a.commandDescriptors.get(l),u=se(e,m),f=a.commandFlagHelp.get(l),h=p?zr(p):null;if(u){pl(u,p,f,h);return}let y=Wr(e,m);p?.description&&y.description(p.description);let k=f;p&&(Dr(y,p),p.flags.length>0&&(an(y,p.flags),k=sn(y,p.flags)??void 0)),k&&y.addHelpText("after",k),h&&y.addHelpText("after",h),y.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...C)=>{let Me=C[C.length-1],W=Me instanceof Tn?Me:y,te=xe(W),wt=Date.now(),De=pt(a.registrations,l,W.args.map(String)),pe=Re(W,W.args.map(String),De),ne=await ta(W,pe,te,De);await Do(te,ne),At(ne,{...te,command:l,commandArgs:W.args.map(String),commandOptions:pe,pmRoot:o}),te.profile&&w(`profile:command=${l} took_ms=${Date.now()-wt}`)})};for(let l of s)d(l);oa(e,c,a.commandDescriptors)}var $e=Wn(import.meta.url,["../.."])??"0.0.0",b=jt($e);function ia(e){e.hook("preAction",async(t,n)=>{de=null,F=null,je(),Nt(n);let o=n.optsWithGlobals(),r=xe(n),i=$(n),a=n.args.map(String),s=Re(n,a),c={...r};ho(i,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),mi(n,i,c,s),await Oo(i,c);let d=E(process.cwd(),r.path),l=await Xi(n);if(!l){de=Zn({commandName:i,commandArgs:a,commandOptions:s,globalOptions:c,pmRoot:d}),F=await $t({command:i,pm_version:$e,args:a,options:s,global:c,pm_root:d}),Ot(i,a,s,{source_context:F?.source_context,source_context_source:F?.source_context_source}),Rt(i),await mn(i,s,d,En()),await dn(i,a,s,c,d);return}eo(l.hooks),to(l.commands),no(l.parsers),oo(l.preflight),B(l.services),ro(l.renderers),io(l.registrations);let m=pt(l.registrations,i,a);s=Re(n,a,m),mi(n,i,c,s);let p=await qe({command:i,args:a,options:s,global:c,pm_root:l.pmRoot});c.profile&&p.warnings.length>0&&w(`profile:extensions parser_warnings=${M(p.warnings)}`),a=p.context.args,s=p.context.options,c=p.context.global,Je(n,s);let u=await co({command:i,args:a,options:s,global:c,pm_root:l.pmRoot,decision:En()});c.profile&&u.warnings.length>0&&w(`profile:extensions preflight_warnings=${M(u.warnings)}`),a=u.context.args,s=u.context.options,c=u.context.global,Je(n,s);let f=u.decision;await mn(i,s,l.pmRoot,f),await dn(i,a,s,c,l.pmRoot);let h=f.run_extension_migrations?await Zi(l.registrations.migrations,l.pmRoot):[];c.profile&&h.length>0&&w(`profile:extensions migration_warnings=${M(h)}`);let y=Yr(l.registrations.migrations);de={hooks:l.hooks,commandName:i,commandArgs:a,commandOptions:{...s},globalOptions:{...c},pmRoot:l.pmRoot,profileEnabled:!!c.profile,migrationBlockers:y},oe(void 0),Ue({command:i,args:a,options:{...s},global:{...c},pm_root:l.pmRoot}),F=await $t({command:i,pm_version:$e,args:a,options:s,global:c,pm_root:l.pmRoot}),Ot(i,a,s,{source_context:F?.source_context,source_context_source:F?.source_context_source}),Rt(i);let k=await Yn(l.hooks,{command:i,args:a,options:{...s},global:{...c},pm_root:l.pmRoot});c.profile&&k.length>0&&w(`profile:extensions hook_warnings=${M(k)}`),f.enforce_mandatory_migration_gate&&Xr(i,s,y)}),e.hook("postAction",async()=>{let t=Si();ye(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Pe(t)})}ia(b);var ul=new Set(["--version","-V"]),fl=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),aa=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"]),sa=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),gl=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),hl=new Set(["claim","close-task","pause-task","release","start-task","test"]),xn={setup:!0,listQuery:!0,mutation:!0,operation:!0},yl=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 yt(e){return e.some(t=>ul.has(t))}function ca(e){if(yt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||N(e).requested)return xn;let t=S(e);if(!t)return xn;let n=t.trim().toLowerCase();return fl.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:aa.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:sa.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:gl.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:xn}function la(e){return e.length===0||N(e).requested}var hi=Symbol("pmCliIdempotentTopLevelRegistration");function da(e){let t=e;if(t[hi])return;t[hi]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let i=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===i||a.aliases().includes(i))?new Tn(i):n(o,...r)})}async function wl(e,t){if(da(e),t.setup){let{registerSetupCommands:n}=await Yc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Xc(),o=typeof t.targetCommandName=="string"&&aa.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Qc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Zc();n(e)}}function ma(e,t){return yt(t)?!1:N(t).requested?!0:!!S(t)}function pa(e){if(yt(e))return!1;let t=S(e);return t?yl.has(t):!1}function _l(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(d=>{let l=d.indexOf("=");return l>=0?d.slice(0,l):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),i=r?e.argv.map(d=>{let l=d.indexOf("=");return(l>=0?d.slice(0,l):d)===o?l>=0?`${r}${d.slice(l)}`:r:d}):e.argv,a=ze(i),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:c,sourceDisplay:s}}function ua(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),r=o.length>0?o.join(" "):"the canonical flag",i=sa.has(t)||hl.has(t),a=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",c=_l({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`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:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function bl(e){return async t=>{let n=_t(t.errorCode),o=Tt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Io({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:$e,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 fa(e){if(e.bootstrapGlobal.noExtensions)return;let t=Fe(e.invocationArgv),n=await ht(e.bootstrapPmRoot);if(n&&ft(n.discovery,t)){let o=await me(e.bootstrapPmRoot,t);ga(o);return}n&>(Nn(e.invocationArgv),n,t),B({overrides:[]})}function ga(e){if(!e){B({overrides:[]});return}B(e.services)}async function jn(e){ye(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Pe({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 ha(){ye(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Pe({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function ya(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(Lt(e.error)||!n))return!1;let o=Y(e.error),r=e.error instanceof v?e.error.exitCode:Dt(t),i=e.error instanceof v?e.error.context:void 0,a=_i(i,e.invocationArgv,o),s=Sr(o,a),c=e.bootstrapGlobal.lean?ot(nn(o,r,a)):nn(o,r,a),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?_o(c,u=>`${JSON.stringify(u,null,2)}
|
|
29
|
+
`):c,null,2):Er(o,a);w(d);let{errorCategory:l,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await mt({command:e.attemptedCommand,error_code:s.code,error_category:l,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:F?.source_context});return await jn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:l,commandResolution:m,resolutionStage:"execute"}),p&&(It(Ut(e.error,o)),await we(Rn)),process.exitCode=r,!0}async function wa(e,t){let n=un(e.invocationArgv),o=`unknown command '${n}'`,r=E(process.cwd(),e.bootstrapGlobal.path),i=await Qi(r),a=Fe(e.invocationArgv),s=await wn(r,{},Ne(a)),c=await Te({message:o},b,i,{failedExtensions:s}),d=on(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:l,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await mt({command:n,error_code:d.code,error_category:l,exit_code:g.USAGE,error_message:d.detail,command_resolution:m,resolution_stage:"parse",source_context:F?.source_context}),u=e.jsonErrors?await yn({message:o},b,i,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await hn({message:o},b,i,{failedExtensions:s}),f=pn(u,e.jsonErrors,s);await jn({errorMessage:o,exitCode:g.USAGE,classificationCode:d.code,errorCategory:l,commandResolution:m,resolutionStage:"parse"}),w(f),p&&await we(Rn),process.exitCode=g.USAGE}async function _a(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=N(e.invocationArgv);return r.requested&&!oi(b,r.commandPathTokens)?(await wa(e,t),!0):(await ha(),!0)}async function ba(e,t){let n=await Te(e.error,b,O),o=on(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:r,commandResolution:i}=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 mt({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:g.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:F?.source_context}),s=e.jsonErrors?await yn(e.error,b,O,e.bootstrapGlobal.lean===!0):await hn(e.error,b,O),c=await ri(o.code,e.bootstrapPmRoot,{},Ne(Fe(e.invocationArgv))),d=pn(s,e.jsonErrors,c);await jn({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:i,resolutionStage:"parse"}),w(d),a&&await we(Rn),process.exitCode=g.USAGE}function xa(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 va(e){let t=e.error.code,n=String(e.error.message??"");if(!await _a(e,t,n)){if(t==="commander.version"){await ha();return}await ba(e,t)}}async function qn(e){let t=q(e.invocationArgv),n=E(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:S(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:bl({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await fa({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await ya(o,Mt(e.error))){if(xa(e.error)){await va(o);return}await Ri({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function xl(e){b=jt($e),ia(b),Oe=null,ee=null,O=new Map,ao();let t=[...e],n,o;try{let r=Qe(e);t=r.argv;let i=[process.argv[0],process.argv[1],...t],a=t.length===0,s=q(t);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=Zo(s.author),ua(r),o=Jo(t);let c=ca(t);if(await wl(b,c),la(t)&&fr(b,t),ma(b,t)?await ra(b,t):(O=new Map,B({overrides:[]})),pa(t)&&await Di(b,t),na(b),await ci(b,t,O))return;if(a){b.outputHelp();return}let m=await I(E(process.cwd(),s.path)),p=await di(t,E(process.cwd(),s.path),s.noExtensions,me);await Fo({pmRoot:E(process.cwd(),s.path),packages:p?.contextIntentPackages},()=>mo(m.agent_identity.harness_signals,()=>b.parseAsync(i),{probesEnabled:m.agent_identity?.probes_enabled}))}catch(r){await qn({error:r,invocationArgv:t})}finally{o?.(),n?.()}}async function Xd(e=process.argv.slice(2)){try{await $o(process.env,()=>xl(e))}catch(t){await qn({error:t,invocationArgv:[...e]})}}var Qd={activationCommandMatchesProbe:ji,applyDynamicExtensionRootHelpVisibility:oa,bootstrapProfileEnabled:Nn,buildBootstrapActivationProbe:Fe,buildPostActionTelemetryOutcome:Si,buildPmCliRecoveryContext:_i,buildRuntimeExtensionDiscoverySnapshotCacheKey:Fn,buildRuntimeExtensionActivationScope:Un,buildRuntimeExtensionSnapshotCacheKey:Li,buildRuntimeExtensionFilterForProbe:Ki,addRuntimeFieldOption:kn,collectActivationCommandCandidates:Ne,collectExtensionFlagDefinitionsForCommand:vn,collectExtensionFlagDefinitionsForInvocation:pt,collectLeadingCommandArgs:Ui,collectParsedActivationCommandArgs:Ji,collectRuntimeFieldLooseFlagDefinitionsForCommand:Mi,commandHasLongOption:Ni,commandHasShortOption:Fi,commandPathNeedsSearchExtensions:zi,commandPathNeedsTemplateExtensions:Dn,describeUnknownError:Y,defaultPreflightDecision:En,discoveryNeedsActivationForProbe:ft,emitExtensionProfile:Yi,emitExtensionSkippedProfile:gt,emitSettingsReadWarnings:An,ensureIdempotentTopLevelCommandRegistration:da,enforceExplicitRetryForFlagTypos:ua,envFlagEnabled:Ti,executeRegisteredRuntimeMigrations:Zi,extractCommandScopedOptions:Re,extensionActivationCommands:Mn,extensionCapabilities:ut,extensionNeedsActivationForProbe:Ln,extensionProvidesTemplatesRuntime:Wi,hasAnyCapability:Ie,hasGlobalExtensionContributions:Bi,handleGenericRunPmCliError:Ri,handleRunPmCliCommanderError:va,handleRunPmCliError:qn,handleRunPmCliHelpDisplayError:_a,handleRunPmCliKnownError:ya,handleRunPmCliCommanderUsageError:ba,handleUnknownHelpCommandError:wa,inferMissingFieldsFromErrorMessage:wi,inferPostActionErrorCode:Ei,inferPostActionFailureMessage:ki,invocationRequestsVersion:yt,isCommanderError:Lt,loadRuntimeExtensionCommandDescriptorsForRecovery:Qi,loadRuntimeExtensionDiscoverySnapshot:ht,loadRuntimeExtensionSnapshot:me,maybeLoadRuntimeExtensions:Xi,maybeAttachCreateUpdatePolicyHelpText:Pn,maybeLogHandledCliErrorToSentry:mt,matchesStaticExtensionCommand:Sn,normalizeTelemetryCommandResolution:xi,normalizeTelemetryErrorCategory:Ci,normalizeTelemetryResolutionStage:vi,normalizeThrownExitCode:Dt,probeUsesAnyFlag:Gi,prepareExtensionServicesForRunPmCliError:fa,readRecordBoolean:bi,readRecordNumber:In,readRecordString:le,recordCliReadOutputInvocationProvenance:yi,registerDynamicExtensionCommandPaths:ra,registerRuntimeSchemaFieldFlags:Di,resolveCoreCommandRegistrationSelection:ca,resolveStaticExtensionActivationDecision:Vi,resolveUnknownHelpToken:un,readThrownExitCode:Mt,runAndClearAfterCommandHooks:Pe,runRequiredExtensionCommand:ta,shouldAttachRichHelpTextForInvocation:la,shouldLogHandledErrorToSentry:Oi,shouldRegisterDynamicExtensionPaths:ma,shouldRegisterRuntimeSchemaFlags:pa,shouldHandleRunPmCliCommanderError:xa,setActiveExtensionHookContextForTest:zc,setActiveRuntimeExtensionCommandDescriptorsForTest:Gc,setRecoveredExtensionServices:ga,toLooseFieldDefinitionType:Cn,isImporterOrExporterCommandPath:Ii,validateDynamicExtensionCommandInvocation:Pi,wrapProgramActionsForExtensionHandlers:na,wrapThrownErrorForSentry:Ut};export{Qd as _testOnly,Xd as runPmCli};
|
|
29
30
|
//# sourceMappingURL=main.js.map
|