@unbrained/pm-cli 2026.10.20 → 2026.10.21
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 +25 -0
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-QETMESEB.js → chunk-4OYU5OXQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-5PZ7JNMI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-C6SAXKBO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-DIKQ2AL5.js +2 -0
- package/dist/cli-bundle/chunks/chunk-DIR3YEFD.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-DJQVNDXO.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-DR6DUBTU.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-EMGMLKRV.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-PNPE2OVJ.js → chunk-KBSVPUFD.js} +46 -45
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-MOC5BJHW.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-MZZIAC6S.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-NNB65OOO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-QPV6UD55.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-TMXWWOPJ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-V3XONSVC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-V5GJTXYW.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-ZNKFMIVA.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-65XXSPPR.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-FNWOVJLN.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-6PT5Y2EZ.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-TAIQV46L.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-ONIRO22G.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-OQMUZBJV.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-FCPVFO3B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-32ZKLRWM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-44353U27.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4HJVAUFX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-5IMM7GOF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-J6EYUGAR.js → chunk-6QSZHRM7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-7UD7XTOE.js} +10 -10
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-CUWNNU4N.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-E2S42XCT.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GRSQGMRR.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-HNCMYF2W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-37SU7BZI.js → chunk-IAGFXKMZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JI3RXXRN.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-JMZPZQHR.js +26 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-KVYUQS6Y.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-O3M6YWVL.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-P5D7MHDS.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-PDOWLRHC.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-T27TLSEU.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-VD64TPXI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GYHZ7W6O.js → chunk-VE6MTRH5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XE7P7N5X.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-YIWDX6KO.js +91 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-CRP6HAZY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-KM57KDDF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-UJYGWNZ7.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- 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 +23 -23
- 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 +58 -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 +2 -2
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +29 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +26 -3
- package/docs/SDK.md +67 -0
- package/docs/TESTING.md +18 -0
- package/docs/agent-task-token-baseline.json +1 -1
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import"./chunks/chunk-DEZPZOQ7.js";import{B as yi,C as wn,a as sn,d as M,e as D,f as A,g as K,h as x,i as Fa,n as Ge,o as La,p as Ha,t as za,u as ui,v as fi,w as _n,y as gi,z as hi}from"./chunks/chunk-
|
|
2
|
-
`)}function
|
|
3
|
-
`)}function xi(e,t){return t==="detailed"?ks(e):Cs(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var xs={cal:"calendar",ctx:"context"};function Es(e,t){return e.commands.find(n=>n.name()===t)??null}function Ss(e,t){let n=e;for(let o of t){let a=Es(n,o);if(!a)return null;n=a}return n}function bn(e,t,n,o){let a=Ss(e,t.split(" ").filter(i=>i.length>0));a&&a.addHelpText("after",xi(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function oe(e){return e.includes("--all")||e.includes("--explain")}var ue={"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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "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 R){let n=ue[e];n&&(ue[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var xe={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."]},Ei=W.filter(e=>e.lifecycle==="deprecated");for(let e of Ei){let t=ue[e.alias];ue[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[xe,...Object.values(ue)])e.examples=e.examples.map(t=>{for(let n of Ei){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function As(e){let t=N(e??"");return t?xs[t]??t:""}function kn(e){let t=As(e);return t?ue[t]??xe:xe}function Si(e,t){let n=kn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:ki(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Ts(){let e=W.filter(({lifecycle:n})=>n==="permanent"),t=W.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(" ")} (${Yo(n)})`)].join(`
|
|
4
|
-
`)}function
|
|
5
|
-
`,s=t.visibleCommands(e);for(let l of s)pe(l)===void 0&&(l.name()==="help"||a.has(l.name()))&&n.add(l);for(let l of s)pe(l)==="core"&&(n.add(l),
|
|
6
|
-
`)}function Di(e,t){return t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),$s(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 js(e,t){if(e.flag)return e.flag;let n=o=>{let a=o.split("=",1)[0];return D([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 Us(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 qs(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=D(e.recovery?.normalized_args??[]),o=q(n),a=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,i=js(e,a),r=Us(e,a,i);return{surface:i??e.recovery?.missing?.[0]??_n(a)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function Hs(e,t){return Di({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:qs(e,t)},e)}function On(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 _a(Hs(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return Di({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function Rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function zs(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 ge(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 Ri(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Gs(e){return _n(e?.normalized_args)}function Ws(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 Vs(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,k(s)}}}function Bs(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Ks(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 ae(e,t,n){if(!n)return e;let o=Rt(t),a=Tt(n.code,e.code),i=Tt(n.type,$i(a)),r=ge(n.examples)??e.examples,s=ge(n.nextSteps)??e.nextSteps,l=ge(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?Bs(o):void 0,d=Se(n.recovery),m=d&&e.recovery?Se({...e.recovery,...d}):d??e.recovery;return{...e,code:a,type:i,title:c??e.title,happened:o.length>0?o:e.happened,required:Tt(n.required,e.required),why:Tt(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Ks(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,availableDependencies:n.available_dependencies,recovery:m}}function Js(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=ta(process.cwd(),a);return ae(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 Ys(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 ae(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 Xs(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(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 Zs(e,t,n){return t.includes("is locked")?ae(C({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function Qs(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 ae(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 el(e,t,n){return t.startsWith("No update flags provided")?ae(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 tl(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Se(n?.recovery),a=Gs(o),i=a?`pm ${a} --help`:"pm <command> --help",r=Ws(t),s=Se({...o,allowed_values:o?.allowed_values??r}),l=Vs(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 ae(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 In(e,t){let n=Rt(e);return(Js(e,n,t)??Ys(e,n,t)??Xs(e,n,t)??Zs(e,n,t)??Qs(e,n,t)??el(e,n,t)??tl(e,n,t))||ae(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 nl(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 ol(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function al(e){if(!(!Array.isArray(e)||e.length===0))return k(e)}function $n(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 U(e,t={}){let n=$n(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,a=typeof e?.attemptedCommand=="string"?e.attemptedCommand:al(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Se({attempted_command:a,normalized_args:o,provided_fields:n,suggested_retry:i,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Tn(e,t){return!t||e.includes(t)?e:[...e,t]}var il=new Set(["--add","--add-json","--remove"]),rl=new Set(["command","cmd","path"]);function sl(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(il.has(o))return o}}function ll(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"||!rl.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 k(l)}}function cl(e,t,n,o){let a=e.match(/required option '([^']+)' not specified/);if(!a)return null;let i=ol(a[1]),r=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=$n(o?.providedOptionFlags),c=[i],d=nl(t,i,n),m=s?Tn(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?Tn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Tn(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:U(o,{missing:c})})}function dl(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:U(n,{missing:[a]})})}function ml(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:U(t,{suggested_flags:n})})}var pl={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 ul(e){let t=ge(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function fl(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,i.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,a?`Replay with suggested correction: ${a}`:void 0].filter(l=>typeof l=="string")}function gl(e,t){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(ui(t))return{};let n=e.normalizedInvocationArgs;if(n===void 0)return{};if(n.filter(i=>i===t||i.startsWith(`${t}=`)).length!==1)return{};let o=n.findIndex(i=>i===t||i.startsWith(`${t}=`));if(o<0||n.includes("--")||!n[o]?.includes("=")&&o!==n.length-1&&n[o+1]?.startsWith("-")!==!0)return{};let a=D(n.filter((i,r)=>r!==o));return{retryCommand:k(a),suggestedRetryArgs:a}}function hl(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let a=n??{},i=o[1],r=$n(a.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=gl(a,i);if(t==="update"&&(i==="--file"||i==="--doc"))return ml(i,n,r);let c=ul(a),d=fl(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 ${H(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:pl[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:d,recovery:U(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 yl(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:Ri([t.installCommand,...n]),nextSteps:Ri([i,...r]),recovery:U(a)})}function _l(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],a=ge(t?.unknownCommandExamples),i=ge(t?.unknownCommandNextSteps),r=Ds(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))?yl(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:U(t)})}function wl(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ge(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 ${H(t)?.canonical??t} --help`],nextSteps:a?[`Retry with the declared hyphenated action: ${a}`]:["Choose one value from recovery.allowed_values."],recovery:U(e,{allowed_values:o,suggested_retry:a})})}function vl(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,a=sl(o);if(!a)return null;let i=ll(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:U(n,i?{suggested_retry:i}:{})})}var bl=new Set(["comments","docs","files","learnings","notes","test"]);function Cl(e,t,n){if(!/too many arguments/i.test(e)||!bl.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:U(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var kl=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"]),Ii=new Set(["context","ctx"]);function xl(e,t,n){if(!/too many arguments/i.test(e)||!Ii.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>Ii.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(kl.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:U(n,{suggested_retry:l})})}function Pn(e,t,n,o){let a=Rt(e);return(cl(a,t,n,o)??dl(a,t,o)??hl(a,t,o)??_l(a,o)??wl(o)??Cl(a,t,o)??vl(a,t,o)??xl(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:U(o)})}function Ni(e,t){let n=In(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&n.title==="Tracker is not initialized"&&n.recovery?.suggested_retry_args?[`Error: ${n.title}`,`Run: ${k(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
7
|
-
`):an(
|
|
1
|
+
import"./chunks/chunk-DEZPZOQ7.js";import{B as yi,C as wn,a as sn,d as M,e as D,f as A,g as K,h as x,i as Fa,n as Ge,o as La,p as Ha,t as za,u as ui,v as fi,w as _n,y as gi,z as hi}from"./chunks/chunk-5PZ7JNMI.js";import{a as de,b as ln,c as cn,d as dn,e as mn}from"./chunks/chunk-2B5HAZFK.js";import{Ta as pi,f as Aa,i as Da}from"./chunks/chunk-EMGMLKRV.js";import"./chunks/chunk-NNB65OOO.js";import"./chunks/chunk-ZNKFMIVA.js";import{F as li,b as ai,d as xt,g as ii,h as ri,i as J,j as si,md as mi,rc as di}from"./chunks/chunk-DR6DUBTU.js";import"./chunks/chunk-DIKQ2AL5.js";import{ea as ci,g as Na}from"./chunks/chunk-V3XONSVC.js";import{a as $a}from"./chunks/chunk-MZZIAC6S.js";import"./chunks/chunk-4D25HF3V.js";import{$d as ke,Ae as ei,Be as ti,Bf as Ct,Cf as kt,Df as hn,Ef as Ve,Ff as E,Gf as ni,H as _t,Hf as yn,I as Pa,Lf as L,Rb as Ma,Sb as ne,Sd as Ga,Td as un,Ub as ja,Ud as bt,Vb as Ua,Vd as Wa,W as wt,Wd as Va,Xb as qa,Xd as Ba,Y as He,Yd as Ka,Z as vt,Zd as fn,Zf as oi,_d as Ja,ce as Ya,de as Xa,ja as ze,oe as We,re as Za,ue as Qa,ze as gn}from"./chunks/chunk-V5GJTXYW.js";import"./chunks/chunk-RUKSEZE7.js";import"./chunks/chunk-DJQVNDXO.js";import"./chunks/chunk-IB7UB5TE.js";import{$b as we,A as Zo,Aa as B,Cd as C,D as Fe,Db as en,Dd as qe,Hc as ca,Hf as Sa,Ic as da,If as be,J as Xt,Jc as ma,Kc as pa,Kf as rn,Lc as te,Lf as _,Mc as ua,N as Qo,Nc as nn,Ob as oa,Oc as se,Pc as fa,Qc as ut,Tc as ve,Uc as le,Xb as ee,Xc as ga,Yc as ft,_b as aa,ac as tn,bc as pt,be as _a,cd as on,ce as an,ch as Ta,d as R,dd as gt,dh as Oa,ed as ha,f as q,fc as ia,fd as ya,ff as xa,g as I,hb as Le,hc as ra,i as W,j as Yt,jf as Ea,k as H,l as Yo,lg as pn,lh as ht,ma as Zt,oe as wa,pa as re,pe as va,pi as yt,qe as ba,ra as ea,re as Ca,sa as mt,se as ka,si as Ra,uc as sa,va as Qt,vc as je,vf as ce,vi as Ce,wa as ta,wi as $,xa as S,xc as Ue,xi as Ia,yc as la,z as Xo,za as na}from"./chunks/chunk-KBSVPUFD.js";import"./chunks/chunk-4OYU5OXQ.js";import"./chunks/chunk-VS565KBX.js";import{A as g,B as dt,C as b,E as V}from"./chunks/chunk-GWIGZDRS.js";import"./chunks/chunk-XAWE4EAK.js";import{Command as jo,CommanderError as qr}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 j(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function me(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return j(t)}function Y(e){let t=new Set,n=[];for(let o of e){let a=me(o);a&&(t.has(a)||n.push(a),t.add(a))}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 vn=new Set(["--fields","--output-include","--depth","--for","--token-budget"]),Et=new Set(["--full","--brief","--compact"]);function vs(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 bs(e){let t=ne(x([...e])),n=new Set([...ja,...Ua,...qa].flatMap(r=>r.keys.map(s=>`--${s.replace(/[A-Z]/g,l=>`-${l.toLowerCase()}`)}`))),o=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,r.flag]))),a=new Map([...ze,...t].flatMap(r=>[r.flag,...r.aliases??[]].map(s=>[s,vs(r,n)])));for(let r of vn)a.set(r,!0);for(let r of Et)a.set(r,!1);let i=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(!a.has(l)&&!s.includes("="))return;i.set(r,o.get(l)??l),a.get(l)&&!s.includes("=")&&(r+=1)}return i}function _i(e,t,n){let o=new Set;for(let[a,i]of t)n.has(i)&&(o.add(a),vn.has(i)&&!e[a].includes("=")&&o.add(a+1));return e.filter((a,i)=>!o.has(i))}function Cs(e,t){let n=t.find(a=>Et.has(a));if(n===void 0)return;let o=[...new Set(e.values())].filter(a=>Et.has(a));return o.length===1?o[0]:n}function wi(e,t,n){if(!n||!["unknown_field_projection","projection_options_mutually_exclusive"].includes(t??""))return n;let o=n.suggested_retry_args,a={...n,suggested_retry:void 0,suggested_retry_args:void 0};if(!o)return a;let i=bs(e);if(!i)return a;let r;if(t==="unknown_field_projection"){let s=o.indexOf("--fields");if(s<0||o[s+1]===void 0)return a;let l=[...i].find(([c,d])=>d==="--fields")?.[0]??-1;if(l<0)return a;r=_i(e,i,new Set(["--fields"])),r.splice(l,0,"--fields",o[s+1])}else{let s=Cs(i,o);if(s===void 0||![...i.values()].includes(s))return a;let l=new Set([...vn,...Et].filter(c=>c!==s));r=_i(e,i,l)}return{...n,suggested_retry:C(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]="afa4a7a0-d9de-529d-92dd-3e9704ea00d2")}catch{}})();async function vi(e,t){await ei(e,{ok:t.ok,error:t.error,result:le(),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 bi(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await xa({pmRoot:e.pmRoot,result:le()})}catch(o){t=o}let n=await $(e.pmRoot);if(await Ea({pmRoot:e.pmRoot,author:ht(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]="5efa5c0f-8a74-5b20-bc2d-0016fe62411b")}catch{}})();var Ci=new WeakMap;function St(e,t){Ci.set(e,t)}function pe(e){return Ci.get(e)}function ki(e){return e.length>0?[e[0]]:[]}function ks(e){let t=["","Intent:",` ${e.why}`],n=ki(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(`
|
|
2
|
+
`)}function xs(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(`
|
|
3
|
+
`)}function xi(e,t){return t==="detailed"?xs(e):ks(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Es={cal:"calendar",ctx:"context"};function Ss(e,t){return e.commands.find(n=>n.name()===t)??null}function As(e,t){let n=e;for(let o of t){let a=Ss(n,o);if(!a)return null;n=a}return n}function bn(e,t,n,o){let a=As(e,t.split(" ").filter(i=>i.length>0));a&&a.addHelpText("after",xi(n,o))}function Cn(e){return e.includes("--explain")?"detailed":"compact"}function oe(e){return e.includes("--all")||e.includes("--explain")}var ue={"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:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "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 R){let n=ue[e];n&&(ue[t]={...n,examples:n.examples.map(o=>o.replace(`pm ${e}`,`pm ${t}`))})}var xe={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."]},Ei=W.filter(e=>e.lifecycle==="deprecated");for(let e of Ei){let t=ue[e.alias];ue[e.alias]={...t,why:`Deprecated: use pm ${e.canonical_argv.join(" ")}. ${t.why}`}}for(let e of[xe,...Object.values(ue)])e.examples=e.examples.map(t=>{for(let n of Ei){let o=n.alias.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replaceAll(new RegExp(`\\bpm ${o}(?![\\w-])`,"g"),`pm ${n.canonical_argv.join(" ")}`)}return t});function Ts(e){let t=N(e??"");return t?Es[t]??t:""}function kn(e){let t=Ts(e);return t?ue[t]??xe:xe}function Si(e,t){let n=kn(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:ki(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Os(){let e=W.filter(({lifecycle:n})=>n==="permanent"),t=W.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(" ")} (${Yo(n)})`)].join(`
|
|
4
|
+
`)}function Rs(e,t,n,o){let a=new Set(ii);e.configureHelp({visibleCommands(r){let s=t.visibleCommands(r);return n?s.filter(l=>(pe(l)??J(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=>a.has(l.flags))}});let i=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),...i]})}function Is(e,t,n,o){let a=new Set(si("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let r=()=>`${i.formatHelp(e,i)}${o}
|
|
5
|
+
`,s=t.visibleCommands(e);for(let l of s)pe(l)===void 0&&(l.name()==="help"||a.has(l.name()))&&n.add(l);for(let l of s)pe(l)==="core"&&(n.add(l),ri(r()).within_budget||n.delete(l))}function Ai(e,t=process.argv.slice(2)){let n=e.createHelp(),o=oe(t),a=new Set;Rs(e,n,o,a);let i=Cn(t),r=xi(xe,i);e.addHelpText("after",r),o&&e.addHelpText("after",Os()),Is(e,n,a,r);for(let[d,m]of Object.entries(ue))bn(e,d,m,i);let s=N(A(t).commandPathTokens.join(" ")),l=He(s);if(l){bn(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,vt(l.accepted_flags)]},i);return}let c=wt.filter(({parent:d})=>d===s);c.length>0&&bn(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.`]},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]="2efeb172-b440-5df6-ad48-4c54087835e0")}catch{}})();function xn(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:a}of R){if(t&&!R.some(c=>c.canonical.startsWith(`${o} `)))continue;let i=e.commands.findIndex(c=>c.name()===n);if(i<0)continue;let r=e.commands[i],s=e;for(let c of a.slice(0,-1))s!==e&&s.enablePositionalOptions(),s=s.commands.find(d=>d.name()===c)??s.command(c).description(`Discover ${c} operations.`);let l=a[a.length-1];if(s.commands.some(c=>c.name()===l))throw new Error(`Cannot install canonical command ${o}: destination already exists.`);e.commands.splice(i,1),r.name(l),St(r,J(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]="15df6b29-c194-5a96-8b6b-13db3f513b55")}catch{}})();function Ot(e){let{why:t,title:n,...o}=e;return o}var $s=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ps(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!$s.has(e.code)}function $i(e){return`urn:pm-cli:error:${e}`}function k(e){return{...e,type:$i(e.code)}}var Ee={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Ti={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Oi={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},At={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ds={guide:Ee,shell:Ee,completion:Ee,"completion-statuses":Ee,"completion-tags":Ee,"completion-types":Ee,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Ti,cal:Ti,reindex:Oi,"search-advanced":Oi,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":At,"dedupe-audit":At,"dedupe-merge":At,normalize:At};function Ns(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ds[t]}function En(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Ms(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 Fs(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 Sn(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function Pi(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string")?[...e]:void 0}function X(e,t,n){if(t==="normalized_args"||t==="suggested_retry_args"){let a=Pi(n);a&&(e[t]=a);return}if(t==="parsed_positionals"){if(!Array.isArray(n))return;let a=n.map(i=>({role:typeof i?.role=="string"?i.role.trim():"",value:typeof i?.value=="string"?i.value.trim():""})).filter(i=>i.role.length>0&&i.value.length>0);a.length>0&&(e.parsed_positionals=a);return}let o=Ms(n);o&&(e[t]=o)}function Ls(e,t){if(!$a(t))return;let{requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}=t;e.token_budget={requested_tokens:n,feasible_tokens:o,minimum_feasible_tokens:a,minimum_status:i,basis:r,reason:s}}function Se(e){if(!e||typeof e!="object")return;let t={};Ls(t,e.token_budget),e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Sn(t,"attempted_command",e.attempted_command),X(t,"normalized_args",e.normalized_args),X(t,"parsed_positionals",e.parsed_positionals),X(t,"provided_fields",e.provided_fields),X(t,"missing",e.missing),X(t,"missing_required_fields",e.missing_required_fields),X(t,"suggested_flags",e.suggested_flags),X(t,"allowed_values",e.allowed_values),X(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),Sn(t,"suggested_retry",e.suggested_retry),X(t,"suggested_retry_args",e.suggested_retry_args),typeof e.retry_after_ms=="number"&&Number.isSafeInteger(e.retry_after_ms)&&e.retry_after_ms>=0&&(t.retry_after_ms=e.retry_after_ms);let n=Fs(e.fallback_candidates);return n&&(t.fallback_candidates=n),Sn(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function An(e,t,n){n&&e.push(` ${t}: ${n}`)}function fe(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function js(e){let t=Se(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(An(n,"suggested_retry",t.suggested_retry),An(n,"attempted_command",t.attempted_command),fe(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(fe(n,"provided_fields",t.provided_fields,", "),fe(n,"missing",t.missing,", "),fe(n,"missing_required_fields",t.missing_required_fields,", "),fe(n,"suggested_flags",t.suggested_flags,", "),fe(n,"allowed_values",t.allowed_values,", "),fe(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}`),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),An(n,"next_best_command",t.next_best_command),t.fallback_candidates&&t.fallback_candidates.length>0){n.push(" fallback_candidates:");for(let o of t.fallback_candidates)n.push(` - ${o.source}: ${o.command} (${o.reason})`)}return n}function Di(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...En("Next steps:",e.nextSteps))),t.push("","What happened:",` ${e.happened}`),e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...En("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...En("Verification errors:",e.verificationErrors)));let n=js(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
6
|
+
`)}function Ni(e,t){return t.previewStorage!==void 0&&(e.preview_storage=t.previewStorage),t.transactionOperation!==void 0&&(e.transaction_operation=t.transactionOperation),t.tombstone!==void 0&&(e.tombstone=t.tombstone,e.item_id=t.itemId),Ps(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 Us(e,t){if(e.flag)return e.flag;let n=o=>{let a=o.split("=",1)[0];return D([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 qs(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 Hs(e,t){if(e.policyViolations?.length)return{surface:`policy:${e.policyViolations.map(s=>s.policy_id).join(",")}`,policies:e.policyViolations,policy_violation_count:e.policyViolationCount,missing_fields:[...new Set(e.policyViolations.flatMap(s=>s.missing_fields))],exit_code:t};let n=D(e.recovery?.normalized_args??[]),o=q(n),a=o?[o.alias,...n.slice(o.canonical_argv.length)]:n,i=Us(e,a),r=qs(e,a,i);return{surface:i??e.recovery?.missing?.[0]??_n(a)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function zs(e,t){return Ni({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:Hs(e,t),...e.changed===!1?{changed:!1}:{}},e)}function On(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 _a(zs(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function Rn(e){return Ni({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,...e.changed===!1?{changed:!1}:{}},e)}function Rt(e){return e.replace(/\(outputHelp\)/g,"").trim()}function Gs(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 ge(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 Ri(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Ws(e){return _n(e?.normalized_args)}function Vs(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 Bs(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,C(s)}}}function Ks(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Tt(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function Js(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 ae(e,t,n){if(!n)return e;let o=Rt(t),a=Tt(n.code,e.code),i=Tt(n.type,$i(a)),r=ge(n.examples)??e.examples,s=ge(n.nextSteps)??e.nextSteps,l=ge(n.verification_errors)??e.verificationErrors,c=e.code==="command_failed"&&n.code?Ks(o):void 0,d=Se(n.recovery),m=d&&e.recovery?Se({...e.recovery,...d}):d??e.recovery;return{...e,code:a,changed:n.changed,type:i,title:c??e.title,happened:o.length>0?o:e.happened,required:Tt(n.required,e.required),why:Tt(n.why,e.why),examples:r,nextSteps:s,verificationErrors:l,policyViolations:n.policy_violations,policyViolationCount:n.policy_violation_count,flag:Js(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,availableDependencies:n.available_dependencies,recovery:m}}function Ys(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=ta(process.cwd(),a);return ae(k(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 Xs(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 ae(k({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 Zs(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:ae(k({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 Qs(e,t,n){if(!t.includes("is locked"))return null;let o=Pi(n?.recovery?.normalized_args),a=o?C(o):void 0,i=ae(k({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 el(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 ae(k({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 tl(e,t,n){return t.startsWith("No update flags provided")?ae(k({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 nl(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Se(n?.recovery),a=Ws(o),i=a?`pm ${a} --help`:"pm <command> --help",r=Vs(t),s=Se({...o,allowed_values:o?.allowed_values??r}),l=Bs(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 ae(k({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 In(e,t){let n=Rt(e);return(Ys(e,n,t)??Xs(e,n,t)??Zs(e,n,t)??Qs(e,n,t)??el(e,n,t)??tl(e,n,t)??nl(e,n,t))||ae(k({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 ol(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 al(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function il(e){if(!(!Array.isArray(e)||e.length===0))return C(e)}function $n(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 U(e,t={}){let n=$n(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,a=typeof e?.attemptedCommand=="string"?e.attemptedCommand:il(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Se({attempted_command:a,normalized_args:o,provided_fields:n,suggested_retry:i,suggested_retry_args:e?.suggestedRetryArgs,...t})}function Tn(e,t){return!t||e.includes(t)?e:[...e,t]}var rl=new Set(["--add","--add-json","--remove"]),sl=new Set(["command","cmd","path"]);function ll(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(rl.has(o))return o}}function cl(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"||!sl.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 C(l)}}function dl(e,t,n,o){let a=e.match(/required option '([^']+)' not specified/);if(!a)return null;let i=al(a[1]),r=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=$n(o?.providedOptionFlags),c=[i],d=ol(t,i,n),m=s?Tn(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?Tn(p,`Replay with preserved arguments: ${s}`):p,f=l&&l.length>0?Tn(u,`Already provided options: ${l.join(", ")}`):u;return k({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:U(o,{missing:c})})}function ml(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let a=o[1];return k({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:U(n,{missing:[a]})})}function pl(e,t,n){return k({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:U(t,{suggested_flags:n})})}var ul={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 fl(e){let t=ge(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function gl(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,i.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,a?`Replay with suggested correction: ${a}`:void 0].filter(l=>typeof l=="string")}function hl(e,t){if(["--dry-run","--check","--check-only","--plan","--preview"].includes(t.split("=",1)[0]))return{};if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};if(ui(t))return{};let n=e.normalizedInvocationArgs;if(n===void 0)return{};if(n.filter(i=>i===t||i.startsWith(`${t}=`)).length!==1)return{};let o=n.findIndex(i=>i===t||i.startsWith(`${t}=`));if(o<0||n.includes("--")||!n[o]?.includes("=")&&o!==n.length-1&&n[o+1]?.startsWith("-")!==!0)return{};let a=D(n.filter((i,r)=>r!==o));return{retryCommand:C(a),suggestedRetryArgs:a}}function yl(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let a=n??{},i=o[1],r=$n(a.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=hl(a,i);if(t==="update"&&(i==="--file"||i==="--doc"))return pl(i,n,r);let c=fl(a),d=gl(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 ${H(t)?.canonical??t} --help`:"pm --help --all"].filter(p=>typeof p=="string");return k({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:ul[c.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:d,recovery:U(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 _l(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 k({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:Ri([t.installCommand,...n]),nextSteps:Ri([i,...r]),recovery:U(a)})}function wl(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],a=ge(t?.unknownCommandExamples),i=ge(t?.unknownCommandNextSteps),r=Ns(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))?_l(o,r,s,l,t):k({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:U(t)})}function vl(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ge(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let a=e?.suggestedRetryCommand;return k({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 ${H(t)?.canonical??t} --help`],nextSteps:a?[`Retry with the declared hyphenated action: ${a}`]:["Choose one value from recovery.allowed_values."],recovery:U(e,{allowed_values:o,suggested_retry:a})})}function bl(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,a=ll(o);if(!a)return null;let i=cl(o);return k({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:U(n,i?{suggested_retry:i}:{})})}var Cl=new Set(["comments","docs","files","learnings","notes","test"]);function kl(e,t,n){if(!/too many arguments/i.test(e)||!Cl.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 k({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:U(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var xl=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"]),Ii=new Set(["context","ctx"]);function El(e,t,n){if(!/too many arguments/i.test(e)||!Ii.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],a=o.findIndex(c=>Ii.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(xl.has(m)){c=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let l=`pm get ${s}`;return k({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:U(n,{suggested_retry:l})})}function Pn(e,t,n,o){let a=Rt(e);return(dl(a,t,n,o)??ml(a,t,o)??yl(a,t,o)??wl(a,o)??vl(o)??kl(a,t,o)??bl(a,t,o)??El(a,t,o))||k({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:U(o)})}function Mi(e,t){let n=In(e,t);return(t?.code==="tracker_root_missing"||t?.code==="tracker_not_initialized")&&n.title==="Tracker is not initialized"&&n.recovery?.suggested_retry_args?[`Error: ${n.title}`,`Run: ${C(n.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
7
|
+
`):an(Di(n),n.required).output}function Fi(e,t){return Rn(In(e,t))}function Dn(e,t,n){return On(In(e,n),t)}function Li(e,t,n,o){let a=Pn(e,t,n,o);return an(Di(a),a.required).output}function Nn(e,t,n,o){return Rn(Pn(e,t,n,o))}function It(e,t,n,o,a){return On(Pn(e,t,n,a),o)}function ji(e,t){let n=Ui(e);return On(n,t)}function Ui(e){let t=Rt(e);return Gs(t)?k({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."]}):k({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 qi(e){return Rn(Ui(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]="f3c73e79-571d-5a1b-94cd-db8c1b8ca7a4")}catch{}})();var Be=Qo.join("|"),Sl={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"},Al={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"]}},Hi=["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 Tl(e,t){let n=Al[e];if(!n)return[];let o=j(t);for(let[a,i]of Object.entries(n))if(j(a)===o)return i;return[]}function Mn(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:ce(c,d=>`${JSON.stringify(d,null,2)}
|
|
8
8
|
`),null,2)}let o=n.map(r=>`- ${r.layer}:${r.name}: ${r.error}`).join(`
|
|
9
9
|
`),a=n.find(r=>r.declared_command_match===!0);if(!a)return`${e}
|
|
10
10
|
Extension activation failures:
|
|
@@ -16,23 +16,23 @@ ${i}`:""}
|
|
|
16
16
|
|
|
17
17
|
${e}
|
|
18
18
|
Extension activation failures:
|
|
19
|
-
${o}`}function Fn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function
|
|
20
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function
|
|
21
|
-
`):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
|
|
19
|
+
${o}`}function Fn(e){return A(e).commandPathTokens[0]??x(e)??"<command>"}function Vi(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let a=o.shift();if(!a)continue;let i=N(E(a)),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i),o.push(...a.commands)}for(let a of t.keys()){let i=N(a),r=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!r&&n.add(i)}return[...n].sort((a,i)=>a.localeCompare(i))}function zi(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let a=n.split(" ");if(n===o)return 0;if(a.includes(o))return 1;if(a.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let s of a){let l=en(s,o,i);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?4+r:Number.POSITIVE_INFINITY}function Gi(e){return j(e).slice(2).replace(/-/g,"")}function Ln(e){return C(e)}function Ol(e){let t=H(e)?.canonical??Yt[e]??e,n=t.split(" ")[0]?.trim().toLowerCase();if(!n)return null;let o=Sl[n];return o?{packageAlias:o,canonicalPath:t,installCommand:`pm package install ${o} --project`}:null}function Wi(e){let t=ci(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Rl(e,t){let n=Wi(e);if(n.length===0)return[];let o=[];for(let a of t.values()){let i=new Set,r=a.source;if(r)for(let s of[r.name,r.package]){let l=Wi(s??"");l.length>0&&i.add(l)}i.size!==0&&[...i].some(s=>s===n||s.includes(n)||n.includes(s))&&o.push(a.command)}return[...new Set(o)].sort((a,i)=>a.localeCompare(i))}function Ke(e,t){let n=new Set,o=t??ne(e);for(let a of o){a.flag.startsWith("--")&&n.add(j(a.flag));for(let i of a.aliases??[])i.startsWith("--")&&n.add(j(i))}return[...n].sort((a,i)=>a.localeCompare(i))}function Il(e,t){if(!e.startsWith("--"))return[];let n=Gi(e);if(n.length===0)return[];let o=n.length>=8?2:1,a=[];for(let i of t){let r=Gi(i);if(r===n)continue;if(n.length>=3&&r.startsWith(n)){a.push({flag:i,rank:0,distance:r.length-n.length});continue}let s=en(n,r,o);s===null||s<=0||a.push({flag:i,rank:1,distance:s})}return a.sort((i,r)=>i.rank!==r.rank?i.rank-r.rank:i.distance!==r.distance?i.distance-r.distance:i.flag.localeCompare(r.flag)).map(i=>i.flag).slice(0,3)}var $t,$l=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 Pl(){if($t)return $t;let e=new Map;for(let t of Le)if(!$l.has(t))for(let n of Ke(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return $t=e,$t}function Dl(e,t){if(!e.startsWith("--"))return[];let n=Pl().get(j(e));if(!n)return[];let o=t?.trim().toLowerCase(),a=new Set(Ke(o));return[...new Set(n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:Ke(i).filter(r=>a.has(r)).length})).sort((i,r)=>i.sharedFlagCount!==r.sharedFlagCount?r.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(r.command)).map(({command:i})=>H(i)?.canonical??i))]}function Nl(e,t,n){for(let o=0;o<e.length;o+=1){let a=e[o];if(!a.startsWith("--"))continue;let i=a.indexOf("="),r=i>=0?a.slice(0,i):a;if(j(r)!==j(t))continue;let s=[...e];return s[o]=i>=0?`${n}${a.slice(i)}`:n,s}}function Ml(e){let t=new Set(e.commandPaths),n=i=>Math.min(zi(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?zi(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,a=(i,r)=>{if(!Number.isFinite(r)||!t.has(i))return;let s=o.get(i);(s===void 0||r<s)&&o.set(i,r)};for(let i of e.commandPaths)a(i,n(i));for(let[i,r]of Object.entries(Yt))i!=="read"&&a(r,n(i));return[...o.entries()].sort(([i,r],[s,l])=>r!==l?r-l:i.localeCompare(s)).map(([i])=>i)}function Fl(e){let t=H(e.normalizedUnknown),n=yi(e.commandPaths,e.primaryToken),o=Ml(e),a=Rl(e.primaryToken,e.extensionDescriptors).filter(i=>e.commandPaths.includes(i));return wn([...t&&e.commandPaths.includes(t.canonical)?[t.canonical_argv.join(" ")]:[],...n,...o,...a],e.commandPaths,e.primaryToken).filter(i=>!e.normalizedUnknown.includes(" ")||i!==e.normalizedUnknown)}function Ll(e){return[...new Set(e.map(t=>t.split(" ")[0]).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function jl(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 Ul(e,t,n){let o=K([...t]),a=[];for(;o!==void 0;){if(a.push(t[o]),t[o]===e)return a.join(" ");if(!n.includes(a.join(" ")))return e;let i=K(t.slice(o+1));o=i===void 0?void 0:o+1+i}return e}function ql(e,t){if(!e)return;let n=M([...t]);return[...n.path?["--pm-path",S(process.cwd(),n.path)]:[],...n.noExtensions?["--no-extensions"]:[],...e.split(" "),"--help"]}function jn(e,t,n,o=[]){let a=e.match(/unknown command '([^']+)'/i);if(!a||typeof a[1]!="string")return;let i=Vi(t,n),r=Ul(a[1],o,i),s=N(r);if(s.length===0||i.length===0)return;let l=Ol(s);if(l&&!i.includes(l.canonicalPath.split(" ")[0]))return{unknownCommandExamples:[l.installCommand,`pm ${l.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${s}" is provided by the "${l.packageAlias}" package. Install it with: ${l.installCommand}. Command after installation: pm ${l.canonicalPath}.`],suggestedRetryCommand:l.installCommand};let c=s.split(" ")[0],d=Fl({commandPaths:i,normalizedUnknown:s,primaryToken:c,extensionDescriptors:n}),m=Ll(i),p=hi(s,i),u=ql(p,o),f=[...new Set([...p?[p]:[],...d.length>0?d:wn(m,i)])].slice(0,3),h=jl(f,d.length>0),v=d.length>0?`Did you mean: ${f.join(", ")}?`:null;return{...u?{suggestedRetryCommand:C(u),suggestedRetryArgs:u}:{},unknownCommandExamples:u?[C(u),...h.slice(1)]:h,unknownCommandNextSteps:[...v?[v]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...v?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function Hl(e){return Array.from(new Set(e))}function zl(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
20
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Gl(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 Wl(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function Ae(e,t){if(t.length===0)return!0;let n=e;for(let[o,a]of t.entries()){let i=Wl(n,a);if(!i){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=i}return!0}async function Vl(e,t,n,o){try{let a=S(process.cwd(),e.path);if(!await V(B(a)))return{allowedTypes:Be};let i=await $(a),r=e.noExtensions?void 0:se(),s=re(i,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 _t(a,d,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Be,pmRoot:a,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Be}}}function Bl(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Hl([...Tl(t,n[1]),...Il(n[1],Ke(t))]).filter(r=>fi(n[1],r)):void 0,a=n?Dl(n[1],t):[],i=n!==null&&Ke(t).includes(j(n[1]));return{match:n,suggestions:o,otherCommands:a,scope:i?"declared_on_path":a.length>0?"declared_elsewhere":"declared_nowhere"}}function Kl(e,t,n){if(!t||!n||n.length===0)return;let o=Nl(e,t[1],n[0]);return o?Ln(o):void 0}function Jl(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Gl(zl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let a=x(t);if(a)return gi(t,a,[o])}function Yl(e,t){if(!/too many arguments/i.test(e))return;let n=K(t),o=q(t.slice(n));if(o?.alias!=="schema")return;let a=n+o.canonical_argv.length-1,i=t[a+1]?.trim().toLowerCase(),r=t[a+2]?.trim().toLowerCase();if(!i||!r)return;let s=`${i}-${r}`;if(!Hi.includes(s))return;let l=[...t.slice(0,a+1),s,...t.slice(a+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${i} ${r}`,unknownSubcommandAllowedValues:[...Hi],suggestedRetryCommand:Ln(l)}}function Xl(e,t,n,o){let a=K(t),i=q(t.slice(a))?.alias??x(t);if(!/unknown option /i.test(e)||i===void 0)return i;let r=H(i)?.canonical??i;return Le.some(s=>s===i)||Vi(n,o).includes(r)?i:void 0}async function Je(e,t,n,o={},a=process.argv.slice(2)){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",r=Ge([...a]).argv,s=M(r),l=Xl(i,r,t,n),c=Ln(r),d=Y(r),m=await Vl(s,i,r,l),p=m.allowedTypes,u=jn(i,t,n,r),f=Bl(i,l),h=Yl(i,r),v=h?.suggestedRetryCommand??Kl(r,f.match,f.suggestions)??Jl(i,r);return{message:i,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:v,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function Un(e,t,n,o={},a=process.argv.slice(2)){let i=await Je(e,t,n,o,a),{message:r,commandName:s,allowedTypes:l,...c}=i,d=Li(r,s,l,c),m=await ya("help_format",{message:d,command:s,allowed_types:l});return m.handled&&typeof m.result=="string"?m.result:d}async function qn(e,t,n,o=!1,a={},i=process.argv.slice(2)){let r=await Je(e,t,n,a,i),s=It(r.message,r.commandName,r.allowedTypes,g.USAGE,r),l=o?Ot(s):s,c=M(r.normalizedInvocationArgs).tokenAccounting===!0;return JSON.stringify(c?ce(l,d=>`${JSON.stringify(d,null,2)}
|
|
21
|
+
`):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 Bi(e,t,n,o){if(n)return null;let a=e.some(r=>r==="--for"||r.startsWith("--for=")),i=x(e)==="contracts"&&e.includes("--full");return a||i?await o(t):null}import{Option as Zl}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]="c077f66e-bac4-58af-92cd-a19c30ada04d")}catch{}})();function w(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ji(e,t){let n=new Map;for(let o of e){let a=w(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let r=w(i.command),s=r.split(" "),l=s.at(-1),c=s.slice(1).join(" "),d=c?`${s[0]}-${l} ${c}`:`${s[0]}-${l}`;if(l&&a===d){n.set(a,r);break}}}return n}function Hn(e,t,n,o){if(!t||!n)return;let a,i=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>i&&p.every((u,f)=>c[f]===u)&&(a=m,i=p.length)}}let r=a?.flags.find(s=>s.long===n||s.short===n);if(r)return Ql(r).takesValue}function Ye(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Te(e){return typeof e=="boolean"?e:void 0}function Ql(e){let t=we(e);return{takesValue:t.value_arity!=="none",valueName:t.value_name}}function ec(e){let t=ee(e.long);if(!t||!t.startsWith("--")||t.length<3)return null;let n=zn(e);if(!n)return null;let o=Ye(e.description)??"Extension-provided option.",a=[];Te(e.required)===!0&&a.push("required"),Te(e.enabled)===!1&&a.push("disabled");let i=a.length>0?` [${a.join(", ")}]`:"";return`${n} ${o}${i}`}function Yi(e){let t=[...new Set(e.map(ec).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
22
22
|
Extension-provided flags:
|
|
23
23
|
${t.join(`
|
|
24
|
-
`)}`}function
|
|
24
|
+
`)}`}function Xi(e){let t=new Map;for(let a of e){let i=w(a.target_command);if(i.length===0)continue;let r=t.get(i)??[];r.push(...a.flags),t.set(i,r)}let n=[...t.entries()].sort(([a],[i])=>a.localeCompare(i)),o=new Map;for(let[a,i]of n){let r=Yi(i);r&&o.set(a,r)}return o}function Zi(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Ki(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let a=o.trim();a.length===0||n.has(a)||(n.add(a),t.push(a))}return t}function tc(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 nc(e){let t=new Map;for(let n of e){let o=w(n.command);if(o.length===0)continue;let a=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,i=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:Zi(o,n.action),description:a,intent:i,examples:Ki(n.examples),failure_hints:Ki(n.failure_hints),arguments:tc(n.arguments),flags:[],tier:n.tier??"standard",family:n.family??"extensions",source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function oc(e){let t=new Map;for(let n of e){let o=w(n.target_command);if(o.length===0)continue;let a=t.get(o)??[];a.push(...n.flags),t.set(o,a)}return t}function ac(e,t,n){let o=new Set;for(let a of e){let i=w(a);i.length>0&&o.add(i)}for(let a of t.keys())o.add(a);for(let a of n.keys())o.add(a);return o}function ic(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function Qi(e,t,n,o=new Map){let a=nc(t),i=oc(n),r=ac(e,a,i),s=new Map,l=[...r].sort((c,d)=>c.localeCompare(d));for(let c of l){let d=ic(c,a,o)??a.get(c),m=i.get(c)??(d?i.get(d.command):void 0)??[];if(d){s.set(c,{...d,command:c,flags:m});continue}s.set(c,{command:c,action:Zi(c,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function rc(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function er(e,t){for(let n of t.arguments)e.argument(rc(n),n.description??"Extension argument.")}function sc(e){if(Te(e.visible)===!1)return null;let t=ee(e.long),n=Ye(e.short),o=n&&n.startsWith("-")&&!n.startsWith("--")?n:null,a=t&&t.startsWith("--")&&t.length>2?t:null,i=[o,a].filter(r=>r!==null);return i.length>0?i:null}function zn(e){let t=sc(e);if(!t)return null;let{value_name:n,value_arity:o}=we(e),a=n?o==="optional"?` [${n}]`:` <${n}>`:"";return`${t.join(", ")}${a}`}function lc(e){return zn(e)}function tr(e){let t=Ye(e.description)??"Extension-provided option.",n=[];Te(e.required)===!0&&n.push("required"),Te(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function nr(e,t){let n=ee(t.long),o=Ye(t.short);return e.options.some(a=>{let i=a;return n!==null&&i.long===n||o!==null&&i.short===o})}function Gn(e,t){for(let n of t){if(nr(e,n))continue;let o=lc(n);if(!o)continue;let a=tr(n),i=new Zl(o,a);if(i.negate=!1,n.list!==!0){e.addOption(i);continue}e.addOption(i.argParser((r,s=[])=>[...Array.isArray(s)?s:[s],r]))}}function Wn(e,t){return Yi(t.filter(n=>!nr(e,n)))}function cc(e){let t=zn(e);if(!t)return null;let n=ee(e.long),o=Ye(e.short),a=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,r=we(e),s=Te(e.required)===!0;return{flags:t,long:a,short:i,description:tr(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}}function or(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let a=cc(o);!a||n.has(a.flags)||(n.add(a.flags),t.push(a))}return t}function ar(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(a=>a.flags));for(let a of t)o.has(a.flags)||(o.add(a.flags),n.push(a));return n}function ir(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:`
|
|
25
25
|
Extension command metadata:
|
|
26
26
|
${t.join(`
|
|
27
|
-
`)}`}function Vn(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 Xe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Vn(o).includes(n))??null}function Z(e,t){let n=e;for(let o of t){let a=Xe(n,o);if(!a)return null;n=a}return n}var Bn=new WeakSet;function ir(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&&R.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let i=Xe(n,a);if(i){n=i;continue}let r=n.command(a);Bn.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 cc(e,t){let n=t.join(" "),o=R.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=Xe(a,r);if(!s)return null;i.push(r);let l=s.commands.length>0||R.some(c=>c.canonical.startsWith(`${i.join(" ")} `));if(!Bn.has(s)&&(i.length===t.length||!l))return{core_path:i.join(" "),extension_path:t.join(" ")};a=s}return null}function dc(e,t,n,o,a=!1){let i=t.split(" ").filter(d=>d.length>0),r=cc(e,i),s=Z(e,i),l=R.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bn.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 rr(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=dc(e,i,o,n.get(i),t.includes(i));return r?(a(r),!o.has(i)&&Z(e,i.split(" "))!==null):!0})}function sr(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 mc=new Set(["__proto__","prototype","constructor"]),Kn=Symbol("looseOptionOccurrences");function Ze(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function pc(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 Jn(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 Pt(e){return mc.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 aa(t)}function Qe(e){let t=[],n=ee(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let a=Ze(n.slice(2));a.length>0&&!Pt(a)&&t.push(a)}if(o.startsWith("-")&&!o.startsWith("--")){let a=Ze(o.slice(1));a.length>0&&!Pt(a)&&t.push(a)}return[...new Set(t)]}function cr(e){let t=new Set;for(let n of e)for(let o of Qe(n))t.add(o);return t}function uc(e){let t=ee(e.long)??"";if(t.startsWith("--")){let n=Ze(t.slice(2));if(n.length>0&&!Pt(n))return n}return Qe(e)[0]??null}function dr(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 Yn(e,t,n){if(t.length===0)return;let o=new Set,a=new Map,i=[],r=[];for(let s of t){let l=Qe(s),c=dr(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 b(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=a.get(s);if(l)throw new b(`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 b(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function fc(e){return typeof e=="string"||e==null?e:String(e)}function gc(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 hc(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 yc={string:fc,number:gc,boolean:hc};function Oe(e,t){return Array.isArray(e)?e.map(n=>Oe(n,t)):yc[t](e)}function mr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(a=>a!=null&&a!==""):tn(e);return t?o.map(a=>Oe(a,t)):o}function _c(e,t,n,o){return n?mr(e,t,o):t?Oe(e,t):e}function wc(e,t,n){let o=e[Kn];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 pr(e){return we(e).value_arity==="none"}function Xn(e,t,n,o,a){let i=dr(e),r=a?` for extension command '${a}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new b(`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 Zn(e,t){return e.value_validation==="strict"&&t!=="string"}function vc(e,t){let n=e[Kn];if(!n)return[];let o=new Set(t);return n.filter(a=>o.has(a.key))}function bc(e,t,n,o){if(pr(e))for(let a of vc(n,t)){if(a.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?tn(a.value):[a.value];for(let r of i){let s=pt(Oe(r,"boolean"),"boolean");s!==null&&Xn(e,"boolean",r,s.expected,o)}}}function Cc(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=pt(s,t);Xn(e,t,s,l.expected,a)}}function Qn(e,t,n,o){if(!Zn(e,n))return t;let a=n==="boolean"&&pr(e),i=r=>{let s=pt(r,n);return s===null?r:a&&typeof r=="string"?!0:Xn(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(i):i(t)}function kc(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 ur(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=uc(i);r&&xc(a,i,r,n,o)}return a}function xc(e,t,n,o,a){let i=t.list===!0,r=Qe(t),s=lr(t);s&&!i&&Ec(e,t,n,r,s,a),kc(e,n,r,i);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=_c(t.default,s,i,l));return}if(s==="boolean"&&Zn(t,s)&&bc(t,r,o,a),i){e[n]=Sc(t,r,o,e[n],s,l,a);return}s&&(e[n]=Qn(t,Oe(e[n],s),s,a))}function Ec(e,t,n,o,a,i){for(let r of o)r!==n&&Object.hasOwn(e,r)&&Qn(t,Oe(e[r],a),a,i)}function Sc(e,t,n,o,a,i,r){let s=wc(n,t,o);a&&Zn(e,a)&&Cc(e,a,s,i,r);let l=mr(s,a,i);return a?Qn(e,l,a,r):l}function fr(e){let t=Object.create(null),n=[];Object.defineProperty(t,Kn,{value:n});let o=0;for(;o<e.length;){let a=Jn(e,o);if(!a){o+=1;continue}let i=Ze(a.key);if(i.length===0||Pt(i)){o+=a.consumed;continue}pc(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=Jn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function eo(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 Qe(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=Jn(e,i);if(r){let s=Ze(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 Re 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 to(e,t={},n=[]){let o={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...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(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(a){return[{layer:"runtime",name:"extension-loader",error:a instanceof Error?a.message:String(a)}]}}async function hr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let a=await to(t,n,o),i={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...n};try{let r=i.resolveImplicitPmRoot(process.cwd());if(Re.resolve(r)===Re.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=${Re.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Re.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 ${Re.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Re.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 yr={core:0,standard:1,full:2,internal:3};function _r(e,t,n=!0){let o=t.get(I(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)=>yr[l.tier]<yr[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 wr(e,t){if(t.length===0)return e;let n=Z(e,t);if(n)return n;let o=t.join(" ");if(I(o)!==o||!Le.some(a=>a===o)&&!Ma(o)&&!He(o)&&!Ae(e,t))return null;for(let a=t.length-1;a>0;a-=1){let i=Z(e,t.slice(0,a));if(i)return i}return t.length===1?e:null}function Ac(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function vr(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 Tc(e){let t=new Map;for(let n of e){let o=n,a=vr(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 Oc(e){return k(e)}function Rc(e){let t=e.options??[],n=Tc(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=vr(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:Ac(i),variadic:a.variadic===!0,required:m,aliases:l,alias_for:d};return a.defaultValue!==void 0&&(f.default_value=a.defaultValue),f})}function Ic(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 $c(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 Pc(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||(pe(a)??J(a.name()))!=="internal").map(a=>{let i=N(E(a)),r=i,s=pe(a),l=_r(i,t,s!==void 0),c=W.find(({alias:d})=>d===i);return{name:a.name().trim(),aliases:Vn(a),description:a.description().trim(),tier:l?.tier??s??J(r),family:l?.family??Ct(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((a,i)=>a.name.localeCompare(i.name))}function Dc(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 Nc(e,t,n,o,a){let i=e!==void 0&&kn(e)===xe,r=i?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Si(e,n),s=a?"positional_action":o?.intent||o?.description?"extension":i?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Dc(n,r,o),intentSource:s}}function Mc(e,t){return e===void 0?null:t?.tier??J(e)}function Fc(e,t){return e===void 0?null:t?.family??Ct(e)}function Lc(e,t,n){if(!(t!==e||!n))return W.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:wr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function jc(e,t,n,o,a=new Map,i=!1){if(!e){let s=$c(t),l=Pc(t,a,i),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...wt.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:J(n.split(" ")[0]),family:Ct(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 Uc(e,t,n,o,a){let i=Cn(n),r=oe(n),s=N(E(t)),l=N(o.join(" ")),c=l.length>s.length?l:s,d=He(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?a.get(I(p)):void 0,h=p?_r(p,a,pe(t)!==void 0):void 0,{narrative:w,intentSource:P}=Nc(p,t.description().trim(),i,f,d!==void 0),z=Ic(or(Rc(t),nr(f))),Q=jc(d,t,m,z,a,r),G=Lc(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:Mc(u,h),capability_family:Fc(u,h),description:d?.description??t.description(),usage:Q.usage,intent:d?.description??w.intent,intent_source:P,examples:d?[d.example]:w.examples,tips:d?[vt(d.accepted_flags)]:w.tips,arguments:Q.arguments,options:Q.options,subcommands:Q.subcommands,has_subcommands:Q.subcommands.length>0,...G===void 0?{}:{command_aliases:G}}}async function br(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=wr(e,i.commandPathTokens);if(!r){if(!a.quiet){let s=`unknown command '${i.commandPathTokens.join(" ")}'`,l=jn(s,e,n,t),c=It(s,"help",Be,g.USAGE,{...l,attemptedCommand:Oc(t),normalizedInvocationArgs:[...t],providedOptionFlags:Y(t)}),d=a.tokenAccounting?ce(c,m=>`${JSON.stringify(m,null,2)}
|
|
27
|
+
`)}`}function Vn(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 Xe(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Vn(o).includes(n))??null}function Z(e,t){let n=e;for(let o of t){let a=Xe(n,o);if(!a)return null;n=a}return n}var Bn=new WeakSet;function rr(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&&R.some(s=>s.canonical===t.join(" "))&&n.enablePositionalOptions();let i=Xe(n,a);if(i){n=i;continue}let r=n.command(a);Bn.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 dc(e,t){let n=t.join(" "),o=R.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=Xe(a,r);if(!s)return null;i.push(r);let l=s.commands.length>0||R.some(c=>c.canonical.startsWith(`${i.join(" ")} `));if(!Bn.has(s)&&(i.length===t.length||!l))return{core_path:i.join(" "),extension_path:t.join(" ")};a=s}return null}function mc(e,t,n,o,a=!1){let i=t.split(" ").filter(d=>d.length>0),r=dc(e,i),s=Z(e,i),l=R.some(d=>d.canonical===t&&d.alias===o?.action&&!e.commands.some(m=>m.name()===d.alias)&&(s===null||Bn.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 sr(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=mc(e,i,o,n.get(i),t.includes(i));return r?(a(r),!o.has(i)&&Z(e,i.split(" "))!==null):!0})}function lr(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 pc=new Set(["__proto__","prototype","constructor"]),Kn=Symbol("looseOptionOccurrences");function Ze(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(t,n)=>n.toUpperCase())}function uc(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 Jn(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 Pt(e){return pc.has(e)}function cr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return aa(t)}function Qe(e){let t=[],n=ee(e.long)??"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let a=Ze(n.slice(2));a.length>0&&!Pt(a)&&t.push(a)}if(o.startsWith("-")&&!o.startsWith("--")){let a=Ze(o.slice(1));a.length>0&&!Pt(a)&&t.push(a)}return[...new Set(t)]}function dr(e){let t=new Set;for(let n of e)for(let o of Qe(n))t.add(o);return t}function fc(e){let t=ee(e.long)??"";if(t.startsWith("--")){let n=Ze(t.slice(2));if(n.length>0&&!Pt(n))return n}return Qe(e)[0]??null}function mr(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 Yn(e,t,n){if(t.length===0)return;let o=new Set,a=new Map,i=[],r=[];for(let s of t){let l=Qe(s),c=mr(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 b(`Unknown option '--${s}' for extension command '${n}'.${c}`,g.USAGE)}let l=a.get(s);if(l)throw new b(`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 b(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function gc(e){return typeof e=="string"||e==null?e:String(e)}function hc(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 yc(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 _c={string:gc,number:hc,boolean:yc};function Oe(e,t){return Array.isArray(e)?e.map(n=>Oe(n,t)):_c[t](e)}function pr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(a=>a!=null&&a!==""):tn(e);return t?o.map(a=>Oe(a,t)):o}function wc(e,t,n,o){return n?pr(e,t,o):t?Oe(e,t):e}function vc(e,t,n){let o=e[Kn];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 ur(e){return we(e).value_arity==="none"}function Xn(e,t,n,o,a){let i=mr(e),r=a?` for extension command '${a}'`:"",s=n===!0?"no value":JSON.stringify(n);throw new b(`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 Zn(e,t){return e.value_validation==="strict"&&t!=="string"}function bc(e,t){let n=e[Kn];if(!n)return[];let o=new Set(t);return n.filter(a=>o.has(a.key))}function Cc(e,t,n,o){if(ur(e))for(let a of bc(n,t)){if(a.attached!==!0)continue;let i=e.list===!0&&e.repeatable!==!0?tn(a.value):[a.value];for(let r of i){let s=pt(Oe(r,"boolean"),"boolean");s!==null&&Xn(e,"boolean",r,s.expected,o)}}}function kc(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=pt(s,t);Xn(e,t,s,l.expected,a)}}function Qn(e,t,n,o){if(!Zn(e,n))return t;let a=n==="boolean"&&ur(e),i=r=>{let s=pt(r,n);return s===null?r:a&&typeof r=="string"?!0:Xn(e,n,r,s.expected,o)};return Array.isArray(t)?t.map(i):i(t)}function xc(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 fr(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=fc(i);r&&Ec(a,i,r,n,o)}return a}function Ec(e,t,n,o,a){let i=t.list===!0,r=Qe(t),s=cr(t);s&&!i&&Sc(e,t,n,r,s,a),xc(e,n,r,i);let l=t.repeatable===!0;if(!Object.hasOwn(e,n)){t.default!==void 0&&(e[n]=wc(t.default,s,i,l));return}if(s==="boolean"&&Zn(t,s)&&Cc(t,r,o,a),i){e[n]=Ac(t,r,o,e[n],s,l,a);return}s&&(e[n]=Qn(t,Oe(e[n],s),s,a))}function Sc(e,t,n,o,a,i){for(let r of o)r!==n&&Object.hasOwn(e,r)&&Qn(t,Oe(e[r],a),a,i)}function Ac(e,t,n,o,a,i,r){let s=vc(n,t,o);a&&Zn(e,a)&&kc(e,a,s,i,r);let l=pr(s,a,i);return a?Qn(e,l,a,r):l}function gr(e){let t=Object.create(null),n=[];Object.defineProperty(t,Kn,{value:n});let o=0;for(;o<e.length;){let a=Jn(e,o);if(!a){o+=1;continue}let i=Ze(a.key);if(i.length===0||Pt(i)){o+=a.consumed;continue}uc(t,i,a.value),n.push({...a,key:i}),o+=a.consumed}return t}function hr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Jn(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function eo(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let r of t){let s=cr(r);for(let l of Qe(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=Jn(e,i);if(r){let s=Ze(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 Re 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 to(e,t={},n=[]){let o={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...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(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(a){return[{layer:"runtime",name:"extension-loader",error:a instanceof Error?a.message:String(a)}]}}async function yr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let a=await to(t,n,o),i={readSettings:$,loadExtensions:je,activateExtensions:Ue,resolveImplicitPmRoot:Qt,...n};try{let r=i.resolveImplicitPmRoot(process.cwd());if(Re.resolve(r)===Re.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=${Re.resolve(t)} extension_discovery_root=${c.roots.project}; cwd_storage_root=${Re.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 ${Re.resolve(r)}, or install the extension into the selected tracker with "pm --pm-path ${Re.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 _r={core:0,standard:1,full:2,internal:3};function wr(e,t,n=!0){let o=t.get(I(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)=>_r[l.tier]<_r[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 vr(e,t){if(t.length===0)return e;let n=Z(e,t);if(n)return n;let o=t.join(" ");if(I(o)!==o||!Le.some(a=>a===o)&&!Ma(o)&&!He(o)&&!Ae(e,t))return null;for(let a=t.length-1;a>0;a-=1){let i=Z(e,t.slice(0,a));if(i)return i}return t.length===1?e:null}function Tc(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function br(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 Oc(e){let t=new Map;for(let n of e){let o=n,a=br(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 Rc(e){return C(e)}function Ic(e){let t=e.options??[],n=Oc(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=br(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:Tc(i),variadic:a.variadic===!0,required:m,aliases:l,alias_for:d};return a.defaultValue!==void 0&&(f.default_value=a.defaultValue),f})}function $c(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 Pc(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 Dc(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||(pe(a)??J(a.name()))!=="internal").map(a=>{let i=N(E(a)),r=i,s=pe(a),l=wr(i,t,s!==void 0),c=W.find(({alias:d})=>d===i);return{name:a.name().trim(),aliases:Vn(a),description:a.description().trim(),tier:l?.tier??s??J(r),family:l?.family??xt(r),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((a,i)=>a.name.localeCompare(i.name))}function Nc(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 Mc(e,t,n,o,a){let i=e!==void 0&&kn(e)===xe,r=i?{intent:t,examples:[`pm ${e} --help`],tips:[],detail_mode:n}:Si(e,n),s=a?"positional_action":o?.intent||o?.description?"extension":i?t?"command_description":"unavailable":e?"help_bundle":"root_help_bundle";return{narrative:Nc(n,r,o),intentSource:s}}function Fc(e,t){return e===void 0?null:t?.tier??J(e)}function Lc(e,t){return e===void 0?null:t?.family??xt(e)}function jc(e,t,n){if(!(t!==e||!n))return W.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],available:vr(e,o.canonical.split(" "))!==null,lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Uc(e,t,n,o,a=new Map,i=!1){if(!e){let s=Pc(t),l=Dc(t,a,i),c=new Set(l.map(({name:d})=>d));return{arguments:s,options:o,subcommands:[...l,...wt.filter(({parent:d,action:m})=>d===n&&!c.has(m)).map(({action:d,description:m})=>({name:d,aliases:[],description:m,tier:J(n.split(" ")[0]),family:xt(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 qc(e,t,n,o,a){let i=Cn(n),r=oe(n),s=N(E(t)),l=N(o.join(" ")),c=l.length>s.length?l:s,d=He(c),m=d?.command??s,p=m.length>0?m:void 0,u=p,f=p?a.get(I(p)):void 0,h=p?wr(p,a,pe(t)!==void 0):void 0,{narrative:v,intentSource:P}=Mc(p,t.description().trim(),i,f,d!==void 0),z=$c(ar(Ic(t),or(f))),Q=Uc(d,t,m,z,a,r),G=jc(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:Fc(u,h),capability_family:Lc(u,h),description:d?.description??t.description(),usage:Q.usage,intent:d?.description??v.intent,intent_source:P,examples:d?[d.example]:v.examples,tips:d?[vt(d.accepted_flags)]:v.tips,arguments:Q.arguments,options:Q.options,subcommands:Q.subcommands,has_subcommands:Q.subcommands.length>0,...G===void 0?{}:{command_aliases:G}}}async function Cr(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=vr(e,i.commandPathTokens);if(!r){if(!a.quiet){let s=`unknown command '${i.commandPathTokens.join(" ")}'`,l=jn(s,e,n,t),c=It(s,"help",Be,g.USAGE,{...l,attemptedCommand:Rc(t),normalizedInvocationArgs:[...t],providedOptionFlags:Y(t)}),d=a.tokenAccounting?ce(c,m=>`${JSON.stringify(m,null,2)}
|
|
28
28
|
`):c;be(`${JSON.stringify(d,null,2)}
|
|
29
|
-
`)}return process.exitCode=g.USAGE,!0}if(!a.quiet){let s=
|
|
30
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
31
|
-
`)}function
|
|
32
|
-
`)}let i=n.indexOf("--"),r=i<0?n:n.slice(0,i),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=
|
|
33
|
-
`)}function Cr(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let a=Xe(e,o);a&&a.addHelpText("after",Wc(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]="714821f9-dd8f-5958-a751-29e8dfc06471")}catch{}})();function Vc(e,t){return Fe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function Bc(e){return Fe(e.status)?.toLowerCase()??"pending"}function Kc(e){return e.mandatory===!0}function Jc(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 Er(e){let t=[];return e.forEach((n,o)=>{if(!Kc(n.definition))return;let a=Bc(n.definition);a!=="applied"&&t.push({layer:n.layer,name:n.name,id:Vc(n.definition,o),status:a})}),t.sort(Jc),t}function kr(e){return Array.isArray(e)&&e.length>0}var Yc=new Set(["create","beads import","todos import"]),Xc=new Set(["restore","update","close","delete","append","claim","release"]),Zc=new Set(["comments","notes","learnings"]),Qc=new Set(["files","docs","test"]),ed=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 no(e,t){let n=t.force===!0;return Yc.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Xc.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Zc.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:Qc.has(e)?{isMutation:kr(t.add)||kr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function td(e,t,n){if(no(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Xa(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(a=>ed.has(a.trim().toLowerCase())):!1}function xr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function nd(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(Fe(t[1])||a.push("source"),Fe(n.to)||a.push("--to"),a.length!==0)throw new b(`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 od(e,t,n,o,a){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||xr(n.status)!==xr(a.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let r=re(a,se()),s=await _t(o,i,a.id_prefix,a.item_format,r.type_to_folder);if(!s)return;let l=await Pa(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)||_(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function oo(e,t,n,o,a){if(!td(e,t,n)||(nd(e,t,n),!await V(B(a))))return;let i=await Ce(a);o.json!==!0&&await od(e,t,n,a,i.settings);let r=Ya({author:ht(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)_(`warning:${s}`)}function Sr(e,t,n){if(n.length===0)return;let o=no(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 b(`Write command "${e}" blocked by unresolved mandatory extension migrations (${a.join(",")}). ${i}`,g.CONFLICT)}async function ao(e,t,n,o){if(!no(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(B(n)))return;let{settings:a,metadata:i,warnings:r}=await Ce(n);for(let s of r)_(`warning:${s}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Ra(a),await Ia(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let s=re(a,se());await Za(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 io(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=v(n);o.length!==0&&t.push(o)}return t}function $e(e){let t=v(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(a=>a.length>0);for(let a of io(e.commandArgs))o.push(...a.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(a=>[a,I(a)]))]}function ro(e,t){let n=v(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 Nt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...T(n.commands),...T(n.command_handlers),...T(n.command_overrides),...T(n.flag_commands),...T(n.parser_overrides),...Ar(n.preflight_ownership),...Ar(n.renderer_ownership)]:[]}function T(e){return e??[]}function Ar(e){return T(e).flatMap(t=>t.commands)}function et(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Tr=new Set(["hooks","parser","preflight","renderers"]),Or=new Set(["commands","schema","services","importers"]),ad=new Set(["reindex","search","search-advanced"]),id=new Set(["--template"]);function Ie(e,t){for(let n of t)if(e.has(n))return!0;return!1}function so(e){let t=v(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return ad.has(n??t)}function lo(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 Mt(e){return v(e.commandPath??"")==="create"&&lo(e,id)}function co(e){return e.some(t=>{let n=v(t);return n==="templates"||n.startsWith("templates ")})}function Dt(e,t){return e.some(n=>ro(n,t))||Mt(t)&&co(e)}function mo(e){return[T(e.hooks).length,(e.preflight_overrides??0)-T(e.preflight_ownership).length,T(e.item_types).length,T(e.item_fields).length,T(e.relationship_kinds).length,T(e.service_overrides).length,T(e.assurance_providers).length,T(e.renderer_overrides).length-T(e.renderer_ownership).length].some(t=>t>0)}function po(e,t){let n=e.activation?.commands??[];if(n.length>0)return Dt(n,t);let o=Nt(e);if(Dt(o,t)||et(e).has("search")&&so(t.commandPath))return!0;if(e.contributions)return mo(e.contributions)}function Ft(e,t){let n=po(e,t);if(n!==void 0)return n;let o=et(e);return!!(Ie(o,Tr)||Ie(o,Or))}function tt(e,t){return e.effective.length===0?!1:nt(t)!=="all"?e.effective.some(n=>Ft(n,t)):e.effective.some(n=>{let o=et(n);return Nt(n).length>0||Ie(o,Tr)||Ie(o,Or)||o.has("search")})}function nt(e){if(v(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]??v(e.commandPath??"");if(t.length===0)return"all";let n=Mt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function uo(e){return nt(e)==="all"?void 0:t=>Ft(t,e)}function Pe(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=D(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 fo(e){let t=e.args.map(String);if(v(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 Lt=Symbol.for("pm.readOutputInvocationProvenance");function ie(e,t){let n=Reflect.get(e,Lt);n!==void 0&&Reflect.set(t,Lt,n)}function go(e,t,n){let o=va(t,n);if(!o)return;let a=e;for(;a.parent;)a=a.parent;let i=a.rawArgs,r=new Set(Y(i.slice(2))),s=wa.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,Lt);Reflect.set(n,Lt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),ie(n,e)}function rd(e){let t=e.optsWithGlobals(),n=E(e);if(I(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 b(`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 ho(e,t,n,o){go(e,t,o);let a=n.outputInclude;if(a===void 0)return;let{selectors:i,modes:r}=ka(t,a,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;ie(o,e);let s=Ca(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");xt(e,n)}function De(e,t,n=[]){let o={...rd(e)};ie(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=fr(t);for(let[i,r]of Object.entries(a))o[i]===void 0&&(o[i]=r);if(n.length>0){let i=cr(n),r=ne(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]);Yn(s,[...r,...n],E(e));let l=ur(o,n,a,E(e));return ie(o,l),l}return o}function jt(e,t){let n=v(t);return n.length===0?[]:e.flags.filter(o=>I(v(o.target_command))===I(n)).flatMap(o=>o.flags)}function ot(e,t,n){let o=jt(e,t),a=[t],i=[];for(let r of n){if(r.startsWith("-"))break;a.push(r);let s=jt(e,a.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Ut(e){return e.arguments??[]}function Rr(e){let t=Ut(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function yo(e,t){if(!e)return!1;let n=v(t);return e.importers.some(o=>v(`${o.importer} import`)===n)||e.exporters.some(o=>v(`${o.exporter} export`)===n)}function _o(e,t){let n=Ut(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 b(`Missing required argument for extension command '${e.command}'. Usage: ${Rr(e)}${r}`,g.USAGE);if(t.length>a){let s=t.slice(a).join(" ");throw new b(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${Rr(e)}${r}`,g.USAGE)}}function sd(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function ld(e,t,n){if(n.length>0){Yn(t,n,e.command);return}let o=Object.keys(t).filter(a=>t[a]!==void 0).sort();if(o.length!==0)throw new b(`Unknown option '${o.map(sd).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function wo(e,t,n,o){e&&(_o(e,t),ld(e,n,o))}import{Command as Ir}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 cd=new Set(["--version","-V"]);function at(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function $r(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new Ir().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let a of ze)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 dd=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),vo=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"]),Pr=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"]),md=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),pd=new Set(["claim","close-task","pause-task","release","start-task","test"]),he={setup:!0,listQuery:!0,mutation:!0,operation:!0},ud=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 it(e){return e.some(t=>cd.has(t))}function fd(e,t){if(!R.some(o=>o.canonical_argv[0]===t))return;let n=new Ir().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of ni(t,ne(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 he;let a=q([t,...o.operands])?.alias;if(R.some(i=>i.alias===a))return{...he,targetCommandName:a}}catch{return he}}function bo(e){if(it(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return he;let t=x(e);if(!t)return he;let n=t.trim().toLowerCase(),o=D(e),a=q(o)?.alias;return R.some(i=>i.alias===a)?{...he,targetCommandName:a}:fd(o,n==="ctx"?"context":n)||(dd.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:vo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Pr.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:md.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:he)}function Co(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function ko(e,t){return at(t)||it(t)?!1:oe(t)||A(t).requested?!0:!!x(t)}function xo(e){if(it(e))return!1;let t=x(e);return t?ud.has(t):!1}function gd(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=qe(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 Eo(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=Pr.has(t)||pd.has(t),r=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=gd({argv:e.argv,normalizedDisplay:a,normalizedTokens:o,rawFrom:n.from});throw new b(`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:[k(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:k(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 hd=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"]),yd=new Set(["parse","preflight","execute","unknown"]),_d=new Set(["usage","validation","conflict","runtime","unknown"]);function ye(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 So(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function qt(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 Ao(e){if(!e)return;let t=e.trim().toLowerCase();if(hd.has(t))return t}function To(e){if(!e)return;let t=e.trim().toLowerCase();if(yd.has(t))return t}function Oo(e){if(!e)return;let t=e.trim().toLowerCase();if(_d.has(t))return t}function Ro(e){let t=ye(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(So(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=qt(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=>Xt(r)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Io(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 $o(){let e=Xt(le()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=qt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,a=ri(o),i=ye(e,"error_code","errorCode")??Io(a,o),r=Oo(ye(e,"error_category","errorCategory"))??(a?void 0:dt(i)),s=a?void 0:Ro(e)??`command_exit_${o}`,l=Ao(ye(e,"command_resolution","commandResolution"))??bt({ok:a,errorCode:i,errorCategory:r}),c=To(ye(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]="35d509e8-a50c-5f5b-b00e-810ebdc01e07")}catch{}})();var Po="PM_CLI_PACKAGE_ROOT",qr=Symbol("pm.deprecatedAliasInvocation"),Gt=new Map;for(let e of W){let t=e.alias.split(" ")[0],n=Gt.get(t)??[];n.push(e),Gt.set(t,n)}for(let e of Gt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function wd(){return Xo(import.meta.url,["../.."])}(typeof process.env[Po]!="string"||process.env[Po]?.trim().length===0)&&(process.env[Po]=wd());var Ne=null,F=null,Wt=null;function vd(e){Ne=e}function bd(e){O=e}var rt=null,_e=null,O=new Map,Uo=250,Cd=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),kd=new Set(["1","true","yes","on"]),xd=We(()=>import("./chunks/register-setup-AOUZQQWB.js")),Ed=We(()=>import("./chunks/register-list-query-NNDV6F6I.js")),Sd=We(()=>import("./chunks/register-mutation-3GCBSNQS.js")),Ad=We(()=>import("./chunks/register-operations-YKDGNKUL.js"));function zt(e){return k(e)}function Hr(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=>me(o)??o))];return n.length>0?n:void 0}function Td(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Y(t),a=new Set(o.map(d=>me(d)??d)),i=Hr(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=>me(m)).filter(m=>m!==void 0))),c=i?.filter(d=>{let m=me(d)??d;return a.has(m)?!1:l.has(m)||Hn(t,r,m,O)!==void 0});return c&&c.length>0?c:void 0}function Od(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let a=n?.[0],i=a?me(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=Hn(e,r,i,O),d=i?l?.isBoolean()===!0||c===!1?[i]:[i,"<value>"]:[],m=i?zt([...e,...d]):t;return m===t?void 0:m}function Rd(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 Id(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,...Rd(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function zr(e,t,n){let o=qe(t),a=D(o),i=K(a),[r,s]=i===void 0?[]:a.slice(i,i+2),l=o.includes("--explain"),c=wi(o,e?.code,e?.recovery),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:zt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:zt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=zt(o),p=Y(o),u=Td(n,o,d),f=Od(o,m,u,d),h=Id({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return{...e,recovery:h}}async function lt(e){let t=F;F=null,await vi(t,e);let n=Ne;if(Ne=null,!n){ft();return}let o=[],a=ga();try{await bi({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 ra(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:le(),affected:a}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{ft()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${L(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${L(o)}`)}async function Gr(){await Ga()}function Wr(e){return kd.has((process.env[e]??"").trim().toLowerCase())}function Vr(e){return Wr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!Cd.has(Math.trunc(e))}async function Vt(e){return Vr(e.exit_code)?(await Gr(),Ja(e),!0):!1}async function Br(e){let t=de(e.error),n=Ui(t);e.bootstrapGlobal.json?_(JSON.stringify(Li(t,g.GENERIC_FAILURE),null,2)):_(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",a="runtime_failed";try{await Gr(),fn(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 Jt(!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||_(`Failed to report error: ${de(i)}`)}try{await lt({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||_(`Failed to run error hooks: ${de(i)}`)}try{await ke()}catch(i){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${de(i)}`)}}var $d={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"},Do=new Map;function No(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Kr(e,t){return e.options.some(n=>n.long===t)}function Jr(e,t){return e.options.some(n=>n.short===t)}function Mo(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(Jr(e,a))return;if(o){e.option(`${a} <value>`,`${i} (repeatable)`,yn);return}e.option(`${a} <value>`,i);return}let r=a.startsWith("--")?a:`--${a}`;if(!Kr(e,r)){if(o){e.option(`${r} <value>`,`${i} (repeatable)`,yn);return}e.option(`${r} <value>`,i)}}async function Yr(e,t){let n=$d[e];if(!n)return[];let o=`${t}:${n}`,a=Do.get(o);if(a)return a;if(!await V(B(t)))return Do.set(o,[]),[];let i=await $(t),r=(pn(i.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:No(s.type),value_type:No(s.type)})));return Do.set(o,r),r}async function Xr(e,t){let n=M(t),o=S(process.cwd(),n.path);if(!await V(B(o)))return;let a=_e?.key===zo(o)?_e.snapshot:null,i=a===null?await $(o):a.settings,r=pn(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=Z(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";Mo(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Mo(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function qo(e,t,n,o,a){let i=x(n);if(!(i!=="create"&&i!=="update"))try{let r=a??await $(t),s=re(r,o);Cr(e,s,n)}catch{}}function Fo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Zr(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ho(e){return e.some(t=>t==="--profile")}function zo(e){return`pm-root:${e}`}function Lo(e){for(let t of e)t.startsWith("settings_read_")&&_(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Qr(e,t){e.profile&&(_(`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&&_(`profile:extensions activation_warnings=${L(t.activationWarnings)}`))}function Bt(e,t,n){if(!e)return;let o=v(n.commandPath??"")||"<none>";_(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Kt(e,t=Ce){let n=zo(e);if(_e?.key===n)return _e.snapshot;try{let o=Date.now(),{settings:a,warnings:i}=await t(e),r=await sa({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:a,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return _e={key:n,snapshot:s},s}catch{return _e={key:n,snapshot:null},null}}async function Me(e,t,n=$){let o=t?nt(t):"all",a=Zr(e,o);if(rt?.key===a)return rt.snapshot;try{let i=await n(e),r=await je({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?uo(t):void 0}),s=await Ue({...r,loaded:r.loaded}),l=[...new Set(s.commands.handlers.map(u=>v(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),c=Yi(s.registrations.flags),d=Ki(s.commands.handlers,s.registrations.commands),m=Zi(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 rt={key:a,snapshot:p},p}catch{return rt={key:a,snapshot:null},null}}async function es(e){let t=Ve(e);if(t.noExtensions){let r=S(process.cwd(),t.path);return await V(B(r))&&Lo((await Ce(r)).warnings),null}let n=S(process.cwd(),t.path),o=await Kt(n);if(!o)return null;Lo(o.settingsReadWarnings);let a={commandPath:E(e),commandArgs:fo(e)};if(!tt(o.discovery,a))return Bt(t.profile,o,a),null;let i=await Me(n,a);return i?(Qr(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 Go(e){let t=await Me(e);return t?new Map(t.commandDescriptors):O}async function Pd(e,t){return!e.requested||t.noExtensions||Ae(y,e.commandPathTokens)?O:Go(S(process.cwd(),t.path))}async function ts(e,t){return(await Na({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=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Da(e,pi.forActiveExtensionHost({pmRoot:e,author:o}),o,v(n))}async function os(e,t,n,o=[]){let a=E(e),i=eo(e.args.map(String),o),r={...t},s={...n},l=S(process.cwd(),n.path),c=await gt({command:a,args:i,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${L(c.warnings)}`),i=c.context.args,r=c.context.options,s=c.context.global,wo(O.get(v(a)),i,r,o),ve(void 0),ut({command:a,args:i,options:{...r},global:{...s},pm_root:l});let d=await on({command:a,args:i,options:r,global:s,pm_root:l,sdk:ns(l,s,a)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${L(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new b(`Command "${a}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new b(`Command "${a}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ve(d.result),d.result}var Dr=Symbol("pm.wrappedActionHandler");function Dd(e,t){let n=e[e.length-1];return n instanceof jo?n:t}function Nr(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${L(n)}`)}function Nd(e){let t=O.get(v(e.commandPath));if(!t||!yo(e.activeRegistrations,e.commandPath))return;let n=Ut(t).length===0?gr(e.commandArgs):eo(e.commandArgs,e.extensionFlagDefinitions);_o(t,n)}function Md(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 as(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Dr]!==!0){let a=o._actionHandler;o._actionHandler=async function(...i){let r=Dd(i,n),s=Date.now();hn(r);let l=Ve(r),c=I(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await a.apply(this,i);let d=S(process.cwd(),l.path),m=r.args.map(String),p=se(),u=p?ot(p,c,m):[],f=await Yr(c,d),h=De(r,m,[...u,...f]),w=await gt({command:c,args:m,options:h,global:l,pm_root:d});Nr(l.profile,"parser_warnings",w.warnings),m=w.context.args,h=w.context.options,ie(r,h),l=w.context.global,Nd({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await li(l),xt(r,l),Md(r,i,m),kt(r,h),ve(void 0),ut({command:c,args:m,options:{...h},global:{...l},pm_root:d});let P=await on({command:c,args:m,options:h,global:l,pm_root:d,sdk:ns(d,l,c)});if(Nr(l.profile,"command_handler_warnings",P.warnings),P.handled){ve(P.result),rn(P.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&_(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await a.apply(this,i)},o[Dr]=!0}for(let a of n.commands)t(a)};t(e)}async function Ht(e){O=new Map,te({overrides:[]}),e&&await qo(e.rootProgram,e.pmRoot,e.invocationArgv,oa(),e.settings)}function Fd(e,t,n,o){if(t?.flags&&t.flags.length>0){Gn(e,t.flags);let a=Wn(e,t.flags);a&&e.addHelpText("after",a)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function is(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");St(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 rs(e,t){let n=M(t),o=S(process.cwd(),n.path);if(n.noExtensions){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t});return}let a=await Kt(o),i=Pe(t);if(!a){await Ht();return}if(!tt(a.discovery,i)){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings}),Bt(Ho(t),a,i);return}let r=await Me(o,i);if(!r){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings});return}te(r.services),O=new Map(r.commandDescriptors),await qo(e,o,t,r.registrations,r.settings);let s=rr(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>sr(r.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(z=>z.length>0),p=r.commandDescriptors.get(d),u=Z(e,m),f=r.commandFlagHelp.get(d),h=p?ar(p):null;if(u){Fd(u,p,f,h);return}let w=ir(e,m);p?.description&&w.description(p.description);let P=f;p&&(Qi(w,p),p.flags.length>0&&(Gn(w,p.flags),P=Wn(w,p.flags)??void 0)),P&&w.addHelpText("after",P),h&&w.addHelpText("after",h),w.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let Q=z[z.length-1],G=Q instanceof jo?Q:w,ct=Ve(G),_s=Date.now(),Bo=ot(r.registrations,d,G.args.map(String)),Ko=De(G,G.args.map(String),Bo),Jo=await os(G,Ko,ct,Bo);await ci(ct,Jo),rn(Jo,{...ct,command:d,commandArgs:G.args.map(String),commandOptions:Ko,pmRoot:o}),ct.profile&&_(`profile:command=${d} took_ms=${Date.now()-_s}`)})};for(let d of s)c(d);is(e,l,r.commandDescriptors)}var st=Zo(import.meta.url,["../.."])??"0.0.0",y=sn(st);async function Mr(e){if(!F)return;let t=Reflect.get(e,qr);typeof t=="string"&&await mi(t)}async function Fr(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function Lr(e,t,n){!F||!await un(!0)||(Wa(e,t,n,{source_context:F.source_context,source_context_source:F.source_context_source}),Va(e),Wt=F)}async function Jt(e,t,n){let o=Wt;if(!o)return;Wt=null;let a=!1;try{let i=await $(o.global_pm_root);a=i.telemetry.enabled&&i.telemetry.installation_id===o.installation_id}catch{}await un(a)?Ka(e,t,n):Ba()}async function Ld(e){let t=await es(e);return nn(t?.registrations??null),t}function ss(e,t){t&&at(t)||(e.hook("preAction",async(n,o)=>{Ne=null,F=null,Wt=null,ft(),hn(o);let a=o.optsWithGlobals(),i=Ve(o),r=I(E(o)),s=o.args.map(String),l=De(o,s),c={...i},d=S(process.cwd(),i.path),m=await Ld(o);if(ba(r,{...l,outputInclude:a.outputInclude,outputLimit:a.outputLimit,outputBudget:a.outputBudget,outputFormat:a.outputFormat,outputSession:a.outputSession,outputCursor:a.outputCursor}),ho(o,r,c,l),await Fr(o,void 0,()=>Qa(r,c)),!m){Ne=la({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:d}),await Mr(e),await Lr(r,s,l),await ao(r,l,d,Fo()),await oo(r,s,l,c,d);return}ca(m.hooks),da(m.commands),ma(m.parsers),pa(m.preflight),te(m.services),ua(m.renderers),nn(m.registrations);let p=ot(m.registrations,r,s);l=De(o,s,p),ho(o,r,c,l);let u=await gt({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${L(u.warnings)}`),s=u.context.args,l=u.context.options,ie(o,l),c=u.context.global,kt(o,l);let f=await ha({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Fo()});c.profile&&f.warnings.length>0&&_(`profile:extensions preflight_warnings=${L(f.warnings)}`),s=f.context.args,l=f.context.options,ie(o,l),c=f.context.global,kt(o,l);let h=f.decision;await ao(r,l,m.pmRoot,h),await oo(r,s,l,c,m.pmRoot);let w=h.run_extension_migrations?await Fr(o,[],()=>ts(m.registrations.migrations,m.pmRoot)):[];c.profile&&w.length>0&&_(`profile:extensions migration_warnings=${L(w)}`);let P=Er(m.registrations.migrations);Ne={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:P},ve(void 0),ut({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:m.pmRoot}),await Mr(e),await Lr(r,s,l);let z=await ia(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&z.length>0&&_(`profile:extensions hook_warnings=${L(z)}`),h.enforce_mandatory_migration_gate&&Sr(r,l,P)}),e.hook("postAction",async()=>{let n=$o();await Jt(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 lt(n),await ke()}))}ss(y);var jr=Symbol("pmCliIdempotentTopLevelRegistration");function ls(e){let t=e;if(t[jr])return;t[jr]=!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 jd(e,t){if(ls(e),t.setup){let{registerSetupCommands:n}=await xd();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Ed(),o=typeof t.targetCommandName=="string"&&vo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Sd();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Ad();n(e)}}function Ud(e){return async t=>{let n=dt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ti({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:st,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 cs(e){if(e.bootstrapGlobal.noExtensions||at(e.invocationArgv))return;let t=Pe(e.invocationArgv),n=await Kt(e.bootstrapPmRoot);if(n&&tt(n.discovery,t)){let o=await Me(e.bootstrapPmRoot,t);ds(o);return}n&&Bt(Ho(e.invocationArgv),n,t),te({overrides:[]})}function ds(e){if(!e){te({overrides:[]});return}te(e.services)}async function Wo(e){await Jt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await lt({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 ms(){await Jt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await lt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function ps(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof b)&&(dn(e.error)||!n))return!1;let o=de(e.error),a=e.error instanceof b?e.error.exitCode:cn(t),i=e.error instanceof b?e.error.context:void 0,r=zr(i,e.invocationArgv,o),s=Mi(o,r),l=e.bootstrapGlobal.lean?Ot(Dn(o,a,r)):Dn(o,a,r),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ce(l,u=>`${JSON.stringify(u,null,2)}
|
|
34
|
-
`):l,null,2):
|
|
35
|
-
`):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:a,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Vt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:a,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:F?.source_context});return await Wo({errorMessage:o,exitCode:a,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(mn(e.error,o)),await ke(Uo)),process.exitCode=a,!0}async function
|
|
36
|
-
`):_(h),u&&await ke(Uo),process.exitCode=g.USAGE}async function
|
|
37
|
-
`):_(c),r&&await ke(Uo),process.exitCode=g.USAGE}function
|
|
29
|
+
`)}return process.exitCode=g.USAGE,!0}if(!a.quiet){let s=qc(e,r,t,i.commandPathTokens,n),l=A(o).commandPathTokens;s.requested_path=l;let c=H(l.join(" "));c&&(s.resolved_path=c.canonical),r===e&&!oe(t)&&(s.omission_receipt={has_omissions:!0,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}),Sa(`${JSON.stringify(s,null,2)}
|
|
30
|
+
`)}return process.exitCode=g.SUCCESS,!0}function Hc(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(`
|
|
31
|
+
`)}function zc(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)":"",a=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${a.length>0?a.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Gc(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let a of[...t.required_create_fields,...t.required_create_repeatables])o.add(a);return{progressive:n,strict:o}}function Wc(e,t,n,o){let a=new Set(n),i=o.filter(l=>!a.has(l)),r=l=>l.length>0?l.map(c=>Zt("create",c)).join(", "):"none";e.push(` required in strict mode: ${r(i)}`);let s=i.map(di).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 Vc(e,t,n){let o=La(n);if(!o)return Hc(e,t);let a=ea(o,t);if(!a){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
|
|
32
|
+
`)}let i=n.indexOf("--"),r=i<0?n:n.slice(0,i),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=Gc(e,a),m=mt(a,e,d.progressive),p=mt(a,e,c?d.strict:d.progressive),u=h=>h.length>0?h.map(v=>Zt(e,v)).join(", "):"none",f=["",`Type-aware option policies for ${a.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=mt(a,e,d.strict);Wc(f,a,m.required,h.required)}return zc(f,a),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
|
|
33
|
+
`)}function kr(e,t,n){let o=x(n);if(o!=="create"&&o!=="update")return;let a=Xe(e,o);a&&a.addHelpText("after",Vc(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]="714821f9-dd8f-5958-a751-29e8dfc06471")}catch{}})();function Bc(e,t){return Fe(e.id)||`migration-${String(t+1).padStart(3,"0")}`}function Kc(e){return Fe(e.status)?.toLowerCase()??"pending"}function Jc(e){return e.mandatory===!0}function Yc(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 Sr(e){let t=[];return e.forEach((n,o)=>{if(!Jc(n.definition))return;let a=Kc(n.definition);a!=="applied"&&t.push({layer:n.layer,name:n.name,id:Bc(n.definition,o),status:a})}),t.sort(Yc),t}function xr(e){return Array.isArray(e)&&e.length>0}var Xc=new Set(["create","beads import","todos import"]),Zc=new Set(["restore","update","close","delete","append","claim","release"]),Qc=new Set(["comments","notes","learnings"]),ed=new Set(["files","docs","test"]),td=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 no(e,t){let n=t.force===!0;return Xc.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:Zc.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:Qc.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:ed.has(e)?{isMutation:xr(t.add)||xr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function nd(e,t,n){if(no(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return Xa(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(a=>td.has(a.trim().toLowerCase())):!1}function Er(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function od(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(Fe(t[1])||a.push("source"),Fe(n.to)||a.push("--to"),a.length!==0)throw new b(`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 ad(e,t,n,o,a){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Er(n.status)!==Er(a.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let r=re(a,se()),s=await _t(o,i,a.id_prefix,a.item_format,r.type_to_folder);if(!s)return;let l=await Pa(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)||_(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function oo(e,t,n,o,a){if(!nd(e,t,n)||(od(e,t,n),!await V(B(a))))return;let i=await Ce(a);o.json!==!0&&await ad(e,t,n,a,i.settings);let r=Ya({author:ht(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)_(`warning:${s}`)}function Ar(e,t,n){if(n.length===0)return;let o=no(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 b(`Write command "${e}" blocked by unresolved mandatory extension migrations (${a.join(",")}). ${i}`,g.CONFLICT)}async function ao(e,t,n,o){if(!no(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await V(B(n)))return;let{settings:a,metadata:i,warnings:r}=await Ce(n);for(let s of r)_(`warning:${s}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(Ra(a),await Ia(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let s=re(a,se());await Za(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 io(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(a=>a.length>0);for(let a of io(e.commandArgs))o.push(...a.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n.flatMap(a=>[a,I(a)]))]}function ro(e,t){let n=w(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 Nt(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...O(n.commands),...O(n.command_handlers),...O(n.command_overrides),...O(n.flag_commands),...O(n.parser_overrides),...Tr(n.preflight_ownership),...Tr(n.renderer_ownership)]:[]}function O(e){return e??[]}function Tr(e){return O(e).flatMap(t=>t.commands)}function et(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Or=new Set(["hooks","parser","preflight","renderers"]),Rr=new Set(["commands","schema","services","importers"]),id=new Set(["reindex","search","search-advanced"]),rd=new Set(["--template"]);function Ie(e,t){for(let n of t)if(e.has(n))return!0;return!1}function so(e){let t=w(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return id.has(n??t)}function lo(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 Mt(e){return w(e.commandPath??"")==="create"&&lo(e,rd)}function co(e){return e.some(t=>{let n=w(t);return n==="templates"||n.startsWith("templates ")})}function Dt(e,t){return e.some(n=>ro(n,t))||Mt(t)&&co(e)}function mo(e){return[O(e.hooks).length,(e.preflight_overrides??0)-O(e.preflight_ownership).length,O(e.item_types).length,O(e.item_fields).length,O(e.relationship_kinds).length,O(e.service_overrides).length,O(e.assurance_providers).length,O(e.renderer_overrides).length-O(e.renderer_ownership).length].some(t=>t>0)}function po(e,t){let n=e.activation?.commands??[];if(n.length>0)return Dt(n,t);let o=Nt(e);if(Dt(o,t)||et(e).has("search")&&so(t.commandPath))return!0;if(e.contributions)return mo(e.contributions)}function Ft(e,t){let n=po(e,t);if(n!==void 0)return n;let o=et(e);return!!(Ie(o,Or)||Ie(o,Rr))}function tt(e,t){return e.effective.length===0?!1:nt(t)!=="all"?e.effective.some(n=>Ft(n,t)):e.effective.some(n=>{let o=et(n);return Nt(n).length>0||Ie(o,Or)||Ie(o,Rr)||o.has("search")})}function nt(e){if(w(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]??w(e.commandPath??"");if(t.length===0)return"all";let n=Mt(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function uo(e){return nt(e)==="all"?void 0:t=>Ft(t,e)}function Pe(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=D(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 fo(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 Lt=Symbol.for("pm.readOutputInvocationProvenance");function ie(e,t){let n=Reflect.get(e,Lt);n!==void 0&&Reflect.set(t,Lt,n)}function go(e,t,n){let o=va(t,n);if(!o)return;let a=e;for(;a.parent;)a=a.parent;let i=a.rawArgs,r=new Set(Y(i.slice(2))),s=wa.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,Lt);Reflect.set(n,Lt,{canonical_include_modes:c?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),ie(n,e)}function sd(e){let t=e.optsWithGlobals(),n=E(e);if(I(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 b(`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 ho(e,t,n,o){go(e,t,o);let a=n.outputInclude;if(a===void 0)return;let{selectors:i,modes:r}=ka(t,a,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),r.length===0)return;ie(o,e);let s=Ca(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 De(e,t,n=[]){let o={...sd(e)};ie(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=gr(t);for(let[i,r]of Object.entries(a))o[i]===void 0&&(o[i]=r);if(n.length>0){let i=dr(n),r=ne(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]);Yn(s,[...r,...n],E(e));let l=fr(o,n,a,E(e));return ie(o,l),l}return o}function jt(e,t){let n=w(t);return n.length===0?[]:e.flags.filter(o=>I(w(o.target_command))===I(n)).flatMap(o=>o.flags)}function ot(e,t,n){let o=jt(e,t),a=[t],i=[];for(let r of n){if(r.startsWith("-"))break;a.push(r);let s=jt(e,a.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Ut(e){return e.arguments??[]}function Ir(e){let t=Ut(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function yo(e,t){if(!e)return!1;let n=w(t);return e.importers.some(o=>w(`${o.importer} import`)===n)||e.exporters.some(o=>w(`${o.exporter} export`)===n)}function _o(e,t){let n=Ut(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 b(`Missing required argument for extension command '${e.command}'. Usage: ${Ir(e)}${r}`,g.USAGE);if(t.length>a){let s=t.slice(a).join(" ");throw new b(`Too many arguments for extension command '${e.command}': ${s}. Usage: ${Ir(e)}${r}`,g.USAGE)}}function ld(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function cd(e,t,n){if(n.length>0){Yn(t,n,e.command);return}let o=Object.keys(t).filter(a=>t[a]!==void 0).sort();if(o.length!==0)throw new b(`Unknown option '${o.map(ld).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function wo(e,t,n,o){e&&(_o(e,t),cd(e,n,o))}import{Command as $r}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 dd=new Set(["--version","-V"]);function at(e){let t=D(e);return["package","packages","extension"].includes(t[0]??"")&&t[1]==="inventory"}function Pr(e){if(D(e)[0]!=="item"||!e.includes("--dry-run"))return;let t=new $r().configureOutput({writeErr:()=>{}}).exitOverride(),n=new Set;for(let a of ze)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 md=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),vo=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"]),Dr=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"]),pd=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),ud=new Set(["claim","close-task","pause-task","release","start-task","test"]),he={setup:!0,listQuery:!0,mutation:!0,operation:!0},fd=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 it(e){return e.some(t=>dd.has(t))}function gd(e,t){if(!R.some(o=>o.canonical_argv[0]===t))return;let n=new $r().configureOutput({writeErr:()=>{}}).exitOverride();for(let o of ai(t,ne(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 he;let a=q([t,...o.operands])?.alias;if(R.some(i=>i.alias===a))return{...he,targetCommandName:a}}catch{return he}}function bo(e){if(it(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||A(e).requested)return he;let t=x(e);if(!t)return he;let n=t.trim().toLowerCase(),o=D(e),a=q(o)?.alias;return R.some(i=>i.alias===a)?{...he,targetCommandName:a}:gd(o,n==="ctx"?"context":n)||(md.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:vo.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Dr.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:pd.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:he)}function Co(e){return e.length===0||A(e).requested||e.includes("--explain")&&x(e)===void 0}function ko(e,t){return at(t)||it(t)?!1:oe(t)||A(t).requested?!0:!!x(t)}function xo(e){if(it(e))return!1;let t=x(e);return t?fd.has(t):!1}function hd(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=qe(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 Eo(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=Dr.has(t)||ud.has(t),r=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=hd({argv:e.argv,normalizedDisplay:a,normalizedTokens:o,rawFrom:n.from});throw new b(`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:[C(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:C(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 yd=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"]),_d=new Set(["parse","preflight","execute","unknown"]),wd=new Set(["usage","validation","conflict","runtime","unknown"]);function ye(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 So(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function qt(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 Ao(e){if(!e)return;let t=e.trim().toLowerCase();if(yd.has(t))return t}function To(e){if(!e)return;let t=e.trim().toLowerCase();if(_d.has(t))return t}function Oo(e){if(!e)return;let t=e.trim().toLowerCase();if(wd.has(t))return t}function Ro(e){let t=ye(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(So(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let o=qt(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=>Xt(r)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Io(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 $o(){let e=Xt(le()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=qt(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,a=li(o),i=ye(e,"error_code","errorCode")??Io(a,o),r=Oo(ye(e,"error_category","errorCategory"))??(a?void 0:dt(i)),s=a?void 0:Ro(e)??`command_exit_${o}`,l=Ao(ye(e,"command_resolution","commandResolution"))??bt({ok:a,errorCode:i,errorCategory:r}),c=To(ye(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]="3e4a18e9-6c97-5b44-95bc-678c3e7bdbcc")}catch{}})();var Po="PM_CLI_PACKAGE_ROOT",Hr=Symbol("pm.deprecatedAliasInvocation"),Gt=new Map;for(let e of W){let t=e.alias.split(" ")[0],n=Gt.get(t)??[];n.push(e),Gt.set(t,n)}for(let e of Gt.values())e.sort((t,n)=>n.alias.split(" ").length-t.alias.split(" ").length);function vd(){return Xo(import.meta.url,["../.."])}(typeof process.env[Po]!="string"||process.env[Po]?.trim().length===0)&&(process.env[Po]=vd());var Ne=null,F=null,Wt=null;function bd(e){Ne=e}function Cd(e){T=e}var rt=null,_e=null,T=new Map,Uo=250,kd=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),xd=new Set(["1","true","yes","on"]),Ed=We(()=>import("./chunks/register-setup-OQMUZBJV.js")),Sd=We(()=>import("./chunks/register-list-query-6PT5Y2EZ.js")),Ad=We(()=>import("./chunks/register-mutation-TAIQV46L.js")),Td=We(()=>import("./chunks/register-operations-ONIRO22G.js"));function zt(e){return C(e)}function zr(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=>me(o)??o))];return n.length>0?n:void 0}function Od(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=Y(t),a=new Set(o.map(d=>me(d)??d)),i=zr(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=>me(m)).filter(m=>m!==void 0))),c=i?.filter(d=>{let m=me(d)??d;return a.has(m)?!1:l.has(m)||Hn(t,r,m,T)!==void 0});return c&&c.length>0?c:void 0}function Rd(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let a=n?.[0],i=a?me(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=Hn(e,r,i,T),d=i?l?.isBoolean()===!0||c===!1?[i]:[i,"<value>"]:[],m=i?zt([...e,...d]):t;return m===t?void 0:m}function Id(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 $d(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,...Id(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Gr(e,t,n){let o=qe(t),a=D(o),i=K(a),[r,s]=i===void 0?[]:a.slice(i,i+2),l=o.includes("--explain"),c=wi(o,e?.code,e?.recovery),d=c&&(r==="history-redact"||r==="history"&&s==="redact")?{...c,...c.attempted_command?{attempted_command:zt(o)}:{},...c.normalized_args?{normalized_args:[...o]}:{},...c.suggested_retry?{suggested_retry:zt(o)}:{},...c.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:c;if(d?.recovery_mode==="compact"&&!l)return{...e,recovery:d};let m=zt(o),p=Y(o),u=Od(n,o,d),f=Rd(o,m,u,d),h=$d({invocationArgv:o,attemptedCommand:m,providedFields:p,inferredMissing:u,suggestedRetry:f,existingRecovery:d});return{...e,recovery:h}}async function lt(e){let t=F;F=null,await vi(t,e);let n=Ne;if(Ne=null,!n){ft();return}let o=[],a=ga();try{await bi({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 ra(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:le(),affected:a}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{ft()}!n.globalOptions.json&&o.length>0&&_(`[pm] warning: afterCommand hook_warnings=${L(o)}`),n.profileEnabled&&o.length>0&&_(`profile:extensions hook_warnings=${L(o)}`)}async function Wr(){await Ga()}function Vr(e){return xd.has((process.env[e]??"").trim().toLowerCase())}function Br(e){return Vr("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!kd.has(Math.trunc(e))}async function Vt(e){return Br(e.exit_code)?(await Wr(),Ja(e),!0):!1}async function Kr(e){let t=de(e.error),n=qi(t);e.bootstrapGlobal.json?_(JSON.stringify(ji(t,g.GENERIC_FAILURE),null,2)):_(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",a="runtime_failed";try{await Wr(),fn(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 Jt(!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||_(`Failed to report error: ${de(i)}`)}try{await lt({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||_(`Failed to run error hooks: ${de(i)}`)}try{await ke()}catch(i){e.bootstrapGlobal.json||_(`Failed to flush error reporting: ${de(i)}`)}}var Pd={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"},Do=new Map;function No(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Jr(e,t){return e.options.some(n=>n.long===t)}function Yr(e,t){return e.options.some(n=>n.short===t)}function Mo(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(Yr(e,a))return;if(o){e.option(`${a} <value>`,`${i} (repeatable)`,yn);return}e.option(`${a} <value>`,i);return}let r=a.startsWith("--")?a:`--${a}`;if(!Jr(e,r)){if(o){e.option(`${r} <value>`,`${i} (repeatable)`,yn);return}e.option(`${r} <value>`,i)}}async function Xr(e,t){let n=Pd[e];if(!n)return[];let o=`${t}:${n}`,a=Do.get(o);if(a)return a;if(!await V(B(t)))return Do.set(o,[]),[];let i=await $(t),r=(pn(i.schema).command_to_fields.get(n)??[]).flatMap(s=>[s.cli_flag,...s.cli_aliases].map(l=>({long:`--${l}`,type:No(s.type),value_type:No(s.type)})));return Do.set(o,r),r}async function Zr(e,t){let n=M(t),o=S(process.cwd(),n.path);if(!await V(B(o)))return;let a=_e?.key===zo(o)?_e.snapshot:null,i=a===null?await $(o):a.settings,r=pn(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=Z(e,l.path.split(" "));if(c)for(let d of r.command_to_fields.get(l.command)??[]){let m=d.description??"";Mo(c,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)Mo(c,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function qo(e,t,n,o,a){let i=x(n);if(!(i!=="create"&&i!=="update"))try{let r=a??await $(t),s=re(r,o);kr(e,s,n)}catch{}}function Fo(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Qr(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ho(e){return e.some(t=>t==="--profile")}function zo(e){return`pm-root:${e}`}function Lo(e){for(let t of e)t.startsWith("settings_read_")&&_(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function es(e,t){e.profile&&(_(`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&&_(`profile:extensions activation_warnings=${L(t.activationWarnings)}`))}function Bt(e,t,n){if(!e)return;let o=w(n.commandPath??"")||"<none>";_(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function Kt(e,t=Ce){let n=zo(e);if(_e?.key===n)return _e.snapshot;try{let o=Date.now(),{settings:a,warnings:i}=await t(e),r=await sa({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:a,discovery:r,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return _e={key:n,snapshot:s},s}catch{return _e={key:n,snapshot:null},null}}async function Me(e,t,n=$){let o=t?nt(t):"all",a=Qr(e,o);if(rt?.key===a)return rt.snapshot;try{let i=await n(e),r=await je({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?uo(t):void 0}),s=await Ue({...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=Xi(s.registrations.flags),d=Ji(s.commands.handlers,s.registrations.commands),m=Qi(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 rt={key:a,snapshot:p},p}catch{return rt={key:a,snapshot:null},null}}async function ts(e){let t=Ve(e);if(t.noExtensions){let r=S(process.cwd(),t.path);return await V(B(r))&&Lo((await Ce(r)).warnings),null}let n=S(process.cwd(),t.path),o=await Kt(n);if(!o)return null;Lo(o.settingsReadWarnings);let a={commandPath:E(e),commandArgs:fo(e)};if(!tt(o.discovery,a))return Bt(t.profile,o,a),null;let i=await Me(n,a);return i?(es(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 Go(e){let t=await Me(e);return t?new Map(t.commandDescriptors):T}async function Dd(e,t){return!e.requested||t.noExtensions||Ae(y,e.commandPathTokens)?T:Go(S(process.cwd(),t.path))}async function ns(e,t){return(await Na({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 os(e,t,n){let o=t.author;return Da(e,pi.forActiveExtensionHost({pmRoot:e,author:o}),o,w(n))}async function as(e,t,n,o=[]){let a=E(e),i=eo(e.args.map(String),o),r={...t};delete r.author;let s={...n},l=S(process.cwd(),n.path),c=await gt({command:a,args:i,options:r,global:s,pm_root:l});n.profile&&c.warnings.length>0&&_(`profile:extensions parser_warnings=${L(c.warnings)}`),i=c.context.args,r=c.context.options,s=c.context.global,wo(T.get(w(a)),i,r,o),ve(void 0),ut({command:a,args:i,options:{...r},global:{...s},pm_root:l});let d=await on({command:a,args:i,options:r,global:s,pm_root:l,sdk:os(l,s,a)});if(s.profile&&d.warnings.length>0&&_(`profile:extensions command_handler_warnings=${L(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new b(`Command "${a}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new b(`Command "${a}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ve(d.result),d.result}var Nr=Symbol("pm.wrappedActionHandler");function Nd(e,t){let n=e[e.length-1];return n instanceof jo?n:t}function Mr(e,t,n){e&&n.length>0&&_(`profile:extensions ${t}=${L(n)}`)}function Md(e){let t=T.get(w(e.commandPath));if(!t||!yo(e.activeRegistrations,e.commandPath))return;let n=Ut(t).length===0?hr(e.commandArgs):eo(e.commandArgs,e.extensionFlagDefinitions);_o(t,n)}function Fd(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 is(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Nr]!==!0){let a=o._actionHandler;o._actionHandler=async function(...i){let r=Nd(i,n),s=Date.now();hn(r);let l=Ve(r),c=I(E(r));if(["package inventory","packages inventory","extension inventory"].includes(c))return await a.apply(this,i);let d=S(process.cwd(),l.path),m=r.args.map(String),p=se(),u=p?ot(p,c,m):[],f=await Xr(c,d),h=De(r,m,[...u,...f]);T.has(w(c))&&delete h.author;let v=await gt({command:c,args:m,options:h,global:l,pm_root:d});Mr(l.profile,"parser_warnings",v.warnings),m=v.context.args,h=v.context.options,ie(r,h),l=v.context.global,Md({activeRegistrations:p,commandPath:c,commandArgs:m,extensionFlagDefinitions:u}),l=await ni(l),kt(r,l),Fd(r,i,m),Ct(r,h),ve(void 0),ut({command:c,args:m,options:{...h},global:{...l},pm_root:d});let P=await on({command:c,args:m,options:h,global:l,pm_root:d,sdk:os(d,l,c)});if(Mr(l.profile,"command_handler_warnings",P.warnings),P.handled){ve(P.result),rn(P.result,{...l,command:c,commandArgs:m,commandOptions:h,pmRoot:d}),l.profile&&_(`profile:command=${c} took_ms=${Date.now()-s}`);return}return await a.apply(this,i)},o[Nr]=!0}for(let a of n.commands)t(a)};t(e)}async function Ht(e){T=new Map,te({overrides:[]}),e&&await qo(e.rootProgram,e.pmRoot,e.invocationArgv,oa(),e.settings)}function Ld(e,t,n,o){if(t?.flags&&t.flags.length>0){Gn(e,t.flags);let a=Wn(e,t.flags);a&&e.addHelpText("after",a)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function rs(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");St(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 ss(e,t){let n=M(t),o=S(process.cwd(),n.path);if(n.noExtensions){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t});return}let a=await Kt(o),i=Pe(t);if(!a){await Ht();return}if(!tt(a.discovery,i)){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings}),Bt(Ho(t),a,i);return}let r=await Me(o,i);if(!r){await Ht({rootProgram:e,pmRoot:o,invocationArgv:t,settings:a.settings});return}te(r.services),T=new Map(r.commandDescriptors),await qo(e,o,t,r.registrations,r.settings);let s=sr(e,r.commandHandlers,r.commandDescriptors,r.commandAliases,d=>lr(r.activationWarnings,_,d)),l=new Set(e.commands.map(d=>d.name())),c=d=>{let m=d.split(" ").filter(z=>z.length>0),p=r.commandDescriptors.get(d),u=Z(e,m),f=r.commandFlagHelp.get(d),h=p?ir(p):null;if(u){Ld(u,p,f,h);return}let v=rr(e,m);p?.description&&v.description(p.description);let P=f;p&&(er(v,p),p.flags.length>0&&(Gn(v,p.flags),P=Wn(v,p.flags)??void 0)),P&&v.addHelpText("after",P),h&&v.addHelpText("after",h),v.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...z)=>{let Q=z[z.length-1],G=Q instanceof jo?Q:v,ct=Ve(G),ws=Date.now(),Bo=ot(r.registrations,d,G.args.map(String)),Ko=De(G,G.args.map(String),Bo),Jo=await as(G,Ko,ct,Bo);await oi(ct,Jo),rn(Jo,{...ct,command:d,commandArgs:G.args.map(String),commandOptions:Ko,pmRoot:o}),ct.profile&&_(`profile:command=${d} took_ms=${Date.now()-ws}`)})};for(let d of s)c(d);rs(e,l,r.commandDescriptors)}var st=Zo(import.meta.url,["../.."])??"0.0.0",y=sn(st);async function Fr(e){if(!F)return;let t=Reflect.get(e,Hr);typeof t=="string"&&await mi(t)}async function Lr(e,t,n){let o=E(e);return["item mutate","item complete"].includes(o)&&e.optsWithGlobals().dryRun===!0?t:n()}async function jr(e,t,n){!F||!await un(!0)||(Wa(e,t,n,{source_context:F.source_context,source_context_source:F.source_context_source}),Va(e),Wt=F)}async function Jt(e,t,n){let o=Wt;if(!o)return;Wt=null;let a=!1;try{let i=await $(o.global_pm_root);a=i.telemetry.enabled&&i.telemetry.installation_id===o.installation_id}catch{}await un(a)?Ka(e,t,n):Ba()}async function jd(e){let t=await ts(e);return nn(t?.registrations??null),t}function ls(e,t){t&&at(t)||(e.hook("preAction",async(n,o)=>{Ne=null,F=null,Wt=null,ft(),hn(o);let a=o.optsWithGlobals(),i=Ve(o),r=I(E(o)),s=o.args.map(String),l=De(o,s),c={...i},d=S(process.cwd(),i.path),m=await jd(o);if(ba(r,{...l,outputInclude:a.outputInclude,outputLimit:a.outputLimit,outputBudget:a.outputBudget,outputFormat:a.outputFormat,outputSession:a.outputSession,outputCursor:a.outputCursor}),ho(o,r,c,l),await Lr(o,void 0,()=>Qa(r,c)),!m){Ne=la({commandName:r,commandArgs:s,commandOptions:l,globalOptions:c,pmRoot:d}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:d}),await Fr(e),await jr(r,s,l),await ao(r,l,d,Fo()),await oo(r,s,l,c,d);return}ca(m.hooks),da(m.commands),ma(m.parsers),pa(m.preflight),te(m.services),ua(m.renderers),nn(m.registrations);let p=ot(m.registrations,r,s);l=De(o,s,p),ho(o,r,c,l);let u=await gt({command:r,args:s,options:l,global:c,pm_root:m.pmRoot});c.profile&&u.warnings.length>0&&_(`profile:extensions parser_warnings=${L(u.warnings)}`),s=u.context.args,l=u.context.options,ie(o,l),c=u.context.global,Ct(o,l);let f=await ha({command:r,args:s,options:l,global:c,pm_root:m.pmRoot,decision:Fo()});c.profile&&f.warnings.length>0&&_(`profile:extensions preflight_warnings=${L(f.warnings)}`),s=f.context.args,l=f.context.options,ie(o,l),c=f.context.global,Ct(o,l);let h=f.decision;await ao(r,l,m.pmRoot,h),await oo(r,s,l,c,m.pmRoot);let v=h.run_extension_migrations?await Lr(o,[],()=>ns(m.registrations.migrations,m.pmRoot)):[];c.profile&&v.length>0&&_(`profile:extensions migration_warnings=${L(v)}`);let P=Sr(m.registrations.migrations);Ne={hooks:m.hooks,commandName:r,commandArgs:s,commandOptions:{...l},globalOptions:{...c},pmRoot:m.pmRoot,profileEnabled:!!c.profile,migrationBlockers:P},ve(void 0),ut({command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot}),F=await gn({command:r,pm_version:st,args:s,options:l,global:c,pm_root:m.pmRoot}),await Fr(e),await jr(r,s,l);let z=await ia(m.hooks,{command:r,args:s,options:{...l},global:{...c},pm_root:m.pmRoot});c.profile&&z.length>0&&_(`profile:extensions hook_warnings=${L(z)}`),h.enforce_mandatory_migration_gate&&Ar(r,l,P)}),e.hook("postAction",async()=>{let n=$o();await Jt(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 lt(n),await ke()}))}ls(y);var Ur=Symbol("pmCliIdempotentTopLevelRegistration");function cs(e){let t=e;if(t[Ur])return;t[Ur]=!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 Ud(e,t){if(cs(e),t.setup){let{registerSetupCommands:n}=await Ed();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await Sd(),o=typeof t.targetCommandName=="string"&&vo.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await Ad();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await Td();n(e)}}function qd(e){return async t=>{let n=dt(t.errorCode),o=bt({ok:!1,errorCode:t.errorCode,errorCategory:n});return await ti({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:st,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 ds(e){if(e.bootstrapGlobal.noExtensions||at(e.invocationArgv))return;let t=Pe(e.invocationArgv),n=await Kt(e.bootstrapPmRoot);if(n&&tt(n.discovery,t)){let o=await Me(e.bootstrapPmRoot,t);ms(o);return}n&&Bt(Ho(e.invocationArgv),n,t),te({overrides:[]})}function ms(e){if(!e){te({overrides:[]});return}te(e.services)}async function Wo(e){await Jt(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await lt({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 ps(){await Jt(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await lt({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function us(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof b)&&(dn(e.error)||!n))return!1;let o=de(e.error),a=e.error instanceof b?e.error.exitCode:cn(t),i=e.error instanceof b?e.error.context:void 0,r=Gr(i,e.invocationArgv,o),s=Fi(o,r),l=e.bootstrapGlobal.lean?Ot(Dn(o,a,r)):Dn(o,a,r),c=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ce(l,u=>`${JSON.stringify(u,null,2)}
|
|
34
|
+
`):l,null,2):Mi(o,r);e.jsonErrors?be(`${c}
|
|
35
|
+
`):_(c);let{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:a,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await Vt({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:a,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:F?.source_context});return await Wo({errorMessage:o,exitCode:a,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(fn(mn(e.error,o)),await ke(Uo)),process.exitCode=a,!0}async function fs(e,t){let n=A(e.invocationArgv).commandPathTokens.join(" ")||Fn(e.invocationArgv),o=I(n),a=`unknown command '${n}'`,i=S(process.cwd(),e.bootstrapGlobal.path),r=e.bootstrapGlobal.noExtensions?T:await Go(i),s=Pe(e.invocationArgv),l=e.bootstrapGlobal.noExtensions?[]:await to(i,{},$e(s)),c=await Je({message:a},y,r,{failedExtensions:l},e.invocationArgv),d=Nn(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 Vt({command:o,error_code:d.code,error_category:m,exit_code:g.USAGE,error_message:d.detail,command_resolution:p,resolution_stage:"parse"}),f=e.jsonErrors?await qn({message:a},y,r,e.bootstrapGlobal.lean===!0,{failedExtensions:l},e.invocationArgv):await Un({message:a},y,r,{failedExtensions:l},e.invocationArgv),h=Mn(f,e.jsonErrors,l);await Wo({errorMessage:a,exitCode:g.USAGE,classificationCode:d.code,errorCategory:m,commandResolution:p,resolutionStage:"parse"}),e.jsonErrors?be(`${h}
|
|
36
|
+
`):_(h),u&&await ke(Uo),process.exitCode=g.USAGE}async function gs(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&&!Ae(y,o.commandPathTokens)?(await fs(e,t),!0):(await ps(),!0)}async function hs(e,t){let n=await Je(e.error,y,T,{},e.invocationArgv),o=Nn(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:a,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),r=await Vt({command:e.attemptedCommand,error_code:o.code,error_category:a,exit_code:g.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:F?.source_context}),s=e.jsonErrors?await qn(e.error,y,T,e.bootstrapGlobal.lean===!0,{},e.invocationArgv):await Un(e.error,y,T,{},e.invocationArgv),l=await yr(o.code,e.bootstrapPmRoot,{},$e(Pe(e.invocationArgv))),c=Mn(s,e.jsonErrors,l);await Wo({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:a,commandResolution:i,resolutionStage:"parse"}),e.jsonErrors?be(`${c}
|
|
37
|
+
`):_(c),r&&await ke(Uo),process.exitCode=g.USAGE}function ys(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 _s(e){let t=e.error.code,n=String(e.error.message??"");if(!await gs(e,t,n)){if(t==="commander.version"){await ps();return}await hs(e,t)}}async function Vo(e){let t=M(e.invocationArgv),n=S(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:x(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:qd({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await ds({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await us(o,ln(e.error))){if(ys(e.error)){await _s(o);return}await Kr({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}function Hd(e,t,n){let o=n.requested?n.commandPathTokens:D(t),a=q(o);if(a&&!Z(e,[...a.canonical_argv]))throw new qr(g.USAGE,"commander.unknownCommand",`unknown command '${a.alias}'`)}function zd(e,t){let n=K(t);if(n===void 0)return;if(["pm","pm-cli"].includes(t[n]?.trim().toLowerCase())){let r=K(t.slice(n+1));if(r===void 0)return;n+=r+1}let o=Gt.get(t[n]),a=t.slice(n).filter(r=>!["--global","--project","--local"].includes(r)),i=o?.find(r=>r.alias.split(" ").every((s,l)=>a[l]===s));i?.lifecycle==="deprecated"&&Reflect.set(e,Hr,i.alias)}function Gd(e){return[process.argv[0],process.argv[1]??"pm",...e]}async function Wd(e,t){y=sn(st),y.hook("preAction",(i,r)=>{t.configurationOnly=["item mutate","item complete"].includes(E(r))&&r.optsWithGlobals().dryRun===!0}),ls(y,e),rt=null,_e=null,T=new Map,fa();let n=[...e],o,a;try{let i=Ge(e);n=i.argv,zd(y,e);let r=Gd(n),s=n.length===0,l=M(n);if(l.authorMissingValue)throw new b("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});o=Ha(l.author),Eo(i),a=Fa(n);let c=bo(n);await Ud(y,c),xn(y,!0),ko(y,n)?await ss(y,n):(T=new Map,te({overrides:[]})),xo(n)&&await Zr(y,n),xn(y);let d=A(n);Hd(y,n,d),Co(n)&&Ai(y,n),is(y);let m=await Dd(d,l);if(await Cr(y,n,m,e))return;if(d.requested&&!Ae(y,d.commandPathTokens))throw new qr(g.USAGE,"commander.helpDisplayed","(outputHelp)");if(s||oe(n)&&x(n)===void 0){y.outputHelp();return}if(at(n)){await y.parseAsync(r);return}let p=S(process.cwd(),l.path),u=await $(p),f=await Bi(n,p,l.noExtensions,Me);await Aa({pmRoot:p,packages:f?.contextIntentPackages},()=>Ta({env:{...process.env,PM_PATH:p},argv:r,cwd:process.cwd()},()=>Oa(u.agent_identity.harness_signals,()=>y.parseAsync(r),{probesEnabled:u.agent_identity?.probes_enabled})))}catch(i){await Vo({error:i,invocationArgv:n})}finally{a?.(),o?.()}}async function _u(e=process.argv.slice(2)){let t=e;try{t=Ge(e).argv}catch{}let n=Pr(t),o={configurationOnly:n!==void 0},a=()=>o.configurationOnly,i=async()=>{try{await za(process.env,()=>Wd(e,o))}catch(r){await Vo({error:r,invocationArgv:[...e]})}};if(n!==void 0){let r=S(process.cwd(),M(t).path),s=S(process.cwd(),n.path),l=na(process.cwd());await yt(r,()=>yt(s,()=>yt(l,i,a),a),a)}else await i()}var wu={activationCommandMatchesProbe:ro,applyDynamicExtensionRootHelpVisibility:rs,bootstrapProfileEnabled:Ho,buildBootstrapActivationProbe:Pe,buildPostActionTelemetryOutcome:$o,buildPmCliRecoveryContext:Gr,buildRuntimeExtensionDiscoverySnapshotCacheKey:zo,buildRuntimeExtensionActivationScope:nt,buildRuntimeExtensionSnapshotCacheKey:Qr,buildRuntimeExtensionFilterForProbe:uo,addRuntimeFieldOption:Mo,collectActivationCommandCandidates:$e,collectExtensionFlagDefinitionsForCommand:jt,collectExtensionFlagDefinitionsForInvocation:ot,collectLeadingCommandArgs:io,collectParsedActivationCommandArgs:fo,collectRuntimeFieldLooseFlagDefinitionsForCommand:Xr,commandHasLongOption:Jr,commandHasShortOption:Yr,commandPathNeedsSearchExtensions:so,commandPathNeedsTemplateExtensions:Mt,describeUnknownError:de,defaultPreflightDecision:Fo,discoveryNeedsActivationForProbe:tt,emitExtensionProfile:es,emitExtensionSkippedProfile:Bt,emitSettingsReadWarnings:Lo,ensureIdempotentTopLevelCommandRegistration:cs,enforceExplicitRetryForFlagTypos:Eo,envFlagEnabled:Vr,executeRegisteredRuntimeMigrations:ns,extractCommandScopedOptions:De,extensionActivationCommands:Nt,extensionCapabilities:et,extensionNeedsActivationForProbe:Ft,extensionProvidesTemplatesRuntime:co,hasAnyCapability:Ie,hasGlobalExtensionContributions:mo,handleGenericRunPmCliError:Kr,handleRunPmCliCommanderError:_s,handleRunPmCliError:Vo,handleRunPmCliHelpDisplayError:gs,handleRunPmCliKnownError:us,handleRunPmCliCommanderUsageError:hs,handleUnknownHelpCommandError:fs,inferMissingFieldsFromErrorMessage:zr,inferPostActionErrorCode:Io,inferPostActionFailureMessage:Ro,invocationRequestsVersion:it,isCommanderError:dn,loadRuntimeExtensionCommandDescriptorsForRecovery:Go,loadRuntimeExtensionDiscoverySnapshot:Kt,loadRuntimeExtensionSnapshot:Me,maybeLoadRuntimeExtensions:ts,maybeAttachCreateUpdatePolicyHelpText:qo,maybeLogHandledCliErrorToSentry:Vt,matchesStaticExtensionCommand:Dt,normalizeTelemetryCommandResolution:Ao,normalizeTelemetryErrorCategory:Oo,normalizeTelemetryResolutionStage:To,normalizeThrownExitCode:cn,probeUsesAnyFlag:lo,prepareExtensionServicesForRunPmCliError:ds,readRecordBoolean:So,readRecordNumber:qt,readRecordString:ye,recordCliReadOutputInvocationProvenance:go,registerDynamicExtensionCommandPaths:ss,registerRuntimeSchemaFieldFlags:Zr,resolveCoreCommandRegistrationSelection:bo,resolveStaticExtensionActivationDecision:po,resolveUnknownHelpToken:Fn,readThrownExitCode:ln,runAndClearAfterCommandHooks:lt,runRequiredExtensionCommand:as,shouldAttachRichHelpTextForInvocation:Co,shouldLogHandledErrorToSentry:Br,shouldRegisterDynamicExtensionPaths:ko,shouldRegisterRuntimeSchemaFlags:xo,shouldHandleRunPmCliCommanderError:ys,setActiveExtensionHookContextForTest:bd,setActiveRuntimeExtensionCommandDescriptorsForTest:Cd,setRecoveredExtensionServices:ms,toLooseFieldDefinitionType:No,isImporterOrExporterCommandPath:yo,validateDynamicExtensionCommandInvocation:wo,wrapProgramActionsForExtensionHandlers:is,wrapThrownErrorForSentry:mn};export{wu as _testOnly,_u as runPmCli};
|
|
38
38
|
//# sourceMappingURL=main.js.map
|