@unbrained/pm-cli 2026.11.1 → 2026.11.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +32 -0
- package/CONTRIBUTING.md +1 -1
- package/dist/cli/error-guidance.d.ts +9 -0
- package/dist/cli/error-guidance.js +4 -3
- package/dist/cli/main.js +1 -1
- package/dist/cli/migration-gates.js +1 -1
- package/dist/cli/runtime/field-route-retry.d.ts +15 -0
- package/dist/cli/runtime/field-route-retry.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-2GK2IVU5.js → chunk-2CBHQXYJ.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-32BCU6HN.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-MTRIGD7M.js → chunk-5IPXDZKU.js} +42 -42
- package/dist/cli-bundle/chunks/{chunk-O56O7NIE.js → chunk-5JZMF4M5.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TYERATXH.js → chunk-7ZEFHFAU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-B6UTLYLM.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-N45IXPCA.js → chunk-DEJHTFEF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ICT6E4IW.js → chunk-HBKD5HZB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6PKWKVS6.js → chunk-JPKIUWLG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WFBYKDB2.js → chunk-L6LCLC37.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y7CKVU56.js → chunk-MQJXZX3Q.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NR4KABHC.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-WX25MU4N.js → chunk-O4ZLEN4T.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-F3ECOBKA.js → chunk-PWD5RY2D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SBVX5CMV.js → chunk-RSAN2YUU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NILQ2ZMV.js → chunk-TZ3D3DPQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MRUA2Z43.js → chunk-UJMQP2HP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TMPO4CTZ.js → chunk-UYNMKUGA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UUN3WNMQ.js → chunk-XRMYA4R7.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-UEEG47TU.js → chunk-Y7H55PCY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5KW4WUAK.js → chunk-YWS4XV4I.js} +4 -4
- package/dist/cli-bundle/chunks/chunk-ZOAJNPBL.js +129 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-KGMJVFH2.js → indexed-receipt-blobs-I6RQGD6Y.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-ZHLJTBD7.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-BOOCJPCU.js → mutation-admission-ZQMRMGIB.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-23OX36Q3.js → register-list-query-I6AZA3IX.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-JPJ5YNDX.js → register-mutation-3DAXCLXR.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-IGR7ERY5.js → register-operations-G3QGGQ5Z.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-BMIFKZZP.js → register-setup-LDXHMNOT.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-YWSWFOZY.js → settlement-hook-JHXLUBEN.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-ON7CYYPM.js → stage-7H36OTDJ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3XGKBVJ3.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WX2RVS2Y.js → chunk-4HY6EGPB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-3NYWMUX3.js → chunk-D4XQOMG4.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-UQIBGLDR.js → chunk-F3X6UWMI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JLXGRDTG.js → chunk-G6ERMFJ5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-VFQAZLKO.js → chunk-HJ27QLZV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5TWS5KOM.js → chunk-HOXIIZEO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-HUXZCPWT.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LVA76N27.js → chunk-I5FODKYB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-DFUTCKUF.js → chunk-IDAYTYNN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2Y77HWIX.js → chunk-IKXJ57XA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RPUDOJVB.js → chunk-LKN2WGGB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MOY6KZGJ.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PAT6QF63.js → chunk-PWUTFKSI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PZRB7IXH.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-RY4QEMAE.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6GMYW42K.js → chunk-TYHDZUL4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WSYPVBKS.js +80 -0
- package/dist/cli-bundle/focused-chunks/{chunk-Z7GIVH6B.js → chunk-WXLG7HZ5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5WCQFH6D.js → chunk-WZDFCVLX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VS2ZFPXD.js → chunk-YGO3FWA2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-YVLAP3BL.js +23 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6OKPYCLU.js → chunk-ZQRCVRGS.js} +54 -54
- package/dist/cli-bundle/focused-chunks/chunk-ZYXQACPB.js +2 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-KHWT44EK.js → indexed-receipt-blobs-7XGVHYAO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-transaction-7VLPA2SU.js → item-transaction-PZ2FQ6B2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-2DH27R5Y.js → mutation-admission-XOOK6XFH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-SJV52ZTV.js → settlement-hook-H56537UV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-FYOBWQA7.js → stage-4SQHVI3O.js} +2 -2
- package/dist/cli-bundle/main.js +30 -29
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- 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 +11 -11
- package/dist/core/extensions/extension-hook-runtime.js +1 -1
- package/dist/core/extensions/extension-types.d.ts +5 -0
- package/dist/core/extensions/extension-types.js +1 -1
- package/dist/core/extensions/item-fields.d.ts +1 -1
- package/dist/core/extensions/item-fields.js +1 -1
- package/dist/core/item/parse.js +2 -2
- package/dist/core/lock/lock-confinement.d.ts +55 -0
- package/dist/core/lock/lock-confinement.js +2 -0
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock.js +2 -2
- package/dist/core/schema/runtime-field-values.d.ts +30 -0
- package/dist/core/schema/runtime-field-values.js +1 -1
- package/dist/core/sentry/helpers.js +1 -1
- package/dist/core/sentry/instrument.js +1 -1
- package/dist/core/shared/error-details.d.ts +98 -0
- package/dist/core/shared/error-details.js +2 -0
- package/dist/core/shared/errors.d.ts +43 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/settings-sections.d.ts +61 -0
- package/dist/core/store/settings-sections.js +3 -0
- package/dist/core/store/settings-validator.d.ts +4 -0
- package/dist/core/store/settings-validator.js +1 -1
- package/dist/core/store/settings.d.ts +29 -2
- package/dist/core/store/settings.js +4 -3
- package/dist/core/telemetry/consent.js +2 -2
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/core/test/background-runs.js +3 -3
- package/dist/mcp/server.js +2 -2
- package/dist/sdk/config.js +1 -1
- package/dist/sdk/errors.d.ts +6 -2
- package/dist/sdk/errors.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/error-code-catalog-rows.d.ts +39 -0
- package/dist/sdk/generated/error-code-catalog-rows.js +2 -0
- package/dist/sdk/generated/generated-error-code-catalog-part-1.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.d.ts +3 -3
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/generated-error-code-catalog.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/lifecycle/core-field-recovery.d.ts +26 -0
- package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
- package/dist/sdk/lifecycle/create.js +1 -1
- package/dist/sdk/lifecycle/update.js +2 -2
- package/dist/sdk/mcp/discovery.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/runtime-primitives.d.ts +2 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/entry.d.ts +5 -0
- package/dist/sdk/test/entry.js +2 -2
- package/dist/sdk/test/execution.d.ts +1 -2
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/test/linked-command-detection.d.ts +10 -0
- package/dist/sdk/test/linked-command-detection.js +1 -1
- package/dist/sdk/test/update.d.ts +2 -0
- package/dist/sdk/test/update.js +1 -1
- package/docs/AGENT_EVIDENCE_CONSISTENCY.md +10 -0
- package/docs/CONFIGURATION.md +9 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +9 -6
- package/docs/EXTENSIONS.md +2 -2
- package/docs/LINKED_TEST_EDITS.md +38 -5
- package/docs/RELEASING.md +22 -2
- package/docs/SDK.md +103 -1
- package/docs/SDK_CONFIGURATION_SAFETY.md +55 -0
- package/docs/TESTING.md +2 -1
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +15 -3
- package/marketplace.json +1 -1
- package/package.json +9 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-5WVE7XBS.js +0 -114
- package/dist/cli-bundle/chunks/chunk-E74BORFX.js +0 -128
- package/dist/cli-bundle/chunks/chunk-MP2DQJH2.js +0 -3
- package/dist/cli-bundle/chunks/chunk-O6TFUV6M.js +0 -31
- package/dist/cli-bundle/chunks/item-transaction-Q5S5YLEJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3Z53POXU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7WJDRZOR.js +0 -22
- package/dist/cli-bundle/focused-chunks/chunk-AL7SOFUL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CIQ6YWCW.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-GE755ODZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-JCR32IAO.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-M22TI7LP.js +0 -79
- package/dist/cli-bundle/focused-chunks/chunk-SXZM4PSS.js +0 -44
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,42 +1,43 @@
|
|
|
1
|
-
import"./chunks/chunk-DEZPZOQ7.js";import{A as
|
|
2
|
-
`),null,2)}async function
|
|
3
|
-
`)})}import{Command as
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function Bi(e,t){return t==="detailed"?Qs(e):Zs(e)}function L(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var el={cal:"calendar",ctx:"context"};function tl(e,t){return e.commands.find(n=>n.name()===t)??null}function nl(e,t){let n=e;for(let o of t){let a=tl(n,o);if(!a)return null;n=a}return n}function Rn(e,t,n,o){let a=nl(e,t.split(" ").filter(i=>i.length>0));a&&a.addHelpText("after",Bi(n,o))}function In(e){return e.includes("--explain")?"detailed":"compact"}function ie(e){return e.includes("--all")||e.includes("--explain")}var fe={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of P){let n=fe[e];n&&(fe[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Ae={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Vi=B.filter(e=>e.lifecycle==="deprecated");for(let e of Vi){let t=fe[e.alias];fe[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Ae,...Object.values(fe)])e.examples=e.examples.map(t=>{for(let n of Vi){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function ol(e){let t=L(e??"");return t?el[t]??t:""}function Pn(e){let t=ol(e);return t?fe[t]??Ae:Ae}function Ki(e,t){let n=Pn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Wi(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function al(){let e=B.filter(({lifecycle:n})=>n==="permanent"),t=B.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${ra(n)})`)].join(`
|
|
6
|
-
`)}function
|
|
7
|
-
`,s=t.visibleCommands(e);for(let l of s)ue(l)===void 0&&(l.name()==="help"||
|
|
8
|
-
`)
|
|
1
|
+
import"./chunks/chunk-DEZPZOQ7.js";import{A as On,C as ja,D as Ua,F as qa,G as Tn,a as En,d as M,e as L,f as A,g as Y,h as x,i as ga,n as Be,o as ha,p as va,t as ba,u as $a,v as Da,w as Ma,x as La,y as Na,z as Fa}from"./chunks/chunk-HBKD5HZB.js";import{Ua as Pa,f as ma,k as pa}from"./chunks/chunk-5IPXDZKU.js";import"./chunks/chunk-B6UTLYLM.js";import"./chunks/chunk-YWS4XV4I.js";import{F as Oa,b as xa,d as St,g as Ea,h as Sa,i as X,j as Aa,pd as Ia,rc as Ra}from"./chunks/chunk-NR4KABHC.js";import"./chunks/chunk-PWD5RY2D.js";import{ha as Ta,j as ua}from"./chunks/chunk-MQJXZX3Q.js";import"./chunks/chunk-XRMYA4R7.js";import"./chunks/chunk-L6LCLC37.js";import{Cc as aa,Dc as ra,G as fi,Kg as ka,Oc as ze,Rc as sa,Xc as la,Yb as hn,_b as Ki,ad as xn,bc as Ji,bd as ca,bf as fa,cc as Yi,cd as da,cf as ie,ec as Xi,ef as ya,ff as _a,gd as Ct,hf as wa,ic as Zi,id as Ge,jc as Qi,jd as kt,kc as yn,mb as vt,mc as ea,mg as xt,nb as Vi,nc as me,ng as Et,oc as _n,og as Sn,pc as wn,pg as Ve,qc as vn,qg as E,rc as bn,rg as Ca,sc as bt,sg as An,tc as Cn,uc as ta,vc as na,vd as We,wc as oa,wg as q,xc as kn,yc as ia,zc as Ee}from"./chunks/chunk-ZOAJNPBL.js";import"./chunks/chunk-SPPHDVZE.js";import"./chunks/chunk-UJMQP2HP.js";import"./chunks/chunk-2CBHQXYJ.js";import"./chunks/chunk-IB7UB5TE.js";import{Ba as en,Dd as sn,Ea as le,Ed as yt,Fd as Ri,Fg as Li,G as Fe,Ga as di,Gc as wi,Gd as Ii,Gg as Ni,Ha as ut,Hg as Fi,Ic as vi,Ig as ji,Jg as Ui,Ka as tn,La as mi,Li as wt,Ma as T,Mb as gi,Nb as Ce,Oa as pi,Ob as on,Oh as zi,Oi as Gi,Pa as K,Pb as ft,Ph as oe,Pi as Wi,Qb as an,Rh as gn,Sh as v,Si as xe,Ti as D,Ui as Bi,Vc as bi,Wc as qe,Xd as ln,Yc as He,Zc as Ci,aa as ci,bc as hi,cc as yi,fb as _,ff as Pi,gd as ki,gf as $i,gh as qi,hb as ui,hd as xi,ib as je,id as Ei,jd as Si,jg as cn,kd as ne,kg as dn,kh as Hi,lb as te,ld as Ai,lg as Di,md as rn,mg as Mi,nd as ce,od as Oi,of as _t,og as mn,pd as gt,pg as pn,qb as Ue,qg as un,r as P,sd as ke,sg as fn,t as G,td as de,u as $,uc as _i,w as B,wb as nn,wd as Ti,x as Qt,xd as ht,xh as J,y as W,z as li}from"./chunks/chunk-32BCU6HN.js";import"./chunks/chunk-RSAN2YUU.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as pt,C as k,E as V}from"./chunks/chunk-O4ZLEN4T.js";import"./chunks/chunk-XAWE4EAK.js";import{AsyncLocalStorage as el}from"node:async_hooks";(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]="0e47421c-706d-5e31-a466-6152cdeba30f")}catch{}})();var Se=new el;function Ha(e){let t=Se.getStore();return t===void 0?e:t!==null}function Ke(e,t=`warning:${e}`){let n=Se.getStore();n?(!n.has(e)||t!==`warning:${e}`)&&n.set(e,t):v(t)}function Je(e){let t=Se.getStore();if(!t?.size)return e;let n=Reflect.get(e,"warnings"),o=[...t].filter(([r,s])=>s!==`warning:${r}`).map(([r,s])=>({code:r,message:s})),i=Reflect.get(e,"warning_details"),a={...e,warnings:[...Array.isArray(n)?n:[],...t.keys()],...o.length>0?{warning_details:[...Array.isArray(i)?i:[],...o]}:{}};return t.clear(),a}function Rn(e){if(!Se.getStore()?.size)return e;let{token_accounting:t,...n}=Je(JSON.parse(e));return JSON.stringify(t===void 0?n:J(n,o=>`${JSON.stringify(o,null,2)}
|
|
2
|
+
`),null,2)}async function za(e,t){if(!e){await Se.run(null,t);return}let n=new Map;await Se.run(n,async()=>{await t(),n.size>0&&oe(`${JSON.stringify(Je({type:"warning"}))}
|
|
3
|
+
`)})}import{Command as Xo,CommanderError as bs}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]="50318c14-8c1c-50f3-95d0-fd9ea3f0bb69")}catch{}})();function H(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function pe(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return H(t)}function Z(e){let t=new Set,n=[];for(let o of e){let i=pe(o);i&&(t.has(i)||n.push(i),t.add(i))}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]="0b95b409-ef2c-59da-a628-16a2cb4f0ea6")}catch{}})();var In=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),At=new Set(["--full","--brief","--compact"]);function tl(e,t){return!!(e.flag==="--pm-path"||e.value_name||e.list||e.value_type==="number"||e.value_type==="string"||t.has(e.flag))}function nl(e){let t=ie(x([...e])),n=new Set([...ya,..._a,...wa].flatMap(r=>r.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...We,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,r.flag]))),i=new Map([...We,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,tl(r,n)])));for(let r of In)i.set(r,!0);for(let r of At)i.set(r,!1);let a=new Map;for(let r=0;r<e.length;r+=1){let s=e[r];if(s==="--")break;if(!s.startsWith("-"))continue;let l=s.split("=")[0];if(!i.has(l)&&!s.includes("="))return;a.set(r,o.get(l)??l),i.get(l)&&!s.includes("=")&&(r+=1)}return a}function Ga(e,t,n){let o=new Set;for(let[i,a]of t)n.has(a)&&(o.add(i),In.has(a)&&!e[i].includes("=")&&o.add(i+1));return e.filter((i,a)=>!o.has(a))}function ol(e,t){let n=t.find(i=>At.has(i));if(n===void 0)return;let o=[...new Set(e.values())].filter(i=>At.has(i));return o.length===1?o[0]:n}function Wa(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,i={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return i;let a=nl(e);if(!a)return i;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return i;let l=[...a].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return i;r=Ga(e,a,new Set(["--fields"])),r.splice(l,0,"--fields",o[s+1])}else{let s=ol(a,o);if(s===void 0||![...a.values()].includes(s))return i;let l=new Set([...In,...At].filter(c=>c!==s));r=Ga(e,a,l)}return{...n,suggested_retry:_(r),suggested_retry_args: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]="c470fd86-4218-5aed-a681-58557d759b28")}catch{}})();var il="project_schema_field_requires_declared_flag";function al(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o.startsWith("--field=")?t.push({index:n,width:1,assignment:o.slice(8)}):o==="--field"&&n+1<e.length&&(t.push({index:n,width:2,assignment:e[n+1]}),n+=1)}return t}function Ba(e,t,n,o){let i=o?.suggested_flags?.[0];if(t!==il||n===void 0||i===void 0)return o;let a=al(e).filter(({assignment:d})=>d.split("=",1)[0].trim()===n&&d.includes("="));if(a.length!==1)return o;let[r]=a,s=r.assignment.trim(),l=s.slice(s.indexOf("=")+1),c=[...e.slice(0,r.index),i,l,...e.slice(r.index+r.width)];return{...o,suggested_retry:_(c),suggested_retry_args:c}}(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]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function Va(e,t){await ca(e,{ok:t.ok,error:t.error,result:de(),exit_code:t.exit_code,error_code:t.error_code,error_category:t.error_category,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage})}async function Ka(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await qi({pmRoot:e.pmRoot,result:de()})}catch(o){t=o}let n=await D(e.pmRoot);if(await Hi({pmRoot:e.pmRoot,author:_t(e.author,n.author_default),itemIds:e.itemIds,intent:e.intent}),t!==void 0)throw t}(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]="dacf3952-3ae1-57fa-840a-c8a43cf855a5")}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]="9490326e-507d-5b3e-9958-08c12afbc5ff")}catch{}})();var Ja=new WeakMap;function Ot(e,t){Ja.set(e,t)}function ue(e){return Ja.get(e)}function Ya(e){return e.length>0?[e[0]]:[]}function rl(e){let t=["","Intent:",` ${e.why}`],n=Ya(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
|
|
4
|
+
`)}function sl(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
|
|
5
|
+
`)}function Xa(e,t){return t==="detailed"?sl(e):rl(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var ll={cal:"calendar",ctx:"context"};function cl(e,t){return e.commands.find(n=>n.name()===t)??null}function dl(e,t){let n=e;for(let o of t){let i=cl(n,o);if(!i)return null;n=i}return n}function Pn(e,t,n,o){let i=dl(e,t.split(" ").filter(a=>a.length>0));i&&i.addHelpText("after",Xa(n,o))}function $n(e){return e.includes("--explain")?"detailed":"compact"}function ae(e){return e.includes("--all")||e.includes("--explain")}var fe={"item reopen":{why:"Reopens recurring work while archiving earlier closure evidence and declaring its current planning outcome.",examples:['pm item reopen pm-a1b2 "The failure recurred" --expected-result "The recurrence regression passes"'],tips:["Without --expected-result, follow recovery.suggested_retry_args to restore current planning before claiming the item."]},ops:{why:"Groups workspace diagnostics, quality checks, and maintenance under one discoverable command.",examples:["pm ops health --summary","pm ops validate --check-history-drift","pm ops --help"]},init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm package install ./my-package --project","pm package install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm package explore --project","pm package manage --global","pm package describe sample-ext --project","pm package doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm package install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm package upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm package install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm package install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm package init ./my-extension","pm package init ./my-hook-extension --capability hooks","pm package init ./my-search-extension --capability search","pm package init ./my-sync-extension --capability importers","pm package init ./my-domain-extension --capability schema","pm package init ./my-output-extension --capability renderers","pm package --install --project ./my-sync-extension","pm package --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm package install ./my-extension --project","pm package --install --project ./my-extension","pm package doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm package install '*' --project","pm package install ./packages/pm-todos --project","pm package install npm:@scope/pm-package --global","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm package upgrade --dry-run","pm package upgrade --packages-only --project","pm package upgrade todos --dry-run","pm package upgrade --cli-only --repair","pm package upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output.","Bulk creation is pm item mutate --from items.jsonl (JSON Lines, array, or envelope; --upsert-key <field> makes re-runs idempotent)."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list --all --limit 50","pm list --all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list --status open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list --status in_progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list --blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list --status closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list --status canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list --status draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm package install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' with the highest-priority ready item, rationale, and ranked ready and blocked queues.",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspect recorded mutations.",examples:["pm history pm-a1b2 --order oldest_first","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "Done" --resolution "Delivered" --expected "Required outcome" --actual "Verified outcome" --release-assignment --validate-close warn','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list --all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:["pm claim pm-a1b2 --start",'pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim is an atomic test-and-set: a non-terminal item held by another principal refuses with already_claimed_by. Use --if-available to skip that item without failing. Terminal items still require --force, even when --if-available is set. Use --force for coordinated takeovers; stale locks require --force only when governance.force_required_for_stale_lock is enabled.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:["pm release pm-a1b2 --pause",'pm release pm-a1b2 --handoff review --message "Implemented; run linked verification"'],tips:["Register the project queue with pm schema add-status review --role active before using --handoff."]},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm claim --start pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm release --pause pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close --release-assignment pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}};for(let{alias:e,canonical:t}of P){let n=fe[e];n&&(fe[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var Ae={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm package install guide-shell --project","pm list --status open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]},Za=B.filter(e=>e.lifecycle==="deprecated");for(let e of Za){let t=fe[e.alias];fe[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[Ae,...Object.values(fe)])e.examples=e.examples.map(t=>{for(let n of Za){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function ml(e){let t=N(e??"");return t?ll[t]??t:""}function Dn(e){let t=ml(e);return t?fe[t]??Ae:Ae}function Qa(e,t){let n=Dn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:Ya(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function pl(){let e=B.filter(({lifecycle:n})=>n==="permanent"),t=B.filter(({lifecycle:n})=>n==="deprecated");return["","Command aliases:",...e.map(({alias:n,canonical_argv:o})=>` ${n} -> pm ${o.join(" ")}`),"","Deprecated aliases:",...t.map(n=>` ${n.alias} -> pm ${n.canonical_argv.join(" ")} (${li(n)})`)].join(`
|
|
6
|
+
`)}function ul(e,t,n,o){let i=new Set(Ea);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(l=>(ue(l)??X(l.name()))!=="internal"):r!==e?s:s.filter(l=>o.has(l))},visibleOptions(r){let s=t.visibleOptions(r);return r!==e||n?s:s.filter(l=>i.has(l.flags))}});let a=e.options.filter(r=>r.long==="--output-cursor");for(let r of e.commands.flatMap(s=>[s,...s.commands]))["list","search","context"].includes(r.name())&&r.configureHelp({visibleOptions:s=>[...t.visibleOptions(s),...a]})}function fl(e,t,n,o){let i=new Set(Aa("core")),a=e.createHelp();a.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${a.formatHelp(e,a)}${o}
|
|
7
|
+
`,s=t.visibleCommands(e);for(let l of s)ue(l)===void 0&&(l.name()==="help"||i.has(l.name()))&&n.add(l);for(let l of s)ue(l)==="core"&&(n.add(l),Sa(r()).within_budget||n.delete(l))}function er(e,t=process.argv.slice(2)){let n=e.createHelp(),o=ae(t),i=new Set;ul(e,n,o,i);let a=$n(t),r=Xa(Ae,a);e.addHelpText("after",r),o&&e.addHelpText("after",pl()),fl(e,n,i,r);for(let[d,m]of Object.entries(fe))Pn(e,d,m,a);let s=N(A(t).commandPathTokens.join(" ")),l=Ge(s);if(l){Pn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,kt(l.accepted_flags)]},a);return}let c=Ct.filter(({parent:d})=>d===s);c.length>0&&Pn(e,s,{why:`Dispatches one declared positional action: ${c.map(({action:d})=>d).join("|")}.`,examples:c.map(({example:d})=>d),tips:[`Inspect one action directly with pm ${s} <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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function Mn(e,t=!1){e.commands.some(n=>n.name()==="ops")||e.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(let{alias:n,canonical:o,canonical_argv:i}of P){if(t&&!P.some(c=>c.canonical.startsWith(`${o} `)))continue;let a=e.commands.findIndex(c=>c.name()===n);if(a<0)continue;let r=e.commands[a],s=e;for(let c of i.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=i[i.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(a,1),r.name(l),Ot(r,X(o)),s.enablePositionalOptions(),s.addCommand(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]="ada74388-c40b-5e8f-92f5-7162e9441f9b")}catch{}})();function Rt(e){let{title:t,...n}=e;pn(n.why)&&delete n.why,mn(n.required)&&delete n.required;let o=un(n.examples);o.length>0?n.examples=o:delete n.examples;let i=fn(n.recovery);return i===void 0?delete n.recovery:n.recovery=i,n}var gl=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function hl(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!gl.has(e.code)}function lr(e){return`urn:pm-cli:error:${e}`}function C(e){return{...e,type:lr(e.code)}}var Oe={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},tr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},nr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Tt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},yl={guide:Oe,shell:Oe,completion:Oe,"completion-statuses":Oe,"completion-tags":Oe,"completion-types":Oe,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:tr,cal:tr,reindex:nr,"search-advanced":nr,"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 _l(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return yl[t]}function jn(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function wl(e){if(!Array.isArray(e))return;let t=e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function vl(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 Ln(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function cr(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function Q(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let i=cr(n);i&&(e[t]=i);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let i=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);i.length>0&&(e.parsed_positionals=i);return}let o=wl(n);o&&(e[t]=o)}function bl(e,t){if(!Xi(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:i,minimum_status:a,basis:r,reason:s}}var dr=["retry_after_ms","waited_ms","owner_handoffs"];function Cl(e,t){for(let n of dr)typeof t[n]=="number"&&e.push(` ${n}: ${t[n]}`)}function kl(e,t){for(let n of dr){let o=t[n];typeof o=="number"&&Number.isSafeInteger(o)&&o>=0&&(e[n]=o)}}function ye(e){if(!e||typeof e!="object")return;let t={};bl(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Ln(t,"attempted_command",e.attempted_command),Q(t,"normalized_args",e.normalized_args),Q(t,"parsed_positionals",e.parsed_positionals),Q(t,"provided_fields",e.provided_fields),Q(t,"missing",e.missing),Q(t,"missing_required_fields",e.missing_required_fields),Q(t,"suggested_flags",e.suggested_flags),Q(t,"allowed_values",e.allowed_values),Q(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),Ln(t,"suggested_retry",e.suggested_retry),Q(t,"suggested_retry_args",e.suggested_retry_args),kl(t,e);let n=vl(e.fallback_candidates);return n&&(t.fallback_candidates=n),Ln(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Nn(e,t,n){n&&e.push(` ${t}: ${n}`)}function ge(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function xl(e){let t=ye(e);if(!t)return[];let n=["Recovery bundle:"];if(t.token_budget){let o=t.token_budget;n.push(` requested_token_budget: ${o.requested_tokens}`,` feasible_token_budget: ${o.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${o.minimum_feasible_tokens??"not established"}`)}if(Nn(n,"suggested_retry",t.suggested_retry),Nn(n,"attempted_command",t.attempted_command),ge(n,"normalized_args",t.attempted_command?void 0: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(ge(n,"provided_fields",t.provided_fields,", "),ge(n,"missing",t.missing,", "),ge(n,"missing_required_fields",t.missing_required_fields,", "),ge(n,"suggested_flags",t.suggested_flags,", "),ge(n,"allowed_values",t.allowed_values,", "),ge(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}`),Cl(n,t),Nn(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}var or=120;function El(e){if(e.claimedBy===void 0)return;let t=e.claimedAt?` since ${e.claimedAt}`:"",n=Array.from(e.claimedBy);return`Held by: ${n.length>or?`${n.slice(0,or).join("")}...`:e.claimedBy} (${e.claimSource??"unknown"}${t})`}function Sl(e,t){let n=[`Error: ${e.title}`];(!t||!mn(e.required))&&n.push("","What is required:",` ${e.required}`),e.nextSteps&&e.nextSteps.length>0&&(n.push(""),n.push(...jn("Next steps:",e.nextSteps))),e.happened!==e.title&&n.push("","What happened:",` ${e.happened}`);let o=El(e);return o!==void 0&&n.push("",o),n}function Al(e,t){let n=[];e.why&&!(t&&pn(e.why))&&n.push("","Why:",` ${e.why}`);let o=t?un(e.examples):e.examples??[];o.length>0&&n.push("",...jn("Examples:",o));let i=e.verificationErrors??[];return i.length>0&&n.push("",...jn("Verification errors:",i)),n.push(...Ol(e)),n}function Ol(e){if(e.details!==void 0&&Object.keys(e.details).length>0)return["","Details:",...JSON.stringify(e.details,null,2).split(`
|
|
8
|
+
`).map(o=>` ${o}`)];let t=e.detailsOmitted;if(t===void 0)return[];let n=t.path===void 0?` (over ${t.byte_limit} bytes)`:` at ${t.path}`;return["",`Details omitted: ${t.reason}${n}`]}function ir(e,t={}){let n=t.lean===!0,o=[...Sl(e,n),...Al(e,n)],i=xl(n?fn(e.recovery):e.recovery);return i.length>0&&(o.push(""),o.push(...i)),o.join(`
|
|
9
|
+
`)}var Tl="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for the full recovery envelope.",Rl=400,ar=320;function Il(e){let t=ye(e);if(!t)return;let n={};t.suggested_retry&&Buffer.byteLength(t.suggested_retry,"utf8")<=Rl&&(n.suggested_retry=t.suggested_retry);for(let o of["missing","missing_required_fields","allowed_values"]){let i=t[o];i&&i.length>0&&(n[o]=i.slice(0,3))}return t.next_best_command&&(n.next_best_command=t.next_best_command),Object.keys(n).length>0?n:void 0}function Pl(e,t={}){let n=ir(e,t),o=dn("error").default_max_estimated_tokens_by_format.text,i=d=>cn(Buffer.byteLength(d,"utf8"))<=o;if(i(n))return n;let a={...e,why:void 0},r={...a,details:void 0,examples:e.examples?.slice(0,1),nextSteps:e.nextSteps?.slice(0,1),verificationErrors:e.verificationErrors?.slice(0,3)},s={...r,recovery:Il(e.recovery)},l=Array.from(e.happened),c={...s,examples:void 0,happened:l.length>ar?`${l.slice(0,ar).join("")}...`:e.happened};for(let d of[a,r,s,c]){let m=`${ir(d,t)}
|
|
9
10
|
|
|
10
|
-
${vl}`;if(a(m))return m}return n}function kl(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",e.item_id=t.itemId)}function rr(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),kl(e,t),ll(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 El(e,t){if(e.flag)return e.flag;let n=o=>{let a=o.split("=",1)[0];return N([a]).length>0&&!["--help","--no-changed-fields","--version"].includes(a)&&t.some(i=>i===a||i.startsWith(`${a}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function Sl(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(i=>i===n||i.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let a=t.indexOf(n);return t[a+1]}}function Al(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=N(e.recovery?.normalized_args??[]),o=G(n),a=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,i=El(e,a),r=Sl(e,a,i);return{surface:i??e.recovery?.missing?.[0]??Sn(a)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Tl(e,t){return rr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Al(e,t),...e.changed===!1?{changed:!1}:{}},e)}function Fn(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 Da(Tl(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function jn(e){return rr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function It(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Ol(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 he(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 tr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Rl(e){return Sn(e?.normalized_args)}function Il(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 Pl(e,t){let n=e?.normalized_args,o=e?.provided_fields,a=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!a))for(let i of o){let r=n.findIndex(s=>s===i);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=a,w(s)}}}function $l(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ot(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Dl(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function re(e,t,n){if(!n)return e;let o=It(t),a=Ot(n.code,e.code),i=Ot(n.type,or(a)),r=he(n.examples)??e.examples,s=he(n.nextSteps)??e.nextSteps,l=he(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?$l(o):void 0,d=ye(n.recovery),m=d&&e.recovery?ye({...e.recovery,...d}):d??e.recovery;return{...e,code:a,changed:n.changed,sideEffects:n.side_effects,type:i,title:c??e.title,happened:o.length>0?o:e.happened,required:Ot(n.required,e.required),why:Ot(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Dl(n,m)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,availableDependencies:n.available_dependencies,recovery:m}}function Ml(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 a=o[1],i=ca(process.cwd(),a);return re(C(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${a}, 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 Nl(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let a=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(a),r=i?`The item ID "${a}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${a}" exists in the active tracker scope.`;return re(C({code:"item_not_found",title:"Item ID not found",flag:"id",value:a,happened:r,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 Ll(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:re(C({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 Fl(e,t,n){if(!t.includes("is locked"))return null;let o=ar(n?.recovery?.normalized_args),a=o?w(o):void 0,i=re(C({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:a?[a]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(i.recovery={...i.recovery,suggested_retry:a,suggested_retry_args:[...o]}),i}function jl(e,t,n){let o=t.match(/^Missing required option /),a=t.match(/^Missing required options /);if(!o&&!a)return null;let i=!!a,r=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",l=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return re(C({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.":l,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 Ul(e,t,n){return t.startsWith("No update flags provided")?re(C({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 ql(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=ye(n?.recovery),a=Rl(o),i=a?`pm ${a} --help`:"pm <command> --help",r=n?.allowed??Il(t),s=ye({...o,allowed_values:o?.allowed_values??r}),l=Pl(o,r),c=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return re(C({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:d,recovery:s}),e,n)}function Un(e,t){let n=It(e);return(Ml(e,n,t)??Nl(e,n,t)??Ll(e,n,t)??Fl(e,n,t)??jl(e,n,t)??Ul(e,n,t)??ql(e,n,t))||re(C({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 Hl(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 zl(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Gl(e){if(!(!Array.isArray(e)||e.length===0))return w(e)}function qn(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 j(e,t={}){let n=qn(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,a=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Gl(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return ye({attempted_command:a,normalized_args:o,provided_fields:n,suggested_retry:i,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Nn(e,t){return!t||e.includes(t)?e:[...e,t]}var Wl=new Set(["--add","--add-json","--remove"]),Bl=new Set(["command","cmd","path"]);function Vl(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(Wl.has(o))return o}}function Kl(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 a=e[o];if(a!=="--add"&&a!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!Bl.has(i))return;let r=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${i}=${r.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return w(l)}}function Jl(e,t,n,o){let a=e.match(/required option '([^']+)' not specified/);if(!a)return null;let i=zl(a[1]),r=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=qn(o?.providedOptionFlags),c=[i],d=Hl(t,i,n),m=s?Nn(d,s):d,p=r?[`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?Nn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Nn(u,`Already provided options: ${l.join(", ")}`):u;return C({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:r?"--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:j(o,{missing:c})})}function Yl(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let a=o[1];return C({code:"missing_required_argument",title:`Missing required argument ${a}`,happened:`Command invocation omitted positional argument ${a}.`,required:`Provide ${a} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:j(n,{missing:[a]})})}function Xl(e,t,n){return C({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:j(t,{suggested_flags:n})})}var Zl={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 Ql(e){let t=he(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function ec(e,t,n,o,a){let i=o.otherCommands.slice(0,3),r=o.candidateTotal-i.length,s=r>0?` and ${String(r)} 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?void 0:tc(e,t),i.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,lr(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,a?`Replay with suggested correction: ${a}`:void 0].filter(l=>typeof l=="string")}var sr=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function tc(e,t){if(t===void 0||!sr.includes(e.split("=",1)[0]))return;let n=Ri(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${Ii(n)}.`}function nc(e,t,n){let o=Pi(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:w(o),suggestedRetryArgs:o}:[...sr,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function lr(e){return/\s/u.test(e)}function oc(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(a=>!a.startsWith("-")))return{};let o=[...N(e.filter((a,i)=>i!==n)),"--",t];return{retryCommand:w(o),suggestedRetryArgs:o}}function ac(e,t,n){if(lr(t))return oc(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=nc(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if($i(t))return{};let a=e.normalizedInvocationArgs;if(a===void 0)return{};if(a.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let i=a.findIndex(s=>s===t||s.startsWith(`${t}=`));if(i<0||a.includes("--")||!a[i]?.includes("=")&&i!==a.length-1&&a[i+1]?.startsWith("-")!==!0)return{};let r=N(a.filter((s,l)=>l!==i));return{retryCommand:w(r),suggestedRetryArgs:r}}function ic(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let a=n??{},i=o[1],r=qn(a.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=ac(a,i,t);if(t==="update"&&(i==="--file"||i==="--doc"))return Xl(i,n,r);let c=Ql(a),d=ec(i,t,r,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(i.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${W(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return C({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:Zl[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:d,recovery:j(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:a.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function rc(e,t,n,o,a){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return C({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:tr([t.installCommand,...n]),nextSteps:tr([i,...r]),recovery:j(a)})}function sc(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],a=he(t?.unknownCommandExamples),i=he(t?.unknownCommandNextSteps),r=dl(o),s=a??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!c.has(d))?rc(o,r,s,l,t):C({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:l,recovery:j(t)})}function lc(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=he(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let a=e?.suggestedRetryCommand;return C({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...a?[a]:[],`pm ${W(t)?.canonical??t} --help`],nextSteps:a?[`Retry with the declared hyphenated action: ${a}`]:["Choose one value from recovery.allowed_values."],recovery:j(e,{allowed_values:o,suggested_retry:a})})}function cc(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,a=Vl(o);if(!a)return null;let i=Kl(o);return C({code:"linked_test_value_not_quoted",title:`Linked-test ${a} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${a} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${a} 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:j(n,i?{suggested_retry:i}:{})})}var dc=new Set(["comments","docs","files","learnings","notes","test"]);function mc(e,t,n){if(!/too many arguments/i.test(e))return null;let o=pa(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let a=o.retryArgs?w(o.retryArgs):void 0,i=w(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return C({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:a?`Retry the explicit collection mutation: ${a}`:`Supply the actual command and its metadata together, for example ${i}.`,examples:[a??i],recovery:j(n,{suggested_retry:a,suggested_retry_args:o.retryArgs})})}function pc(e,t,n){if(!/too many arguments/i.test(e)||!dc.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>c===t),i=o[a+1],r=o[a+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return C({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:[l,`pm ${t} --help`],recovery:j(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var uc=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"]),nr=new Set(["context","ctx"]);function fc(e,t,n){if(!/too many arguments/i.test(e)||!nr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>nr.has(c)),i=a===-1?1:a+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(i)){if(c){c=!1;continue}let m=d.split("=")[0];if(uc.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return C({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 ${l} 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:[l,`pm context --parent ${s}`],recovery:j(n,{suggested_retry:l})})}function Hn(e,t,n,o){let a=It(e);return(Jl(a,t,n,o)??Yl(a,t,o)??ic(a,t,o)??sc(a,o)??lc(o)??pc(a,t,o)??cc(a,t,o)??mc(a,t,o)??fc(a,t,o))||C({code:"invalid_command_usage",title:"Invalid command usage",happened:a,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:j(o)})}function cr(e,t,n={}){let o=Un(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${w(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
11
|
-
`):
|
|
11
|
+
${Tl}`;if(i(m))return m}return n}function $l(e,t){t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),t.lease!==void 0&&(e.lease=t.lease,e.current_owner=t.currentOwner??null,e.item_id=t.itemId),t.claimedBy!==void 0&&(e.claimed_by=t.claimedBy,e.claimed_at=t.claimedAt??null,e.claim_source=t.claimSource??"unknown",e.item_id=t.itemId)}function mr(e,t){return t.sideEffects!==void 0&&(e.side_effects=t.sideEffects),t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),$l(e,t),hl(t)&&(e.why=t.why),t.examples&&t.examples.length>0&&(e.examples=t.examples),t.nextSteps&&t.nextSteps.length>0&&(e.next_steps=t.nextSteps),t.verificationErrors&&t.verificationErrors.length>0&&(e.verification_errors=t.verificationErrors),t.flag!==void 0&&(e.flag=t.flag),t.value!==void 0&&(e.value=t.value),t.unmatchedSelectors!==void 0&&(e.unmatched_selectors=t.unmatchedSelectors),t.availableDependencies!==void 0&&(e.available_dependencies=t.availableDependencies),t.recovery&&(e.recovery=t.recovery),e}function Dl(e,t){if(e.flag)return e.flag;let n=o=>{let i=o.split("=",1)[0];return L([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))};return[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(o=>o[0]).find(o=>n(o))}function Ml(e,t,n){if(e.value!==void 0)return e.value;if(e.flag===void 0&&n){let o=t.find(a=>a===n||a.startsWith(`${n}=`));if(o?.startsWith(`${n}=`))return o.slice(n.length+1);let i=t.indexOf(n);return t[i+1]}}function Ll(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=L(e.recovery?.normalized_args??[]),o=G(n),i=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,a=Dl(e,i),r=Ml(e,i,a);return{surface:a??e.recovery?.missing?.[0]??On(i)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Nl(e,t){let n=mr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Ll(e,t),...e.changed===!1?{changed:!1}:{}},e);return e.details!==void 0&&(n.details=e.details),e.detailsOmitted!==void 0&&(n.details_omitted=e.detailsOmitted),n}function Un(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?"recovery_bundle":"error";return Di(Fl(Nl(e,t),o),{diagnosticClass:o})}function Fl(e,t){if(e.details===void 0)return e;let n=dn(t).default_max_estimated_tokens_by_format.json;if(cn(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))<=n)return e;let{details:o,...i}=e;return{...i,details_omitted:{reason:"diagnostic_budget",byte_limit:Ki.max_bytes}}}function qn(e){return mr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function It(e){return e.replace(/\(outputHelp\)/g,"").trim()}function jl(e){let t=e.toLowerCase();return t.includes("cannot find module")||t.includes("cannot find package")||t.includes("err_module_not_found")||t.includes("module_not_found")}function he(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 rr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Ul(e){return On(e?.normalized_args)}function ql(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 Hl(e,t){let n=e?.normalized_args,o=e?.provided_fields,i=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!i))for(let a of o){let r=n.findIndex(s=>s===a);if(r>=0&&r<n.length-1&&!n[r+1]?.startsWith("-")){let s=[...n];return s[r+1]=i,_(s)}}}function zl(e){let t=e.split(/\r?\n/)[0].trim();if(t.length===0)return;let n=Array.from(t);return n.length<=120?t:`${n.slice(0,117).join("")}...`}function Ye(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Gl(e,t){if(e.flag!==void 0)return e.flag;if(e.field===void 0)return;let n=e.field.startsWith("--")?e.field:`--${e.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return t?.normalized_args?.some(o=>o===n||o.startsWith(`${n}=`))?n:void 0}function Wl(e,t,n,o){let i=e.code==="command_failed"||e.code==="invalid_argument_value"&&t!==e.code;return(n.code&&i?zl(o):void 0)??e.title}function Bl(e){let t=Yi(e);return t===void 0?{}:"details"in t?{details:t.details}:{detailsOmitted:t.details_omitted}}function re(e,t,n){if(!n)return e;let o=It(t),i=Ye(n.code,e.code),a=Ye(n.type,lr(i)),r=he(n.examples)??e.examples,s=he(n.nextSteps)??e.nextSteps,l=he(n.verification_errors)??e.verificationErrors,c=ye(n.recovery),d=c&&e.recovery?ye({...e.recovery,...c}):c??e.recovery;return{...e,code:i,changed:n.changed,sideEffects:n.side_effects,type:a,title:Wl(e,i,n,o),happened:o.length>0?o:e.happened,required:Ye(n.required,e.required),why:Ye(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Gl(n,d)??e.flag,value:n.value??e.value,unmatchedSelectors:n.unmatched_selectors,itemId:n.item_id,transactionOperation:n.transaction_operation,previewStorage:n.preview_storage,tombstone:n.tombstone,lease:n.lease,currentOwner:n.current_owner,claimedBy:n.claimed_by,claimedAt:n.claimed_at,claimSource:n.claim_source,availableDependencies:n.available_dependencies,recovery:d,...Bl(n)}}function Vl(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let i=o[1],a=mi(process.cwd(),i);return re(C(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${i}, but found a tracker at ${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 Kl(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let i=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(i),r=a?`The item ID "${i}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${i}" exists in the active tracker scope.`;return re(C({code:"item_not_found",title:"Item ID not found",flag:"id",value:i,happened:r,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 Jl(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:re(C({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 Yl(e,t,n){if(!t.includes("is locked"))return null;let o=cr(n?.recovery?.normalized_args),i=o?_(o):void 0,a=re(C({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:i?[i]:["pm gc --scope locks --dry-run"]}),e,n);return o&&(a.recovery={...a.recovery,suggested_retry:i,suggested_retry_args:[...o]}),a}function Xl(e,t,n){let o=t.match(/^Missing required option /),i=t.match(/^Missing required options /);if(!o&&!i)return null;let a=!!i,r=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=r??"",l=r?`Pass ${r} with a valid value before running the command.`:"Provide the required option for this command invocation.";return re(C({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.":l,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 Zl(e,t,n){return t.startsWith("No update flags provided")?re(C({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 Ql(e,t){if(e.startsWith("Invalid "))return!0;if(!e.includes(" must be ")&&!e.includes(" requires "))return!1;let n=Ye(t?.code,void 0);return n===void 0||n==="invalid_argument_value"||t?.allowed!==void 0}function ec(e,t,n){if(!Ql(t,n))return null;let o=ye(n?.recovery),i=Ul(o),a=i?`pm ${i} --help`:"pm <command> --help",r=n?.allowed??ql(t),s=ye({...o,allowed_values:o?.allowed_values??r}),l=Hl(o,r),c=l?[l,a]:[a,"pm contracts --command <command> --flags-only --json"],d=r.length>0?[`Allowed values: ${r.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return re(C({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:d,recovery:s}),e,n)}function Hn(e,t){let n=It(e);return(Vl(e,n,t)??Kl(e,n,t)??Jl(e,n,t)??Yl(e,n,t)??Xl(e,n,t)??Zl(e,n,t)??ec(e,n,t))||re(C({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 tc(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 nc(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function oc(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function zn(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 j(e,t={}){let n=zn(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,i=typeof e?.attemptedCommand=="string"?e.attemptedCommand:oc(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return ye({attempted_command:i,normalized_args:o,provided_fields:n,suggested_retry:a,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Fn(e,t){return!t||e.includes(t)?e:[...e,t]}var ic=new Set(["--add","--add-json","--remove"]),ac=new Set(["command","cmd","path"]);function rc(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(ic.has(o))return o}}function sc(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let i=e[o];if(i!=="--add"&&i!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!ac.has(a))return;let r=[];for(let c=o+2;c<e.length;c+=1){let d=e[c];if(d.startsWith("--")&&d.length>2)break;r.push(d)}if(r.length<2)return;let s=`${a}=${r.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+r.length)];return _(l)}}function lc(e,t,n,o){let i=e.match(/required option '([^']+)' not specified/);if(!i)return null;let a=nc(i[1]),r=a.startsWith("--type"),s=o?.suggestedRetryCommand,l=zn(o?.providedOptionFlags),c=[a],d=tc(t,a,n),m=s?Fn(d,s):d,p=r?[`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?Fn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Fn(u,`Already provided options: ${l.join(", ")}`):u;return C({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:r?"--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:j(o,{missing:c})})}function cc(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let i=o[1];return C({code:"missing_required_argument",title:`Missing required argument ${i}`,happened:`Command invocation omitted positional argument ${i}.`,required:`Provide ${i} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:j(n,{missing:[i]})})}function dc(e,t,n){return C({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:j(t,{suggested_flags:n})})}var mc={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 pc(e){let t=he(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function uc(e,t,n,o,i){let a=o.otherCommands.slice(0,3),r=o.candidateTotal-a.length,s=r>0?` and ${String(r)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i?void 0:fc(e,t),a.length?`${e} is accepted by ${a.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,ur(e)?`"${e}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`:o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,i?`Replay with suggested correction: ${i}`:void 0].filter(l=>typeof l=="string")}var pr=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function fc(e,t){if(t===void 0||!pr.includes(e.split("=",1)[0]))return;let n=Da(t);return n===void 0?void 0:`Completeness controls accepted by pm ${n.command}: ${Ma(n)}.`}function gc(e,t,n){let o=La(n??"",e.normalizedInvocationArgs??[],t);return o?{retryCommand:_(o),suggestedRetryArgs:o}:[...pr,"--toon",...n==="activity"?["--since"]:[]].includes(t.split("=",1)[0])?{}:void 0}function ur(e){return/\s/u.test(e)}function hc(e,t){let n=e?.indexOf(t)??-1;if(e===void 0||n<0||e.includes("--")||e.lastIndexOf(t)!==n)return{};if(e.slice(n+1).some(i=>!i.startsWith("-")))return{};let o=[...L(e.filter((i,a)=>a!==n)),"--",t];return{retryCommand:_(o),suggestedRetryArgs:o}}function yc(e,t,n){if(ur(t))return hc(e.normalizedInvocationArgs,t);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};let o=gc(e,t,n);if(o)return o;if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(Na(t))return{};let i=e.normalizedInvocationArgs;if(i===void 0)return{};if(i.filter(s=>s===t||s.startsWith(`${t}=`)).length!==1)return{};let a=i.findIndex(s=>s===t||s.startsWith(`${t}=`));if(a<0||i.includes("--")||!i[a]?.includes("=")&&a!==i.length-1&&i[a+1]?.startsWith("-")!==!0)return{};let r=L(i.filter((s,l)=>l!==a));return{retryCommand:_(r),suggestedRetryArgs:r}}function _c(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let i=n??{},a=o[1],r=zn(i.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=yc(i,a,t);if(t==="update"&&(a==="--file"||a==="--doc"))return dc(a,n,r);let c=pc(i),d=uc(a,t,r,c,s);["--dry-run","--check","--check-only","--plan","--preview"].includes(a.split("=",1)[0])&&d.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.");let m=[s,t?`pm ${W(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return C({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:mc[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:a,value:a,examples:m,nextSteps:d,recovery:j(n,{suggested_flags:r.length>0?r:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:c.otherCommands,candidate_commands_total:c.candidateTotal||void 0,candidate_commands_truncated:i.unknownOptionOtherCommandsTruncated,option_scope:c.optionScope})})}function wc(e,t,n,o,i){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,r=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return C({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:rr([t.installCommand,...n]),nextSteps:rr([a,...r]),recovery:j(i)})}function vc(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],i=he(t?.unknownCommandExamples),a=he(t?.unknownCommandNextSteps),r=_l(o),s=i??["pm --help"],l=a??["Verify spelling and active extensions, then rerun."],c=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=r?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return r&&(!d||!c.has(d))?wc(o,r,s,l,t):C({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:l,recovery:j(t)})}function bc(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=he(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let i=e?.suggestedRetryCommand;return C({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,value:n,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...i?[i]:[],`pm ${W(t)?.canonical??t} --help`],nextSteps:i?[`Retry with the declared hyphenated action: ${i}`]:["Choose one value from recovery.allowed_values."],recovery:j(e,{allowed_values:o,suggested_retry:i})})}function Cc(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,i=rc(o);if(!i)return null;let a=sc(o);return C({code:"linked_test_value_not_quoted",title:`Linked-test ${i} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${i} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${i} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...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:j(n,a?{suggested_retry:a}:{})})}var kc=new Set(["comments","docs","files","learnings","notes","test"]);function xc(e,t,n){if(!/too many arguments/i.test(e))return null;let o=fi(t,n?.normalizedInvocationArgs??[]);if(!o)return null;let i=o.retryArgs?_(o.retryArgs):void 0,a=_(o.templateArgs??["test",o.itemId,"--add",`command=<actual command>,${o.value}`]);return C({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${t}.`,required:i?`Retry the explicit collection mutation: ${i}`:`Supply the actual command and its metadata together, for example ${a}.`,examples:[i??a],recovery:j(n,{suggested_retry:i,suggested_retry_args:o.retryArgs})})}function Ec(e,t,n){if(!/too many arguments/i.test(e)||!kc.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>c===t),a=o[i+1],r=o[i+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!r||r.startsWith("-")||!s||s.toLowerCase()!==r.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return C({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:[l,`pm ${t} --help`],recovery:j(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:l})})}var Sc=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"]),sr=new Set(["context","ctx"]);function Ac(e,t,n){if(!/too many arguments/i.test(e)||!sr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],i=o.findIndex(c=>sr.has(c)),a=i===-1?1:i+1,r=e.match(/got \d+:\s*(\S+)/i),s=r?r[1].replace(/\.$/,""):void 0;if(s===void 0){let c=!1;for(let d of o.slice(a)){if(c){c=!1;continue}let m=d.split("=")[0];if(Sc.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return C({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 ${l} 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:[l,`pm context --parent ${s}`],recovery:j(n,{suggested_retry:l})})}function Gn(e,t,n,o){let i=It(e);return(lc(i,t,n,o)??cc(i,t,o)??_c(i,t,o)??vc(i,o)??bc(o)??Ec(i,t,o)??Cc(i,t,o)??xc(i,t,o)??Ac(i,t,o))||C({code:"invalid_command_usage",title:"Invalid command usage",happened:i,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:j(o)})}function fr(e,t,n={}){let o=Hn(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&o.title==="Tracker is not initialized"&&o.recovery?.suggested_retry_args?[`Error: ${o.title}`,`Run: ${_(o.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
12
|
+
`):gr(o,n)}function gr(e,t){let n=a=>Mi(Pl(e,a),e.required).output,o=n(t);if(t.lean!==!0)return o;let i=n({});return Buffer.byteLength(i,"utf8")<Buffer.byteLength(o,"utf8")?i:o}function hr(e,t){return qn(Hn(e,t))}function Wn(e,t,n){return Un(Hn(e,n),t)}function yr(e,t,n,o,i={}){let a=Gn(e,t,n,o);return gr(a,i)}function Bn(e,t,n,o){return qn(Gn(e,t,n,o))}function Pt(e,t,n,o,i){return Un(Gn(e,t,n,i),o)}function _r(e,t){let n=wr(e);return Un(n,t)}function wr(e){let t=It(e);return jl(t)?C({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."]}):C({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 vr(e){return qn(wr(e))}(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]="4647d40c-70a2-5ffe-a91f-d43e9c522114")}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]="e860a827-39e1-5d6c-b76e-0d77365ba202")}catch{}})();var Xe=ci.join("|"),Oc={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"},Tc={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"]}},br=["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 Rc(e,t){let n=Tc[e];if(!n)return[];let o=H(t);for(let[i,a]of Object.entries(n))if(H(i)===o)return a;return[]}function Vn(e,t,n){if(n.length===0)return e;if(t){let r=n.find(d=>d.declared_command_match===!0),{token_accounting:s,...l}=JSON.parse(e),c={...l,...r?{extension_command_failure:{code:"extension_command_activation_failed",extension:r.name,layer:r.layer,error:r.error,recovery_commands:r.recovery_commands??[]}}:{},failed_extensions:n};return JSON.stringify(s===void 0?c:J(c,d=>`${JSON.stringify(d,null,2)}
|
|
12
13
|
`),null,2)}let o=n.map(r=>`- ${r.layer}:${r.name}: ${r.error}`).join(`
|
|
13
|
-
`),
|
|
14
|
+
`),i=n.find(r=>r.declared_command_match===!0);if(!i)return`${e}
|
|
14
15
|
Extension activation failures:
|
|
15
|
-
${o}`;let
|
|
16
|
-
`);return`Extension command unavailable: ${
|
|
17
|
-
${
|
|
16
|
+
${o}`;let a=(i.recovery_commands??[]).map(r=>`- ${r}`).join(`
|
|
17
|
+
`);return`Extension command unavailable: ${i.layer}:${i.name}
|
|
18
|
+
${i.error}${a.length>0?`
|
|
18
19
|
Recovery:
|
|
19
|
-
${
|
|
20
|
+
${a}`:""}
|
|
20
21
|
|
|
21
22
|
${e}
|
|
22
23
|
Extension activation failures:
|
|
23
|
-
${o}`}function
|
|
24
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function
|
|
25
|
-
`):l,null,2)}(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]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function
|
|
24
|
+
${o}`}function Kn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function Sr(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let i=o.shift();if(!i)continue;let a=N(E(i)),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a),o.push(...i.commands)}for(let i of t.keys()){let a=N(i),r=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!r&&n.add(a)}return[...n].sort((i,a)=>i.localeCompare(a))}function Cr(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" ");if(n===o)return 0;if(i.includes(o))return 1;if(i.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of i){let l=an(s,o,a);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function kr(e){return H(e).slice(2).replace(/-/g,"")}function Jn(e){return _(e)}function Ic(e){let t=W(e)?.canonical??Qt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=Oc[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function xr(e){let t=Ta(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Pc(e,t){let n=xr(e);if(n.length===0)return[];let o=[];for(let i of t.values()){let a=new Set,r=i.source;if(r)for(let s of[r.name,r.package]){let l=xr(s??"");l.length>0&&a.add(l)}a.size!==0&&[...a].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(i.command)}return[...new Set(o)].sort((i,a)=>i.localeCompare(a))}function Ze(e,t){let n=new Set,o=t??ie(e);for(let i of o){i.flag.startsWith("--")&&n.add(H(i.flag));for(let a of i.aliases??[])a.startsWith("--")&&n.add(H(a))}return[...n].sort((i,a)=>i.localeCompare(a))}function $c(e,t){if(!e.startsWith("--"))return[];let n=kr(e);if(n.length===0)return[];let o=n.length>=8?2:1,i=[];for(let a of t){let r=kr(a);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){i.push({flag:a,rank:0,distance:r.length-n.length});continue}let s=an(n,r,o);s===null||s<=0||i.push({flag:a,rank:1,distance:s})}return i.sort((a,r)=>a.rank!==r.rank?a.rank-r.rank:a.distance!==r.distance?a.distance-r.distance:a.flag.localeCompare(r.flag)).map(a=>a.flag).slice(0,3)}var $t,Dc=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 Mc(){if($t)return $t;let e=new Map;for(let t of Fe)if(!Dc.has(t))for(let n of Ze(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return $t=e,$t}function Lc(e,t){if(!e.startsWith("--"))return[];let n=Mc().get(H(e));if(!n)return[];let o=t?.trim().toLowerCase(),i=new Set(Ze(o));return[...new Set(n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:Ze(a).filter(r=>i.has(r)).length})).sort((a,r)=>a.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(r.command)).map(({command:a})=>W(a)?.canonical??a))]}function Nc(e,t,n){for(let o=0;o<e.length;o+=1){let i=e[o];if(!i.startsWith("--"))continue;let a=i.indexOf("="),r=a>=0?i.slice(0,a):i;if(H(r)!==H(t))continue;let s=[...e];return s[o]=a>=0?`${n}${i.slice(a)}`:n,s}}function Fc(e){let t=new Set(e.commandPaths),n=a=>Math.min(Cr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Cr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,i=(a,r)=>{if(!Number.isFinite(r)||!t.has(a))return;let s=o.get(a);(s===void 0||r<s)&&o.set(a,r)};for(let a of e.commandPaths)i(a,n(a));for(let[a,r]of Object.entries(Qt))a!=="read"&&i(r,n(a));return[...o.entries()].sort(([a,r],[s,l])=>r!==l?r-l:a.localeCompare(s)).map(([a])=>a)}function jc(e){let t=W(e.normalizedUnknown),n=qa(e.commandPaths,e.primaryToken),o=Fc(e),i=Pc(e.primaryToken,e.extensionDescriptors).filter(a=>e.commandPaths.includes(a));return Tn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...i],e.commandPaths,e.primaryToken).filter(a=>!e.normalizedUnknown.includes(" ")||a!==e.normalizedUnknown)}function Uc(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qc(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help --all"])]:[...new Set(["pm --help --all",...n])]}function Hc(e,t,n){let o=Y([...t]),i=[];for(;o!==void 0;){if(i.push(t[o]),t[o]===e)return i.join(" ");if(!n.includes(i.join(" ")))return e;let a=Y(t.slice(o+1));o=a===void 0?void 0:o+1+a}return e}function Er(e,t){if(!e)return;let n=M([...t]);return[...ui(n),...e.split(" "),"--help"]}function Yn(e,t,n,o=[]){let i=e.match(/unknown command '([^']+)'/i);if(!i||typeof i[1]!="string")return;let a=Sr(t,n),r=Hc(i[1],o,a),s=N(r);if(s.length===0||a.length===0)return;let l=$a(s,a);if(l){let I=Er("update",o),z=I.slice(0,-2);return{suggestedRetryCommand:_(I),suggestedRetryArgs:I,unknownCommandExamples:[_(I),...l.examples.map(U=>_([...z,...U]))],unknownCommandNextSteps:l.nextSteps}}let c=Ic(s);if(c&&!a.includes(c.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[c.installCommand,`pm ${c.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${c.packageAlias}" package. Install it with: ${c.installCommand}. Command after installation: pm ${c.canonicalPath}.`],suggestedRetryCommand:c.installCommand};let d=s.split(" ")[0],m=jc({commandPaths:a,normalizedUnknown:s,primaryToken:d,extensionDescriptors:n}),p=Uc(a),u=Ua(s,a),f=Er(u,o),h=[...new Set([...u?[u]:[],...m.length>0?m:Tn(p,a)])].slice(0,3),b=qc(h,m.length>0),S=m.length>0?`Did you mean: ${h.join(", ")}?`:null;return{...f?{suggestedRetryCommand:_(f),suggestedRetryArgs:f}:{},unknownCommandExamples:f?[_(f),...b.slice(1)]:b,unknownCommandNextSteps:[...S?[S]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...S?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function zc(e){return Array.from(new Set(e))}function Gc(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
25
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Wc(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 Bc(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 Te(e,t){if(t.length===0)return!0;let n=e;for(let[o,i]of t.entries()){let a=Bc(n,i);if(!a){let r=n.registeredArguments;return r.length>0&&(n.commands.length===0||r[0]?.required===!0)&&(r.at(-1)?.variadic===!0||t.length-o<=r.length)}n=a}return!0}async function Vc(e,t,n,o){try{let i=T(process.cwd(),e.path);if(!await V(K(i)))return{allowedTypes:Xe};let a=await D(i),r=e.noExtensions?void 0:ce(),s=le(a,r),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let c=n.findIndex(m=>m===o),d=n[c+2];if(n[c+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{l=(await vt(i,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Xe,pmRoot:i,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Xe}}}function Kc(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?zc([...Rc(t,n[1]),...$c(n[1],Ze(t))]).filter(r=>Fa(n[1],r)):void 0,i=n?Lc(n[1],t):[],a=n!==null&&Ze(t).includes(H(n[1]));return{match:n,suggestions:o,otherCommands:i,scope:a?"declared_on_path":i.length>0?"declared_elsewhere":"declared_nowhere"}}function Jc(e,t,n){if(!t||!n||n.length===0)return;let o=Nc(e,t[1],n[0]);return o?Jn(o):void 0}function Yc(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Wc(Gc(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let i=x(t);if(i)return ja(t,i,[o])}function Xc(e,t){if(!/too many arguments/i.test(e))return;let n=Y(t),o=G(t.slice(n));if(o?.alias!=="schema")return;let i=n+o.canonical_argv.length-1,a=t[i+1]?.trim().toLowerCase(),r=t[i+2]?.trim().toLowerCase();if(!a||!r)return;let s=`${a}-${r}`;if(!br.includes(s))return;let l=[...t.slice(0,i+1),s,...t.slice(i+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${a} ${r}`,unknownSubcommandAllowedValues:[...br],suggestedRetryCommand:Jn(l)}}function Zc(e,t,n,o){let i=Y(t),a=G(t.slice(i))?.alias??x(t);if(!/unknown option /i.test(e)||a===void 0)return a;let r=W(a)?.canonical??a;return Fe.some(s=>s===a)||Sr(n,o).includes(r)?a:void 0}async function Qe(e,t,n,o={},i=process.argv.slice(2)){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Be([...i]).argv,s=M(r),l=Zc(a,r,t,n),c=Jn(r),d=Z(r),m=await Vc(s,a,r,l),p=m.allowedTypes,u=Yn(a,t,n,r),f=Kc(a,l),h=Xc(a,r),b=h?.suggestedRetryCommand??Jc(r,f.match,f.suggestions)??Yc(a,r);return{message:a,commandName:l,allowedTypes:p,attemptedCommand:c,normalizedInvocationArgs:[...r],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:b,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function Xn(e,t,n,o={},i=process.argv.slice(2)){let a=await Qe(e,t,n,o,i),{message:r,commandName:s,allowedTypes:l,...c}=a,d=M(a.normalizedInvocationArgs).lean,m=yr(r,s,l,c,{lean:d}),p=await Ii("help_format",{message:m,command:s,allowed_types:l});return p.handled&&typeof p.result=="string"?p.result:m}async function Zn(e,t,n,o=!1,i={},a=process.argv.slice(2)){let r=await Qe(e,t,n,i,a),s=Pt(r.message,r.commandName,r.allowedTypes,g.USAGE,r),l=o?Rt(s):s,c=M(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(c?J(l,d=>`${JSON.stringify(d,null,2)}
|
|
26
|
+
`):l,null,2)}(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]="e57ce782-5c73-5c74-a929-0971a990a355")}catch{}})();async function Ar(e,t,n,o){if(n)return null;let i=e.some(r=>r==="--for"||r.startsWith("--for=")),a=x(e)==="contracts"&&e.includes("--full");return i||a?await o(t):null}import{Option as Qc}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]="dd8f1dc7-7987-56d4-8521-f8383b1cc5ae")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Tr(e,t){let n=new Map;for(let o of e){let i=w(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let r=w(a.command),s=r.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&i===d){n.set(i,r);break}}}return n}function Qn(e,t,n,o){if(!t||!n)return;let i,a=0;for(let[s,l]of e.entries()){if(l!==t)continue;let c=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>c[f]===u)&&(i=m,a=p.length)}}let r=i?.flags.find(s=>s.long===n||s.short===n);if(r)return ed(r).takesValue}function Mt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Dt(e){return typeof e=="boolean"?e:void 0}function ed(e){let t=Ce(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function td(e){let t=te(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=eo(e);return n?`${n} ${to(e)}`:null}function Rr(e){let t=[...new Set(e.map(td).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
26
27
|
Extension-provided flags:
|
|
27
28
|
${t.join(`
|
|
28
|
-
`)}`}function
|
|
29
|
+
`)}`}function Ir(e){let t=new Map;for(let i of e){let a=w(i.target_command);if(a.length===0)continue;let r=t.get(a)??[];r.push(...i.flags),t.set(a,r)}let n=[...t.entries()].sort(([i],[a])=>i.localeCompare(a)),o=new Map;for(let[i,a]of n){let r=Rr(a);r&&o.set(i,r)}return o}function Pr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Or(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let i=o.trim();i.length===0||n.has(i)||(n.add(i),t.push(i))}return t}function nd(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 od(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Pr(o,n.action),description:i,intent:a,examples:Or(n.examples),failure_hints:Or(n.failure_hints),arguments:nd(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",source:{layer:n.layer,name:n.name,package:n.source_package,version:n.source_version}})}return t}function id(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let i=t.get(o)??[];i.push(...n.flags),t.set(o,i)}return t}function ad(e,t,n){let o=new Set;for(let i of e){let a=w(i);a.length>0&&o.add(a)}for(let i of t.keys())o.add(i);for(let i of n.keys())o.add(i);return o}function rd(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function $r(e,t,n,o=new Map){let i=od(t),a=id(n),r=ad(e,i,a),s=new Map,l=[...r].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=rd(c,i,o)??i.get(c),m=a.get(c)??(d?a.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:Pr(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function sd(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(sd(n),n.description??"Extension argument.")}function ld(e){if(Dt(e.visible)===!1)return null;let t=te(e.long),n=Mt(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,i=t&&t.startsWith("--")&&t.length>2?t:null,a=[o,i].filter(r=>r!==null);return a.length>0?a:null}function eo(e){let t=ld(e);if(!t)return null;let{value_name:n,value_arity:o}=Ce(e),i=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${i}`}function cd(e){return eo(e)}function to(e){let t=Mt(e.description)??"Extension-provided option.",n=[];Dt(e.required)===!0&&n.push("required"),Dt(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"",i=e.default!==void 0?` (default: ${JSON.stringify(e.default)})`:"";return`${t}${o}${i}`}function Mr(e,t){let n=te(t.long),o=Mt(t.short);return e.options.some(i=>{let a=i;return n!==null&&a.long===n||o!==null&&a.short===o})}function no(e,t){for(let n of t){if(Mr(e,n))continue;let o=cd(n);if(!o)continue;let i=to(n),a=new Qc(o,i);if(a.negate=!1,n.list!==!0){e.addOption(a);continue}e.addOption(a.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function oo(e,t){return Rr(t.filter(n=>!Mr(e,n)))}function dd(e){let t=eo(e);if(!t)return null;let n=te(e.long),o=Mt(e.short),i=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=Ce(e),s=Dt(e.required)===!0;return{flags:t,long:i,short:a,description:to(e),takes_value:r.value_arity!=="none",value_required:r.value_arity==="required",value_name:r.value_name,variadic:!1,required:s,aliases:[],alias_for:null,...e.default!==void 0?{default_value:e.default}:{}}}function Lr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let i=dd(o);!i||n.has(i.flags)||(n.add(i.flags),t.push(i))}return t}function Nr(e,t){if(t.length===0)return e;let n=new Map(e.map(o=>[o.flags,o]));for(let o of t){let i=n.get(o.flags);n.set(o.flags,i?{...i,...o.default_value!==void 0?{default_value:o.default_value}:{}}:o)}return[...n.values()]}function Fr(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:`
|
|
29
30
|
Extension command metadata:
|
|
30
31
|
${t.join(`
|
|
31
|
-
`)}`}function no(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 Qe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:no(o).includes(n))??null}function ee(e,t){let n=e;for(let o of t){let a=Qe(n,o);if(!a)return null;n=a}return n}var oo=new WeakSet;function Dr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let a=t[o];o>0&&P.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let i=Qe(n,a);if(i){n=i;continue}let r=n.command(a);oo.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function Zc(e,t){let n=t.join(" "),o=P.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let a=e,i=[];for(let r of t){let s=Qe(a,r);if(!s)return null;i.push(r);let l=s.commands.length>0||P.some(c=>c.canonical.startsWith(`${i.join(" ")} `));if(!oo.has(s)&&(i.length===t.length||!l))return{core_path:i.join(" "),extension_path:t.join(" ")};a=s}return null}function Qc(e,t,n,o,a=!1){let i=t.split(" ").filter(d=>d.length>0),r=Zc(e,i),s=ee(e,i),l=P.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||oo.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!a||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${c}`}function Mr(e,t,n,o,a){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,r)=>i.localeCompare(r)).filter(i=>{let r=Qc(e,i,o,n.get(i),t.includes(i));return r?(a(r),!o.has(i)&&ee(e,i.split(" "))!==null):!0})}function Nr(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]="c6ed71d0-b878-575e-b990-356afdc45688")}catch{}})();var ed=new Set(["__proto__","prototype","constructor"]),ao=Symbol("looseOptionOccurrences");function et(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function td(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 io(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(1,r).trim(),value:n.slice(r+1),attached:!0};let s=n.slice(1).trim(),l=e[t+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:s,value:l}:{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),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let a=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:a,value:i}:{consumed:1,key:a,value:!0}}function Nt(e){return ed.has(e)}function Lr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return ua(t)}function tt(e){let t=[],n=te(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let a=et(n.slice(2));a.length>0&&!Nt(a)&&t.push(a)}if(o.startsWith("-")&&!o.startsWith("--")){let a=et(o.slice(1));a.length>0&&!Nt(a)&&t.push(a)}return[...new Set(t)]}function Fr(e){let t=new Set;for(let n of e)for(let o of tt(n))t.add(o);return t}function nd(e){let t=te(e.long)??"";if(t.startsWith("--")){let n=et(t.slice(2));if(n.length>0&&!Nt(n))return n}return tt(e)[0]??null}function jr(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 ro(e,t,n){if(t.length===0)return;let o=new Set,a=new Map,i=[],r=[];for(let s of t){let l=tt(s),c=jr(s);c!==null&&r.push(c);for(let d of l)o.add(d),s.enabled===!1&&a.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&i.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new x(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=a.get(s);if(l)throw new x(`Option '${l}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of i)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new x(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function od(e){return typeof e=="string"||e==null?e:String(e)}function ad(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 id(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 rd={string:od,number:ad,boolean:id};function Re(e,t){return Array.isArray(e)?e.map(n=>Re(n,t)):rd[t](e)}function Ur(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(a=>a!=null&&a!==""):on(e);return t?o.map(a=>Re(a,t)):o}function sd(e,t,n,o){return n?Ur(e,t,o):t?Re(e,t):e}function ld(e,t,n){let o=e[ao];if(!o||o.length===0)return n;let a=new Set(t);return o.filter(i=>a.has(i.key)).map(i=>i.value)}function qr(e){return Ce(e).value_arity==="none"}function so(e,t,n,o,a){let i=jr(e),r=a?` for extension command '${a}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new x(`Option '${i}'${r} expects ${o}; received ${s}.`,g.USAGE,{code:"extension_flag_value_invalid",required:`Pass ${i} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${i}.`,`Run pm ${a??"<command>"} --help to review the declared flag contract.`]})}function lo(e,t){return e.value_validation==="strict"&&t!=="string"}function cd(e,t){let n=e[ao];if(!n)return[];let o=new Set(t);return n.filter(a=>o.has(a.key))}function dd(e,t,n,o){if(qr(e))for(let a of cd(n,t)){if(a.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?on(a.value):[a.value];for(let r of i){let s=ut(Re(r,"boolean"),"boolean");s!==null&&so(e,"boolean",r,s.expected,o)}}}function md(e,t,n,o,a){let i=Array.isArray(n)?n.flat(1/0):[n],r=o?i:i.flatMap(s=>typeof s=="string"?s.split(","):[s]);for(let s of r)if(typeof s=="string"&&s.trim().length===0){let l=ut(s,t);so(e,t,s,l.expected,a)}}function co(e,t,n,o){if(!lo(e,n))return t;let a=n==="boolean"&&qr(e),i=r=>{let s=ut(r,n);return s===null?r:a&&typeof r=="string"?!0:so(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(i):i(t)}function pd(e,t,n,o){for(let a of n)if(!(a===t||!Object.hasOwn(e,a))){if(Object.hasOwn(e,t)){if(o){let i=e[t],r=e[a];e[t]=[...Array.isArray(i)?i:[i],...Array.isArray(r)?r:[r]].filter(s=>s!=null)}delete e[a];continue}e[t]=e[a],delete e[a]}}function Hr(e,t,n=e,o){if(t.length===0)return e;let a=Object.create(null);for(let[i,r]of Object.entries(e))a[i]=r;for(let i of t){let r=nd(i);r&&ud(a,i,r,n,o)}return a}function ud(e,t,n,o,a){let i=t.list===!0,r=tt(t),s=Lr(t);s&&!i&&fd(e,t,n,r,s,a),pd(e,n,r,i);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=sd(t.default,s,i,l));return}if(s==="boolean"&&lo(t,s)&&dd(t,r,o,a),i){e[n]=gd(t,r,o,e[n],s,l,a);return}s&&(e[n]=co(t,Re(e[n],s),s,a))}function fd(e,t,n,o,a,i){for(let r of o)r!==n&&Object.hasOwn(e,r)&&co(t,Re(e[r],a),a,i)}function gd(e,t,n,o,a,i,r){let s=ld(n,t,o);a&&lo(e,a)&&md(e,a,s,i,r);let l=Ur(s,a,i);return a?co(e,l,a,r):l}function zr(e){let t=Object.create(null),n=[];Object.defineProperty(t,ao,{value:n});let o=0;for(;o<e.length;){let a=io(e,o);if(!a){o+=1;continue}let i=et(a.key);if(i.length===0||Nt(i)){o+=a.consumed;continue}td(t,i,a.value),n.push({...a,key:i}),o+=a.consumed}return t}function Gr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=io(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function mo(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let r of t){let s=Lr(r);for(let l of tt(r))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let a=[],i=0;for(;i<e.length;){if(e[i]==="--"){a.push(...e.slice(i+1));break}let r=io(e,i);if(r){let s=et(r.key);if(n.has(s)){let l=e[i],c=o.has(s)&&!l.includes("=")?1:r.consumed;i+=c;continue}}a.push(e[i]),i+=1}return a}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]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function po(e,t={},n=[]){let o={readSettings:D,loadExtensions:qe,activateExtensions:He,resolveImplicitPmRoot:tn,...t};try{let a=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(i);return[...i.failed,...r.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),c=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(L).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(L),m=c.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...c.length>0?{declared_commands:c}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(a){return[{layer:"runtime",name:"extension-loader",error:a instanceof Error?a.message:String(a)}]}}async function Wr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let a=await po(t,n,o),i={readSettings:D,loadExtensions:qe,activateExtensions:He,resolveImplicitPmRoot:tn,...n};try{let r=i.resolveImplicitPmRoot(process.cwd());if(Ie.resolve(r)===Ie.resolve(t))return a;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(r)]),[c,d]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:r,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(c.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 a;a.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Ie.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Ie.resolve(r)} 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(r)}, or install the extension into the selected tracker with "pm --pm-path ${Ie.resolve(t)} install <package> --project".`})}catch{}return 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]="3f896a8d-2c03-5f9c-9909-4684a187870d")}catch{}})();var Br={core:0,standard:1,full:2,internal:3};function Vr(e,t,n=!0){let o=t.get($(e));if(o)return o;if(!n)return;let a=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(a.length===0)return;let i=a.reduce((s,l)=>Br[l.tier]<Br[s]?l.tier:s,"internal"),r=new Set(a.map(({family:s})=>s));return{tier:i,family:r.size===1?a[0].family:"extensions"}}function Kr(e,t){if(t.length===0)return e;let n=ee(e,t);if(n)return n;let o=t.join(" ");if($(o)!==o||!Fe.some(a=>a===o)&&!di(o)&&!Ge(o)&&!Oe(e,t))return null;for(let a=t.length-1;a>0;a-=1){let i=ee(e,t.slice(0,a));if(i)return i}return t.length===1?e:null}function hd(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 yd(e){let t=new Map;for(let n of e){let o=n,a=Jr(n);if(!a||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(a)??[];i.push(o.long.trim()),t.set(a,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(a=>a.trim()).filter(a=>a.length>0))].sort((a,i)=>a.localeCompare(i)));return t}function _d(e){return w(e)}function wd(e){let t=e.options??[],n=yd(t);return t.map(o=>{let a=o,i=typeof a.flags=="string"?a.flags.trim():"",r=typeof a.description=="string"?a.description.trim():"",s=Jr(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==a.long).map(h=>h.trim()).filter(h=>h.length>0),c=r.match(/^Alias for ([^ ]+)/i),d=c&&c[1]?c[1].trim():null,m=a.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=i.includes("<"),u=p||i.includes("["),f={flags:i,long:typeof a.long=="string"?a.long:null,short:typeof a.short=="string"?a.short:null,description:r,takes_value:u,value_required:p,value_name:hd(i),variadic:a.variadic===!0,required:m,aliases:l,alias_for:d};return a.defaultValue!==void 0&&(f.default_value=a.defaultValue),f})}function vd(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 a=o.alias_for,i=t.get(a);if(!i)continue;let r=o.long,s=new Set([...i.aliases??[],r]);i.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function bd(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",a=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||a?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:a}})}function Cd(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(a=>a.name()!=="help"||e.parent===null).filter(a=>!n||(ue(a)??X(a.name()))!=="internal").map(a=>{let i=L(E(a)),r=i,s=ue(a),l=Vr(i,t,s!==void 0),c=B.find(({alias:d})=>d===i);return{name:a.name().trim(),aliases:no(a),description:a.description().trim(),tier:l?.tier??s??X(r),family:l?.family??Et(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((a,i)=>a.name.localeCompare(i.name))}function xd(e,t,n){if(!n)return t;let o=n.examples??[],a=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"?a.length>0?[...a]:[...t.tips]:[],detail_mode:e}}function kd(e,t,n,o,a){let i=e!==void 0&&Pn(e)===Ae,r=i?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Ki(e,n),s=a?"positional_action":o?.intent||o?.description?"extension":i?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:xd(n,r,o),intentSource:s}}function Ed(e,t){return e===void 0?null:t?.tier??X(e)}function Sd(e,t){return e===void 0?null:t?.family??Et(e)}function Ad(e,t,n){if(!(t!==e||!n))return B.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Kr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Td(e,t,n,o,a=new Map,i=!1){if(!e){let s=bd(t),l=Cd(t,a,i),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...bt.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:X(n.split(" ")[0]),family:Et(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:c,value_kind:d,polymorphic:m})=>({name:s,required:l,variadic:c,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&r.has(s)||l.some(c=>r.has(c))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:c})=>{let d=c?`${s}...`:s;return l?`<${d}>`:`[${d}]`})].join(" ")}}function Od(e,t,n,o,a){let i=In(n),r=ie(n),s=L(E(t)),l=L(o.join(" ")),c=l.length>s.length?l:s,d=Ge(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?a.get($(p)):void 0,h=p?Vr(p,a,ue(t)!==void 0):void 0,{narrative:b,intentSource:S}=kd(p,t.description().trim(),i,f,d!==void 0),I=vd(Pr(wd(t),Ir(f))),z=Td(d,t,m,I,a,r),U=Ad(e,t,r);return{format:"pm_help_v1",detail_mode:i,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:Ed(u,h),capability_family:Sd(u,h),description:d?.description??t.description(),usage:z.usage,intent:d?.description??b.intent,intent_source:S,examples:d?[d.example]:b.examples,tips:d?[Ct(d.accepted_flags)]:b.tips,arguments:z.arguments,options:z.options,subcommands:z.subcommands,has_subcommands:z.subcommands.length>0,...U===void 0?{}:{command_aliases:U}}}async function Yr(e,t,n,o=t){let a=M(t);if(!a.json)return!1;let i=A(t);if(!i.requested)return!1;let r=Kr(e,i.commandPathTokens);if(!r){if(!a.quiet){let s=`unknown command '${i.commandPathTokens.join(" ")}'`,l=Kn(s,e,n,t),c=Pt(s,"help",Ye,g.USAGE,{...l,attemptedCommand:_d(t),normalizedInvocationArgs:[...t],providedOptionFlags:Z(t)}),d=a.tokenAccounting?J(c,m=>`${JSON.stringify(m,null,2)}
|
|
32
|
+
`)}`}function io(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 et(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:io(o).includes(n))??null}function ee(e,t){let n=e;for(let o of t){let i=et(n,o);if(!i)return null;n=i}return n}var ao=new WeakSet;function jr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let i=t[o];o>0&&P.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let a=et(n,i);if(a){n=a;continue}let r=n.command(i);ao.add(r),o<t.length-1?(r.description("Extension-provided command group."),r.action(()=>{r.help()})):r.description("Extension-provided command path."),n=r}return n}function md(e,t){let n=t.join(" "),o=P.find(r=>n===r.canonical||n.startsWith(`${r.canonical} `));if(o)return{core_path:o.canonical,extension_path:n};let i=e,a=[];for(let r of t){let s=et(i,r);if(!s)return null;a.push(r);let l=s.commands.length>0||P.some(c=>c.canonical.startsWith(`${a.join(" ")} `));if(!ao.has(s)&&(a.length===t.length||!l))return{core_path:a.join(" "),extension_path:t.join(" ")};i=s}return null}function pd(e,t,n,o,i=!1){let a=t.split(" ").filter(d=>d.length>0),r=md(e,a),s=ee(e,a),l=P.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||ao.has(s)));if(!r||r.core_path===t&&s!==null&&!n.has(t)&&!i||l&&!n.has(t))return null;let c=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${r.extension_path}:core_owner=pm-cli:${r.core_path}:extension_owner=${c}`}function Ur(e,t,n,o,i){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,r)=>a.localeCompare(r)).filter(a=>{let r=pd(e,a,o,n.get(a),t.includes(a));return r?(i(r),!o.has(a)&&ee(e,a.split(" "))!==null):!0})}function qr(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]="c6ed71d0-b878-575e-b990-356afdc45688")}catch{}})();var ud=new Set(["__proto__","prototype","constructor"]),ro=Symbol("looseOptionOccurrences");function tt(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function fd(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 so(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let r=n.indexOf("=");if(r>=0)return{consumed:1,key:n.slice(1,r).trim(),value:n.slice(r+1),attached:!0};let s=n.slice(1).trim(),l=e[t+1];return typeof l=="string"&&!l.startsWith("-")?{consumed:2,key:s,value:l}:{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),attached:!0};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let i=n.slice(2).trim(),a=e[t+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:i,value:a}:{consumed:1,key:i,value:!0}}function Lt(e){return ud.has(e)}function Hr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return gi(t)}function nt(e){let t=[],n=te(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let i=tt(n.slice(2));i.length>0&&!Lt(i)&&t.push(i)}if(o.startsWith("-")&&!o.startsWith("--")){let i=tt(o.slice(1));i.length>0&&!Lt(i)&&t.push(i)}return[...new Set(t)]}function zr(e){let t=new Set;for(let n of e)for(let o of nt(n))t.add(o);return t}function gd(e){let t=te(e.long)??"";if(t.startsWith("--")){let n=tt(t.slice(2));if(n.length>0&&!Lt(n))return n}return nt(e)[0]??null}function Gr(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 lo(e,t,n){if(t.length===0)return;let o=new Set,i=new Map,a=[],r=[];for(let s of t){let l=nt(s),c=Gr(s);c!==null&&r.push(c);for(let d of l)o.add(d),s.enabled===!1&&i.set(d,c);s.required===!0&&s.enabled!==!1&&l.length>0&&a.push({keys:l,label:c})}for(let s of Object.keys(e)){if(!o.has(s)){let c=r.length>0?` Expected one of: ${[...new Set(r)].join(", ")}.`:"";throw new k(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=i.get(s);if(l)throw new k(`Option '${l}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of a)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new k(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function hd(e){return typeof e=="string"||e==null?e:String(e)}function yd(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 _d(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 wd={string:hd,number:yd,boolean:_d};function Re(e,t){return Array.isArray(e)?e.map(n=>Re(n,t)):wd[t](e)}function Wr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(i=>i!=null&&i!==""):on(e);return t?o.map(i=>Re(i,t)):o}function vd(e,t,n,o){return n?Wr(e,t,o):t?Re(e,t):e}function bd(e,t,n){let o=e[ro];if(!o||o.length===0)return n;let i=new Set(t);return o.filter(a=>i.has(a.key)).map(a=>a.value)}function Br(e){return Ce(e).value_arity==="none"}function co(e,t,n,o,i){let a=Gr(e),r=i?` for extension command '${i}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new k(`Option '${a}'${r} expects ${o}; received ${s}.`,g.USAGE,{code:"extension_flag_value_invalid",required:`Pass ${a} ${t==="number"?"<number>":"<true|false|1|0>"}.`,why:`The flag declares value_type ${t} with value_validation strict, so a malformed token is refused before the extension handler runs.`,nextSteps:[`Re-run with a valid ${t} value for ${a}.`,`Run pm ${i??"<command>"} --help to review the declared flag contract.`]})}function mo(e,t){return e.value_validation==="strict"&&t!=="string"}function Cd(e,t){let n=e[ro];if(!n)return[];let o=new Set(t);return n.filter(i=>o.has(i.key))}function kd(e,t,n,o){if(Br(e))for(let i of Cd(n,t)){if(i.attached!==!0)continue;let a=e.list===!0&&e.repeatable!==!0?on(i.value):[i.value];for(let r of a){let s=ft(Re(r,"boolean"),"boolean");s!==null&&co(e,"boolean",r,s.expected,o)}}}function xd(e,t,n,o,i){let a=Array.isArray(n)?n.flat(1/0):[n],r=o?a:a.flatMap(s=>typeof s=="string"?s.split(","):[s]);for(let s of r)if(typeof s=="string"&&s.trim().length===0){let l=ft(s,t);co(e,t,s,l.expected,i)}}function po(e,t,n,o){if(!mo(e,n))return t;let i=n==="boolean"&&Br(e),a=r=>{let s=ft(r,n);return s===null?r:i&&typeof r=="string"?!0:co(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(a):a(t)}function Ed(e,t,n,o){for(let i of n)if(!(i===t||!Object.hasOwn(e,i))){if(Object.hasOwn(e,t)){if(o){let a=e[t],r=e[i];e[t]=[...Array.isArray(a)?a:[a],...Array.isArray(r)?r:[r]].filter(s=>s!=null)}delete e[i];continue}e[t]=e[i],delete e[i]}}function Vr(e,t,n=e,o){if(t.length===0)return e;let i=Object.create(null);for(let[a,r]of Object.entries(e))i[a]=r;for(let a of t){let r=gd(a);r&&Sd(i,a,r,n,o)}return i}function Sd(e,t,n,o,i){let a=t.list===!0,r=nt(t),s=Hr(t);s&&!a&&Ad(e,t,n,r,s,i),Ed(e,n,r,a);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=vd(t.default,s,a,l));return}if(s==="boolean"&&mo(t,s)&&kd(t,r,o,i),a){e[n]=Od(t,r,o,e[n],s,l,i);return}s&&(e[n]=po(t,Re(e[n],s),s,i))}function Ad(e,t,n,o,i,a){for(let r of o)r!==n&&Object.hasOwn(e,r)&&po(t,Re(e[r],i),i,a)}function Od(e,t,n,o,i,a,r){let s=bd(n,t,o);i&&mo(e,i)&&xd(e,i,s,a,r);let l=Wr(s,i,a);return i?po(e,l,i,r):l}function Kr(e){let t=Object.create(null),n=[];Object.defineProperty(t,ro,{value:n});let o=0;for(;o<e.length;){let i=so(e,o);if(!i){o+=1;continue}let a=tt(i.key);if(a.length===0||Lt(a)){o+=i.consumed;continue}fd(t,a,i.value),n.push({...i,key:a}),o+=i.consumed}return t}function Jr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=so(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function uo(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let r of t){let s=Hr(r);for(let l of nt(r))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let i=[],a=0;for(;a<e.length;){if(e[a]==="--"){i.push(...e.slice(a+1));break}let r=so(e,a);if(r){let s=tt(r.key);if(n.has(s)){let l=e[a],c=o.has(s)&&!l.includes("=")?1:r.consumed;a+=c;continue}}i.push(e[a]),a+=1}return i}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]="4a2291ff-7618-518c-8bff-e9aa0e2f8af2")}catch{}})();async function fo(e,t={},n=[]){let o={readSettings:D,loadExtensions:qe,activateExtensions:He,resolveImplicitPmRoot:tn,...t};try{let i=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),r=await o.activateExtensions(a);return[...a.failed,...r.failed].map(s=>{let l=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),c=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(N).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(N),m=c.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...c.length>0?{declared_commands:c}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(i){return[{layer:"runtime",name:"extension-loader",error:i instanceof Error?i.message:String(i)}]}}async function Yr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let i=await fo(t,n,o),a={readSettings:D,loadExtensions:qe,activateExtensions:He,resolveImplicitPmRoot:tn,...n};try{let r=a.resolveImplicitPmRoot(process.cwd());if(Ie.resolve(r)===Ie.resolve(t))return i;let[s,l]=await Promise.all([a.readSettings(t),a.readSettings(r)]),[c,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:r,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(c.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 i;i.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${Ie.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Ie.resolve(r)} 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(r)}, or install the extension into the selected tracker with "pm --pm-path ${Ie.resolve(t)} install <package> --project".`})}catch{}return i}(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]="3f896a8d-2c03-5f9c-9909-4684a187870d")}catch{}})();var Xr={core:0,standard:1,full:2,internal:3};function Zr(e,t,n=!0){let o=t.get($(e));if(o)return o;if(!n)return;let i=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(i.length===0)return;let a=i.reduce((s,l)=>Xr[l.tier]<Xr[s]?l.tier:s,"internal"),r=new Set(i.map(({family:s})=>s));return{tier:a,family:r.size===1?i[0].family:"extensions"}}function Qr(e,t){if(t.length===0)return e;let n=ee(e,t);if(n)return n;let o=t.join(" ");if($(o)!==o||!Fe.some(i=>i===o)&&!fa(o)&&!Ge(o)&&!Te(e,t))return null;for(let i=t.length-1;i>0;i-=1){let a=ee(e,t.slice(0,i));if(a)return a}return t.length===1?e:null}function Td(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function es(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 Rd(e){let t=new Map;for(let n of e){let o=n,i=es(n);if(!i||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(i)??[];a.push(o.long.trim()),t.set(i,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(i=>i.trim()).filter(i=>i.length>0))].sort((i,a)=>i.localeCompare(a)));return t}function Id(e){return _(e)}function Pd(e){let t=e.options??[],n=Rd(t);return t.map(o=>{let i=o,a=typeof i.flags=="string"?i.flags.trim():"",r=typeof i.description=="string"?i.description.trim():"",s=es(o),l=(s?n.get(s)??[]:[]).filter(h=>h!==i.long).map(h=>h.trim()).filter(h=>h.length>0),c=r.match(/^Alias for ([^ ]+)/i),d=c&&c[1]?c[1].trim():null,m=i.mandatory===!0||r.includes("[required]")||r.toLowerCase().includes("required;"),p=a.includes("<"),u=p||a.includes("["),f={flags:a,long:typeof i.long=="string"?i.long:null,short:typeof i.short=="string"?i.short:null,description:r,takes_value:u,value_required:p,value_name:Td(a),variadic:i.variadic===!0,required:m,aliases:l,alias_for:d};return i.defaultValue!==void 0&&(f.default_value=i.defaultValue),f})}function $d(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let i=o.alias_for,a=t.get(i);if(!a)continue;let r=o.long,s=new Set([...a.aliases??[],r]);a.aliases=[...s].sort((l,c)=>l.localeCompare(c))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Dd(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(n=>{let o=typeof n.name=="function"?n.name():typeof n.name=="string"?n.name:"argument",i=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():null;return{name:o.trim(),required:n.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:n.variadic===!0,description:i}})}function Md(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(i=>i.name()!=="help"||e.parent===null).filter(i=>!n||(ue(i)??X(i.name()))!=="internal").map(i=>{let a=N(E(i)),r=a,s=ue(i),l=Zr(a,t,s!==void 0),c=B.find(({alias:d})=>d===a);return{name:i.name().trim(),aliases:io(i),description:i.description().trim(),tier:l?.tier??s??X(r),family:l?.family??St(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function Ld(e,t,n){if(!n)return t;let o=n.examples??[],i=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?i.length>0?[...i]:[...t.tips]:[],detail_mode:e}}function Nd(e,t,n,o,i){let a=e!==void 0&&Dn(e)===Ae,r=a?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Qa(e,n),s=i?"positional_action":o?.intent||o?.description?"extension":a?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Ld(n,r,o),intentSource:s}}function Fd(e,t){return e===void 0?null:t?.tier??X(e)}function jd(e,t){return e===void 0?null:t?.family??St(e)}function Ud(e,t,n){if(!(t!==e||!n))return B.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:Qr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function qd(e,t,n,o,i=new Map,a=!1){if(!e){let s=Dd(t),l=Md(t,i,a),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...Ct.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:X(n.split(" ")[0]),family:St(n.split(" ")[0])}))].sort((d,m)=>d.name.localeCompare(m.name)),usage:[n,s.reduce((d,m)=>m.required?d.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):d,t.usage())].filter(d=>d.length>0).join(" ")}}let r=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:c,value_kind:d,polymorphic:m})=>({name:s,required:l,variadic:c,description:m?`Polymorphic ${d} value; inspect the action contract before mutation.`:`${d.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&r.has(s)||l.some(c=>r.has(c))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:c})=>{let d=c?`${s}...`:s;return l?`<${d}>`:`[${d}]`})].join(" ")}}function Hd(e,t,n,o,i){let a=$n(n),r=ae(n),s=N(E(t)),l=N(o.join(" ")),c=l.length>s.length?l:s,d=Ge(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?i.get($(p)):void 0,h=p?Zr(p,i,ue(t)!==void 0):void 0,{narrative:b,intentSource:S}=Nd(p,t.description().trim(),a,f,d!==void 0),I=$d(Nr(Pd(t),Lr(f))),z=qd(d,t,m,I,i,r),U=Ud(e,t,r);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:m.length>0?m:e.name(),visibility_tier:Fd(u,h),capability_family:jd(u,h),description:d?.description??t.description(),usage:z.usage,intent:d?.description??b.intent,intent_source:S,examples:d?[d.example]:b.examples,tips:d?[kt(d.accepted_flags)]:b.tips,arguments:z.arguments,options:z.options,subcommands:z.subcommands,has_subcommands:z.subcommands.length>0,...U===void 0?{}:{command_aliases:U}}}async function ts(e,t,n,o=t){let i=M(t);if(!i.json)return!1;let a=A(t);if(!a.requested)return!1;let r=Qr(e,a.commandPathTokens);if(!r){if(!i.quiet){let s=`unknown command '${a.commandPathTokens.join(" ")}'`,l=Yn(s,e,n,t),c=Pt(s,"help",Xe,g.USAGE,{...l,attemptedCommand:Id(t),normalizedInvocationArgs:[...t],providedOptionFlags:Z(t)}),d=i.tokenAccounting?J(c,m=>`${JSON.stringify(m,null,2)}
|
|
32
33
|
`):c;oe(`${JSON.stringify(d,null,2)}
|
|
33
|
-
`)}return process.exitCode=g.USAGE,!0}if(!
|
|
34
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
35
|
-
`)}function
|
|
36
|
-
`)}let
|
|
37
|
-
`)}function Xr(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let a=Qe(e,o);a&&a.addHelpText("after",Dd(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]="75ebde30-dc8a-5541-b8ba-649906912b78")}catch{}})();function Md(e,t){return Ue(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function Nd(e){return Ue(e.status)?.toLowerCase()??"pending"}function Ld(e){return e.mandatory===!0}function Fd(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 es(e){let t=[];return e.forEach((n,o)=>{if(!Ld(n.definition))return;let a=Nd(n.definition);a!=="applied"&&t.push({layer:n.layer,name:n.name,id:Md(n.definition,o),status:a})}),t.sort(Fd),t}function Zr(e){return Array.isArray(e)&&e.length>0}var jd=new Set(["create","beads import","todos import"]),Ud=new Set(["restore","update","close","delete","append","claim","release"]),qd=new Set(["comments","notes","learnings"]),Hd=new Set(["files","docs","test"]),zd=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 uo(e,t){let n=t.force===!0;return jd.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Ud.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:qd.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Hd.has(e)?{isMutation:Zr(t.add)||Zr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function Gd(e,t,n){if(uo(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return ni(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(a=>zd.has(a.trim().toLowerCase())):!1}function Qr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Wd(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let a=[];if(Ue(t[1])||a.push("source"),Ue(n.to)||a.push("--to"),a.length!==0)throw new x(`Schema migration requires ${a.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:a.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:a,suggested_flags:a.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function Bd(e,t,n,o,a){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Qr(n.status)!==Qr(a.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let r=le(a,ce()),s=await wt(o,i,a.id_prefix,a.item_format,r.type_to_folder);if(!s)return;let l=await Ba(s,{schema:a.schema}),c=typeof n.assignee=="string"?n.assignee.trim():void 0;(c===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(c.toLowerCase())&&c)||v(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function fo(e,t,n,o,a){if(!Gd(e,t,n)||(Wd(e,t,n),!await V(K(a))))return;let i=await ke(a);Fi(o.json===!0)||await Bd(e,t,n,a,i.settings);let r=ti({author:yt(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 r.warnings)Ke(s)}function ts(e,t,n){if(n.length===0)return;let o=uo(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let a=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new x(`Write command "${e}" blocked by unresolved mandatory extension migrations (${a.join(",")}). ${i}`,g.CONFLICT)}async function go(e,t,n,o){if(!uo(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(K(n)))return;let{settings:a,metadata:i,warnings:r}=await ke(n);for(let s of r)Ke(s);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Ga(a),await Wa(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let s=le(a,ce());await oi(n,a.item_format,"item_format:pre_mutation_sync",s.type_to_folder,a.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]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function ho(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(a=>a.length>0);for(let a of ho(e.commandArgs))o.push(...a.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(a=>[a,$(a)]))]}function yo(e,t){let n=_(e);if(n.length===0)return!1;let o=$e(t);for(let a of o)if(a===n||a.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(a=>n.startsWith(`${a} `)):!1}function Ft(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...R(n.commands),...R(n.command_handlers),...R(n.command_overrides),...R(n.flag_commands),...R(n.parser_overrides),...ns(n.preflight_ownership),...ns(n.renderer_ownership)]:[]}function R(e){return e??[]}function ns(e){return R(e).flatMap(t=>t.commands)}function nt(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var os=new Set(["hooks","parser","preflight","renderers"]),as=new Set(["commands","schema","services","importers"]),Vd=new Set(["reindex","search","search-advanced"]),Kd=new Set(["--template"]);function Pe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function _o(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Vd.has(n??t)}function wo(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 jt(e){return _(e.commandPath??"")==="create"&&wo(e,Kd)}function vo(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Lt(e,t){return e.some(n=>yo(n,t))||jt(t)&&vo(e)}function bo(e){return[R(e.hooks).length,(e.preflight_overrides??0)-R(e.preflight_ownership).length,R(e.item_types).length,R(e.item_fields).length,R(e.relationship_kinds).length,R(e.service_overrides).length,R(e.assurance_providers).length,R(e.renderer_overrides).length-R(e.renderer_ownership).length].some(t=>t>0)}function Co(e,t){let n=e.activation?.commands??[];if(n.length>0)return Lt(n,t);let o=Ft(e);if(Lt(o,t)||nt(e).has("search")&&_o(t.commandPath))return!0;if(e.contributions)return bo(e.contributions)}function Ut(e,t){let n=Co(e,t);if(n!==void 0)return n;let o=nt(e);return!!(Pe(o,os)||Pe(o,as))}function ot(e,t){return e.effective.length===0?!1:at(t)!=="all"?e.effective.some(n=>Ut(n,t)):e.effective.some(n=>{let o=nt(n);return Ft(n).length>0||Pe(o,os)||Pe(o,as)||o.has("search")})}function at(e){if(_(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=$e(e).filter(o=>o.split(" ").every(a=>!a.startsWith("-"))).sort((o,a)=>a.length-o.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=jt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function xo(e){return at(e)==="all"?void 0:t=>Ut(t,e)}function De(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[a,...i]=t.commandPathTokens;return{commandPath:a,commandArgs:i,allowCommandPrefixMatch:!0}}let n=N(e),o=n.findIndex(a=>a.trim().length>0&&!a.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function ko(e){let t=e.args.map(String);if(_(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(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]="298624a5-da1b-53ca-aefb-19fbc3fa0401")}catch{}})();var qt=Symbol.for("pm.readOutputInvocationProvenance");function se(e,t){let n=Reflect.get(e,qt);n!==void 0&&Reflect.set(t,qt,n)}function Eo(e,t,n){let o=La(t,n);if(!o)return;let a=e;for(;a.parent;)a=a.parent;let i=a.rawArgs,r=new Set(Z(i.slice(2))),s=Na.find(d=>d.command===o),l=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,qt);Reflect.set(n,qt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),se(n,e)}function Jd(e){let t=e.optsWithGlobals(),n=E(e);if($(n)===n)return t;let o=e.opts();for(let a=e.parent;a?.parent;a=a.parent)for(let i of a.options){let r=i.attributeName(),s=a.getOptionValueSource(r)==="cli";if(s&&!e.options.some(l=>l.long===i.long))throw new x(`Unknown option '${i.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:i.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let l=a.getOptionValue(r);e.setOptionValueWithSource(r,l,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function So(e,t,n,o){Eo(e,t,o);let a=n.outputInclude;if(a===void 0)return;let{selectors:i,modes:r}=Ua(t,a,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;se(o,e);let s=ja(t);for(let c of r){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let c=e;c;c=c.parent)c.setOptionValueWithSource("outputInclude",l,"cli");kt(e,n)}function Me(e,t,n=[]){let o={...Jd(e)};se(e,o),delete o.json,delete o.quiet,delete o.path,delete o.pmPath,delete o.noExtensions,delete o.extensions,delete o.profile,delete o.pager,delete o.changedFields,delete o.fullChangedFields,delete o.idOnly,delete o.lean,delete o.tokenAccounting,delete o.outputInclude,delete o.outputLimit,delete o.outputBudget,delete o.outputFormat,delete o.outputSession;let a=zr(t);for(let[i,r]of Object.entries(a))o[i]===void 0&&(o[i]=r);if(n.length>0){let i=Fr(n),r=ae(E(e)).map(c=>({long:c.flag,short:c.short,aliases:c.aliases})),s={...a};for(let c of i)o[c]!==void 0&&(s[c]=o[c]);ro(s,[...r,...n],E(e));let l=Hr(o,n,a,E(e));return se(o,l),l}return o}function Ht(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>$(_(o.target_command))===$(n)).flatMap(o=>o.flags)}function it(e,t,n){let o=Ht(e,t),a=[t],i=[];for(let r of n){if(r.startsWith("-"))break;a.push(r);let s=Ht(e,a.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function zt(e){return e.arguments??[]}function is(e){let t=zt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Ao(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 To(e,t){let n=zt(e),o=n.filter(s=>s.required).length,a=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],r=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new x(`Missing required argument for extension command '${e.command}'. Usage: ${is(e)}${r}`,g.USAGE);if(t.length>a){let s=t.slice(a).join(" ");throw new x(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${is(e)}${r}`,g.USAGE)}}function Yd(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function Xd(e,t,n){if(n.length>0){ro(t,n,e.command);return}let o=Object.keys(t).filter(a=>t[a]!==void 0).sort();if(o.length!==0)throw new x(`Unknown option '${o.map(Yd).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function Oo(e,t,n,o){e&&(To(e,t),Xd(e,n,o))}import{Command 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]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var Zd=new Set(["--version","-V"]);function rt(e){let t=N(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function ss(e){if(N(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new rs().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let a of We)for(let i of[a.flag,a.short,...a.aliases??[]]){if(i===void 0||n.has(i))continue;n.add(i);let r=a.value_name!==void 0||a.flag==="--pm-path";t.option(`${i}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var Qd=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ro=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"]),ls=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),em=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),tm=new Set(["claim","close-task","pause-task","release","start-task","test"]),_e={setup:!0,listQuery:!0,mutation:!0,operation:!0},nm=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 st(e){return e.some(t=>Zd.has(t))}function om(e,t){if(!P.some(o=>o.canonical_argv[0]===t))return;let n=new rs().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of vi(t,ae(t))){let a=o.takes_value?o.value_required?" <value>":" [value]":"";for(let i of[o.flag,o.short,...o.aliases??[]])i!==void 0&&n.option(`${i}${a}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return _e;let a=G([t,...o.operands])?.alias;if(P.some(i=>i.alias===a))return{..._e,targetCommandName:a}}catch{return _e}}function Io(e){if(st(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return _e;let t=k(e);if(!t)return _e;let n=t.trim().toLowerCase(),o=N(e),a=G(o)?.alias;return P.some(i=>i.alias===a)?{..._e,targetCommandName:a}:om(o,n==="ctx"?"context":n)||(Qd.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ro.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:ls.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:em.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:_e)}function Po(e){return e.length===0||A(e).requested||e.includes("--explain")&&k(e)===void 0}function $o(e,t){return rt(t)||st(t)?!1:ie(t)||A(t).requested?!0:!!k(t)}function Do(e){if(st(e))return!1;let t=k(e);return t?nm.has(t):!1}function am(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,a=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),i=a?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${a}${c.slice(d)}`:a:c}):e.argv,r=je(i),s=a&&n>=0?`${o}=[redacted]`:t,l=a&&e.normalizedDisplay.includes("=")?`${a}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:l,sourceDisplay:s}}function Mo(e){let t=e.commandName;if(!t)return;let n=e.trace.find(c=>c.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(c=>c.length>0),a=o.length>0?o.join(" "):"the canonical flag",i=ls.has(t)||tm.has(t),r=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=am({argv:e.argv,normalizedDisplay:a,normalizedTokens:o,rawFrom:n.from});throw new x(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[w(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:w(l.argv)}})}(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]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var im=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"]),rm=new Set(["parse","preflight","execute","unknown"]),sm=new Set(["usage","validation","conflict","runtime","unknown"]);function we(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let a=o.trim();if(a.length>0)return a}}}function No(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Gt(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 Lo(e){if(!e)return;let t=e.trim().toLowerCase();if(im.has(t))return t}function Fo(e){if(!e)return;let t=e.trim().toLowerCase();if(rm.has(t))return t}function jo(e){if(!e)return;let t=e.trim().toLowerCase();if(sm.has(t))return t}function Uo(e){let t=we(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof i=="string")return i.trim()}if(No(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=Gt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(r=>nn(r)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function qo(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 Ho(){let e=nn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Gt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,a=ki(o),i=we(e,"error_code","errorCode")??qo(a,o),r=jo(we(e,"error_category","errorCategory"))??(a?void 0:mt(i)),s=a?void 0:Uo(e)??`command_exit_${o}`,l=Lo(we(e,"command_resolution","commandResolution"))??vt({ok:a,errorCode:i,errorCategory:r}),c=Fo(we(e,"resolution_stage","resolutionStage"))??"execute";return{ok:a,error:s,exit_code:o,error_code:i,error_category:r,command_resolution:l,resolution_stage:c}}(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]="b14d6057-de6b-5844-aee9-201364902f93")}catch{}})();var zo="PM_CLI_PACKAGE_ROOT",hs=Symbol("pm.deprecatedAliasInvocation"),Vt=new Map;for(let e of B){let t=e.alias.split(" ")[0],n=Vt.get(t)??[];n.push(e),Vt.set(t,n)}for(let e of Vt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function lm(){return fa(import.meta.url,["../.."])}(typeof process.env[zo]!="string"||process.env[zo]?.trim().length===0)&&(process.env[zo]=lm());var be=null,F=null,Kt=null;function cm(e){be=e}function dm(e){T=e}var lt=null,ve=null,T=new Map,Yo=250,mm=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),pm=new Set(["1","true","yes","on"]),um=ze(()=>import("./chunks/register-setup-BMIFKZZP.js")),fm=ze(()=>import("./chunks/register-list-query-23OX36Q3.js")),gm=ze(()=>import("./chunks/register-mutation-JPJ5YNDX.js")),hm=ze(()=>import("./chunks/register-operations-IGR7ERY5.js"));function Bt(e){return w(e)}function ys(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=>pe(o)??o))];return n.length>0?n:void 0}function ym(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Z(t),a=new Set(o.map(d=>pe(d)??d)),i=ys(e),r=t.find(d=>y.commands.some(m=>m.name()===d)),s=r?y.commands.find(d=>d.name()===r):void 0,l=new Set([...y.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>pe(m)).filter(m=>m!==void 0))),c=i?.filter(d=>{let m=pe(d)??d;return a.has(m)?!1:l.has(m)||Xn(t,r,m,T)!==void 0});return c&&c.length>0?c:void 0}function _m(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let a=n?.[0],i=a?pe(a):void 0,r=e.find(p=>y.commands.some(u=>u.name()===p)),s=r?y.commands.find(p=>p.name()===r):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,c=Xn(e,r,i,T),d=i?l?.isBoolean()===!0||c===!1?[i]:[i,"<value>"]:[],m=i?Bt([...e,...d]):t;return m===t?void 0:m}function wm(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 a=e[o];a!=null&&(n[o]=a)}return n}function vm(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,...wm(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function _s(e,t,n){let o=je(t),a=N(o),i=Y(a),[r,s]=i===void 0?[]:a.slice(i,i+2),l=o.includes("--explain"),c=qi(o,e?.code,e?.recovery),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:Bt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:Bt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=Bt(o),p=Z(o),u=ym(n,o,d),f=_m(o,m,u,d),h=vm({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return{...e,recovery:h}}async function ct(e){let t=F;F=null,await Hi(t,e);let n=be;if(be=null,!n){gt();return}let o=[],a=Aa();try{await zi({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?a?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await _a(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:de(),affected:a}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{gt()}!n.globalOptions.json&&o.length>0&&v(`[pm] warning: afterCommand hook_warnings=${q(o)}`),n.profileEnabled&&o.length>0&&v(`profile:extensions hook_warnings=${q(o)}`)}async function ws(e,t){await Ja();let n=F,o=be,a=n?.command??o?.commandName??e,i=n??fn(o?.globalOptions??t),r=T.get(_(a))?.source;vn(a,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:i.source_context,source_context_source:i.source_context_source,pm_version:n?.pm_version??Ne,extension:r})}function vs(e){return pm.has((process.env[e]??"").trim().toLowerCase())}function bs(e){return vs("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!mm.has(Math.trunc(e))}async function Jt(e,t){return bs(e.exit_code)?(await ws(e.command,t),ei({...e,source_context:e.source_context??fn(t).source_context}),!0):!1}async function Cs(e){let t=me(e.error),n=gr(t);e.bootstrapGlobal.json?v(JSON.stringify(Je(ur(t,g.GENERIC_FAILURE)),null,2)):v(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",a="runtime_failed";try{await ws(e.attemptedCommand,e.bootstrapGlobal),bn(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,a=i.commandResolution,await Zt(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||v(`Failed to report error: ${me(i)}`)}try{await ct({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:a,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||v(`Failed to run error hooks: ${me(i)}`)}try{await Ee()}catch(i){e.bootstrapGlobal.json||v(`Failed to flush error reporting: ${me(i)}`)}}var bm={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"},Go=new Map;function Wo(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function xs(e,t){return e.options.some(n=>n.long===t)}function ks(e,t){return e.options.some(n=>n.short===t)}function Bo(e,t,n,o){let a=t.trim();if(!a)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(a.startsWith("-")&&!a.startsWith("--")){if(ks(e,a))return;if(o){e.option(`${a} <value>`,`${i} (repeatable)`,En);return}e.option(`${a} <value>`,i);return}let r=a.startsWith("--")?a:`--${a}`;if(!xs(e,r)){if(o){e.option(`${r} <value>`,`${i} (repeatable)`,En);return}e.option(`${r} <value>`,i)}}async function Es(e,t){let n=bm[e];if(!n)return[];let o=`${t}:${n}`,a=Go.get(o);if(a)return a;if(!await V(K(t)))return Go.set(o,[]),[];let i=await D(t),r=(ln(i.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:Wo(s.type),value_type:Wo(s.type)})));return Go.set(o,r),r}async function Ss(e,t){let n=M(t),o=O(process.cwd(),n.path);if(!await V(K(o)))return;let a=ve?.key===Qo(o)?ve.snapshot:null,i=a===null?await D(o):a.settings,r=ln(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 l of s){let c=ee(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";Bo(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Bo(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function Xo(e,t,n,o,a){let i=k(n);if(!(i!=="create"&&i!=="update"))try{let r=a??await D(t),s=le(r,o);Xr(e,s,n)}catch{}}function Vo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function As(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Zo(e){return e.some(t=>t==="--profile")}function Qo(e){return`pm-root:${e}`}function Ko(e){for(let t of e)t.startsWith("settings_read_")&&Ke(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Ts(e,t){e.profile&&(v(`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&&v(`profile:extensions activation_warnings=${q(t.activationWarnings)}`))}function Yt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";v(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Xt(e,t=ke){let n=Qo(e);if(ve?.key===n)return ve.snapshot;try{let o=Date.now(),{settings:a,warnings:i}=await t(e),r=await wa({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:a,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return ve={key:n,snapshot:s},s}catch{return ve={key:n,snapshot:null},null}}async function Le(e,t,n=D){let o=t?at(t):"all",a=As(e,o);if(lt?.key===a)return lt.snapshot;try{let i=await n(e),r=await qe({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?xo(t):void 0}),s=await He({...r,loaded:r.loaded}),l=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),c=Sr(s.registrations.flags),d=kr(s.commands.handlers,s.registrations.commands),m=Tr(l,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:i,commandHandlers:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return lt={key:a,snapshot:p},p}catch{return lt={key:a,snapshot:null},null}}async function Os(e){let t=Ve(e);if(t.noExtensions){let r=O(process.cwd(),t.path);return await V(K(r))&&Ko((await ke(r)).warnings),null}let n=O(process.cwd(),t.path),o=await Xt(n);if(!o)return null;Ko(o.settingsReadWarnings);let a={commandPath:E(e),commandArgs:ko(e)};if(!ot(o.discovery,a))return Yt(t.profile,o,a),null;let i=await Le(n,a);return i?(Ts(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 ea(e){let t=await Le(e);return t?new Map(t.commandDescriptors):T}async function Cm(e,t){return!e.requested||t.noExtensions||Oe(y,e.commandPathTokens)?T:ea(O(process.cwd(),t.path))}async function Rs(e,t){return(await ci({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function Is(e,t,n){let o=t.author;return li(e,Ti.forActiveExtensionHost({pmRoot:e,author:o}),o,_(n))}async function Ps(e,t,n,o=[]){let a=E(e),i=mo(e.args.map(String),o),r={...t};delete r.author;let s={...n},l=O(process.cwd(),n.path),c=await ht({command:a,args:i,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&v(`profile:extensions parser_warnings=${q(c.warnings)}`),i=c.context.args,r=c.context.options,s=c.context.global,Oo(T.get(_(a)),i,r,o),xe(void 0),ft({command:a,args:i,options:{...r},global:{...s},pm_root:l});let d=await sn({command:a,args:i,options:r,global:s,pm_root:l,sdk:Is(l,s,a)});if(s.profile&&d.warnings.length>0&&v(`profile:extensions command_handler_warnings=${q(d.warnings)}`),!d.handled)throw d.warnings.length>0?Ya(a,d):new x(`Command "${a}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return d.exitCode!==void 0&&(process.exitCode=d.exitCode),xe(d.result),d.result}var cs=Symbol("pm.wrappedActionHandler");function xm(e,t){let n=e[e.length-1];return n instanceof Jo?n:t}function ds(e,t,n){e&&n.length>0&&v(`profile:extensions ${t}=${q(n)}`)}function km(e){let t=T.get(_(e.commandPath));if(!t||!Ao(e.activeRegistrations,e.commandPath))return;let n=zt(t).length===0?Gr(e.commandArgs):mo(e.commandArgs,e.extensionFlagDefinitions);To(t,n)}function Em(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 $s(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[cs]!==!0){let a=o._actionHandler;o._actionHandler=async function(...i){let r=xm(i,n),s=Date.now();kn(r);let l=Ve(r),c=$(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await a.apply(this,i);let d=O(process.cwd(),l.path),m=r.args.map(String),p=ce(),u=p?it(p,c,m):[],f=await Es(c,d),h=Me(r,m,[...u,...f]);T.has(_(c))&&delete h.author;let b=await ht({command:c,args:m,options:h,global:l,pm_root:d});ds(l.profile,"parser_warnings",b.warnings),m=b.context.args,h=b.context.options,se(r,h),l=b.context.global,km({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await _i(l),kt(r,l),Em(r,i,m),xt(r,h),xe(void 0),ft({command:c,args:m,options:{...h},global:{...l},pm_root:d});let S=await sn({command:c,args:m,options:h,global:l,pm_root:d,sdk:Is(d,l,c)});if(ds(l.profile,"command_handler_warnings",S.warnings),S.handled){xe(S.result),un(S.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&v(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await a.apply(this,i)},o[cs]=!0}for(let a of n.commands)t(a)};t(e)}async function Wt(e){T=new Map,ne({overrides:[]}),e&&await Xo(e.rootProgram,e.pmRoot,e.invocationArgv,ha(),e.settings)}function Sm(e,t,n,o){if(t?.flags&&t.flags.length>0){eo(e,t.flags);let a=to(e,t.flags);a&&e.addHelpText("after",a)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function Ds(e,t,n){let o={core:0,standard:1,full:2,internal:3},a=(i,r)=>{let s=r.join(" "),l=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),c=l.length===0?"standard":l.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");At(i,c);for(let d of i.commands)a(d,[...r,d.name()])};for(let i of e.commands)t.has(i.name())||a(i,[i.name()])}async function Ms(e,t){let n=M(t),o=O(process.cwd(),n.path);if(n.noExtensions){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let a=await Xt(o),i=De(t);if(!a){await Wt();return}if(!ot(a.discovery,i)){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings}),Yt(Zo(t),a,i);return}let r=await Le(o,i);if(!r){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings});return}ne(r.services),T=new Map(r.commandDescriptors),await Xo(e,o,t,r.registrations,r.settings);let s=Mr(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>Nr(r.activationWarnings,v,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(I=>I.length>0),p=r.commandDescriptors.get(d),u=ee(e,m),f=r.commandFlagHelp.get(d),h=p?$r(p):null;if(u){Sm(u,p,f,h);return}let b=Dr(e,m);p?.description&&b.description(p.description);let S=f;p&&(Or(b,p),p.flags.length>0&&(eo(b,p.flags),S=to(b,p.flags)??void 0)),S&&b.addHelpText("after",S),h&&b.addHelpText("after",h),b.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...I)=>{let z=I[I.length-1],U=z instanceof Jo?z:b,dt=Ve(U),Vs=Date.now(),oa=it(r.registrations,d,U.args.map(String)),aa=Me(U,U.args.map(String),oa),ia=await Ps(U,aa,dt,oa);await wi(dt,ia),un(ia,{...dt,command:d,commandArgs:U.args.map(String),commandOptions:aa,pmRoot:o}),dt.profile&&v(`profile:command=${d} took_ms=${Date.now()-Vs}`)})};for(let d of s)c(d);Ds(e,l,r.commandDescriptors)}var Ne=ga(import.meta.url,["../.."])??"0.0.0",y=xn(Ne);async function ms(e){if(!F)return;let t=Reflect.get(e,hs);typeof t=="string"&&await Ai(t)}async function ps(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function us(e,t,n){!F||!await gn(!0)||(vn(e,t,n,{source_context:F.source_context,source_context_source:F.source_context_source}),Xa(e),Kt=F)}async function Zt(e,t,n){let o=Kt;if(!o)return;Kt=null;let a=!1;try{let i=await D(o.global_pm_root);a=i.telemetry.enabled&&i.telemetry.installation_id===o.installation_id}catch{}await gn(a)?Qa(e,t,n):Za()}async function Am(e){let t=await Os(e);return rn(t?.registrations??null),t}function Ns(e,t){t&&rt(t)||(e.hook("preAction",async(n,o)=>{be=null,F=null,Kt=null,gt(),kn(o);let a=o.optsWithGlobals(),i=Ve(o),r=$(E(o)),s=o.args.map(String),l=Me(o,s),c={...i},d=O(process.cwd(),i.path),m=await Am(o);if(Fa(r,{...l,outputInclude:a.outputInclude,outputLimit:a.outputLimit,outputBudget:a.outputBudget,outputFormat:a.outputFormat,outputSession:a.outputSession,outputCursor:a.outputCursor}),So(o,r,c,l),await ps(o,void 0,()=>ai(r,c)),!m){be=va({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),F=await Cn({command:r,pm_version:Ne,args:s,options:l,global:c,pm_root:d}),await ms(e),await us(r,s,l),await go(r,l,d,Vo()),await fo(r,s,l,c,d);return}ba(m.hooks),Ca(m.commands),xa(m.parsers),ka(m.preflight),ne(m.services),Ea(m.renderers),rn(m.registrations);let p=it(m.registrations,r,s);l=Me(o,s,p),So(o,r,c,l);let u=await ht({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&v(`profile:extensions parser_warnings=${q(u.warnings)}`),s=u.context.args,l=u.context.options,se(o,l),c=u.context.global,xt(o,l);let f=await Ta({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Vo()});c.profile&&f.warnings.length>0&&v(`profile:extensions preflight_warnings=${q(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),c=f.context.global,xt(o,l);let h=f.decision;await go(r,l,m.pmRoot,h),await fo(r,s,l,c,m.pmRoot);let b=h.run_extension_migrations?await ps(o,[],()=>Rs(m.registrations.migrations,m.pmRoot)):[];c.profile&&b.length>0&&v(`profile:extensions migration_warnings=${q(b)}`);let S=es(m.registrations.migrations);be={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:S},xe(void 0),ft({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),F=await Cn({command:r,pm_version:Ne,args:s,options:l,global:c,pm_root:m.pmRoot}),await ms(e),await us(r,s,l);let I=await ya(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&I.length>0&&v(`profile:extensions hook_warnings=${q(I)}`),h.enforce_mandatory_migration_gate&&ts(r,l,S)}),e.hook("postAction",async()=>{let n=Ho();await Zt(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await ct(n),await Ee()}))}Ns(y);var fs=Symbol("pmCliIdempotentTopLevelRegistration");function Ls(e){let t=e;if(t[fs])return;t[fs]=!0;let n=e.command.bind(e);e.command=((o,...a)=>{let i=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===i||r.aliases().includes(i))?new Jo(i):n(o,...a)})}async function Tm(e,t){if(Ls(e),t.setup){let{registerSetupCommands:n}=await um();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await fm(),o=typeof t.targetCommandName=="string"&&Ro.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await gm();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await hm();n(e)}}function Om(e){return async t=>{let n=mt(t.errorCode),o=vt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ri({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Ne,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 Fs(e){if(e.bootstrapGlobal.noExtensions||rt(e.invocationArgv))return;let t=De(e.invocationArgv),n=await Xt(e.bootstrapPmRoot);if(n&&ot(n.discovery,t)){let o=await Le(e.bootstrapPmRoot,t);js(o);return}n&&Yt(Zo(e.invocationArgv),n,t),ne({overrides:[]})}function js(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function ta(e){await Zt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await ct({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 Us(){await Zt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await ct({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function qs(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof x)&&(_n(e.error)||!n))return!1;let o=me(e.error),a=e.error instanceof x?e.error.exitCode:yn(t),i=e.error instanceof x||Ka(e.error)?e.error.context:void 0,r=_s(i,e.invocationArgv,o),s=mr(o,r),l=Je(e.bootstrapGlobal.lean?Rt(zn(o,a,r)):zn(o,a,r)),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?J(l,u=>`${JSON.stringify(u,null,2)}
|
|
38
|
-
`):l,null,2):
|
|
39
|
-
`):v(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:
|
|
40
|
-
`):v(h),u&&await Ee(
|
|
41
|
-
`):v(c),r&&await Ee(
|
|
34
|
+
`)}return process.exitCode=g.USAGE,!0}if(!i.quiet){let s=Hd(e,r,t,a.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=W(l.join(" "));c&&(s.resolved_path=c.canonical),r===e&&!ae(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),zi(`${JSON.stringify(s,null,2)}
|
|
35
|
+
`)}return process.exitCode=g.SUCCESS,!0}function zd(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(`
|
|
36
|
+
`)}function Gd(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",i=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${i.length>0?i.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Wd(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let i of[...t.required_create_fields,...t.required_create_repeatables])o.add(i);return{progressive:n,strict:o}}function Bd(e,t,n,o){let i=new Set(n),a=o.filter(l=>!i.has(l)),r=l=>l.length>0?l.map(c=>en("create",c)).join(", "):"none";e.push(` required in strict mode: ${r(a)}`);let s=a.map(Ra).filter(l=>l!==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 Vd(e,t,n){let o=ha(n);if(!o)return zd(e,t);let i=di(o,t);if(!i){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
|
|
37
|
+
`)}let a=n.indexOf("--"),r=a<0?n:n.slice(0,a),s=r.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),l=s<0?void 0:r[s]?.startsWith("--create-mode=")?r[s]?.slice(14):r[s+1],c=e==="create"&&l?.toLowerCase()==="strict",d=Wd(e,i),m=ut(i,e,d.progressive),p=ut(i,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(b=>en(e,b)).join(", "):"none",f=["",`Type-aware option policies for ${i.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=ut(i,e,d.strict);Bd(f,i,m.required,h.required)}return Gd(f,i),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
|
|
38
|
+
`)}function ns(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let i=et(e,o);i&&i.addHelpText("after",Vd(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]="665c29cd-2a3b-5cfc-9690-6d82541fc5d9")}catch{}})();function Kd(e,t){return Ue(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function Jd(e){return Ue(e.status)?.toLowerCase()??"pending"}function Yd(e){return e.mandatory===!0}function Xd(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 as(e){let t=[];return e.forEach((n,o)=>{if(!Yd(n.definition))return;let i=Jd(n.definition);i!=="applied"&&t.push({layer:n.layer,name:n.name,id:Kd(n.definition,o),status:i})}),t.sort(Xd),t}function os(e){return Array.isArray(e)&&e.length>0}var Zd=new Set(["create","beads import","todos import"]),Qd=new Set(["restore","update","close","delete","append","claim","release"]),em=new Set(["comments","notes","learnings"]),tm=new Set(["files","docs","test"]),nm=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 go(e,t){let n=t.force===!0;return Zd.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Qd.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:em.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:tm.has(e)?{isMutation:os(t.add)||os(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function om(e,t,n){if(go(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return ra(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(i=>nm.has(i.trim().toLowerCase())):!1}function is(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function im(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let i=[];if(Ue(t[1])||i.push("source"),Ue(n.to)||i.push("--to"),i.length!==0)throw new k(`Schema migration requires ${i.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:i.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:i,suggested_flags:i.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function am(e,t,n,o,i){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||is(n.status)!==is(i.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let r=le(i,ce()),s=await vt(o,a,i.id_prefix,i.item_format,r.type_to_folder);if(!s)return;let l=await Vi(s,{schema:i.schema}),c=typeof n.assignee=="string"?n.assignee.trim():void 0;(c===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(c.toLowerCase())&&c)||v(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function ho(e,t,n,o,i){if(!om(e,t,n)||(im(e,t,n),!await V(K(i))))return;let a=await xe(i);Ha(o.json===!0)||await am(e,t,n,i,a.settings);let r=aa({author:_t(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of r.warnings)Ke(s)}function rs(e,t,n){if(n.length===0)return;let o=go(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let i=n.map(r=>`extension_migration_blocking:${r.layer}:${r.name}:${r.id}:${r.status}`),a=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new k(`Write command "${e}" blocked by unresolved mandatory extension migrations (${i.join(",")}). ${a}`,g.CONFLICT)}async function yo(e,t,n,o){if(!go(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(K(n)))return;let{settings:i,metadata:a,warnings:r}=await xe(n);for(let s of r)Ke(s);if(!Wi(i)&&(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(Gi(i),await Bi(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync)){let s=le(i,ce());await sa(n,i.item_format,"item_format:pre_mutation_sync",s.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]="c0826cb1-5181-51b3-9ad9-0cd7a3d2c4b3")}catch{}})();function _o(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=w(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=w(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(i=>i.length>0);for(let i of _o(e.commandArgs))o.push(...i.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(i=>[i,$(i)]))]}function wo(e,t){let n=w(e);if(n.length===0)return!1;let o=$e(t);for(let i of o)if(i===n||i.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(i=>n.startsWith(`${i} `)):!1}function Ft(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...R(n.commands),...R(n.command_handlers),...R(n.command_overrides),...R(n.flag_commands),...R(n.parser_overrides),...ss(n.preflight_ownership),...ss(n.renderer_ownership)]:[]}function R(e){return e??[]}function ss(e){return R(e).flatMap(t=>t.commands)}function ot(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var ls=new Set(["hooks","parser","preflight","renderers"]),cs=new Set(["commands","schema","services","importers"]),rm=new Set(["reindex","search","search-advanced"]),sm=new Set(["--template"]);function Pe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function vo(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return rm.has(n??t)}function bo(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 jt(e){return w(e.commandPath??"")==="create"&&bo(e,sm)}function Co(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function Nt(e,t){return e.some(n=>wo(n,t))||jt(t)&&Co(e)}function ko(e){return[R(e.hooks).length,(e.preflight_overrides??0)-R(e.preflight_ownership).length,R(e.item_types).length,R(e.item_fields).length,R(e.relationship_kinds).length,R(e.service_overrides).length,R(e.assurance_providers).length,R(e.renderer_overrides).length-R(e.renderer_ownership).length].some(t=>t>0)}function xo(e,t){let n=e.activation?.commands??[];if(n.length>0)return Nt(n,t);let o=Ft(e);if(Nt(o,t)||ot(e).has("search")&&vo(t.commandPath))return!0;if(e.contributions)return ko(e.contributions)}function Ut(e,t){let n=xo(e,t);if(n!==void 0)return n;let o=ot(e);return!!(Pe(o,ls)||Pe(o,cs))}function it(e,t){return e.effective.length===0?!1:at(t)!=="all"?e.effective.some(n=>Ut(n,t)):e.effective.some(n=>{let o=ot(n);return Ft(n).length>0||Pe(o,ls)||Pe(o,cs)||o.has("search")})}function at(e){if(w(e.commandPath??"").split(" ")[0]==="completion")return"all";let t=$e(e).filter(o=>o.split(" ").every(i=>!i.startsWith("-"))).sort((o,i)=>i.length-o.length)[0]??w(e.commandPath??"");if(t.length===0)return"all";let n=jt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Eo(e){return at(e)==="all"?void 0:t=>Ut(t,e)}function De(e){let t=A(e);if(t.requested&&t.commandPathTokens.length>0){let[i,...a]=t.commandPathTokens;return{commandPath:i,commandArgs:a,allowCommandPrefixMatch:!0}}let n=L(e),o=n.findIndex(i=>i.trim().length>0&&!i.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function So(e){let t=e.args.map(String);if(w(E(e))==="create"){let n=e.optsWithGlobals();typeof n.template=="string"&&n.template.trim().length>0&&t.push("--template")}return t}(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]="298624a5-da1b-53ca-aefb-19fbc3fa0401")}catch{}})();var qt=Symbol.for("pm.readOutputInvocationProvenance");function se(e,t){let n=Reflect.get(e,qt);n!==void 0&&Reflect.set(t,qt,n)}function Ao(e,t,n){let o=Ni(t,n);if(!o)return;let i=e;for(;i.parent;)i=i.parent;let a=i.rawArgs,r=new Set(Z(a.slice(2))),s=Li.find(d=>d.command===o),l=Object.values(s?.dimensions??{}).flatMap(d=>d.legacy_aliases.flatMap(m=>r.has(m.flag)?[m.flag]:[])),c=Reflect.get(n,qt);Reflect.set(n,qt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),se(n,e)}function lm(e){let t=e.optsWithGlobals(),n=E(e);if($(n)===n)return t;let o=e.opts();for(let i=e.parent;i?.parent;i=i.parent)for(let a of i.options){let r=a.attributeName(),s=i.getOptionValueSource(r)==="cli";if(s&&!e.options.some(l=>l.long===a.long))throw new k(`Unknown option '${a.long}' for ${n}`,g.USAGE,{code:"unknown_option",flag:a.long,required:`Use options declared by pm ${n} --help.`});if(s&&e.getOptionValueSource(r)!=="cli"){let l=i.getOptionValue(r);e.setOptionValueWithSource(r,l,"cli")}r in o?t[r]=o[r]:delete t[r]}return t}function Oo(e,t,n,o){Ao(e,t,o);let i=n.outputInclude;if(i===void 0)return;let{selectors:a,modes:r}=Ui(t,i,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;se(o,e);let s=ji(t);for(let c of r){let d=s.get(c),m=o[d];e.setOptionValueWithSource(d,m,"cli")}let l=a.length>0?a.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let c=e;c;c=c.parent)c.setOptionValueWithSource("outputInclude",l,"cli");Et(e,n)}function Me(e,t,n=[]){let o={...lm(e)};se(e,o),delete o.json,delete o.quiet,delete o.path,delete o.pmPath,delete o.noExtensions,delete o.extensions,delete o.profile,delete o.pager,delete o.changedFields,delete o.fullChangedFields,delete o.idOnly,delete o.lean,delete o.tokenAccounting,delete o.outputInclude,delete o.outputLimit,delete o.outputBudget,delete o.outputFormat,delete o.outputSession;let i=Kr(t);for(let[a,r]of Object.entries(i))o[a]===void 0&&(o[a]=r);if(n.length>0){let a=zr(n),r=ie(E(e)).map(c=>({long:c.flag,short:c.short,aliases:c.aliases})),s={...i};for(let c of a)o[c]!==void 0&&(s[c]=o[c]);lo(s,[...r,...n],E(e));let l=Vr(o,n,i,E(e));return se(o,l),l}return o}function Ht(e,t){let n=w(t);return n.length===0?[]:e.flags.filter(o=>$(w(o.target_command))===$(n)).flatMap(o=>o.flags)}function rt(e,t,n){let o=Ht(e,t),i=[t],a=[];for(let r of n){if(r.startsWith("-"))break;i.push(r);let s=Ht(e,i.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function zt(e){return e.arguments??[]}function ds(e){let t=zt(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function To(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}function Ro(e,t){let n=zt(e),o=n.filter(s=>s.required).length,i=n.some(s=>s.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],r=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new k(`Missing required argument for extension command '${e.command}'. Usage: ${ds(e)}${r}`,g.USAGE);if(t.length>i){let s=t.slice(i).join(" ");throw new k(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${ds(e)}${r}`,g.USAGE)}}function cm(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function dm(e,t,n){if(n.length>0){lo(t,n,e.command);return}let o=Object.keys(t).filter(i=>t[i]!==void 0).sort();if(o.length!==0)throw new k(`Unknown option '${o.map(cm).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function Io(e,t,n,o){e&&(Ro(e,t),dm(e,n,o))}import{Command as ms}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]="0503f6e5-36d9-5afb-a17f-feef2241f984")}catch{}})();var mm=new Set(["--version","-V"]);function st(e){let t=L(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function ps(e){if(L(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new ms().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let i of We)for(let a of[i.flag,i.short,...i.aliases??[]]){if(a===void 0||n.has(a))continue;n.add(a);let r=i.value_name!==void 0||i.flag==="--pm-path";t.option(`${a}${r?" <value>":""}`)}try{t.parseOptions(e)}catch{}let o=t.opts();return{path:o.pmPath??o.path}}var pm=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Po=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"]),us=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","history-repair","history-redact","history-compact","learnings","notes","plan","restore","update","update-many","create"]),um=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),fm=new Set(["claim","close-task","pause-task","release","start-task","test"]),_e={setup:!0,listQuery:!0,mutation:!0,operation:!0},gm=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 lt(e){return e.some(t=>mm.has(t))}function hm(e,t){if(!P.some(o=>o.canonical_argv[0]===t))return;let n=new ms().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of xa(t,ie(t))){let i=o.takes_value?o.value_required?" <value>":" [value]":"";for(let a of[o.flag,o.short,...o.aliases??[]])a!==void 0&&n.option(`${a}${i}`)}try{let o=n.parseOptions(e.slice(1));if(o.unknown.length>0)return _e;let i=G([t,...o.operands])?.alias;if(P.some(a=>a.alias===i))return{..._e,targetCommandName:i}}catch{return _e}}function $o(e){if(lt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return _e;let t=x(e);if(!t)return _e;let n=t.trim().toLowerCase(),o=L(e),i=G(o)?.alias;return P.some(a=>a.alias===i)?{..._e,targetCommandName:i}:hm(o,n==="ctx"?"context":n)||(pm.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Po.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:us.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:um.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:_e)}function Do(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function Mo(e,t){return st(t)||lt(t)?!1:ae(t)||A(t).requested?!0:!!x(t)}function Lo(e){if(lt(e))return!1;let t=x(e);return t?gm.has(t):!1}function ym(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,i=e.normalizedTokens.map(c=>{let d=c.indexOf("=");return d>=0?c.slice(0,d):c}).find(c=>c==="--literal"||c==="--regex"||c==="--replacement"),a=i?e.argv.map(c=>{let d=c.indexOf("=");return(d>=0?c.slice(0,d):c)===o?d>=0?`${i}${c.slice(d)}`:i:c}):e.argv,r=je(a),s=i&&n>=0?`${o}=[redacted]`:t,l=i&&e.normalizedDisplay.includes("=")?`${i}=[redacted]`:e.normalizedDisplay;return{argv:r,normalizedDisplay:l,sourceDisplay:s}}function No(e){let t=e.commandName;if(!t)return;let n=e.trace.find(c=>c.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(c=>c.length>0),i=o.length>0?o.join(" "):"the canonical flag",a=us.has(t)||fm.has(t),r=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",l=ym({argv:e.argv,normalizedDisplay:i,normalizedTokens:o,rawFrom:n.from});throw new k(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:r,examples:[_(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:_(l.argv)}})}(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]="6d83c356-db56-5116-9fe7-e0c27973b36f")}catch{}})();var _m=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"]),wm=new Set(["parse","preflight","execute","unknown"]),vm=new Set(["usage","validation","conflict","runtime","unknown"]);function we(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let i=o.trim();if(i.length>0)return i}}}function Fo(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Gt(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 jo(e){if(!e)return;let t=e.trim().toLowerCase();if(_m.has(t))return t}function Uo(e){if(!e)return;let t=e.trim().toLowerCase();if(wm.has(t))return t}function qo(e){if(!e)return;let t=e.trim().toLowerCase();if(vm.has(t))return t}function Ho(e){let t=we(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(r=>typeof r=="string"&&r.trim().length>0);if(typeof a=="string")return a.trim()}if(Fo(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=Gt(e,"failed");if(typeof o=="number"&&o>0)return`failed_runs:${o}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(r=>nn(r)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function zo(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 Go(){let e=nn(de()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Gt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,i=Oa(o),a=we(e,"error_code","errorCode")??zo(i,o),r=qo(we(e,"error_category","errorCategory"))??(i?void 0:pt(a)),s=i?void 0:Ho(e)??`command_exit_${o}`,l=jo(we(e,"command_resolution","commandResolution"))??bt({ok:i,errorCode:a,errorCategory:r}),c=Uo(we(e,"resolution_stage","resolutionStage"))??"execute";return{ok:i,error:s,exit_code:o,error_code:a,error_category:r,command_resolution:l,resolution_stage:c}}(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]="24927174-96e0-5a97-bf58-8ecd6c4ac0c4")}catch{}})();var Wo="PM_CLI_PACKAGE_ROOT",Cs=Symbol("pm.deprecatedAliasInvocation"),Vt=new Map;for(let e of B){let t=e.alias.split(" ")[0],n=Vt.get(t)??[];n.push(e),Vt.set(t,n)}for(let e of Vt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function bm(){return hi(import.meta.url,["../.."])}(typeof process.env[Wo]!="string"||process.env[Wo]?.trim().length===0)&&(process.env[Wo]=bm());var be=null,F=null,Kt=null;function Cm(e){be=e}function km(e){O=e}var ct=null,ve=null,O=new Map,Zo=250,xm=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),Em=new Set(["1","true","yes","on"]),Sm=ze(()=>import("./chunks/register-setup-LDXHMNOT.js")),Am=ze(()=>import("./chunks/register-list-query-I6AZA3IX.js")),Om=ze(()=>import("./chunks/register-mutation-3DAXCLXR.js")),Tm=ze(()=>import("./chunks/register-operations-G3QGGQ5Z.js"));function Bt(e){return _(e)}function ks(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=>pe(o)??o))];return n.length>0?n:void 0}function Rm(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Z(t),i=new Set(o.map(d=>pe(d)??d)),a=ks(e),r=t.find(d=>y.commands.some(m=>m.name()===d)),s=r?y.commands.find(d=>d.name()===r):void 0,l=new Set([...y.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>pe(m)).filter(m=>m!==void 0))),c=a?.filter(d=>{let m=pe(d)??d;return i.has(m)?!1:l.has(m)||Qn(t,r,m,O)!==void 0});return c&&c.length>0?c:void 0}function Im(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let i=n?.[0],a=i?pe(i):void 0,r=e.find(p=>y.commands.some(u=>u.name()===p)),s=r?y.commands.find(p=>p.name()===r):void 0,l=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,c=Qn(e,r,a,O),d=a?l?.isBoolean()===!0||c===!1?[a]:[a,"<value>"]:[],m=a?Bt([...e,...d]):t;return m===t?void 0:m}function Pm(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let i=e[o];i!=null&&(n[o]=i)}return n}function $m(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,...Pm(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function fs(e,t){return{...e,recovery:t}}function Dm(e,t){if(t!==void 0)return Ba(e,t.code,t.field,Wa(e,t.code,t.recovery))}function xs(e,t,n){let o=je(t),i=L(o),a=Y(i),[r,s]=a===void 0?[]:i.slice(a,a+2),l=o.includes("--explain");e=e===void 0?void 0:Ji(e);let c=Dm(o,e),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:Bt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:Bt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return fs(e,d);let m=Bt(o),p=Z(o),u=Rm(n,o,d),f=Im(o,m,u,d),h=$m({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return fs(e,h)}async function dt(e){let t=F;F=null,await Va(t,e);let n=be;if(be=null,!n){ht();return}let o=[],i=Ti();try{await Ka({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?i?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await vi(n.hooks,{command:n.commandName,args:n.commandArgs,options:{...n.commandOptions},global:{...n.globalOptions},pm_root:n.pmRoot,ok:e.ok,error:e.error,result:de(),affected:i}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{ht()}!n.globalOptions.json&&o.length>0&&v(`[pm] warning: afterCommand hook_warnings=${q(o)}`),n.profileEnabled&&o.length>0&&v(`profile:extensions hook_warnings=${q(o)}`)}async function Es(e,t){await Qi();let n=F,o=be,i=n?.command??o?.commandName??e,a=n??hn(o?.globalOptions??t),r=O.get(w(i))?.source;Cn(i,o?.commandArgs??[],{...o?.commandOptions,...o?.globalOptions},{source_context:a.source_context,source_context_source:a.source_context_source,pm_version:n?.pm_version??Le,extension:r})}function Ss(e){return Em.has((process.env[e]??"").trim().toLowerCase())}function As(e){return Ss("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!xm.has(Math.trunc(e))}async function Jt(e,t){return As(e.exit_code)?(await Es(e.command,t),ia({...e,source_context:e.source_context??hn(t).source_context}),!0):!1}async function Os(e){let t=me(e.error),n=vr(t);e.bootstrapGlobal.json?v(JSON.stringify(Je(_r(t,g.GENERIC_FAILURE)),null,2)):v(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",i="runtime_failed";try{await Es(e.attemptedCommand,e.bootstrapGlobal),kn(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,i=a.commandResolution,await Zt(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||v(`Failed to report error: ${me(a)}`)}try{await dt({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:i,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||v(`Failed to run error hooks: ${me(a)}`)}try{await Ee()}catch(a){e.bootstrapGlobal.json||v(`Failed to flush error reporting: ${me(a)}`)}}var Mm={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"},Bo=new Map;function Vo(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Ts(e,t){return e.options.some(n=>n.long===t)}function Rs(e,t){return e.options.some(n=>n.short===t)}function Ko(e,t,n,o){let i=t.trim();if(!i)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(i.startsWith("-")&&!i.startsWith("--")){if(Rs(e,i))return;if(o){e.option(`${i} <value>`,`${a} (repeatable)`,An);return}e.option(`${i} <value>`,a);return}let r=i.startsWith("--")?i:`--${i}`;if(!Ts(e,r)){if(o){e.option(`${r} <value>`,`${a} (repeatable)`,An);return}e.option(`${r} <value>`,a)}}async function Is(e,t){let n=Mm[e];if(!n)return[];let o=`${t}:${n}`,i=Bo.get(o);if(i)return i;if(!await V(K(t)))return Bo.set(o,[]),[];let a=await D(t),r=(ln(a.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:Vo(s.type),value_type:Vo(s.type)})));return Bo.set(o,r),r}async function Ps(e,t){let n=M(t),o=T(process.cwd(),n.path);if(!await V(K(o)))return;let i=ve?.key===ti(o)?ve.snapshot:null,a=i===null?await D(o):i.settings,r=ln(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 l of s){let c=ee(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";Ko(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Ko(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function Qo(e,t,n,o,i){let a=x(n);if(!(a!=="create"&&a!=="update"))try{let r=i??await D(t),s=le(r,o);ns(e,s,n)}catch{}}function Jo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function $s(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function ei(e){return e.some(t=>t==="--profile")}function ti(e){return`pm-root:${e}`}function Yo(e){for(let t of e)t.startsWith("settings_read_")&&Ke(t,`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Ds(e,t){e.profile&&(v(`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&&v(`profile:extensions activation_warnings=${q(t.activationWarnings)}`))}function Yt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";v(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Xt(e,t=xe){let n=ti(e);if(ve?.key===n)return ve.snapshot;try{let o=Date.now(),{settings:i,warnings:a}=await t(e),r=await bi({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:i,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return ve={key:n,snapshot:s},s}catch{return ve={key:n,snapshot:null},null}}async function Ne(e,t,n=D){let o=t?at(t):"all",i=$s(e,o);if(ct?.key===i)return ct.snapshot;try{let a=await n(e),r=await qe({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Eo(t):void 0}),s=await He({...r,loaded:r.loaded}),l=[...new Set(s.commands.handlers.map(u=>w(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),c=Ir(s.registrations.flags),d=Tr(s.commands.handlers,s.registrations.commands),m=$r(l,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:l,commandFlagHelp:c,commandDescriptors:m,commandAliases:d,loadWarnings:[...r.warnings],activationWarnings:[...s.warnings],loadedCount:r.loaded.length,loadFailedCount:r.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:r.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return ct={key:i,snapshot:p},p}catch{return ct={key:i,snapshot:null},null}}async function Ms(e){let t=Ve(e);if(t.noExtensions){let r=T(process.cwd(),t.path);return await V(K(r))&&Yo((await xe(r)).warnings),null}let n=T(process.cwd(),t.path),o=await Xt(n);if(!o)return null;Yo(o.settingsReadWarnings);let i={commandPath:E(e),commandArgs:So(e)};if(!it(o.discovery,i))return Yt(t.profile,o,i),null;let a=await Ne(n,i);return a?(Ds(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 ni(e){let t=await Ne(e);return t?new Map(t.commandDescriptors):O}async function Lm(e,t){return!e.requested||t.noExtensions||Te(y,e.commandPathTokens)?O:ni(T(process.cwd(),t.path))}async function Ls(e,t){return(await ua({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(n=>n.outcome==="failed").map(n=>`extension_migration_failed:${n.layer}:${n.extension}:${n.id}`)}function Ns(e,t,n){let o=t.author;return pa(e,Pa.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function Fs(e,t,n,o=[]){let i=E(e),a=uo(e.args.map(String),o),r={...t};delete r.author;let s={...n},l=T(process.cwd(),n.path),c=await yt({command:i,args:a,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&v(`profile:extensions parser_warnings=${q(c.warnings)}`),a=c.context.args,r=c.context.options,s=c.context.global,Io(O.get(w(i)),a,r,o),ke(void 0),gt({command:i,args:a,options:{...r},global:{...s},pm_root:l});let d=await sn({command:i,args:a,options:r,global:s,pm_root:l,sdk:Ns(l,s,i)});if(s.profile&&d.warnings.length>0&&v(`profile:extensions command_handler_warnings=${q(d.warnings)}`),!d.handled)throw d.warnings.length>0?ea(i,d):new k(`Command "${i}" is provided by extensions and is not currently available.`,g.NOT_FOUND);return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ke(d.result),d.result}var gs=Symbol("pm.wrappedActionHandler");function Nm(e,t){let n=e[e.length-1];return n instanceof Xo?n:t}function hs(e,t,n){e&&n.length>0&&v(`profile:extensions ${t}=${q(n)}`)}function Fm(e){let t=O.get(w(e.commandPath));if(!t||!To(e.activeRegistrations,e.commandPath))return;let n=zt(t).length===0?Jr(e.commandArgs):uo(e.commandArgs,e.extensionFlagDefinitions);Ro(t,n)}function jm(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 js(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[gs]!==!0){let i=o._actionHandler;o._actionHandler=async function(...a){let r=Nm(a,n),s=Date.now();Sn(r);let l=Ve(r),c=$(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await i.apply(this,a);let d=T(process.cwd(),l.path),m=r.args.map(String),p=ce(),u=p?rt(p,c,m):[],f=await Is(c,d),h=Me(r,m,[...u,...f]);O.has(w(c))&&delete h.author;let b=await yt({command:c,args:m,options:h,global:l,pm_root:d});hs(l.profile,"parser_warnings",b.warnings),m=b.context.args,h=b.context.options,se(r,h),l=b.context.global,Fm({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await Ca(l),Et(r,l),jm(r,a,m),xt(r,h),ke(void 0),gt({command:c,args:m,options:{...h},global:{...l},pm_root:d});let S=await sn({command:c,args:m,options:h,global:l,pm_root:d,sdk:Ns(d,l,c)});if(hs(l.profile,"command_handler_warnings",S.warnings),S.handled){ke(S.result),gn(S.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&v(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await i.apply(this,a)},o[gs]=!0}for(let i of n.commands)t(i)};t(e)}async function Wt(e){O=new Map,ne({overrides:[]}),e&&await Qo(e.rootProgram,e.pmRoot,e.invocationArgv,_i(),e.settings)}function Um(e,t,n,o){if(t?.flags&&t.flags.length>0){no(e,t.flags);let i=oo(e,t.flags);i&&e.addHelpText("after",i)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function Us(e,t,n){let o={core:0,standard:1,full:2,internal:3},i=(a,r)=>{let s=r.join(" "),l=[...n.entries()].filter(([d])=>d===s||d.startsWith(`${s} `)).map(([,d])=>d),c=l.length===0?"standard":l.reduce((d,m)=>o[m.tier]<o[d]?m.tier:d,"internal");Ot(a,c);for(let d of a.commands)i(d,[...r,d.name()])};for(let a of e.commands)t.has(a.name())||i(a,[a.name()])}async function qs(e,t){let n=M(t),o=T(process.cwd(),n.path);if(n.noExtensions){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let i=await Xt(o),a=De(t);if(!i){await Wt();return}if(!it(i.discovery,a)){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings}),Yt(ei(t),i,a);return}let r=await Ne(o,a);if(!r){await Wt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:i.settings});return}ne(r.services),O=new Map(r.commandDescriptors),await Qo(e,o,t,r.registrations,r.settings);let s=Ur(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>qr(r.activationWarnings,v,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(I=>I.length>0),p=r.commandDescriptors.get(d),u=ee(e,m),f=r.commandFlagHelp.get(d),h=p?Fr(p):null;if(u){Um(u,p,f,h);return}let b=jr(e,m);p?.description&&b.description(p.description);let S=f;p&&(Dr(b,p),p.flags.length>0&&(no(b,p.flags),S=oo(b,p.flags)??void 0)),S&&b.addHelpText("after",S),h&&b.addHelpText("after",h),b.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...I)=>{let z=I[I.length-1],U=z instanceof Xo?z:b,mt=Ve(U),Qs=Date.now(),ai=rt(r.registrations,d,U.args.map(String)),ri=Me(U,U.args.map(String),ai),si=await Fs(U,ri,mt,ai);await ka(mt,si),gn(si,{...mt,command:d,commandArgs:U.args.map(String),commandOptions:ri,pmRoot:o}),mt.profile&&v(`profile:command=${d} took_ms=${Date.now()-Qs}`)})};for(let d of s)c(d);Us(e,l,r.commandDescriptors)}var Le=yi(import.meta.url,["../.."])??"0.0.0",y=En(Le);async function ys(e){if(!F)return;let t=Reflect.get(e,Cs);typeof t=="string"&&await Ia(t)}async function _s(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function ws(e,t,n){!F||!await yn(!0)||(Cn(e,t,n,{source_context:F.source_context,source_context_source:F.source_context_source}),ta(e),Kt=F)}async function Zt(e,t,n){let o=Kt;if(!o)return;Kt=null;let i=!1;try{let a=await D(o.global_pm_root);i=a.telemetry.enabled&&a.telemetry.installation_id===o.installation_id}catch{}await yn(i)?oa(e,t,n):na()}async function qm(e){let t=await Ms(e);return rn(t?.registrations??null),t}function Hs(e,t){t&&st(t)||(e.hook("preAction",async(n,o)=>{be=null,F=null,Kt=null,ht(),Sn(o);let i=o.optsWithGlobals(),a=Ve(o),r=$(E(o)),s=o.args.map(String),l=Me(o,s),c={...a},d=T(process.cwd(),a.path),m=await qm(o);if(Fi(r,{...l,outputInclude:i.outputInclude,outputLimit:i.outputLimit,outputBudget:i.outputBudget,outputFormat:i.outputFormat,outputSession:i.outputSession,outputCursor:i.outputCursor}),Oo(o,r,c,l),await _s(o,void 0,()=>la(r,c)),!m){be=Ci({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),F=await xn({command:r,pm_version:Le,args:s,options:l,global:c,pm_root:d}),await ys(e),await ws(r,s,l),await yo(r,l,d,Jo()),await ho(r,s,l,c,d);return}ki(m.hooks),xi(m.commands),Ei(m.parsers),Si(m.preflight),ne(m.services),Ai(m.renderers),rn(m.registrations);let p=rt(m.registrations,r,s);l=Me(o,s,p),Oo(o,r,c,l);let u=await yt({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&v(`profile:extensions parser_warnings=${q(u.warnings)}`),s=u.context.args,l=u.context.options,se(o,l),c=u.context.global,xt(o,l);let f=await Ri({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Jo()});c.profile&&f.warnings.length>0&&v(`profile:extensions preflight_warnings=${q(f.warnings)}`),s=f.context.args,l=f.context.options,se(o,l),c=f.context.global,xt(o,l);let h=f.decision;await yo(r,l,m.pmRoot,h),await ho(r,s,l,c,m.pmRoot);let b=h.run_extension_migrations?await _s(o,[],()=>Ls(m.registrations.migrations,m.pmRoot)):[];c.profile&&b.length>0&&v(`profile:extensions migration_warnings=${q(b)}`);let S=as(m.registrations.migrations);be={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:S},ke(void 0),gt({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),F=await xn({command:r,pm_version:Le,args:s,options:l,global:c,pm_root:m.pmRoot}),await ys(e),await ws(r,s,l);let I=await wi(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&I.length>0&&v(`profile:extensions hook_warnings=${q(I)}`),h.enforce_mandatory_migration_gate&&rs(r,l,S)}),e.hook("postAction",async()=>{let n=Go();await Zt(n.ok,n.error,{error_code:n.error_code,error_category:n.error_category,exit_code:n.exit_code,command_resolution:n.command_resolution,resolution_stage:n.resolution_stage}),await dt(n),await Ee()}))}Hs(y);var vs=Symbol("pmCliIdempotentTopLevelRegistration");function zs(e){let t=e;if(t[vs])return;t[vs]=!0;let n=e.command.bind(e);e.command=((o,...i)=>{let a=o.split(/\s+/u)[0];return e.commands.some(r=>r.name()===a||r.aliases().includes(a))?new Xo(a):n(o,...i)})}async function Hm(e,t){if(zs(e),t.setup){let{registerSetupCommands:n}=await Sm();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Am(),o=typeof t.targetCommandName=="string"&&Po.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Om();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Tm();n(e)}}function zm(e){return async t=>{let n=pt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await da({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Le,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 Gs(e){if(e.bootstrapGlobal.noExtensions||st(e.invocationArgv))return;let t=De(e.invocationArgv),n=await Xt(e.bootstrapPmRoot);if(n&&it(n.discovery,t)){let o=await Ne(e.bootstrapPmRoot,t);Ws(o);return}n&&Yt(ei(e.invocationArgv),n,t),ne({overrides:[]})}function Ws(e){if(!e){ne({overrides:[]});return}ne(e.services)}async function oi(e){await Zt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await dt({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 Bs(){await Zt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await dt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Vs(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof k)&&(vn(e.error)||!n))return!1;let o=me(e.error),i=e.error instanceof k?e.error.exitCode:wn(t),a=e.error instanceof k||Zi(e.error)?e.error.context:void 0,r=xs(a,e.invocationArgv,o),s=hr(o,r),l=Je(e.bootstrapGlobal.lean?Rt(Wn(o,i,r)):Wn(o,i,r)),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?J(l,u=>`${JSON.stringify(u,null,2)}
|
|
39
|
+
`):l,null,2):fr(o,r,{lean:e.bootstrapGlobal.lean===!0});e.jsonErrors?oe(`${c}
|
|
40
|
+
`):v(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:i,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Jt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:i,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:F?.source_context},e.bootstrapGlobal);return await oi({errorMessage:o,exitCode:i,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(kn(bn(e.error,o)),await Ee(Zo)),process.exitCode=i,!0}async function Ks(e,t){let n=A(e.invocationArgv).commandPathTokens.join(" ")||Kn(e.invocationArgv),o=$(n),i=`unknown command '${n}'`,a=T(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?O:await ni(a),s=De(e.invocationArgv),l=e.bootstrapGlobal.noExtensions?[]:await fo(a,{},$e(s)),c=await Qe({message:i},y,r,{failedExtensions:l},e.invocationArgv),d=Bn(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:l}),{errorCategory:m,commandResolution:p}=await e.emitTelemetryCommandError({command:o,errorCode:d.code,errorMessage:d.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),u=await Jt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"},e.bootstrapGlobal),f=e.jsonErrors?await Zn({message:i},y,r,e.bootstrapGlobal.lean===!0,{failedExtensions:l},e.invocationArgv):await Xn({message:i},y,r,{failedExtensions:l},e.invocationArgv),h=Vn(f,e.jsonErrors,l);await oi({errorMessage:i,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?oe(`${Rn(h)}
|
|
41
|
+
`):v(h),u&&await Ee(Zo),process.exitCode=g.USAGE}async function Js(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let o=A(e.invocationArgv);return o.requested&&!Te(y,o.commandPathTokens)?(await Ks(e,t),!0):(await Bs(),!0)}async function Ys(e,t){let n=await Qe(e.error,y,O,{},e.invocationArgv),o=Bn(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:i,commandResolution:a}=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"}),r=await Jt({command:e.attemptedCommand,error_code:o.code,error_category:i,exit_code:g.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:F?.source_context},e.bootstrapGlobal),s=e.jsonErrors?await Zn(e.error,y,O,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await Xn(e.error,y,O,{},e.invocationArgv),l=await Yr(o.code,e.bootstrapPmRoot,{},$e(De(e.invocationArgv))),c=Vn(s,e.jsonErrors,l);await oi({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:i,commandResolution:a,resolutionStage:"parse"}),e.jsonErrors?oe(`${Rn(c)}
|
|
42
|
+
`):v(c),r&&await Ee(Zo),process.exitCode=g.USAGE}function Xs(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 Zs(e){let t=e.error.code,n=String(e.error.message??"");if(!await Js(e,t,n)){if(t==="commander.version"){await Bs();return}await Ys(e,t)}}async function ii(e){let t=M(e.invocationArgv),n=T(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:zm({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await Gs({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Vs(o,_n(e.error))){if(Xs(e.error)){await Zs(o);return}await Os({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function Gm(e,t,n){let o=n.requested?n.commandPathTokens:L(t),i=G(o);if(i&&!ee(e,[...i.canonical_argv]))throw new bs(g.USAGE,"commander.unknownCommand",`unknown command '${i.alias}'`)}function Wm(e,t){let n=Y(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=Y(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Vt.get(t[n]),i=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),a=o?.find(r=>r.alias.split(" ").every((s,l)=>i[l]===s));a?.lifecycle==="deprecated"&&Reflect.set(e,Cs,a.alias)}function Bm(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Vm(e,t){y=En(Le),y.hook("preAction",(a,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),Hs(y,e),ct=null,ve=null,O=new Map,Oi();let n=[...e],o,i;try{let a=Be(e);n=a.argv,Wm(y,e);let r=Bm(n),s=n.length===0,l=M(n);if(l.authorMissingValue)throw new k("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=va(l.author),No(a),i=ga(n);let c=$o(n);await Hm(y,c),Mn(y,!0),Mo(y,n)?await qs(y,n):(O=new Map,ne({overrides:[]})),Lo(n)&&await Ps(y,n),Mn(y);let d=A(n);Gm(y,n,d),Do(n)&&er(y,n),js(y);let m=await Lm(d,l);if(await ts(y,n,m,e))return;if(d.requested&&!Te(y,d.commandPathTokens))throw new bs(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||ae(n)&&x(n)===void 0){y.outputHelp();return}if(st(n)){await y.parseAsync(r);return}let p=T(process.cwd(),l.path),u=await D(p),f=await Ar(n,p,l.noExtensions,Ne);await ma({pmRoot:p,packages:f?.contextIntentPackages},()=>Pi({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>$i(u.agent_identity.harness_signals,()=>y.parseAsync(r),{probesEnabled:u.agent_identity?.probes_enabled})))}catch(a){await ii({error:a,invocationArgv:n})}finally{i?.(),o?.()}}async function Pf(e=process.argv.slice(2)){let t=e;try{t=Be(e).argv}catch{}let n=ps(t),o={configurationOnly:n!==void 0},i=()=>o.configurationOnly,a=()=>za(M(t).json,async()=>{try{await ba(process.env,()=>Vm(e,o))}catch(r){await ii({error:r,invocationArgv:[...e]})}});if(n!==void 0){let r=T(process.cwd(),M(t).path),s=T(process.cwd(),n.path),l=pi(process.cwd());await wt(r,()=>wt(s,()=>wt(l,a,i),i),i)}else await a()}var $f={activationCommandMatchesProbe:wo,applyDynamicExtensionRootHelpVisibility:Us,bootstrapProfileEnabled:ei,buildBootstrapActivationProbe:De,buildPostActionTelemetryOutcome:Go,buildPmCliRecoveryContext:xs,buildRuntimeExtensionDiscoverySnapshotCacheKey:ti,buildRuntimeExtensionActivationScope:at,buildRuntimeExtensionSnapshotCacheKey:$s,buildRuntimeExtensionFilterForProbe:Eo,addRuntimeFieldOption:Ko,collectActivationCommandCandidates:$e,collectExtensionFlagDefinitionsForCommand:Ht,collectExtensionFlagDefinitionsForInvocation:rt,collectLeadingCommandArgs:_o,collectParsedActivationCommandArgs:So,collectRuntimeFieldLooseFlagDefinitionsForCommand:Is,commandHasLongOption:Ts,commandHasShortOption:Rs,commandPathNeedsSearchExtensions:vo,commandPathNeedsTemplateExtensions:jt,describeUnknownError:me,defaultPreflightDecision:Jo,discoveryNeedsActivationForProbe:it,emitExtensionProfile:Ds,emitExtensionSkippedProfile:Yt,emitSettingsReadWarnings:Yo,ensureIdempotentTopLevelCommandRegistration:zs,enforceExplicitRetryForFlagTypos:No,envFlagEnabled:Ss,executeRegisteredRuntimeMigrations:Ls,extractCommandScopedOptions:Me,extensionActivationCommands:Ft,extensionCapabilities:ot,extensionNeedsActivationForProbe:Ut,extensionProvidesTemplatesRuntime:Co,hasAnyCapability:Pe,hasGlobalExtensionContributions:ko,handleGenericRunPmCliError:Os,handleRunPmCliCommanderError:Zs,handleRunPmCliError:ii,handleRunPmCliHelpDisplayError:Js,handleRunPmCliKnownError:Vs,handleRunPmCliCommanderUsageError:Ys,handleUnknownHelpCommandError:Ks,inferMissingFieldsFromErrorMessage:ks,inferPostActionErrorCode:zo,inferPostActionFailureMessage:Ho,invocationRequestsVersion:lt,isCommanderError:vn,loadRuntimeExtensionCommandDescriptorsForRecovery:ni,loadRuntimeExtensionDiscoverySnapshot:Xt,loadRuntimeExtensionSnapshot:Ne,maybeLoadRuntimeExtensions:Ms,maybeAttachCreateUpdatePolicyHelpText:Qo,maybeLogHandledCliErrorToSentry:Jt,matchesStaticExtensionCommand:Nt,normalizeTelemetryCommandResolution:jo,normalizeTelemetryErrorCategory:qo,normalizeTelemetryResolutionStage:Uo,normalizeThrownExitCode:wn,probeUsesAnyFlag:bo,prepareExtensionServicesForRunPmCliError:Gs,readRecordBoolean:Fo,readRecordNumber:Gt,readRecordString:we,recordCliReadOutputInvocationProvenance:Ao,registerDynamicExtensionCommandPaths:qs,registerRuntimeSchemaFieldFlags:Ps,resolveCoreCommandRegistrationSelection:$o,resolveStaticExtensionActivationDecision:xo,resolveUnknownHelpToken:Kn,readThrownExitCode:_n,runAndClearAfterCommandHooks:dt,runRequiredExtensionCommand:Fs,shouldAttachRichHelpTextForInvocation:Do,shouldLogHandledErrorToSentry:As,shouldRegisterDynamicExtensionPaths:Mo,shouldRegisterRuntimeSchemaFlags:Lo,shouldHandleRunPmCliCommanderError:Xs,setActiveExtensionHookContextForTest:Cm,setActiveRuntimeExtensionCommandDescriptorsForTest:km,setRecoveredExtensionServices:Ws,toLooseFieldDefinitionType:Vo,isImporterOrExporterCommandPath:To,validateDynamicExtensionCommandInvocation:Io,wrapProgramActionsForExtensionHandlers:js,wrapThrownErrorForSentry:bn};export{$f as _testOnly,Pf as runPmCli};
|
|
42
43
|
//# sourceMappingURL=main.js.map
|