@unbrained/pm-cli 2026.9.2 → 2026.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +17 -0
- package/dist/cli/after-command-context-usage.js +16 -3
- package/dist/cli-bundle/bundle-manifest.json +154 -154
- package/dist/cli-bundle/chunks/{chunk-T6H5BZCP.js → chunk-34HASX3S.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-AY324UJ5.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-TAG4VC22.js → chunk-DKGP3QLE.js} +27 -27
- package/dist/cli-bundle/chunks/chunk-E5RBBCXO.js +230 -0
- package/dist/cli-bundle/chunks/{chunk-DTGWEL23.js → chunk-EDPIS7EB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-X4RCGLTX.js → chunk-IEHHE6GA.js} +5 -5
- package/dist/cli-bundle/chunks/{chunk-UDW64J2W.js → chunk-L7B7343B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-FZ4Z2J4F.js → chunk-LENC656S.js} +41 -41
- package/dist/cli-bundle/chunks/{chunk-ZLJIFSOE.js → chunk-LISESA7W.js} +33 -33
- package/dist/cli-bundle/chunks/{chunk-3WICXLVT.js → chunk-UPPM2FOZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y7VOMSZT.js → chunk-Y4PJ6HPK.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-XYNX4ASQ.js → register-list-query-W2ZTOMKP.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-WFQ7MJTX.js → register-mutation-RVND5NCG.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-JVTI7JPP.js → register-operations-TTROIVC4.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-KVNC5KPL.js → register-setup-D3ZFHY3L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3ZBI35HU.js +176 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SVXJYD6G.js → chunk-4HJFY4MB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4RRHC3S4.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-4WR46RMG.js +9 -0
- package/dist/cli-bundle/focused-chunks/chunk-5RFXUPN5.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-BWKHEIVF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-4O4CJAR6.js → chunk-D7KXFBXV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MKHG3T76.js → chunk-GHCZ3YFR.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-KB5OFSFD.js → chunk-GT7MXDLW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KBLZRU62.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-KZ2NB3ET.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-M5M6SVHS.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BEVHCEWG.js → chunk-OL5EH6I3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MEASX544.js → chunk-Q45NHPF2.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O67VDLOT.js → chunk-QKHCSUGJ.js} +42 -42
- package/dist/cli-bundle/focused-chunks/chunk-S27XMBIN.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-TXE4TSHM.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-UCLO3XDU.js +2 -0
- package/dist/cli-bundle/main.js +15 -15
- 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 +28 -28
- 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 +35 -33
- 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 +9 -9
- package/dist/core/history/event-classification.d.ts +21 -0
- package/dist/core/history/event-classification.js +109 -0
- package/dist/core/history/event-index.d.ts +14 -3
- package/dist/core/history/event-index.js +543 -88
- package/dist/core/history/history.js +47 -18
- package/dist/core/history/workspace-history.js +7 -6
- package/dist/core/lock/lock.d.ts +22 -2
- package/dist/core/lock/lock.js +121 -19
- package/dist/core/output/output.js +31 -7
- package/dist/core/shared/time.d.ts +2 -0
- package/dist/core/shared/time.js +8 -2
- package/dist/core/store/item-metadata-query-index.js +5 -5
- package/dist/sdk/context/recency.d.ts +9 -0
- package/dist/sdk/context/recency.js +34 -0
- package/dist/sdk/context/usage-egress.d.ts +9 -0
- package/dist/sdk/context/usage-egress.js +30 -0
- package/dist/sdk/context-intent-contracts.js +7 -3
- package/dist/sdk/context-relevance.d.ts +23 -0
- package/dist/sdk/context-relevance.js +94 -23
- package/dist/sdk/context-signal-store.d.ts +7 -3
- package/dist/sdk/context-signal-store.js +155 -42
- package/dist/sdk/context-usage.d.ts +54 -0
- package/dist/sdk/context-usage.js +245 -16
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +14 -14
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +14 -2
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.js +4 -2
- package/dist/sdk/init.d.ts +2 -0
- package/dist/sdk/init.js +18 -9
- package/dist/sdk/query/context.d.ts +3 -1
- package/dist/sdk/query/context.js +21 -9
- package/dist/sdk/query/next.js +18 -9
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +25 -2
- package/dist/sdk/runtime.d.ts +1 -0
- package/dist/sdk/runtime.js +17 -26
- package/dist/types.d.ts +2 -0
- package/dist/types.js +2 -2
- package/docs/CONTEXT_RELEVANCE.md +44 -1
- package/docs/PERFORMANCE.md +6 -3
- package/docs/READ_OUTPUT_CONTRACTS.md +9 -1
- package/docs/SDK.md +11 -8
- package/docs/SDK_CONTEXT.md +7 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
- package/marketplace.json +2 -2
- package/package.json +4 -4
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +241 -24
- package/dist/cli-bundle/chunks/chunk-GOACULJW.js +0 -13
- package/dist/cli-bundle/chunks/chunk-NOPL37X4.js +0 -205
- package/dist/cli-bundle/focused-chunks/chunk-242AXYB2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2FEZ5SKM.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6GCRSLPG.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7VATS5QY.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-JEFKLWMM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PF3E6Q36.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-QDFJIRKN.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-RMRCQPWU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-S4U5CN5Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-T2LXXSOD.js +0 -158
- package/dist/cli-bundle/focused-chunks/chunk-Z2USIBR2.js +0 -5
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{A as Ht,B as
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function gr(e,t){return t==="detailed"?Da(e):Fa(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var La={cal:"calendar",ctx:"context"};function Ua(e,t){return e.commands.find(n=>n.name()===t)??null}function ja(e,t){let n=e;for(let o of t){let r=Ua(n,o);if(!r)return null;n=r}return n}function Vt(e,t,n,o){let r=ja(e,t.split(" ").filter(i=>i.length>0));r&&r.addHelpText("after",gr(n,o))}function Jt(e){return e.includes("--explain")?"detailed":"compact"}function ce(e){return e.includes("--all")||e.includes("--explain")}var hr={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},Kt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function qa(e){let t=N(e??"");return t?La[t]??t:""}function Ha(e){let t=qa(e);return t?hr[t]??Kt:Kt}function yr(e,t){let n=Ha(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:fr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function za(){let e=se.filter(({lifecycle:n})=>n==="permanent"),t=se.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(`
|
|
5
|
-
`)}function
|
|
6
|
-
`,s=t.visibleCommands(e);for(let l of s)Q(l)===void 0&&(l.name()==="help"||r.has(l.name()))&&n.add(l);for(let l of s)Q(l)==="core"&&(n.add(l),
|
|
7
|
-
`)}function Ar(e,t){return Va(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 Qa(e,t){if(e.flag)return e.flag;let n=r=>{let i=r.split("=",1)[0];return Ae([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))},o=[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(r=>r[0]).find(r=>n(r));return o||e.recovery?.provided_fields?.map(r=>r.split("=",1)[0]).find(r=>n(r))}function es(e,t,n){if(e.value!==void 0)return e.value;if(n){let r=t.find(a=>a===n||a.startsWith(`${n}=`));if(r?.startsWith(`${n}=`))return r.slice(n.length+1);let i=t.indexOf(n);return i>=0?t[i+1]:void 0}let o=e.recovery?.allowed_values;if(o?.length)return t.find((r,i)=>i>0&&!r.startsWith("-")&&!o.includes(r))}function ts(e,t){let n=e.recovery?.normalized_args??[],o=Qa(e,n),r=es(e,n,o);return{surface:o??e.recovery?.missing?.[0]??Tr(e.recovery)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function ns(e,t){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:ts(e,t)},e)}function en(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 wo(ns(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function tn(e){return Ar({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function st(e){return e.replace(/\(outputHelp\)/g,"").trim()}function os(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 ne(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 Cr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Tr(e){return tr(e?.normalized_args)}function rs(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 is(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let i of o){let a=n.findIndex(s=>s===i);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=r,A(s)}}}function as(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function it(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function W(e,t,n){if(!n)return e;let o=st(t),r=it(n.code,e.code),i=it(n.type,Er(r)),a=ne(n.examples)??e.examples,s=ne(n.nextSteps)??e.nextSteps,l=ne(n.verification_errors)??e.verificationErrors,d=e.code==="command_failed"&&n.code?as(o):void 0,c=me(n.recovery),m=c&&e.recovery?me({...e.recovery,...c}):c??e.recovery;return{...e,code:r,type:i,title:d??e.title,happened:o.length>0?o:e.happened,required:it(n.required,e.required),why:it(n.why,e.why),examples:a,nextSteps:s,verificationErrors:l,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:m}}function ss(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let r=o[1],i=Zn(process.cwd(),r);return W(x(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${i}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${i} <command>`,`PM_PATH=${i} pm <command>`],nextSteps:[`Re-run with "--pm-path ${i}" or export PM_PATH=${i}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function ls(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=i?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return W(x({code:"item_not_found",title:"Item ID not found",happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:i?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function cs(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:W(x({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function ds(e,t,n){return t.includes("is locked")?W(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function ms(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let i=!!r,a=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",l=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return W(x({code:"missing_required_option",title:i?"Missing required options":`Missing required option ${s}`,happened:t,required:i?"Provide every required option for this command invocation.":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 ps(e,t,n){return t.startsWith("No update flags provided")?W(x({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function us(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=me(n?.recovery),r=Tr(o),i=r?`pm ${r} --help`:"pm <command> --help",a=rs(t),s=me({...o,allowed_values:o?.allowed_values??a}),l=is(o,a),d=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],c=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return W(x({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:d,nextSteps:c,recovery:s}),e,n)}function nn(e,t){let n=st(e),o=ss(e,n,t)??ls(e,n,t)??cs(e,n,t)??ds(e,n,t)??ms(e,n,t)??ps(e,n,t)??us(e,n,t);return o||W(x({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function fs(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 gs(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function hs(e){if(!(!Array.isArray(e)||e.length===0))return A(e)}function on(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function L(e,t={}){let n=on(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:hs(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return me({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:i,...t})}function Qt(e,t){return!t||e.includes(t)?e:[...e,t]}var ys=new Set(["--add","--add-json","--remove"]),ws=new Set(["command","cmd","path"]);function _s(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(ys.has(o))return o}}function bs(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!ws.has(i))return;let a=[];for(let d=o+2;d<e.length;d+=1){let c=e[d];if(c.startsWith("--")&&c.length>2)break;a.push(c)}if(a.length<2)return;let s=`${i}=${a.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return A(l)}}function xs(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let i=gs(r[1]),a=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=on(o?.providedOptionFlags),d=[i],c=fs(t,i,n),m=s?Qt(c,s):c,p=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Qt(p,`Replay with preserved arguments: ${s}`):p,g=l&&l.length>0?Qt(u,`Already provided options: ${l.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${i}`,happened:`Commander rejected the command because ${i} was not provided.`,required:`Pass ${i} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:L(o,{missing:d})})}function vs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function Cs(e,t,n){return x({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:L(t,{suggested_flags:n})})}var ks={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 Es(e){let t=ne(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function Ss(e,t,n,o,r){let i=o.otherCommands.slice(0,3),a=o.candidateTotal-i.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(l=>typeof l=="string")}function As(e,t){if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};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 r=Ae(n.filter((i,a)=>a!==o));return{retryCommand:A(r),suggestedRetryArgs:r}}function Ts(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},i=o[1],a=on(r.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=As(r,i);if(t==="update"&&(i==="--file"||i==="--doc"))return Cs(i,n,a);let d=Es(r),c=Ss(i,t,a,d,s),m=[s,`pm ${t??"<command>"} --help`].filter(p=>typeof p=="string");return x({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:ks[d.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:c,recovery:L(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:d.otherCommands,candidate_commands_total:d.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:d.optionScope})})}function Os(e,t,n,o,r){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:Cr([t.installCommand,...n]),nextSteps:Cr([i,...a]),recovery:L(r)})}function Rs(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ne(t?.unknownCommandExamples),i=ne(t?.unknownCommandNextSteps),a=Ja(o),s=r??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),c=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!c||!d.has(c))?Os(o,a,s,l,t):x({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:l,recovery:L(t)})}function Is(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ne(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function $s(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=_s(o);if(!r)return null;let i=bs(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...i?[i]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...i?[`Replay with the value re-joined into one argument: ${i}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,i?{suggested_retry:i}:{})})}var Ps=new Set(["comments","docs","files","learnings","notes","test"]);function Ns(e,t,n){if(!/too many arguments/i.test(e)||!Ps.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>d===t),i=o[r+1],a=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return x({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[l,`pm ${t} --help`],recovery:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var Ms=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"]),kr=new Set(["context","ctx"]);function Fs(e,t,n){if(!/too many arguments/i.test(e)||!kr.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>kr.has(d)),i=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let c of o.slice(i)){if(d){d=!1;continue}let m=c.split("=")[0];if(Ms.has(m)){d=!c.includes("=");continue}if(!c.startsWith("-")){s=c;break}}}if(!s)return null;let l=`pm get ${s}`;return x({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${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:L(n,{suggested_retry:l})})}function rn(e,t,n,o){let r=st(e),i=xs(r,t,n,o)??vs(r,t,o)??Ts(r,t,o)??Rs(r,o)??Is(o)??Ns(r,t,o)??$s(r,t,o)??Fs(r,t,o);return i||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function Or(e,t){let n=nn(e,t);return Ot(Sr(n),n.required).output}function Rr(e,t){return tn(nn(e,t))}function an(e,t,n){return en(nn(e,n),t)}function Ir(e,t,n,o){let r=rn(e,t,n,o);return Ot(Sr(r),r.required).output}function sn(e,t,n,o){return tn(rn(e,t,n,o))}function lt(e,t,n,o,r){return en(rn(e,t,n,r),o)}function $r(e,t){let n=Pr(e);return en(n,t)}function Pr(e){let t=st(e);return os(t)?x({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):x({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Nr(e){return tn(Pr(e))}import{Option as Ds}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99d39b7c-ec26-5c95-85c0-ac28112a6fe6")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Fr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let a=_(i.command),s=a.split(" "),l=s.at(-1),d=s.slice(1).join(" "),c=d?`${s[0]}-${l} ${d}`:`${s[0]}-${l}`;if(l&&r===c){n.set(r,a);break}}}return n}function ln(e,t,n,o){if(!t||!n)return;let r,i=0;for(let[s,l]of e.entries()){if(l!==t)continue;let d=e.slice(s);for(let[c,m]of o.entries()){let p=c.split(" ");p.length>i&&p.every((u,g)=>d[g]===u)&&(r=m,i=p.length)}}let a=r?.flags.find(s=>s.long===n||s.short===n);if(a)return ct(a).takesValue}function T(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function B(e){return typeof e=="boolean"?e:void 0}function ct(e){let t=T(e.value_type)??T(e.type),n=T(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||B(e.required)===!0||B(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Ls(e){if(B(e.visible)===!1)return null;let n=T(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",i=T(e.value_name),a=i?` <${i}>`:"",s=T(e.description)??"Extension-provided option.",l=[];B(e.required)===!0&&l.push("required"),B(e.enabled)===!1&&l.push("disabled");let d=l.length>0?` [${l.join(", ")}]`:"";return`${r}${n}${a} ${s}${d}`}function Dr(e){let t=[...new Set(e.map(Ls).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
2
|
+
import{A as Ht,B as rr,C as zt,E as ir,d as Uo,h as z,i as Ae,j as P,k as Qo,l as k,m as er,r as tt,s as tr,t as nr,v as or,w as Z,x as Ut,y as jt,z as qt}from"./chunks/chunk-EDPIS7EB.js";import{A as Ho,ab as Zo,f as qo}from"./chunks/chunk-LENC656S.js";import"./chunks/chunk-Y4PJ6HPK.js";import"./chunks/chunk-IEHHE6GA.js";import{$c as Jo,Tb as Vo,Yc as et,ad as Yo,bd as X,cd as Xo,sc as Ko}from"./chunks/chunk-LISESA7W.js";import{Ea as Bo,ma as Wo}from"./chunks/chunk-DKGP3QLE.js";import"./chunks/chunk-AY324UJ5.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$g as y,$m as Ft,Ac as co,Ae as Be,Aj as ve,Bc as Y,Bj as Nt,C as f,Cc as mo,Cf as Ke,Cj as $o,D as vt,Dc as ze,Dj as Ce,E as v,Ec as ae,Fc as se,Fd as Tt,G as _e,Gg as ko,Gj as Po,Hj as No,Ic as po,Jc as Ge,Jm as jo,K as Ct,Km as Ze,Lb as Qn,Lg as Eo,Ma as Et,Oe as A,Oi as Je,Pa as J,Pc as At,Pe as Ve,Pi as Ro,Pk as Ye,Qc as We,Ra as Xn,Rc as uo,Rk as Ee,Sa as He,Sc as fo,Sk as Xe,Tb as eo,Uj as ke,Va as St,Vb as to,Wa as Zn,Xa as E,Xg as So,Xj as Mo,Yg as Ao,Zm as Qe,_a as H,_g as Rt,_j as Do,_m as Dt,aa as Bn,an as Se,ba as Vn,bn as $,c as q,ca as kt,cg as wo,cn as zo,dg as Ot,dk as Mt,dn as Lt,ek as Fo,fk as Lo,hc as no,ic as be,ja as Kn,jn as D,ka as Jn,kc as xe,lc as oo,ma as Yn,se as go,sf as le,sg as _o,tf as ho,tg as bo,uc as ro,ug as xo,ui as To,vc as io,vf as yo,vg as vo,vi as ce,wc as ao,wg as Co,wi as I,wj as Io,xc as so,xi as Oo,xj as It,xn as Go,yc as V,yj as $t,zc as lo,zj as Pt}from"./chunks/chunk-E5RBBCXO.js";import{Command as $n,CommanderError as Xl}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8eca3029-0d1f-569a-84ce-5ccd0b92a272")}catch{}})();var Aa=new Set(["__proto__","prototype","constructor"]),ar=Symbol("looseOptionOccurrences");function Te(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function Ta(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 Gt(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let a=n.indexOf("=");if(a>=0)return{consumed:1,key:n.slice(1,a).trim(),value:n.slice(a+1)};let s=n.slice(1).trim(),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)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),i=e[t+1];return typeof i=="string"&&!i.startsWith("-")?{consumed:2,key:r,value:i}:{consumed:1,key:r,value:!0}}function nt(e){return Aa.has(e)}function sr(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return Bn(t)}function Oe(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=Te(n.slice(2));r.length>0&&!nt(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=Te(o.slice(1));r.length>0&&!nt(r)&&t.push(r)}return[...new Set(t)]}function lr(e){let t=new Set;for(let n of e)for(let o of Oe(n))t.add(o);return t}function Oa(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=Te(t.slice(2));if(n.length>0&&!nt(n))return n}return Oe(e)[0]??null}function Ra(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 Wt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,i=[],a=[];for(let s of t){let l=Oe(s),d=Ra(s);d!==null&&a.push(d);for(let c of l)o.add(c),s.enabled===!1&&r.set(c,d);s.required===!0&&s.enabled!==!1&&l.length>0&&i.push({keys:l,label:d})}for(let s of Object.keys(e)){if(!o.has(s)){let d=a.length>0?` Expected one of: ${[...new Set(a)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${d}`,f.USAGE)}let l=r.get(s);if(l)throw new v(`Option '${l}' is disabled for extension command '${n}'.`,f.USAGE)}for(let s of i)if(!s.keys.some(l=>Object.hasOwn(e,l)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,f.USAGE)}function Ia(e){return typeof e=="string"||e==null?e:String(e)}function $a(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 Pa(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 Na={string:Ia,number:$a,boolean:Pa};function ot(e,t){return Array.isArray(e)?e.map(n=>ot(n,t)):Na[t](e)}function cr(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):Vn(e);return t?o.map(r=>ot(r,t)):o}function Ma(e,t,n,o){return n?cr(e,t,o):t?ot(e,t):e}function Da(e,t,n){let o=e[ar];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(i=>r.has(i.key)).map(i=>i.value)}function dr(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,i]of Object.entries(e))o[r]=i;for(let r of t){let i=Oa(r);if(!i)continue;let a=r.list===!0,s=Oe(r);for(let c of s)if(!(c===i||!Object.hasOwn(o,c))){if(Object.hasOwn(o,i)){if(!a){delete o[c];continue}let m=o[i],p=o[c];o[i]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[c];continue}o[i]=o[c],delete o[c]}let l=sr(r),d=r.repeatable===!0;if(!Object.hasOwn(o,i)){r.default!==void 0&&(o[i]=Ma(r.default,l,a,d));continue}if(a){o[i]=cr(Da(n,s,o[i]),l,d);continue}l&&(o[i]=ot(o[i],l))}return o}function mr(e){let t=Object.create(null),n=[];Object.defineProperty(t,ar,{value:n});let o=0;for(;o<e.length;){let r=Gt(e,o);if(!r){o+=1;continue}let i=Te(r.key);if(i.length===0||nt(i)){o+=r.consumed;continue}Ta(t,i,r.value),n.push({...r,key:i}),o+=r.consumed}return t}function pr(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=Gt(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Bt(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let a of t){let s=sr(a);for(let l of Oe(a))n.add(l),s==="boolean"&&o.add(l)}if(n.size===0)return[...e];let r=[],i=0;for(;i<e.length;){if(e[i]==="--"){r.push(...e.slice(i+1));break}let a=Gt(e,i);if(a){let s=Te(a.key);if(n.has(s)){let l=e[i],d=o.has(s)&&!l.includes("=")?1:a.consumed;i+=d;continue}}r.push(e[i]),i+=1}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c0186e30-9c25-5539-b778-1ef2ee21764a")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1399e88f-710a-5e5c-b4b3-70e35ec401cf")}catch{}})();var ur=new WeakMap;function fr(e,t){ur.set(e,t)}function Q(e){return ur.get(e)}function gr(e){return e.length>0?[e[0]]:[]}function Fa(e){let t=["","Intent:",` ${e.why}`],n=gr(e.examples);return n.length>0&&(t.push("","Example:"),t.push(` ${n[0]}`)),t.push("","Need deeper rationale and more examples?"),t.push(" Re-run with --explain."),t.join(`
|
|
3
|
+
`)}function La(e){let t=["","Why use this command:",` ${e.why}`,"","Examples:",...e.examples.map(n=>` ${n}`)];return e.tips&&e.tips.length>0&&(t.push("","Tips:"),t.push(...e.tips.map(n=>` - ${n}`))),t.join(`
|
|
4
|
+
`)}function hr(e,t){return t==="detailed"?La(e):Fa(e)}function N(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var Ua={cal:"calendar",ctx:"context"};function ja(e,t){return e.commands.find(n=>n.name()===t)??null}function qa(e,t){let n=e;for(let o of t){let r=ja(n,o);if(!r)return null;n=r}return n}function Vt(e,t,n,o){let r=qa(e,t.split(" ").filter(i=>i.length>0));r&&r.addHelpText("after",hr(n,o))}function Jt(e){return e.includes("--explain")?"detailed":"compact"}function de(e){return e.includes("--all")||e.includes("--explain")}var yr={init:{why:"Bootstraps tracker storage and settings so all other commands can run safely.",examples:["pm init","pm init acme","pm init ./pm-sandbox --defaults","pm init --preset minimal","pm init --agent-guidance add","pm init --defaults --with-packages"],tips:["Run this once per repository before create/list/update commands.","A path-like positional (`./dir`, `/tmp/dir`) initializes that tracker path; a plain word remains an id prefix.","Rewriting id prefix, governance preset, or default author on an existing tracker requires --force.","Use --preset for non-interactive automation; omit it in a TTY to use the setup wizard.","Use --agent-guidance add to inject compact AGENTS/CLAUDE workflow guidance, or --agent-guidance status to inspect missing guidance without modifying files.","Use --with-packages when agents need bundled commands such as calendar and templates available immediately."]},config:{why:"Reads or updates project/global settings such as definition-of-done, item format, telemetry, and policy toggles.",examples:["pm config project get definition-of-done",'pm config project set definition-of-done --criterion "tests pass"',"pm config project set item-format --format toon","pm config project set sprint-release-format-policy --policy strict_error","pm config project set governance-preset --policy minimal","pm config project set governance-ownership-enforcement --policy none","pm config project set test-result-tracking --policy enabled","pm config global set telemetry-tracking --policy disabled"]},extension:{why:"Compatibility command for package-backed runtime extension lifecycle operations across project or global scope.",examples:["pm install ./my-package --project","pm install '*' --project","pm package doctor --project --detail summary","pm package manage --global","pm package activate sample-ext --project","pm package deactivate sample-ext --project","pm package uninstall sample-ext --global","pm extension explore --project","pm extension manage --global","pm extension describe sample-ext --project","pm extension doctor --detail deep"],tips:["Prefer pm install and pm package in new user-facing automation.","Use pm extension when maintaining existing extension-specific scripts or debugging the compatibility runtime directly.","Bundled aliases beads and todos resolve to package-shipped extension sources.","Use --gh/--github shorthand for GitHub sources and --ref to pin a branch, tag, or ref.","Install updates settings activation state automatically unless extension allowlist mode is unchanged.","Use --adopt for single-extension adoption and --adopt-all to bulk-register unmanaged installs as managed without reinstalling.","Use --manage for concise triage summaries and remediation-oriented diagnostics alongside full extension details.","Use --describe to map exactly what each loaded extension registers (commands, hooks, item types, providers, overrides) in one call.","Use --doctor for consolidated diagnostics with warning codes, remediation hints, and optional deep detail payloads."]},package:{why:"Installs, explores, manages, diagnoses, adopts, activates, deactivates, and refreshes package-backed pm runtime extensions.",examples:["pm install npm:@scope/pm-package --project","pm package install ./my-package --project","pm package doctor --project --detail deep","pm package manage --project --runtime-probe","pm package describe --project","pm package activate sample-ext --project","pm upgrade --packages-only --dry-run"],tips:["Prefer package vocabulary for user-facing workflows; extension vocabulary remains available for compatibility.","Use pm package describe [name] to map every surface a package registers without reading its manifest or running diagnostics.","Use pm upgrade to refresh the CLI/SDK and managed packages from their recorded sources.","Use --dry-run before upgrade when automation needs a deterministic plan."]},"package init":{why:"Generates an installable starter pm package with package metadata and a root extension entrypoint.",examples:["pm package init ./my-package","pm package init ./my-hook-package --capability hooks","pm package init ./my-search-package --capability search","pm package init ./my-sync-package --capability importers","pm package init ./my-domain-package --capability schema","pm package init ./my-output-package --capability renderers","pm install ./my-sync-package --project","pm package doctor --project --detail summary"],tips:["Use --capability hooks for a starter after_command lifecycle reactor with runnable SDK testing coverage.","Use --capability search for a starter search provider/vector-store adapter with runnable SDK testing coverage.","Use --capability importers for paired import/export commands that move project context across systems.","Use --capability schema for a starter custom item type, field, and migration so pm models your project domain.","Use --capability renderers/parser/preflight/services for starter override surfaces (output renderer, parsed-option rewrite, pre-run gate decision, built-in service) \u2014 one runnable starter per SDK capability.","The generated package is local-install safe; add SDK runtime imports only after declaring dependencies and validating with package doctor.","Use package doctor after changes to verify activation, policy, and collision diagnostics."]},"package install":{why:"Installs pm packages from local paths, npm sources, GitHub sources, bundled aliases, or wildcard/all aliases.",examples:["pm package install ./my-package --project","pm install npm:pm-changelog --project","pm package install --github org/repo/packages/my-pm-package --ref main"],tips:["Prefer the top-level pm install alias in scripts when only installation is needed.","Run pm package manage or pm package doctor after installing external packages."]},"package doctor":{why:"Diagnoses package activation, policy, collision, and managed-state health for project or global package scopes.",examples:["pm package doctor --project --detail summary","pm package doctor --project --detail deep --trace","pm package doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed package registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global package state: PM_GLOBAL_PATH=$(mktemp -d) pm package doctor --project --detail deep --trace.","Non-isolated project diagnostics include global registrations and emit remediation when global package state can affect the result."]},"package catalog":{why:"Lists bundled first-party package catalog metadata and compact field projections.",examples:["pm package catalog --project","pm package catalog --project --fields alias,installed,install_command","pm package list --project --fields alias,package_name,category"],tips:["Use --fields for low-token package discovery in agent loops.","External npm package discovery still belongs to npm search."]},"extension init":{why:"Generates an installable starter runtime extension with manifest and entrypoint files.",examples:["pm extension init ./my-extension","pm extension init ./my-hook-extension --capability hooks","pm extension init ./my-search-extension --capability search","pm extension init ./my-sync-extension --capability importers","pm extension init ./my-domain-extension --capability schema","pm extension init ./my-output-extension --capability renderers","pm extension --install --project ./my-sync-extension","pm extension --doctor --project --detail summary"],tips:["Use --capability hooks when the extension should react to command lifecycle events.","Use --capability search when the extension should register retrieval primitives.","Use --capability importers when the extension should register project-context import/export commands.","Use --capability schema when the extension should register custom item types, fields, and migrations.","Use --capability renderers/parser/preflight/services to override pm's output rendering, parsed options, pre-run gate, or a built-in service.","Use package init for new distributable package workflows; extension init is the compatibility-level runtime scaffold."]},"extension install":{why:"Installs a compatibility runtime extension from local, npm, GitHub, bundled alias, or wildcard sources.",examples:["pm extension install ./my-extension --project","pm extension --install --project ./my-extension","pm extension doctor --project --detail summary"],tips:["Prefer pm install or pm package install for new package-first automation."]},"extension doctor":{why:"Diagnoses compatibility extension activation, policy, collision, and managed-state health for project or global extension scopes.",examples:["pm extension doctor --project --detail summary","pm extension doctor --project --detail deep --trace","pm extension doctor --project --isolated --detail deep --trace"],tips:["Use --isolated (alias --ignore-global) for hermetic project smoke tests that must ignore globally installed extension registrations.","Set PM_GLOBAL_PATH for a whole subprocess suite when every pm invocation must avoid machine-local global extension state: PM_GLOBAL_PATH=$(mktemp -d) pm extension doctor --project --detail deep --trace.","Prefer pm package doctor in new package-first workflows."]},"extension catalog":{why:"Compatibility view of bundled package catalog metadata.",examples:["pm extension catalog --project","pm extension catalog --project --fields alias,installed,install_command"],tips:["Prefer pm package catalog in new user-facing workflows."]},install:{why:"Installs a pm package into project scope by default, using local, npm, GitHub, or bundled alias sources.",examples:["pm install '*' --project","pm install ./packages/pm-todos --project","pm install npm:@scope/pm-package --global","pm install --github org/repo/packages/my-pm-package --ref main"],tips:["Installed packages are recorded in managed state and can be inspected with pm package manage."]},upgrade:{why:"Updates the global pm CLI/SDK and refreshes managed pm packages from recorded install sources.",examples:["pm upgrade --dry-run","pm upgrade --packages-only --project","pm upgrade todos --dry-run","pm upgrade --cli-only --repair","pm upgrade --tag next --dry-run"],tips:["Omit target to include the CLI/SDK plus all managed packages in the selected scope.","Pass a target to refresh one managed package by name, directory, package name, or source.","Use --packages-only in repository automation when the global CLI should not be changed."]},create:{why:"Creates a new planning item with deterministic metadata and history.",examples:['pm create --title "Harden lock flow" --description "Improve stale lock handling" --type Task --status open --priority 1 --message "Create lock hardening task" --create-mode progressive','pm create --title "Weekly planning sync" --description "Recurring coordination meeting" --type Meeting --schedule-preset lightweight','pm create --title "Asset: Hero model" --description "Track playable model asset" --type Asset --status open --priority 1 --message "Create asset item" --type-option category=Character --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this asset item exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/assets/hero.glb,note=tracked asset" --test "command=node scripts/run-tests.mjs test,timeout_seconds=240" --doc "path=README.md,note=asset docs"'],tips:["Use --schedule-preset lightweight for Reminder/Meeting/Event when you want minimal required create inputs.","Use --type <value> to load type-aware policy guidance in --help output."]},focus:{why:"Sets a session focused item so new pm create items default their --parent to it (project management = context management).",examples:["pm focus pm-epic1","pm focus","pm focus --clear"],tips:["Focus is session-local (stored in .agents/pm/runtime/session.json, gitignored) \u2014 it never affects teammates.",'An explicit --parent on pm create always overrides the focused item; use --parent "" to create with no parent.',"A stale focused item produces the same missing-parent validation as an explicit stale --parent."]},update:{why:"Mutates existing item fields while preserving history and lock safety.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --unset close-reason --message "Clear stale close reason after reopen"','pm update pm-a1b2 --unset assignee --deadline +2d --message "Replan ownership and deadline"','pm update pm-a1b2 --body "Backfilled body text for legacy item" --message "Normalize missing body"'],tips:['Use "pm close <ID> <TEXT>" to close items instead of --status closed.',"When reopening from closed to a non-terminal status, update clears stale close_reason unless explicitly set via --close-reason.",'Use "pm append <ID> --body <text>" for additive notes; use update --body to replace body content.']},"update-many":{why:"Bulk-updates matched item sets with dry-run previews and rollback checkpoints for safe large-scale metadata changes.",examples:["pm update-many --filter-status open --status in_progress --dry-run",'pm update-many --filter-tag wave:7 --replace-tests --test "command=node scripts/run-tests.mjs test -- tests/core/history.spec.ts,timeout_seconds=240"','pm update-many --filter-tag governance --reviewer maintainer-review --message "Normalize reviewer metadata"',"pm update-many --rollback ckpt-abc123"],tips:["Use --dry-run first to inspect proposed changes before apply mode.","Linked-array mutation flags mirror pm update semantics (for example --replace-tests, --clear-files, and repeatable --doc/--note seeds).","Checkpoints are enabled by default for apply mode and can be restored with --rollback."]},"close-many":{why:"Bulk-closes matched items with a shared reason routed through full pm close semantics (close validation, active-child orphan checks, blocked-edge cleanup) plus dry-run previews and rollback checkpoints \u2014 unlike update-many --status closed, which bypasses close validation.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met" --dry-run','pm close-many --filter-tag wave:7 --reason "Superseded by redesign" --validate-close warn','pm close-many --ids pm-a,pm-b,pm-c --reason "Closed in batch" --resolution "Verified by integration suite"',"pm close-many --rollback close-many-20260604-abc123"],tips:["At least one filter (--filter-* or --ids) is required so close-many never matches every item.","Already-terminal matches are skipped by default; pass --force to re-close them.","Use --dry-run to preview matches plus per-item skip reasons and active-child orphan warnings before applying.","Checkpoints are enabled by default for apply mode; restore with --rollback <checkpoint-id>."]},templates:{why:"Saves, lists, and inspects reusable create option bundles for repeatable workflows.",examples:['pm templates save triage-default --title "Triage item" --description "..." --type Task --status open --priority 2 --message "Seed triage template"',"pm templates list","pm templates show triage-default"],tips:["Template names are positional arguments (`pm templates save <name>` and `pm templates show <name>`), not --name flags.","Combine templates with explicit create flags; explicit flags always override template defaults."]},deps:{why:"Inspects an item dependency graph as a tree or graph payload to understand blockers and hierarchy links.",examples:["pm deps pm-a1b2","pm deps pm-a1b2 --format graph","pm deps pm-a1b2 --max-depth 2 --collapse repeated --summary"],tips:["Use --summary for lightweight counts when full graph payloads are unnecessary."]},list:{why:"Lists active items with deterministic filtering and ordering.",examples:["pm list --limit 20","pm list --type Task --priority 0 --tag release --status in_progress","pm list --compact --sort deadline --order asc","pm list --fields id,title,parent,type --sort parent --order asc"]},"list-all":{why:"Lists all item states (including terminal states) when you need full visibility.",examples:["pm list-all --limit 50","pm list-all --type Issue --include-body"]},"list-open":{why:"Shows work that is ready to claim and start.",examples:["pm list-open --priority 0 --limit 10"]},"list-in-progress":{why:"Tracks active execution and owner progress.",examples:["pm list-in-progress --priority 0 --limit 20"]},"list-blocked":{why:"Surfaces blocked work that needs intervention.",examples:["pm list-blocked --limit 20"]},"list-closed":{why:"Reviews completed work and closure outcomes.",examples:["pm list-closed --limit 20 --type Task"]},"list-canceled":{why:"Audits intentionally discontinued work.",examples:["pm list-canceled --limit 20"]},"list-draft":{why:"Finds incompletely defined items that need refinement before execution.",examples:["pm list-draft --limit 20"]},aggregate:{why:"Runs grouped aggregation queries for governance checks such as decomposition by parent/type or triage by status/priority.",examples:["pm aggregate --group-by parent,type --count","pm aggregate --group-by type,status --count","pm aggregate --group-by parent,type --count --status open --parent pm-feature01"],tips:["Current aggregate mode is grouped counts only, so pass --count explicitly."]},guide:{why:"Routes local progressive-disclosure documentation so agents can fetch only the context they need.",examples:["pm install guide-shell --project","pm guide","pm guide quickstart","pm guide commands --depth standard","pm guide skills --depth deep --format markdown","pm guide release --json"],tips:["Use brief depth for minimal token footprint, standard for excerpted docs, and deep for full local document rendering.","Use --list to force topic index output even when topic parsing is ambiguous."]},calendar:{why:"Provides deadline/reminder/event scheduling views for planning and coordination.",examples:["pm calendar","pm calendar --view agenda --from +0d --to +7d --tag release","pm calendar --view week --date 2026-04-06 --full-period --include deadlines,events","pm calendar --view month --tag release --format json"],tips:["Day/week/month views are anchored period windows; default mode clips the start to now unless --past or --full-period is set.","--full-period applies only to day/week/month views; use --from/--to to bound agenda windows."]},context:{why:"Builds an agent-optimized snapshot of critical active work plus near-term agenda context with progressive depth levels.",examples:["pm context","pm ctx --depth standard --limit 10","pm ctx --depth deep --tag release","pm ctx --section hierarchy --section progress --section blockers","pm context --depth standard --activity-limit 20 --stale-threshold 14d","pm context --from +0d --to +7d --format markdown --depth deep"],tips:["High-level focus contains Epics/Features and low-level focus contains Tasks/Issues/Chores/Decisions/Event/Reminder/Milestone/Meeting/Plan.","When no open or in-progress work exists, blocked items are shown as fallback context.","--depth brief (default) shows focus+agenda; standard adds hierarchy/activity/progress/workload; deep adds blockers/files/staleness/tests.","--section overrides --depth and selects specific sections: hierarchy, activity, progress, blockers, files, workload, staleness, tests.","Configure defaults via pm config project set context --default-depth standard --activity-limit 15."]},next:{why:"Answers 'what should I work on now?' in one read: the single highest-priority ready item with rationale, plus the ranked ready and blocked queues (project management = context management).",examples:["pm next","pm next --json","pm next --limit 3 --ready-only","pm next --parent pm-mpbb","pm next --tag release --format markdown"],tips:["Ready = active status, no open blockers, and no open children (a concrete leaf); the recommendation resumes in-progress work before starting new work.","An item is blocked when its scalar blocked_by or a blocked_by dependency points at a non-terminal item; the blocked list names the blockers to clear.","Containers (Epics/Features with open children) are never recommended directly \u2014 the actionable leaf beneath them is.","Use --parent to scope to one epic's subtree, or --ready-only to drop the blocked companion list for the tightest output."]},search:{why:"Finds relevant items by keyword, semantic, or hybrid retrieval modes.",examples:['pm search "lock stale retry" --mode keyword --limit 10','pm search "extension migration blockers" --mode hybrid --type Task --priority 0','pm search "Cross-Epic Realism Dependency Council" --mode keyword --title-exact'],tips:["Use --title-exact to require exact normalized title parity, or --phrase-exact to require full-phrase matches in item text fields.","Use --include-linked when linked docs/files/tests should influence scoring."]},eval:{why:"Measures search relevance against a curated golden-query set so retrieval regressions are caught, not guessed.",examples:["pm eval --json","pm eval --mode hybrid --k 10","pm eval --fail-under 0.6 --json","pm eval --queries ./my-eval.json --mode semantic"],tips:["Curate ground truth in <pmRoot>/search/eval-queries.json as an array of {query, relevant_ids, mode?} objects.","Wire --fail-under into CI to fail the build when aggregate nDCG@k drops below your baseline."]},reindex:{why:"Rebuilds search artifacts after large changes to item corpus or provider/vector config.",examples:["pm reindex --mode keyword","pm reindex --mode hybrid --progress --json"],tips:["Use --progress for non-interactive visibility during local embedding runs.","JSON output includes semantic stale/unchanged/embed/upsert counts so agents can gate long reindex work without parsing stderr."]},get:{why:"Shows details for one item by ID, with optional lower-token projections for agent loops.",examples:["pm get pm-a1b2","pm get pm-a1b2 --depth brief --json","pm get pm-a1b2 --fields id,title,status,parent,type --json","pm get pm-a1b2 --at 7 --fields id,title,status,body --json"],tips:["Default depth is standard for body plus linked artifacts without append-only logs; use brief for metadata-only checks or --full for complete history-heavy metadata.","Use --fields for the smallest deterministic item metadata payload when an agent only needs specific fields.","Schedule metadata is normalized under schedule; request schedule.start_at or schedule.location for narrow calendar reads.","Children are type-agnostic and include bounded deterministic samples plus continuation metadata when a parent has direct children.","Use --at <version|timestamp> for a verified read-only historical projection; reconstructed/as_of fields distinguish it from current state.","JSON output shape is { item, linked, claim_state, schedule, children }; body is nested at item.body (parity with list --include-body)."]},history:{why:"Inspects item mutation timeline and audit trail.",examples:["pm history pm-a1b2 --limit 20","pm history pm-a1b2 --full --verify"]},"history-compact":{why:"Compacts long history streams into a synthetic checkpoint while preserving replay integrity. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to sweep many.",examples:["pm history-compact pm-a1b2 --dry-run",'pm history-compact pm-a1b2 --before 25 --message "Compact early history"',"pm history-compact --all-over 500 --dry-run","pm history-compact --closed","pm history-compact --ids pm-a1b2,pm-c3d4 --dry-run"]},activity:{why:"Reviews recent tracker-wide activity across items.",examples:["pm activity --limit 50","pm activity --full --id pm-a1b2 --limit 50","pm activity --id pm-a1b2 --op update --from -7d --to now","pm activity --json --stream rows --limit 200"],tips:["Use --stream with --json for line-delimited automation output; --from is inclusive and --to is exclusive."]},restore:{why:"Restores an item to a prior timestamp/version with history replay safety.",examples:['pm restore pm-a1b2 2026-04-01T00:00:00.000Z --message "Rollback to known-good state"']},close:{why:"Transitions work to terminal closed state with explicit rationale.",examples:['pm close pm-a1b2 "All acceptance criteria met" --message "Close after verification"','pm close pm-a1b2 "Done" --validate-close','pm close pm-a1b2 "Done" --validate-close off','pm close pm-a1b2 "Done" --validate-close strict']},delete:{why:"Removes an item while preserving history evidence and lock/ownership checks.",examples:['pm delete pm-a1b2 --message "Remove duplicate item"']},append:{why:"Adds implementation notes to body without replacing existing content.",examples:['pm append pm-a1b2 --body "Implemented retry with bounded backoff." --message "Record implementation detail"']},comments:{why:"Adds or reviews lightweight status updates linked to an item.",examples:['pm comments pm-a1b2 "Verified fix on Linux and macOS"','pm comments pm-a1b2 --add "Verified fix on Linux and macOS"','printf "%s\\n" "## Verification" "- linux pass" "- mac pass" | pm comments pm-a1b2 --stdin',"pm comments pm-a1b2 --file docs/release-evidence.md",'pm comments pm-a1b2 --add "text: verification note with commas, key-like words, and parser details"','pm comments pm-a1b2 --add "Follow-up needed after review" --force',"pm comments pm-a1b2 --limit 10"],tips:["Use exactly one comment source at a time: positional [text], --add, --stdin, or --file.","Use --force when adding comments to items currently assigned to a different owner.","When --add payload resembles CSV-like key fragments (for example text=hello,scope:project), plain-text fallback is intentional; use explicit text=..., markdown text: ..., or stdin token - for structured intent."]},notes:{why:"Adds or reviews durable implementation notes linked to an item.",examples:['pm notes pm-a1b2 --add "Investigated parser edge case and documented fallback logic."','pm notes pm-a1b2 --add "text: parser rationale with commas, colons, and key-like wording"','pm notes pm-a1b2 --edit 1 --add "Corrected durable note"',"pm notes pm-a1b2 --delete 2","pm notes pm-a1b2 --limit 10"],tips:["CSV-like add payloads with extra key fragments are treated as plain text by design; use explicit text keys (text= or text:) when structured parsing is required."]},learnings:{why:"Adds or reviews post-implementation learnings for future work.",examples:['pm learnings pm-a1b2 --add "Avoid direct test-runner commands in linked tests; use sandbox runner."','pm learnings pm-a1b2 --add "text: lesson with commas, key-like words, and punctuation-safe context"',"pm learnings pm-a1b2 --edit 1 --file docs/corrected-learning.md","pm learnings pm-a1b2 --delete 2","pm learnings pm-a1b2 --limit 10"],tips:["If you intended structured parsing for a key-like payload, prefer explicit text=..., markdown text: ..., or stdin token -; ambiguous CSV-like forms intentionally remain plain text."]},files:{why:"Associates changed source files with tracker items for reproducibility.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,note=help orchestration"','pm files pm-a1b2 --add src/cli/main.ts --note "help orchestration"',"pm files discover pm-a1b2",'pm files discover pm-a1b2 --apply --note "discovered from item text"']},docs:{why:"Associates relevant documentation paths with tracker items.",examples:['pm docs pm-a1b2 --add "path=README.md,note=user-facing command guidance"','pm docs pm-a1b2 --add README.md --note "user-facing command guidance"']},test:{why:"Links test commands/paths and optionally executes them for one item.",examples:['pm test pm-a1b2 --add "command=node scripts/run-tests.mjs test -- tests/unit/output.spec.ts,timeout_seconds=2400"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,assert_stdout_contains=count:,assert_stdout_regex=count:\\s+\\d+"','pm test pm-a1b2 --add "command=pm list-all --type Task --limit 200,pm_context_mode=auto"',"pm test pm-a1b2 --run --timeout 2400 --env-set PORT=0 --env-clear PLAYWRIGHT_BASE_URL --shared-host-safe --pm-context tracker --fail-on-context-mismatch --fail-on-skipped","pm test pm-a1b2 --run --timeout 2400 --pm-context auto","pm test pm-a1b2 --run --background --timeout 2400 --progress"]},"test-all":{why:"Runs linked tests in bulk for release/readiness sweeps.",examples:["pm test-all --status in_progress --limit 5 --offset 10 --timeout 2400","pm test-all --status closed --timeout 3600 --progress --env-set PORT=0 --shared-host-safe --fail-on-skipped","pm test-all --status in_progress --pm-context tracker --fail-on-context-mismatch --require-assertions-for-pm","pm test-all --status in_progress --pm-context auto --fail-on-context-mismatch","pm test-all --status in_progress --background --timeout 3600"]},"test-runs":{why:"Manages background linked-test runs with lifecycle controls and log/status inspection.",examples:["pm test-runs list --status running --limit 20","pm test-runs status tr-abc123","pm test-runs logs tr-abc123 --stream stderr --tail 200","pm test-runs stop tr-abc123","pm test-runs resume tr-abc123"]},stats:{why:"Reports tracker-level totals and distribution by type/status.",examples:["pm stats","pm stats --json"]},telemetry:{why:"Inspects and manages local telemetry queue/runtime state for observability diagnostics.",examples:["pm telemetry status","pm telemetry stats --limit 10","pm telemetry flush","pm telemetry clear"]},health:{why:"Validates tracker/runtime health including extension triage, migration, and integrity diagnostics.",examples:["pm health","pm health --check-only --summary --json","pm health --brief --json","pm health --no-refresh","pm health --refresh-vectors"]},validate:{why:"Runs standalone metadata, resolution, lifecycle (including dependency-cycle diagnostics), linked-file, linked-command reference, and history drift checks with default remediation hints for resolution gaps.",examples:["pm validate","pm validate --check-resolution --json","pm validate --check-lifecycle --dependency-cycle-severity error","pm validate --check-lifecycle --parent-cycle-severity error","pm validate --check-files --scan-mode tracked-all","pm validate --check-files --scan-mode tracked-all-strict --include-pm-internals","pm validate --check-command-references","pm validate --check-resolution --fail-on-warn --json"],tips:["Resolution-gap warnings include default `pm update <id> ...` remediation hint templates in check details."]},gc:{why:"Deletes optional cache artifacts by default to keep local tracker state tidy; use --dry-run to preview targets without deleting files.",examples:["pm gc --dry-run","pm gc"]},claim:{why:"Claims an item to signal active ownership and reduce conflicts.",examples:['pm claim pm-a1b2 --message "Claim for implementation"','pm claim pm-a1b2 --force --message "Take over terminal item"','pm claim pm-a1b2 --author "release-service" --message "Explicit non-agent identity override"'],tips:["Claim takeover for non-terminal items does not require --force; --force is reserved for terminal/lock overrides.","Harness identity is automatic; use --author only to assert an intentional external principal."]},release:{why:"Releases an active claim when paused, handed off, or completed.",examples:['pm release pm-a1b2 --message "Release after closure"']},"start-task":{why:"Lifecycle alias that claims an item and sets status to in_progress.",examples:['pm start-task pm-a1b2 --message "Start implementation"']},"pause-task":{why:"Lifecycle alias that sets status to open and releases active assignment.",examples:['pm pause-task pm-a1b2 --message "Pause for dependency unblock"']},"close-task":{why:"Lifecycle alias that closes with reason text and clears assignment metadata.",examples:['pm close-task pm-a1b2 "All acceptance criteria met" --message "Close and handoff"']},meet:{why:"Shortcut to create a Meeting from friendly time flags (start/duration) without structured --event CSV.",examples:['pm meet "Sprint Planning" --start +1h --duration 1h','pm meet "1:1" --start 2026-07-01T15:00:00Z --end 2026-07-01T15:30:00Z --location "Room A"'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},event:{why:"Shortcut to create an Event from friendly time flags (start/duration) without structured --event CSV.",examples:['pm event "Release v2" --start 2026-07-01T10:00:00Z --duration 2h','pm event "Conference" --start 2026-08-01 --all-day'],tips:["Start defaults to now and duration to 1h; pass --end to set an explicit end instead of --duration.","--duration accepts relative tokens (h/d/w/m where m is months) plus sub-hour forms like 30min or PT30M."]},remind:{why:"Shortcut to create a Reminder from a single point in time without structured --reminder CSV.",examples:['pm remind "Review PR" --at +2d','pm remind "Follow up" --at 2026-07-01T09:00:00Z --text "Ping the team"'],tips:["The reminder time defaults to +1d and the reminder text defaults to the title."]},completion:{why:"Generates shell completion scripts for faster and more reliable command entry.",examples:["pm completion bash","pm completion zsh","pm completion fish","pm completion bash --eager-tags"],tips:["Default scripts resolve tag suggestions lazily at completion time; use --eager-tags to embed current tags directly."]},contracts:{why:"Exposes machine-readable CLI command and tool schema contracts for agent integrations.",examples:["pm contracts","pm contracts --command list --runtime-only","pm contracts --command update --flags-only","pm contracts --availability-only --runtime-only","pm contracts --action create","pm contracts --schema-only"],tips:["Use --command to narrow actions/schema to one CLI surface; combine with --flags-only or --availability-only for lighter payloads."]}},Kt={why:"Provides deterministic project management workflows for humans and coding agents.",examples:["pm init","pm install guide-shell --project","pm list-open --limit 10",'pm create --title "..." --description "..." --type Task --status open --priority 1 --message "..." --create-mode progressive'],tips:["Use <command> --help for command-specific guidance and examples.","Install guide-shell before using pm guide for local docs and skills routing.","Use --json for machine parsing and integration flows.","Use --no-pager to force direct help output in CI and other non-interactive shells."]};function Ha(e){let t=N(e??"");return t?Ua[t]??t:""}function za(e){let t=Ha(e);return t?yr[t]??Kt:Kt}function wr(e,t){let n=za(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:gr(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Ga(){let e=le.filter(({lifecycle:n})=>n==="permanent"),t=le.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(`
|
|
5
|
+
`)}function Wa(e,t,n,o){let r=new Set(Jo);e.configureHelp({visibleCommands(i){let a=t.visibleCommands(i);return n?a.filter(s=>(Q(s)??X(s.name()))!=="internal"):i!==e?a:a.filter(s=>o.has(s))},visibleOptions(i){let a=t.visibleOptions(i);return i!==e||n?a:a.filter(s=>r.has(s.flags))}})}function Ba(e,t,n,o){let r=new Set(Xo("core")),i=e.createHelp();i.prepareContext({error:!1,helpWidth:80,outputHasColors:!1});let a=()=>`${i.formatHelp(e,i)}${o}
|
|
6
|
+
`,s=t.visibleCommands(e);for(let l of s)Q(l)===void 0&&(l.name()==="help"||r.has(l.name()))&&n.add(l);for(let l of s)Q(l)==="core"&&(n.add(l),Yo(a()).within_budget||n.delete(l))}function _r(e,t=process.argv.slice(2)){let n=e.createHelp(),o=de(t),r=new Set;Wa(e,n,o,r);let i=Jt(t),a=hr(Kt,i);e.addHelpText("after",a),o&&e.addHelpText("after",Ga()),Ba(e,n,r,a);for(let[c,m]of Object.entries(yr))Vt(e,c,m,i);let s=N(P(t).commandPathTokens.join(" ")),l=Ee(s);if(l){Vt(e,l.parent,{why:l.description,examples:[l.example],tips:[`Action path: pm ${l.command}`,Xe(l.accepted_flags)]},i);return}let d=Ye.filter(({parent:c})=>c===s);d.length>0&&Vt(e,s,{why:`Dispatches one declared positional action: ${d.map(({action:c})=>c).join("|")}.`,examples:d.map(({example:c})=>c),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]="095bd18e-bfc9-58d8-bcdc-14f47f7a238a")}catch{}})();async function br(e,t){await Fo(e,{ok:t.ok,error:t.error,result:se(),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 xr(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t;try{await ko({pmRoot:e.pmRoot,result:se()})}catch(o){t=o}let n=await I(e.pmRoot);if(await Eo({pmRoot:e.pmRoot,author:Be(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]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function F(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function ee(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return F(t)}function K(e){let t=new Set,n=[];for(let o of e){let r=ee(o);r&&(t.has(r)||n.push(r),t.add(r))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ca79853d-468c-5522-b5f9-6509c66e3d9b")}catch{}})();function at(e){let{why:t,title:n,...o}=e;return o}var Va=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Ka(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!Va.has(e.code)}function Sr(e){return`urn:pm-cli:error:${e}`}function x(e){return{...e,type:Sr(e.code)}}var me={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},vr={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Cr={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},rt={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},Ja={guide:me,shell:me,completion:me,"completion-statuses":me,"completion-tags":me,"completion-types":me,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:vr,cal:vr,reindex:Cr,"search-advanced":Cr,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":rt,"dedupe-audit":rt,"dedupe-merge":rt,normalize:rt};function Ya(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return Ja[t]}function Yt(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function Xa(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 Za(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 Xt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function G(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(i=>({role:typeof i?.role=="string"?i.role.trim():"",value:typeof i?.value=="string"?i.value.trim():""})).filter(i=>i.role.length>0&&i.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=Xa(n);o&&(e[t]=o)}function pe(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Xt(t,"attempted_command",e.attempted_command),G(t,"normalized_args",e.normalized_args),G(t,"parsed_positionals",e.parsed_positionals),G(t,"provided_fields",e.provided_fields),G(t,"missing",e.missing),G(t,"missing_required_fields",e.missing_required_fields),G(t,"suggested_flags",e.suggested_flags),G(t,"allowed_values",e.allowed_values),G(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),Xt(t,"suggested_retry",e.suggested_retry),G(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=Za(e.fallback_candidates);return n&&(t.fallback_candidates=n),Xt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Zt(e,t,n){n&&e.push(` ${t}: ${n}`)}function te(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function Qa(e){let t=pe(e);if(!t)return[];let n=["Recovery bundle:"];if(Zt(n,"suggested_retry",t.suggested_retry),Zt(n,"attempted_command",t.attempted_command),te(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(te(n,"provided_fields",t.provided_fields,", "),te(n,"missing",t.missing,", "),te(n,"missing_required_fields",t.missing_required_fields,", "),te(n,"suggested_flags",t.suggested_flags,", "),te(n,"allowed_values",t.allowed_values,", "),te(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}`),Zt(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 Ar(e){let t=[`Error: ${e.title}`,"","What is required:",` ${e.required}`];e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Yt("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(...Yt("Examples:",e.examples))),e.verificationErrors&&e.verificationErrors.length>0&&(t.push(""),t.push(...Yt("Verification errors:",e.verificationErrors)));let n=Qa(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
7
|
+
`)}function Tr(e,t){return Ka(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 es(e,t){if(e.flag)return e.flag;let n=r=>{let i=r.split("=",1)[0];return Ae([i]).length>0&&!["--help","--no-changed-fields","--version"].includes(i)&&t.some(a=>a===i||a.startsWith(`${i}=`))},o=[...`${e.title} ${e.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(r=>r[0]).find(r=>n(r));return o||e.recovery?.provided_fields?.map(r=>r.split("=",1)[0]).find(r=>n(r))}function ts(e,t,n){if(e.value!==void 0)return e.value;if(n){let r=t.find(a=>a===n||a.startsWith(`${n}=`));if(r?.startsWith(`${n}=`))return r.slice(n.length+1);let i=t.indexOf(n);return i>=0?t[i+1]:void 0}let o=e.recovery?.allowed_values;if(o?.length)return t.find((r,i)=>i>0&&!r.startsWith("-")&&!o.includes(r))}function ns(e,t){let n=e.recovery?.normalized_args??[],o=es(e,n),r=ts(e,n,o);return{surface:o??e.recovery?.missing?.[0]??Or(e.recovery)??"command",...r!==void 0?{rejected_value:r}:{},...e.recovery?.allowed_values?.length?{legal_domain:e.recovery.allowed_values}:{},exit_code:t}}function os(e,t){return Tr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t,refusal:ns(e,t)},e)}function en(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 wo(os(e,t),{diagnosticClass:o?"recovery_bundle":"error"})}function tn(e){return Tr({type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required},e)}function st(e){return e.replace(/\(outputHelp\)/g,"").trim()}function rs(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 ne(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 kr(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function Or(e){return nr(e?.normalized_args)}function is(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 as(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let i of o){let a=n.findIndex(s=>s===i);if(a>=0&&a<n.length-1&&!n[a+1]?.startsWith("-")){let s=[...n];return s[a+1]=r,A(s)}}}function ss(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function it(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function W(e,t,n){if(!n)return e;let o=st(t),r=it(n.code,e.code),i=it(n.type,Sr(r)),a=ne(n.examples)??e.examples,s=ne(n.nextSteps)??e.nextSteps,l=ne(n.verification_errors)??e.verificationErrors,d=e.code==="command_failed"&&n.code?ss(o):void 0,c=pe(n.recovery),m=c&&e.recovery?pe({...e.recovery,...c}):c??e.recovery;return{...e,code:r,type:i,title:d??e.title,happened:o.length>0?o:e.happened,required:it(n.required,e.required),why:it(n.why,e.why),examples:a,nextSteps:s,verificationErrors:l,flag:n.flag,value:n.value,unmatchedSelectors:n.unmatched_selectors,availableDependencies:n.available_dependencies,recovery:m}}function ls(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!o)return null;let r=o[1],i=Zn(process.cwd(),r);return W(x(i?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${i}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${i} <command>`,`PM_PATH=${i} pm <command>`],nextSteps:[`Re-run with "--pm-path ${i}" or export PM_PATH=${i}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function cs(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],i=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),a=i?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return W(x({code:"item_not_found",title:"Item ID not found",happened:a,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:i?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function ds(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:W(x({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function ms(e,t,n){return t.includes("is locked")?W(x({code:"lock_conflict",title:"Lock conflict",happened:t,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),e,n):null}function ps(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let i=!!r,a=i?null:t.replace(/^Missing required option\s+/,"").trim(),s=a??"",l=a?`Pass ${a} with a valid value before running the command.`:"Provide the required option for this command invocation.";return W(x({code:"missing_required_option",title:i?"Missing required options":`Missing required option ${s}`,happened:t,required:i?"Provide every required option for this command invocation.":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 us(e,t,n){return t.startsWith("No update flags provided")?W(x({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function fs(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=pe(n?.recovery),r=Or(o),i=r?`pm ${r} --help`:"pm <command> --help",a=is(t),s=pe({...o,allowed_values:o?.allowed_values??a}),l=as(o,a),d=l?[l,i]:[i,"pm contracts --command <command> --flags-only --json"],c=a.length>0?[`Allowed values: ${a.join("|")}`,`Run "${i}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return W(x({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:d,nextSteps:c,recovery:s}),e,n)}function nn(e,t){let n=st(e),o=ls(e,n,t)??cs(e,n,t)??ds(e,n,t)??ms(e,n,t)??ps(e,n,t)??us(e,n,t)??fs(e,n,t);return o||W(x({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function gs(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 hs(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function ys(e){if(!(!Array.isArray(e)||e.length===0))return A(e)}function on(e){if(!Array.isArray(e))return;let t=e.map(n=>n.trim()).filter(n=>n.length>0);return t.length>0?t:void 0}function L(e,t={}){let n=on(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:ys(o),i=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return pe({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:i,...t})}function Qt(e,t){return!t||e.includes(t)?e:[...e,t]}var ws=new Set(["--add","--add-json","--remove"]),_s=new Set(["command","cmd","path"]);function bs(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(ws.has(o))return o}}function xs(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let i=e[o+1];if(typeof i!="string"||!_s.has(i))return;let a=[];for(let d=o+2;d<e.length;d+=1){let c=e[d];if(c.startsWith("--")&&c.length>2)break;a.push(c)}if(a.length<2)return;let s=`${i}=${a.join(" ")}`,l=[...e.slice(0,o+1),s,...e.slice(o+2+a.length)];return A(l)}}function vs(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let i=hs(r[1]),a=i.startsWith("--type"),s=o?.suggestedRetryCommand,l=on(o?.providedOptionFlags),d=[i],c=gs(t,i,n),m=s?Qt(c,s):c,p=a?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Qt(p,`Replay with preserved arguments: ${s}`):p,g=l&&l.length>0?Qt(u,`Already provided options: ${l.join(", ")}`):u;return x({code:"missing_required_option",title:`Missing required option ${i}`,happened:`Commander rejected the command because ${i} was not provided.`,required:`Pass ${i} with a valid value before running the command.`,why:a?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:g,recovery:L(o,{missing:d})})}function Cs(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return x({code:"missing_required_argument",title:`Missing required argument ${r}`,happened:`Command invocation omitted positional argument ${r}.`,required:`Provide ${r} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${t??"<command>"} --help`],recovery:L(n,{missing:[r]})})}function ks(e,t,n){return x({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:L(t,{suggested_flags:n})})}var Es={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 Ss(e){let t=ne(e.unknownOptionOtherCommands)??[];return{otherCommands:t,optionScope:e.unknownOptionScope??(t.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:e.unknownOptionOtherCommandsTotal??t.length}}function As(e,t,n,o,r){let i=o.otherCommands.slice(0,3),a=o.candidateTotal-i.length,s=a>0?` and ${String(a)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",n.length?`Nearest supported options: ${n.join(", ")}`:void 0,i.length?`${e} is accepted by ${i.join(", ")}${s}. Inspect those command contracts only if you intended a different operation.`:void 0,o.optionScope==="declared_nowhere"?`${e} is not declared on any command path. Use a nearest supported option on ${t??"the attempted command"}, or inspect that command's help.`:void 0,r?`Replay with suggested correction: ${r}`:void 0].filter(l=>typeof l=="string")}function Ts(e,t){if(e.suggestedRetryCommand!==void 0)return{retryCommand:e.suggestedRetryCommand};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 r=Ae(n.filter((i,a)=>a!==o));return{retryCommand:A(r),suggestedRetryArgs:r}}function Os(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},i=o[1],a=on(r.unknownOptionSuggestions)??[],{retryCommand:s,suggestedRetryArgs:l}=Ts(r,i);if(t==="update"&&(i==="--file"||i==="--doc"))return ks(i,n,a);let d=Ss(r),c=As(i,t,a,d,s),m=[s,`pm ${t??"<command>"} --help`].filter(p=>typeof p=="string");return x({code:"unknown_option",title:`Unknown option ${i}`,happened:`Commander does not recognize option ${i} for this command path.`,required:Es[d.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:i,value:i,examples:m,nextSteps:c,recovery:L(n,{suggested_flags:a.length>0?a:void 0,suggested_retry:s,suggested_retry_args:l,candidate_commands:d.otherCommands,candidate_commands_total:d.candidateTotal||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated,option_scope:d.optionScope})})}function Rs(e,t,n,o,r){let i=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,a=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return x({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:kr([t.installCommand,...n]),nextSteps:kr([i,...a]),recovery:L(r)})}function Is(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ne(t?.unknownCommandExamples),i=ne(t?.unknownCommandNextSteps),a=Ya(o),s=r??["pm --help"],l=i??["Verify spelling and active extensions, then rerun."],d=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),c=a?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return a&&(!c||!d.has(c))?Rs(o,a,s,l,t):x({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:l,recovery:L(t)})}function $s(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ne(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return x({code:"unknown_subcommand",title:`Unknown ${t} subcommand ${n}`,happened:`The positional token sequence "${n}" is not a declared ${t} subcommand.`,required:`Use one of: ${o.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...r?[r]:[],`pm ${t} --help`],nextSteps:r?[`Retry with the declared hyphenated action: ${r}`]:["Choose one value from recovery.allowed_values."],recovery:L(e,{allowed_values:o,suggested_retry:r})})}function Ps(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=bs(o);if(!r)return null;let i=xs(o);return x({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...i?[i]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...i?[`Replay with the value re-joined into one argument: ${i}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:L(n,i?{suggested_retry:i}:{})})}var Ns=new Set(["comments","docs","files","learnings","notes","test"]);function Ms(e,t,n){if(!/too many arguments/i.test(e)||!Ns.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>d===t),i=o[r+1],a=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(i?.toLowerCase()!=="add"||!a||a.startsWith("-")||!s||s.toLowerCase()!==a.toLowerCase())return null;let l=`pm ${t} ${s} --add <value>`;return x({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[l,`pm ${t} --help`],recovery:L(n,{parsed_positionals:[{role:"transposed_subcommand",value:i},{role:"item_id",value:s}],suggested_retry:l})})}var Ds=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"]),Er=new Set(["context","ctx"]);function Fs(e,t,n){if(!/too many arguments/i.test(e)||!Er.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(d=>Er.has(d)),i=r===-1?1:r+1,a=e.match(/got \d+:\s*(\S+)/i),s=a?a[1].replace(/\.$/,""):void 0;if(s===void 0){let d=!1;for(let c of o.slice(i)){if(d){d=!1;continue}let m=c.split("=")[0];if(Ds.has(m)){d=!c.includes("=");continue}if(!c.startsWith("-")){s=c;break}}}if(!s)return null;let l=`pm get ${s}`;return x({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${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:L(n,{suggested_retry:l})})}function rn(e,t,n,o){let r=st(e),i=vs(r,t,n,o)??Cs(r,t,o)??Os(r,t,o)??Is(r,o)??$s(o)??Ms(r,t,o)??Ps(r,t,o)??Fs(r,t,o);return i||x({code:"invalid_command_usage",title:"Invalid command usage",happened:r,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${t??"<command>"} --help`],recovery:L(o)})}function Rr(e,t){let n=nn(e,t);return Ot(Ar(n),n.required).output}function Ir(e,t){return tn(nn(e,t))}function an(e,t,n){return en(nn(e,n),t)}function $r(e,t,n,o){let r=rn(e,t,n,o);return Ot(Ar(r),r.required).output}function sn(e,t,n,o){return tn(rn(e,t,n,o))}function lt(e,t,n,o,r){return en(rn(e,t,n,r),o)}function Pr(e,t){let n=Nr(e);return en(n,t)}function Nr(e){let t=st(e);return rs(t)?x({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):x({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function Mr(e){return tn(Nr(e))}import{Option as Ls}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="99d39b7c-ec26-5c95-85c0-ac28112a6fe6")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Fr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let i of t){if(i.layer!==o.layer||i.name!==o.name)continue;let a=_(i.command),s=a.split(" "),l=s.at(-1),d=s.slice(1).join(" "),c=d?`${s[0]}-${l} ${d}`:`${s[0]}-${l}`;if(l&&r===c){n.set(r,a);break}}}return n}function ln(e,t,n,o){if(!t||!n)return;let r,i=0;for(let[s,l]of e.entries()){if(l!==t)continue;let d=e.slice(s);for(let[c,m]of o.entries()){let p=c.split(" ");p.length>i&&p.every((u,g)=>d[g]===u)&&(r=m,i=p.length)}}let a=r?.flags.find(s=>s.long===n||s.short===n);if(a)return ct(a).takesValue}function T(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function B(e){return typeof e=="boolean"?e:void 0}function ct(e){let t=T(e.value_type)??T(e.type),n=T(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||B(e.required)===!0||B(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Us(e){if(B(e.visible)===!1)return null;let n=T(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",i=T(e.value_name),a=i?` <${i}>`:"",s=T(e.description)??"Extension-provided option.",l=[];B(e.required)===!0&&l.push("required"),B(e.enabled)===!1&&l.push("disabled");let d=l.length>0?` [${l.join(", ")}]`:"";return`${r}${n}${a} ${s}${d}`}function Lr(e){let t=[...new Set(e.map(Us).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
8
8
|
Extension-provided flags:
|
|
9
9
|
${t.join(`
|
|
10
|
-
`)}`}function
|
|
10
|
+
`)}`}function Ur(e){let t=new Map;for(let r of e){let i=_(r.target_command);if(i.length===0)continue;let a=t.get(i)??[];a.push(...r.flags),t.set(i,a)}let n=[...t.entries()].sort(([r],[i])=>r.localeCompare(i)),o=new Map;for(let[r,i]of n){let a=Lr(i);a&&o.set(r,a)}return o}function jr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function Dr(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let o of e){if(typeof o!="string")continue;let r=o.trim();r.length===0||n.has(r)||(n.add(r),t.push(r))}return t}function js(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 qs(e){let t=new Map;for(let n of e){let o=_(n.command);if(o.length===0)continue;let r=typeof n.description=="string"&&n.description.trim().length>0?n.description.trim():void 0,i=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:jr(o,n.action),description:r,intent:i,examples:Dr(n.examples),failure_hints:Dr(n.failure_hints),arguments:js(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 Hs(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function zs(e,t,n){let o=new Set;for(let r of e){let i=_(r);i.length>0&&o.add(i)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function Gs(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function qr(e,t,n,o=new Map){let r=qs(t),i=Hs(n),a=zs(e,r,i),s=new Map,l=[...a].sort((d,c)=>d.localeCompare(c));for(let d of l){let c=Gs(d,r,o)??r.get(d),m=i.get(d)??(c?i.get(c.command):void 0)??[];if(c){s.set(d,{...c,command:d,flags:m});continue}s.set(d,{command:d,action:jr(d,void 0),examples:[],failure_hints:[],arguments:[],flags:m,tier:"standard",family:"extensions"})}return s}function Ws(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function Hr(e,t){for(let n of t.arguments)e.argument(Ws(n),n.description??"Extension argument.")}function zr(e){if(B(e.visible)===!1)return null;let n=T(e.long),o=T(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,i=n&&n.startsWith("--")&&n.length>2?n:null,a=[r,i].filter(s=>s!==null);return a.length>0?a:null}function Bs(e){let t=zr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Vs(e){let t=zr(e);if(!t)return null;let{valueName:n}=ct(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function Gr(e){let t=T(e.description)??"Extension-provided option.",n=[];B(e.required)===!0&&n.push("required"),B(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function Wr(e,t){let n=T(t.long),o=T(t.short);return e.options.some(r=>{let i=r;return n!==null&&i.long===n||o!==null&&i.short===o})}function cn(e,t){for(let n of t){if(Wr(e,n))continue;let o=Vs(n);if(!o)continue;let r=Gr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Ls(o,r).argParser((i,a=[])=>[...Array.isArray(a)?a:[a],i]))}}function dn(e,t){return Lr(t.filter(n=>!Wr(e,n)))}function Ks(e){let t=Bs(e);if(!t)return null;let n=T(e.long),o=T(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,i=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:a,valueName:s}=ct(e),l=B(e.required)===!0;return{flags:t,long:r,short:i,description:Gr(e),takes_value:a,value_required:a,value_name:s,variadic:!1,required:l,aliases:[],alias_for:null}}function Br(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=Ks(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function Vr(e,t){if(t.length===0)return e;let n=[...e],o=new Set(e.map(r=>r.flags));for(let r of t)o.has(r.flags)||(o.add(r.flags),n.push(r));return n}function Kr(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:`
|
|
11
11
|
Extension command metadata:
|
|
12
12
|
${t.join(`
|
|
13
|
-
`)}`}function mn(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 Re(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:mn(o).includes(n))??null}function
|
|
13
|
+
`)}`}function mn(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 Re(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:mn(o).includes(n))??null}function ue(e,t){let n=e;for(let o of t){let r=Re(n,o);if(!r)return null;n=r}return n}var Jr=new WeakSet;function Yr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],i=Re(n,r);if(i){n=i;continue}let a=n.command(r);Jr.add(a),o<t.length-1?(a.description("Extension-provided command group."),a.action(()=>{a.help()})):a.description("Extension-provided command path."),n=a}return n}function Js(e,t){let n=e,o=[];for(let r of t){let i=Re(n,r);if(!i)return null;if(o.push(r),!Jr.has(i))return{core_path:o.join(" "),extension_path:t.join(" ")};n=i}return null}function Ys(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),i=Js(e,r);if(!i||i.core_path===t&&!n.has(t))return null;let a=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${i.extension_path}:core_owner=pm-cli:${i.core_path}:extension_owner=${a}`}function Xr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(i=>i.trim().length>0).sort((i,a)=>i.localeCompare(a)).filter(i=>{let a=Ys(e,i,o,n.get(i));return a?(r(a),!1):!0})}function Zr(e,t,n){e.push(n),t(`[pm] warning: ${n}; core command preserved. Rename or namespace the extension command alias.`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function Xs(e,t){let n=_e(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function Zs(e){return _e(e.status)?.toLowerCase()??"pending"}function Qs(e){return e.mandatory===!0}function el(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 ti(e){let t=[];return e.forEach((n,o)=>{if(!Qs(n.definition))return;let r=Zs(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:Xs(n.definition,o),status:r})}),t.sort(el),t}function Qr(e){return Array.isArray(e)&&e.length>0}var tl=new Set(["create","beads import","todos import"]),nl=new Set(["restore","update","close","delete","append","claim","release"]),ol=new Set(["comments","notes","learnings"]),rl=new Set(["files","docs","test"]),il=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 pn(e,t){let n=t.force===!0;return tl.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:nl.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:ol.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:rl.has(e)?{isMutation:Qr(t.add)||Qr(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function al(e,t,n){if(pn(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return No(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>il.has(r.trim().toLowerCase())):!1}function ei(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function sl(e,t,n){let o=t[0]?.trim().toLowerCase()??"";if(e.trim().toLowerCase()!=="schema"||!["rename-type","rename-field","remap-status"].includes(o))return;let r=[];if(_e(t[1])||r.push("source"),_e(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,f.USAGE,{code:"schema_migration_input_required",required:r.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:r,suggested_flags:r.filter(i=>i.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function ll(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||ei(n.status)!==ei(r.schema.workflow.in_progress_status))return;let i=t[0];if(!i)return;let a=J(r,Y()),s=await Je(o,i,r.id_prefix,r.item_format,a.type_to_folder);if(!s)return;let l=await Ro(s,{schema:r.schema}),d=typeof n.assignee=="string"?n.assignee.trim():void 0;(d===void 0?l.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(d.toLowerCase())&&d)||y(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function un(e,t,n,o,r){if(!al(e,t,n)||(sl(e,t,n),!await q(H(r))))return;let i=await ce(r);o.json!==!0&&await ll(e,t,n,r,i.settings);let a=Po({author:Be(o.author,i.settings.author_default),payload:{command:e,args:t,options:n},settings:i.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of a.warnings)y(`warning:${s}`)}function ni(e,t,n){if(n.length===0)return;let o=pn(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(a=>`extension_migration_blocking:${a.layer}:${a.name}:${a.id}:${a.status}`),i=o.forceCapable?"Re-run this command with --force to bypass.":"This command path does not support --force bypass.";throw new v(`Write command "${e}" blocked by unresolved mandatory extension migrations (${r.join(",")}). ${i}`,f.CONFLICT)}async function fn(e,t,n,o){if(!pn(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await q(H(n)))return;let{settings:i,metadata:a,warnings:s}=await ce(n);for(let l of s)y(`warning:${l}`);if(o.enforce_item_format_gate&&!a.has_explicit_item_format&&(To(i),await Oo(n,i,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let l=J(i,Y());await Mo(n,i.item_format,"item_format:pre_mutation_sync",l.type_to_folder,i.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="adb5b95f-be2d-5bcf-b376-09f6094e0bda")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8879d491-9158-548c-bfbd-8ab57d8eb936")}catch{}})();var Ie=Yn.join("|"),cl={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"},dl={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"]}},oi=["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 ml(e,t){let n=dl[e];if(!n)return[];let o=F(t);for(let[r,i]of Object.entries(n))if(F(r)===o)return i;return[]}function gn(e,t,n){if(n.length===0)return e;if(t){let a=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...a?{extension_command_failure:{code:"extension_command_activation_failed",extension:a.name,layer:a.layer,error:a.error,recovery_commands:a.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(a=>`- ${a.layer}:${a.name}: ${a.error}`).join(`
|
|
14
14
|
`),r=n.find(a=>a.declared_command_match===!0);if(!r)return`${e}
|
|
15
15
|
Extension activation failures:
|
|
16
16
|
${o}`;let i=(r.recovery_commands??[]).map(a=>`- ${a}`).join(`
|
|
@@ -21,11 +21,11 @@ ${i}`:""}
|
|
|
21
21
|
|
|
22
22
|
${e}
|
|
23
23
|
Extension activation failures:
|
|
24
|
-
${o}`}function hn(e){return P(e).commandPathTokens[0]??k(e)??"<command>"}function
|
|
25
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function kl(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 El(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(i=>i.trim().toLowerCase()===n))}function _n(e,t){if(t.length===0)return!0;let n=e;for(let[o,r]of t.entries()){let i=El(n,r);if(!i){if(n.commands.some(s=>s.name()!=="help"))return!1;let a=n.registeredArguments;return a.length>0&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=i}return!0}async function Sl(e,t,n,o){try{let r=E(process.cwd(),e.path);if(!await q(H(r)))return{allowedTypes:Ie};let i=await I(r),a=e.noExtensions?void 0:Y(),s=J(i,a),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),c=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&c!==void 0&&!c.startsWith("-"))try{l=(await Je(r,c,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ie,pmRoot:r,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Ie}}}function Al(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?ai([...dl(t,n[1]),...fl(n[1],$e(t))]):void 0,r=n?yl(n[1],t):[],i=n!==null&&$e(t).includes(D(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:i?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Tl(e,t,n){if(!t||!n||n.length===0)return;let o=wl(e,t[1],n[0]);return o?yn(o):void 0}function Ol(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?kl(Cl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return nr(t,r,[o])}function Rl(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=Zo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let i=`${o}-${r}`;if(!ni.includes(i))return;let a=[...t.slice(0,n+1),i,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...ni],suggestedRetryCommand:yn(a)}}async function Pe(e,t,n,o={}){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=tt(process.argv.slice(2)).argv,s=z(a),l=k(a),d=yn(a),c=K(a),m=await Sl(s,i,a,l),p=m.allowedTypes,u=wn(i,t,n),g=Al(i,l),w=Rl(i,a),h=w?.suggestedRetryCommand??Tl(a,g.match,g.suggestions)??Ol(i,a);return{message:i,commandName:l,allowedTypes:p,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:c,unknownOptionSuggestions:g.suggestions,unknownOptionOtherCommands:g.otherCommands.length>0?g.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:g.otherCommands.length>0?g.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:g.otherCommands.length>12||void 0,unknownOptionScope:g.scope,suggestedRetryCommand:h,verifiedCollectionItemId:m.verifiedCollectionItemId,...w,...u,...o}}async function bn(e,t,n,o={}){let r=await Pe(e,t,n,o),{message:i,commandName:a,allowedTypes:s,unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}=r,ye=Ir(i,a,s,{unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}),ie=await fo("help_format",{message:ye,command:a,allowed_types:s});return ie.handled&&typeof ie.result=="string"?ie.result:ye}async function xn(e,t,n,o=!1,r={}){let i=await Pe(e,t,n,r),a=lt(i.message,i.commandName,i.allowedTypes,f.USAGE,{unknownCommandExamples:i.unknownCommandExamples,unknownCommandNextSteps:i.unknownCommandNextSteps,attemptedCommand:i.attemptedCommand,normalizedInvocationArgs:i.normalizedInvocationArgs,providedOptionFlags:i.providedOptionFlags,unknownOptionSuggestions:i.unknownOptionSuggestions,unknownOptionOtherCommands:i.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:i.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:i.unknownOptionOtherCommandsTruncated,unknownOptionScope:i.unknownOptionScope,unknownSubcommandPath:i.unknownSubcommandPath,unknownSubcommandToken:i.unknownSubcommandToken,unknownSubcommandAllowedValues:i.unknownSubcommandAllowedValues,suggestedRetryCommand:i.suggestedRetryCommand,verifiedCollectionItemId:i.verifiedCollectionItemId,failedExtensions:i.failedExtensions});return JSON.stringify(o?at(a):a,null,2)}import ue from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function vn(e,t={},n=[]){let o={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:St,...t};try{let r=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(i);return[...i.failed,...a.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),d=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),c=n.map(N),m=d.some(p=>c.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function si(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await vn(t,n,o),i={readSettings:I,loadExtensions:_e,activateExtensions:be,resolveImplicitPmRoot:St,...n};try{let a=i.resolveImplicitPmRoot(process.cwd());if(ue.resolve(a)===ue.resolve(t))return r;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(a)]),[d,c]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:a,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(c.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${ue.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${ue.resolve(a)} cwd_extension_discovery_root=${c.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 ${ue.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${ue.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43167bb0-7cc0-599f-8587-8583d398f1ad")}catch{}})();var li={core:0,standard:1,full:2,internal:3};function ci(e,t,n=!0){let o=t.get(e);if(o)return o;if(!n)return;let r=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(r.length===0)return;let i=r.reduce((s,l)=>li[l.tier]<li[s]?l.tier:s,"internal"),a=new Set(r.map(({family:s})=>s));return{tier:i,family:a.size===1?r[0].family:"extensions"}}function Il(e,t){if(t.length===0)return e;let n=pe(e,t);if(n)return n;let o=t.join(" ");if(!Ke.some(r=>r===o)&&!Lo(o)&&!Ee(o))return null;for(let r=t.length-1;r>0;r-=1){let i=pe(e,t.slice(0,r));if(i)return i}return t.length===1?e:null}function $l(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function di(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 Pl(e){let t=new Map;for(let n of e){let o=n,r=di(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(r)??[];i.push(o.long.trim()),t.set(r,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,i)=>r.localeCompare(i)));return t}function Nl(e){return A(e)}function Ml(e){let t=e.options??[],n=Pl(t);return t.map(o=>{let r=o,i=typeof r.flags=="string"?r.flags.trim():"",a=typeof r.description=="string"?r.description.trim():"",s=di(o),d=(s?n.get(s)??[]:[]).filter(h=>h!==r.long).map(h=>h.trim()).filter(h=>h.length>0),c=a.match(/^Alias for ([^ ]+)/i),m=c&&c[1]?c[1].trim():null,p=r.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=i.includes("<"),g=u||i.includes("["),w={flags:i,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:a,takes_value:g,value_required:u,value_name:$l(i),variadic:r.variadic===!0,required:p,aliases:d,alias_for:m};return r.defaultValue!==void 0&&(w.default_value=r.defaultValue),w})}function Fl(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,i=t.get(r);if(!i)continue;let a=o.long,s=new Set([...i.aliases??[],a]);i.aliases=[...s].sort((l,d)=>l.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Dl(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",i=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:i}})}function Ll(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(i=>i.name()!=="help"||e.parent===null).filter(i=>!n||(Q(i)??X(i.name()))!=="internal").map(i=>{let a=N($(i)),s=a.split(" ")[0],l=Q(i),d=ci(a,t,l!==void 0),c=se.find(({alias:m})=>m===a);return{name:i.name().trim(),aliases:mn(i),description:i.description().trim(),tier:d?.tier??l??X(s),family:d?.family??et(s),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function Ul(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function jl(e,t){return e===void 0?null:t?.tier??X(e)}function ql(e,t){return e===void 0?null:t?.family??et(e)}function Hl(e,t,n){if(!(t!==e||!n))return se.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function zl(e,t,n,o,r=new Map,i=!1){if(!e){let s=Dl(t),l=Ll(t,r,i),d=new Set(l.map(({name:c})=>c));return{arguments:s,options:o,subcommands:[...l,...Ye.filter(({parent:c,action:m})=>c===n&&!d.has(m)).map(({action:c,description:m})=>({name:c,aliases:[],description:m,tier:X(n.split(" ")[0]),family:et(n.split(" ")[0])}))].sort((c,m)=>c.name.localeCompare(m.name)),usage:[n,s.reduce((c,m)=>m.required?c.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:d,value_kind:c,polymorphic:m})=>({name:s,required:l,variadic:d,description:m?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&a.has(s)||l.some(d=>a.has(d))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:d})=>{let c=d?`${s}...`:s;return l?`<${c}>`:`[${c}]`})].join(" ")}}function Gl(e,t,n,o,r){let i=Jt(n),a=ce(n),s=N($(t)),l=N(o.join(" ")),d=l.length>s.length?l:s,c=Ee(d),m=c?.command??d,p=m.length>0?m:void 0,u=p?.split(" ")[0],g=yr(p,i),w=p?r.get(p):void 0,h=p?ci(p,r,Q(t)!==void 0):void 0,C=Ul(i,g,w),R=Fl(Br(Ml(t),Wr(w))),j=zl(c,t,m,R,r,a),M=Hl(e,t,a);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:jl(u,h),capability_family:ql(u,h),description:c?.description??t.description(),usage:j.usage,intent:c?.description??C.intent,examples:c?[c.example]:C.examples,tips:c?[Xe(c.accepted_flags)]:C.tips,arguments:j.arguments,options:j.options,subcommands:j.subcommands,has_subcommands:j.subcommands.length>0,...M===void 0?{}:{command_aliases:M}}}async function mi(e,t,n){let o=z(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let i=Il(e,r.commandPathTokens);if(!i){if(!o.quiet){let a=`unknown command '${r.commandPathTokens.join(" ")}'`,s=wn(a,e,n),l=lt(a,"help",Ie,f.USAGE,{...s,attemptedCommand:Nl(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});y(JSON.stringify(l,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let a=Gl(e,i,t,r.commandPathTokens,n);Eo(`${JSON.stringify(a,null,2)}
|
|
26
|
-
`)}return process.exitCode=f.SUCCESS,!0}function
|
|
27
|
-
`)}function
|
|
28
|
-
`)}let i=n.indexOf("--"),a=i<0?n:n.slice(0,i),s=a.findIndex(w=>w==="--create-mode"||w.startsWith("--create-mode=")),l=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&l?.toLowerCase()==="strict",c=
|
|
29
|
-
`)}function pi(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=Re(e,o);r&&r.addHelpText("after",Jl(o,t,n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function ui(e,t,n,o){if(n)return null;let r=e.some(a=>a==="--for"||a.startsWith("--for=")),i=k(e)==="contracts"&&e.includes("--full");return r||i?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f947c7f0-adf8-59da-8bc7-9cd746b05839")}catch{}})();var Cn="PM_CLI_PACKAGE_ROOT",ut=Symbol.for("pm.readOutputInvocationProvenance");function Pn(e,t){let n=Reflect.get(e,ut);n!==void 0&&Reflect.set(t,ut,n)}function bi(e,t,n){let o=bo(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let i=r.rawArgs,a=new Set(K(i.slice(2))),s=_o.find(c=>c.command===o),l=Object.values(s.dimensions).flatMap(c=>c.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,ut);Reflect.set(n,ut,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),Pn(n,e)}function Xl(){return Kn(import.meta.url,["../.."])}(typeof process.env[Cn]!="string"||process.env[Cn]?.trim().length===0)&&(process.env[Cn]=Xl());var ge=null,U=null;function Zl(e){ge=e}function Ql(e){O=e}var ec=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"]),tc=new Set(["parse","preflight","execute","unknown"]),nc=new Set(["usage","validation","conflict","runtime","unknown"]),Ne=null,oe=null,O=new Map,Nn=250,oc=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),rc=new Set(["1","true","yes","on"]),ic=ke(()=>import("./chunks/register-setup-KVNC5KPL.js")),ac=ke(()=>import("./chunks/register-list-query-XYNX4ASQ.js")),sc=ke(()=>import("./chunks/register-mutation-WFQ7MJTX.js")),lc=ke(()=>import("./chunks/register-operations-JVTI7JPP.js"));function pt(e){return A(e)}function xi(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=>ee(o)??o))];return n.length>0?n:void 0}function cc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(c=>ee(c)??c)),i=xi(e),a=t.find(c=>b.commands.some(m=>m.name()===c)),s=a?b.commands.find(c=>c.name()===a):void 0,l=new Set([...b.options,...s?.options??[]].flatMap(c=>c.flags.split(/[ ,|]+/).map(m=>ee(m)).filter(m=>m!==void 0))),d=i?.filter(c=>{let m=ee(c)??c;return r.has(m)?!1:l.has(m)||ln(t,a,m,O)!==void 0});return d&&d.length>0?d:void 0}function dc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],i=r?ee(r):void 0,a=e.find(p=>b.commands.some(u=>u.name()===p)),s=a?b.commands.find(p=>p.name()===a):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,d=ln(e,a,i,O),c=i?l?.isBoolean()===!0||d===!1?[i]:[i,"<value>"]:[],m=i?pt([...e,...c]):t;return m===t?void 0:m}function mc(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function pc(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,...mc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function vi(e,t,n){let o=Ve(t),r=o.includes("--explain"),i=e?.recovery,a=i&&o.includes("history-redact")?{...i,...i.attempted_command?{attempted_command:pt(o)}:{},...i.normalized_args?{normalized_args:[...o]}:{},...i.suggested_retry?{suggested_retry:pt(o)}:{},...i.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:i;if(a?.recovery_mode==="compact"&&!r)return{...e,recovery:a};let s=pt(o),l=K(o),d=cc(n,o,a),c=dc(o,s,d,a),m=pc({invocationArgv:o,attemptedCommand:s,providedFields:l,inferredMissing:d,suggestedRetry:c,existingRecovery:a});return{...e,recovery:m}}function fe(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function Ci(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Mn(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 ki(e){if(!e)return;let t=e.trim().toLowerCase();if(ec.has(t))return t}function Ei(e){if(!e)return;let t=e.trim().toLowerCase();if(tc.has(t))return t}function Si(e){if(!e)return;let t=e.trim().toLowerCase();if(nc.has(t))return t}function Ai(e){let t=fe(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(Ci(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=Mn(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(s=>Ct(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Ti(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Oi(){let e=Ct(xe()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Mn(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=Bo(o),i=fe(e,"error_code","errorCode")??Ti(r,o),a=Si(fe(e,"error_category","errorCategory"))??(r?void 0:vt(i)),s=r?void 0:Ai(e)??`command_exit_${o}`,l=ki(fe(e,"command_resolution","commandResolution"))??It({ok:r,errorCode:i,errorCategory:a}),d=Ei(fe(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:i,error_category:a,command_resolution:l,resolution_stage:d}}async function Le(e){let t=U;U=null,await _r(t,e);let n=ge;if(ge=null,!n){Ge();return}let o=[],r=po();try{await br({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await to(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:xe(),affected:r}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{Ge()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${F(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${F(o)}`)}async function Ri(){await Oo()}function Ii(e){return rc.has((process.env[e]??"").trim().toLowerCase())}function $i(e){return Ii("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!oc.has(Math.trunc(e))}async function ft(e){return $i(e.exit_code)?(await Ri(),Ro(e),!0):!1}async function Pi(e){let t=Z(e.error),n=Nr(t);e.bootstrapGlobal.json?y(JSON.stringify($r(t,f.GENERIC_FAILURE),null,2)):y(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Ri(),Nt(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,r=i.commandResolution,ve(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to report error: ${Z(i)}`)}try{await Le({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Z(i)}`)}try{await Ce()}catch(i){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Z(i)}`)}}function fi(e,t,n,o){bi(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:i,modes:a}=Co(t,r,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;Pn(o,e);let s=vo(t);for(let d of a){let c=s.get(d),m=o[c];e.setOptionValueWithSource(c,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",l,"cli");Ft(e,n)}function Me(e,t,n=[]){let r={...e.optsWithGlobals()};Pn(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let i=dr(t);for(let[a,s]of Object.entries(i))r[a]===void 0&&(r[a]=s);if(n.length>0){let a=sr(n),s=Ze($(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),l={...i};for(let d of a)r[d]!==void 0&&(l[d]=r[d]);return Wt(l,[...s,...n],$(e)),cr(r,n,i)}return r}function Sn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function gt(e,t,n){let o=Sn(e,t),r=[t],i=[];for(let a of n){if(a.startsWith("-"))break;r.push(a);let s=Sn(e,r.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Fn(e){return e.arguments??[]}function gi(e){let t=Fn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Ni(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function Mi(e,t){let n=Fn(e),o=n.filter(l=>l.required).length,i=n.some(l=>l.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${gi(e)}${s}`,f.USAGE);if(t.length>i){let l=t.slice(i).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${l}. Usage: ${gi(e)}${s}`,f.USAGE)}}function uc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function fc(e,t,n){if(n.length>0){Wt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(uc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Fi(e,t,n,o){e&&(Mi(e,t),fc(e,n,o))}var gc={create:"create",update:"update","update-many":"update_many",list:"list","list-all":"list","list-draft":"list","list-open":"list","list-in-progress":"list","list-blocked":"list","list-closed":"list","list-canceled":"list",search:"search",calendar:"calendar",context:"context","templates save":"create"},kn=new Map;function An(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Di(e,t){return e.options.some(n=>n.long===t)}function Li(e,t){return e.options.some(n=>n.short===t)}function Tn(e,t,n,o){let r=t.trim();if(!r)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Li(e,r))return;if(o){e.option(`${r} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${r} <value>`,i);return}let a=r.startsWith("--")?r:`--${r}`;if(!Di(e,a)){if(o){e.option(`${a} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${a} <value>`,i)}}async function Ui(e,t){let n=gc[e];if(!n)return[];let o=`${t}:${n}`,r=kn.get(o);if(r)return r;if(!await q(H(t)))return kn.set(o,[]),[];let i=await I(t),s=(Tt(i.schema).command_to_fields.get(n)??[]).flatMap(l=>[l.cli_flag,...l.cli_aliases].map(c=>({long:`--${c}`,type:An(l.type),value_type:An(l.type)})));return kn.set(o,s),s}async function ji(e,t){let n=z(t),o=E(process.cwd(),n.path);if(!await q(H(o)))return;let r=oe?.key===Un(o)?oe.snapshot:null,i=r===null?await I(o):r.settings,a=Tt(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 d=pe(e,l.path.split(" "));if(d)for(let c of a.command_to_fields.get(l.command)??[]){let m=c.description??"";Tn(d,c.cli_flag,m,c.repeatable);for(let p of c.cli_aliases)Tn(d,p,`Alias for --${c.cli_flag}`,c.repeatable)}}}async function Dn(e,t,n,o,r){let i=k(n);if(!(i!=="create"&&i!=="update"))try{let a=r??await I(t),s=J(a,o);pi(e,s,n)}catch{}}function On(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function qi(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ln(e){return e.some(t=>t==="--profile")}function Un(e){return`pm-root:${e}`}function Hi(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ue(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of Hi(e.commandArgs))o.push(...r.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n)]}function zi(e,t){let n=_(e);if(n.length===0)return!1;let o=Ue(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function jn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...hi(n.preflight_ownership),...hi(n.renderer_ownership)]:[]}function S(e){return e??[]}function hi(e){return S(e).flatMap(t=>t.commands)}function ht(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Gi=new Set(["hooks","parser","preflight","renderers"]),Wi=new Set(["commands","schema","services","importers"]),hc=new Set(["reindex","search","search-advanced"]),yc=new Set(["--template"]);function Fe(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Bi(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return hc.has(n??t)}function Vi(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 qn(e){return _(e.commandPath??"")==="create"&&Vi(e,yc)}function Ki(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Rn(e,t){return e.some(n=>zi(n,t))||qn(t)&&Ki(e)}function Ji(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Yi(e,t){let n=e.activation?.commands??[];if(n.length>0)return Rn(n,t);let o=jn(e);if(Rn(o,t)||ht(e).has("search")&&Bi(t.commandPath))return!0;if(e.contributions)return Ji(e.contributions)}function Hn(e,t){let n=Yi(e,t);if(n!==void 0)return n;let o=ht(e);return!!(Fe(o,Gi)||Fe(o,Wi))}function yt(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Hn(o,t)):e.effective.some(o=>{let r=ht(o);return jn(o).length>0||Fe(r,Gi)||Fe(r,Wi)||r.has("search")})}function zn(e){let t=Ue(e).filter(r=>r.split(" ").every(i=>!i.startsWith("-"))).sort((r,i)=>i.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=qn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Xi(e){return zn(e)==="all"?void 0:t=>Hn(t,e)}function je(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...i]=t.commandPathTokens;return{commandPath:r,commandArgs:i,allowCommandPrefixMatch:!0}}let n=Ae(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Zi(e){let t=e.args.map(String);if(_($(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function In(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function Qi(e,t){e.profile&&(y(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${F(t.activationWarnings)}`))}function wt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function _t(e,t=le){let n=Un(e);if(oe?.key===n)return oe.snapshot;try{let o=Date.now(),{settings:r,warnings:i}=await t(e),a=await no({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return oe={key:n,snapshot:s},s}catch{return oe={key:n,snapshot:null},null}}async function he(e,t,n=I){let o=t?zn(t):"all",r=qi(e,o);if(Ne?.key===r)return Ne.snapshot;try{let i=await n(e),a=await _e({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Xi(t):void 0}),s=await be({...a,loaded:a.loaded}),l=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),d=Lr(s.registrations.flags),c=Fr(s.commands.handlers,s.registrations.commands),m=jr(l,s.registrations.commands,s.registrations.flags,c),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:d,commandDescriptors:m,commandAliases:c,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return Ne={key:r,snapshot:p},p}catch{return Ne={key:r,snapshot:null},null}}async function ea(e){let t=Se(e);if(t.noExtensions){let a=E(process.cwd(),t.path);return await q(H(a))&&In((await le(a)).warnings),null}let n=E(process.cwd(),t.path),o=await _t(n);if(!o)return null;In(o.settingsReadWarnings);let r={commandPath:$(e),commandArgs:Zi(e)};if(!yt(o.discovery,r))return wt(t.profile,o,r),null;let i=await he(n,r);return i?(Qi(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 ta(e){let t=await he(e);return t?new Map(t.commandDescriptors):O}async function na(e,t){return(await Go({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function oa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return Uo(e,Xo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ra(e,t,n,o=[]){let r=$(e),i=Bt(e.args.map(String),o),a={...t},s={...n},l=E(process.cwd(),n.path),d=await We({command:r,args:i,options:a,global:s,pm_root:l});n.profile&&d.warnings.length>0&&y(`profile:extensions parser_warnings=${F(d.warnings)}`),i=d.context.args,a=d.context.options,s=d.context.global,Fi(O.get(_(r)),i,a,o),ae(void 0),ze({command:r,args:i,options:{...a},global:{...s},pm_root:l});let c=await At({command:r,args:i,options:a,global:s,pm_root:l,sdk:oa(l,s)});if(s.profile&&c.warnings.length>0&&y(`profile:extensions command_handler_warnings=${F(c.warnings)}`),!c.handled){if(c.warnings.length>0){let m=c.warnings[0],p=c.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:c.errorCode??"command_failed",nextSteps:c.remediation?[c.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return c.exitCode!==void 0&&(process.exitCode=c.exitCode),ae(c.result),c.result}var yi=Symbol("pm.wrappedActionHandler");function wc(e,t){let n=e[e.length-1];return n instanceof $n?n:t}function wi(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${F(n)}`)}function _c(e){let t=O.get(_(e.commandPath));if(!t||!Ni(e.activeRegistrations,e.commandPath))return;let n=Fn(t).length===0?mr(e.commandArgs):Bt(e.commandArgs,e.extensionFlagDefinitions);Mi(t,n)}function bc(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 ia(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[yi]!==!0){let r=o._actionHandler;o._actionHandler=async function(...a){let s=wc(a,n),l=Date.now();Dt(s);let d=Se(s),c=$(s),m=E(process.cwd(),d.path),p=s.args.map(String),u=Y(),g=u?gt(u,c,p):[],w=await Ui(c,m),h=Me(s,p,[...g,...w]),C=await We({command:c,args:p,options:h,global:d,pm_root:m});wi(d.profile,"parser_warnings",C.warnings),p=C.context.args,h=C.context.options,d=C.context.global,_c({activeRegistrations:u,commandPath:c,commandArgs:p,extensionFlagDefinitions:g}),d=await qo(d),Ft(s,d),bc(s,a,p),Qe(s,h),ae(void 0),ze({command:c,args:p,options:{...h},global:{...d},pm_root:m});let R=await At({command:c,args:p,options:h,global:d,pm_root:m,sdk:oa(m,d)});if(wi(d.profile,"command_handler_warnings",R.warnings),R.handled){ae(R.result),Rt(R.result,{...d,command:c,commandArgs:p,commandOptions:h,pmRoot:m}),d.profile&&y(`profile:command=${c} took_ms=${Date.now()-l}`);return}return await r.apply(this,a)},o[yi]=!0}for(let r of n.commands)t(r)};t(e)}async function mt(e){O=new Map,V({overrides:[]}),e&&await Dn(e.rootProgram,e.pmRoot,e.invocationArgv,Qn(),e.settings)}function xc(e,t,n,o){if(t?.flags&&t.flags.length>0){cn(e,t.flags);let r=dn(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function aa(e,t,n){let o={core:0,standard:1,full:2,internal:3},r=(i,a)=>{let s=a.join(" "),l=[...n.entries()].filter(([c])=>c===s||c.startsWith(`${s} `)).map(([,c])=>c),d=l.length===0?"standard":l.reduce((c,m)=>o[m.tier]<o[c]?m.tier:c,"internal");ur(i,d);for(let c of i.commands)r(c,[...a,c.name()])};for(let i of e.commands)t.has(i.name())||r(i,[i.name()])}async function sa(e,t){let n=z(t),o=E(process.cwd(),n.path);if(n.noExtensions){await mt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await _t(o),i=je(t);if(!r){await mt();return}if(!yt(r.discovery,i)){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),wt(Ln(t),r,i);return}let a=await he(o,i);if(!a){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}V(a.services),O=new Map(a.commandDescriptors),await Dn(e,o,t,a.registrations,a.settings);let s=Yr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,c=>Xr(a.activationWarnings,y,c)),l=new Set(e.commands.map(c=>c.name())),d=c=>{let m=c.split(" ").filter(R=>R.length>0),p=a.commandDescriptors.get(c),u=pe(e,m),g=a.commandFlagHelp.get(c),w=p?Vr(p):null;if(u){xc(u,p,g,w);return}let h=Jr(e,m);p?.description&&h.description(p.description);let C=g;p&&(qr(h,p),p.flags.length>0&&(cn(h,p.flags),C=dn(h,p.flags)??void 0)),C&&h.addHelpText("after",C),w&&h.addHelpText("after",w),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let j=R[R.length-1],M=j instanceof $n?j:h,re=Se(M),xt=Date.now(),qe=gt(a.registrations,c,M.args.map(String)),ye=Me(M,M.args.map(String),qe),ie=await ra(M,ye,re,qe);await Ho(re,ie),Rt(ie,{...re,command:c,commandArgs:M.args.map(String),commandOptions:ye,pmRoot:o}),re.profile&&y(`profile:command=${c} took_ms=${Date.now()-xt}`)})};for(let c of s)d(c);aa(e,l,a.commandDescriptors)}var De=Jn(import.meta.url,["../.."])??"0.0.0",b=zt(De);function la(e){e.hook("preAction",async(t,n)=>{ge=null,U=null,Ge(),Dt(n);let o=n.optsWithGlobals(),r=Se(n),i=$(n),a=n.args.map(String),s=Me(n,a),l={...r};xo(i,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),fi(n,i,l,s),await No(i,l);let d=E(process.cwd(),r.path),c=await ea(n);if(!c){ge=oo({commandName:i,commandArgs:a,commandOptions:s,globalOptions:l,pmRoot:d}),U=await Mt({command:i,pm_version:De,args:a,options:s,global:l,pm_root:d}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i),await fn(i,s,d,On()),await un(i,a,s,l,d);return}ro(c.hooks),io(c.commands),ao(c.parsers),so(c.preflight),V(c.services),lo(c.renderers),co(c.registrations);let m=gt(c.registrations,i,a);s=Me(n,a,m),fi(n,i,l,s);let p=await We({command:i,args:a,options:s,global:l,pm_root:c.pmRoot});l.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${F(p.warnings)}`),a=p.context.args,s=p.context.options,l=p.context.global,Qe(n,s);let u=await uo({command:i,args:a,options:s,global:l,pm_root:c.pmRoot,decision:On()});l.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${F(u.warnings)}`),a=u.context.args,s=u.context.options,l=u.context.global,Qe(n,s);let g=u.decision;await fn(i,s,c.pmRoot,g),await un(i,a,s,l,c.pmRoot);let w=g.run_extension_migrations?await na(c.registrations.migrations,c.pmRoot):[];l.profile&&w.length>0&&y(`profile:extensions migration_warnings=${F(w)}`);let h=ei(c.registrations.migrations);ge={hooks:c.hooks,commandName:i,commandArgs:a,commandOptions:{...s},globalOptions:{...l},pmRoot:c.pmRoot,profileEnabled:!!l.profile,migrationBlockers:h},ae(void 0),ze({command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot}),U=await Mt({command:i,pm_version:De,args:a,options:s,global:l,pm_root:c.pmRoot}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i);let C=await eo(c.hooks,{command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot});l.profile&&C.length>0&&y(`profile:extensions hook_warnings=${F(C)}`),g.enforce_mandatory_migration_gate&&ti(i,s,h)}),e.hook("postAction",async()=>{let t=Oi();ve(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Le(t)})}la(b);var vc=new Set(["--version","-V"]),Cc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),ca=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"]),da=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),kc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Ec=new Set(["claim","close-task","pause-task","release","start-task","test"]),En={setup:!0,listQuery:!0,mutation:!0,operation:!0},Sc=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 bt(e){return e.some(t=>vc.has(t))}function ma(e){if(bt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return En;let t=k(e);if(!t)return En;let n=t.trim().toLowerCase();return Cc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:ca.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:da.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:kc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:En}function pa(e){return e.length===0||P(e).requested||e.includes("--explain")&&k(e)===void 0}var _i=Symbol("pmCliIdempotentTopLevelRegistration");function ua(e){let t=e;if(t[_i])return;t[_i]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let i=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===i||a.aliases().includes(i))?new $n(i):n(o,...r)})}async function Ac(e,t){if(ua(e),t.setup){let{registerSetupCommands:n}=await ic();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await ac(),o=typeof t.targetCommandName=="string"&&ca.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await sc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await lc();n(e)}}function fa(e,t){return bt(t)?!1:ce(t)||P(t).requested?!0:!!k(t)}function ga(e){if(bt(e))return!1;let t=k(e);return t?Sc.has(t):!1}function Tc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(d=>{let c=d.indexOf("=");return c>=0?d.slice(0,c):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),i=r?e.argv.map(d=>{let c=d.indexOf("=");return(c>=0?d.slice(0,c):d)===o?c>=0?`${r}${d.slice(c)}`:r:d}):e.argv,a=Ve(i),s=r&&n>=0?`${o}=[redacted]`:t,l=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:l,sourceDisplay:s}}function ha(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),r=o.length>0?o.join(" "):"the canonical flag",i=da.has(t)||Ec.has(t),a=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=Tc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:a,examples:[A(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:A(l.argv)}})}function Oc(e){return async t=>{let n=vt(t.errorCode),o=It({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Fo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:De,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 ya(e){if(e.bootstrapGlobal.noExtensions)return;let t=je(e.invocationArgv),n=await _t(e.bootstrapPmRoot);if(n&&yt(n.discovery,t)){let o=await he(e.bootstrapPmRoot,t);wa(o);return}n&&wt(Ln(e.invocationArgv),n,t),V({overrides:[]})}function wa(e){if(!e){V({overrides:[]});return}V(e.services)}async function Gn(e){ve(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Le({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 _a(){ve(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Le({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function ba(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(qt(e.error)||!n))return!1;let o=Z(e.error),r=e.error instanceof v?e.error.exitCode:jt(t),i=e.error instanceof v?e.error.context:void 0,a=vi(i,e.invocationArgv,o),s=Rr(o,a),l=e.bootstrapGlobal.lean?at(an(o,r,a)):an(o,r,a),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?ko(l,u=>`${JSON.stringify(u,null,2)}
|
|
30
|
-
`):l,null,2):
|
|
24
|
+
${o}`}function hn(e){return P(e).commandPathTokens[0]??k(e)??"<command>"}function pl(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let i=N($(r)),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i),o.push(...r.commands)}for(let r of t.keys()){let i=N(r),a=i.split(" ").some(s=>s.startsWith("_"));i.length>0&&!a&&n.add(i)}return[...n].sort((r,i)=>r.localeCompare(i))}function ri(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let r=n.split(" ");if(n===o)return 0;if(r.includes(o))return 1;if(r.some(s=>s.startsWith(o)))return 2;if(n.includes(o))return 3;let i=o.length>=5?2:1,a=Number.POSITIVE_INFINITY;for(let s of r){let l=kt(s,o,i);l!==null&&(a=Math.min(a,l))}return Number.isFinite(a)?4+a:Number.POSITIVE_INFINITY}function ii(e){return F(e).slice(2).replace(/-/g,"")}function yn(e){return A(e)}function ul(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=cl[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function ai(e){let t=Wo(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function fl(e,t){let n=ai(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let i=new Set,a=r.source;if(a)for(let l of[a.name,a.package]){let d=ai(l??"");d.length>0&&i.add(d)}if(i.size===0)continue;[...i].some(l=>l===n||l.includes(n)||n.includes(l))&&o.push(r.command)}return[...new Set(o)].sort((r,i)=>r.localeCompare(i))}function $e(e,t){let n=new Set,o=t??Ze(e);for(let r of o){r.flag.startsWith("--")&&n.add(F(r.flag));for(let i of r.aliases??[])i.startsWith("--")&&n.add(F(i))}return[...n].sort((r,i)=>r.localeCompare(i))}function gl(e,t){if(!e.startsWith("--"))return[];let n=ii(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let i of t){let a=ii(i);if(a===n)continue;if(n.length>=3&&a.startsWith(n)){r.push({flag:i,rank:0,distance:a.length-n.length});continue}let s=kt(n,a,o);s===null||s<=0||r.push({flag:i,rank:1,distance:s})}return r.sort((i,a)=>i.rank!==a.rank?i.rank-a.rank:i.distance!==a.distance?i.distance-a.distance:i.flag.localeCompare(a.flag)).map(i=>i.flag).slice(0,3)}var dt,hl=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 yl(){if(dt)return dt;let e=new Map;for(let t of Ke)if(!hl.has(t))for(let n of $e(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return dt=e,dt}function wl(e,t){if(!e.startsWith("--"))return[];let n=yl().get(F(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set($e(o));return n.filter(i=>i!==o).map(i=>({command:i,sharedFlagCount:$e(i).filter(a=>r.has(a)).length})).sort((i,a)=>i.sharedFlagCount!==a.sharedFlagCount?a.sharedFlagCount-i.sharedFlagCount:i.command.localeCompare(a.command)).map(({command:i})=>i)}function _l(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let i=r.indexOf("="),a=i>=0?r.slice(0,i):r;if(F(a)!==F(t))continue;let s=[...e];return s[o]=i>=0?`${n}${r.slice(i)}`:n,s}}function bl(e){let t=new Set(e.commandPaths),n=i=>Math.min(ri(i,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?ri(i,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(i,a)=>{if(!Number.isFinite(a)||!t.has(i))return;let s=o.get(i);(s===void 0||a<s)&&o.set(i,a)};for(let i of e.commandPaths)r(i,n(i));for(let[i,a]of Object.entries(ho))i!=="read"&&r(a,n(i));return[...o.entries()].sort(([i,a],[s,l])=>a!==l?a-l:i.localeCompare(s)).map(([i])=>i)}function xl(e){let t=ir(e.commandPaths,e.primaryToken),n=bl(e),o=fl(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return si([...t,...n,...o])}function vl(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Cl(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function wn(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=N(o[1]);if(r.length===0)return;let i=pl(t,n);if(i.length===0)return;let a=r.split(" ")[0],s=xl({commandPaths:i,normalizedUnknown:r,primaryToken:a,extensionDescriptors:n}),l=vl(i),d=(s.length>0?s:l).slice(0,3),c=Cl(d,s.length>0),m=ul(r),p=s.length>0?`Did you mean: ${d.join(", ")}?`:null;return{unknownCommandExamples:c,unknownCommandNextSteps:[...p?[p]:[],'Run "pm --help" to list commands available in this runtime, including active extensions.',"Use one of the suggested command paths above with --help to inspect valid flags and usage.",...m?[m]:[]]}}function si(e){return Array.from(new Set(e))}function kl(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
25
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function El(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 Sl(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(i=>i.trim().toLowerCase()===n))}function _n(e,t){if(t.length===0)return!0;let n=e;for(let[o,r]of t.entries()){let i=Sl(n,r);if(!i){if(n.commands.some(s=>s.name()!=="help"))return!1;let a=n.registeredArguments;return a.length>0&&(a.at(-1)?.variadic===!0||t.length-o<=a.length)}n=i}return!0}async function Al(e,t,n,o){try{let r=E(process.cwd(),e.path);if(!await q(H(r)))return{allowedTypes:Ie};let i=await I(r),a=e.noExtensions?void 0:Y(),s=J(i,a),l;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let d=n.findIndex(m=>m===o),c=n[d+2];if(n[d+1]?.toLowerCase()==="add"&&c!==void 0&&!c.startsWith("-"))try{l=(await Je(r,c,i.id_prefix,i.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ie,pmRoot:r,settings:i,typeToFolder:s.type_to_folder,verifiedCollectionItemId:l}}catch{return{allowedTypes:Ie}}}function Tl(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?si([...ml(t,n[1]),...gl(n[1],$e(t))]):void 0,r=n?wl(n[1],t):[],i=n!==null&&$e(t).includes(F(n[1]));return{match:n,suggestions:o,otherCommands:r,scope:i?"declared_on_path":r.length>0?"declared_elsewhere":"declared_nowhere"}}function Ol(e,t,n){if(!t||!n||n.length===0)return;let o=_l(e,t[1],n[0]);return o?yn(o):void 0}function Rl(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?El(kl(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return or(t,r,[o])}function Il(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=Qo(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let i=`${o}-${r}`;if(!oi.includes(i))return;let a=[...t.slice(0,n+1),i,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...oi],suggestedRetryCommand:yn(a)}}async function Pe(e,t,n,o={}){let i=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",a=tt(process.argv.slice(2)).argv,s=z(a),l=k(a),d=yn(a),c=K(a),m=await Al(s,i,a,l),p=m.allowedTypes,u=wn(i,t,n),g=Tl(i,l),w=Il(i,a),h=w?.suggestedRetryCommand??Ol(a,g.match,g.suggestions)??Rl(i,a);return{message:i,commandName:l,allowedTypes:p,attemptedCommand:d,normalizedInvocationArgs:[...a],providedOptionFlags:c,unknownOptionSuggestions:g.suggestions,unknownOptionOtherCommands:g.otherCommands.length>0?g.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:g.otherCommands.length>0?g.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:g.otherCommands.length>12||void 0,unknownOptionScope:g.scope,suggestedRetryCommand:h,verifiedCollectionItemId:m.verifiedCollectionItemId,...w,...u,...o}}async function bn(e,t,n,o={}){let r=await Pe(e,t,n,o),{message:i,commandName:a,allowedTypes:s,unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}=r,we=$r(i,a,s,{unknownCommandExamples:l,unknownCommandNextSteps:d,attemptedCommand:c,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:g,unknownOptionOtherCommandsTotal:w,unknownOptionOtherCommandsTruncated:h,unknownOptionScope:C,unknownSubcommandPath:R,unknownSubcommandToken:j,unknownSubcommandAllowedValues:M,suggestedRetryCommand:re,verifiedCollectionItemId:xt,failedExtensions:qe}),ie=await fo("help_format",{message:we,command:a,allowed_types:s});return ie.handled&&typeof ie.result=="string"?ie.result:we}async function xn(e,t,n,o=!1,r={}){let i=await Pe(e,t,n,r),a=lt(i.message,i.commandName,i.allowedTypes,f.USAGE,{unknownCommandExamples:i.unknownCommandExamples,unknownCommandNextSteps:i.unknownCommandNextSteps,attemptedCommand:i.attemptedCommand,normalizedInvocationArgs:i.normalizedInvocationArgs,providedOptionFlags:i.providedOptionFlags,unknownOptionSuggestions:i.unknownOptionSuggestions,unknownOptionOtherCommands:i.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:i.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:i.unknownOptionOtherCommandsTruncated,unknownOptionScope:i.unknownOptionScope,unknownSubcommandPath:i.unknownSubcommandPath,unknownSubcommandToken:i.unknownSubcommandToken,unknownSubcommandAllowedValues:i.unknownSubcommandAllowedValues,suggestedRetryCommand:i.suggestedRetryCommand,verifiedCollectionItemId:i.verifiedCollectionItemId,failedExtensions:i.failedExtensions});return JSON.stringify(o?at(a):a,null,2)}import fe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3543bab-fa67-5e91-a700-0cbee84f2dc8")}catch{}})();async function vn(e,t={},n=[]){let o={readSettings:I,loadExtensions:be,activateExtensions:xe,resolveImplicitPmRoot:St,...t};try{let r=await o.readSettings(e),i=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),a=await o.activateExtensions(i);return[...i.failed,...a.failed].map(s=>{let l=(i.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),d=[...l?.contributions?.commands??[],...l?.contributions?.command_handlers??[],...l?.activation?.commands??[]].map(N).filter((p,u,g)=>p.length>0&&g.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),c=n.map(N),m=d.some(p=>c.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...d.length>0?{declared_commands:d}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function li(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await vn(t,n,o),i={readSettings:I,loadExtensions:be,activateExtensions:xe,resolveImplicitPmRoot:St,...n};try{let a=i.resolveImplicitPmRoot(process.cwd());if(fe.resolve(a)===fe.resolve(t))return r;let[s,l]=await Promise.all([i.readSettings(t),i.readSettings(a)]),[d,c]=await Promise.all([i.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),i.loadExtensions({pmRoot:a,settings:l,cwd:process.cwd(),noExtensions:!1})]),m=new Set(d.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(c.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,g)=>u.localeCompare(g));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${fe.resolve(t)} extension_discovery_root=${d.roots.project}; cwd_storage_root=${fe.resolve(a)} cwd_extension_discovery_root=${c.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 ${fe.resolve(a)}, or install the extension into the selected tracker with "pm --pm-path ${fe.resolve(t)} install <package> --project".`})}catch{}return r}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="43167bb0-7cc0-599f-8587-8583d398f1ad")}catch{}})();var ci={core:0,standard:1,full:2,internal:3};function di(e,t,n=!0){let o=t.get(e);if(o)return o;if(!n)return;let r=[...t.entries()].filter(([s])=>s.startsWith(`${e} `)).map(([,s])=>s);if(r.length===0)return;let i=r.reduce((s,l)=>ci[l.tier]<ci[s]?l.tier:s,"internal"),a=new Set(r.map(({family:s})=>s));return{tier:i,family:a.size===1?r[0].family:"extensions"}}function $l(e,t){if(t.length===0)return e;let n=ue(e,t);if(n)return n;let o=t.join(" ");if(!Ke.some(r=>r===o)&&!jo(o)&&!Ee(o))return null;for(let r=t.length-1;r>0;r-=1){let i=ue(e,t.slice(0,r));if(i)return i}return t.length===1?e:null}function Pl(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function mi(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 Nl(e){let t=new Map;for(let n of e){let o=n,r=mi(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let i=t.get(r)??[];i.push(o.long.trim()),t.set(r,i)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,i)=>r.localeCompare(i)));return t}function Ml(e){return A(e)}function Dl(e){let t=e.options??[],n=Nl(t);return t.map(o=>{let r=o,i=typeof r.flags=="string"?r.flags.trim():"",a=typeof r.description=="string"?r.description.trim():"",s=mi(o),d=(s?n.get(s)??[]:[]).filter(h=>h!==r.long).map(h=>h.trim()).filter(h=>h.length>0),c=a.match(/^Alias for ([^ ]+)/i),m=c&&c[1]?c[1].trim():null,p=r.mandatory===!0||a.includes("[required]")||a.toLowerCase().includes("required;"),u=i.includes("<"),g=u||i.includes("["),w={flags:i,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:a,takes_value:g,value_required:u,value_name:Pl(i),variadic:r.variadic===!0,required:p,aliases:d,alias_for:m};return r.defaultValue!==void 0&&(w.default_value=r.defaultValue),w})}function Fl(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,i=t.get(r);if(!i)continue;let a=o.long,s=new Set([...i.aliases??[],a]);i.aliases=[...s].sort((l,d)=>l.localeCompare(d))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Ll(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",i=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0||i?.toLowerCase().startsWith("required;")===!0,variadic:o.variadic===!0,description:i}})}function Ul(e,t=new Map,n=!1){let o=e.createHelp().visibleCommands(e);return(n?[...new Set([...o,...e.commands])]:o).filter(i=>i.name()!=="help"||e.parent===null).filter(i=>!n||(Q(i)??X(i.name()))!=="internal").map(i=>{let a=N($(i)),s=a.split(" ")[0],l=Q(i),d=di(a,t,l!==void 0),c=le.find(({alias:m})=>m===a);return{name:i.name().trim(),aliases:mn(i),description:i.description().trim(),tier:d?.tier??l??X(s),family:d?.family??et(s),...c?{alias_for:c.canonical,alias_lifecycle:c.lifecycle,...c.lifecycle==="deprecated"?{deprecated:!0}:{}}:{}}}).sort((i,a)=>i.name.localeCompare(a.name))}function jl(e,t,n){if(!n)return t;let o=n.examples??[],r=n.failure_hints??[];return{intent:n.intent??n.description??t.intent,examples:e==="detailed"?o.length>0?[...o]:[...t.examples]:o.length>0?[o[0]]:[...t.examples],tips:e==="detailed"?r.length>0?[...r]:[...t.tips]:[],detail_mode:e}}function ql(e,t){return e===void 0?null:t?.tier??X(e)}function Hl(e,t){return e===void 0?null:t?.family??et(e)}function zl(e,t,n){if(!(t!==e||!n))return le.map(o=>({alias:o.alias,canonical:o.canonical,canonical_argv:[...o.canonical_argv],lifecycle:o.lifecycle,hidden:o.hidden,deprecated:o.lifecycle==="deprecated"}))}function Gl(e,t,n,o,r=new Map,i=!1){if(!e){let s=Ll(t),l=Ul(t,r,i),d=new Set(l.map(({name:c})=>c));return{arguments:s,options:o,subcommands:[...l,...Ye.filter(({parent:c,action:m})=>c===n&&!d.has(m)).map(({action:c,description:m})=>({name:c,aliases:[],description:m,tier:X(n.split(" ")[0]),family:et(n.split(" ")[0])}))].sort((c,m)=>c.name.localeCompare(m.name)),usage:[n,s.reduce((c,m)=>m.required?c.replace(`[${m.name}${m.variadic?"...":""}]`,`<${m.name}${m.variadic?"...":""}>`):c,t.usage())].filter(c=>c.length>0).join(" ")}}let a=new Set(e.accepted_flags);return{arguments:e.slots.map(({name:s,required:l,variadic:d,value_kind:c,polymorphic:m})=>({name:s,required:l,variadic:d,description:m?`Polymorphic ${c} value; inspect the action contract before mutation.`:`${c.replaceAll("_"," ")} value.`})),options:o.filter(({long:s,aliases:l})=>s!==null&&a.has(s)||l.some(d=>a.has(d))),subcommands:[],usage:[e.command,...e.slots.map(({name:s,required:l,variadic:d})=>{let c=d?`${s}...`:s;return l?`<${c}>`:`[${c}]`})].join(" ")}}function Wl(e,t,n,o,r){let i=Jt(n),a=de(n),s=N($(t)),l=N(o.join(" ")),d=l.length>s.length?l:s,c=Ee(d),m=c?.command??d,p=m.length>0?m:void 0,u=p?.split(" ")[0],g=wr(p,i),w=p?r.get(p):void 0,h=p?di(p,r,Q(t)!==void 0):void 0,C=jl(i,g,w),R=Fl(Vr(Dl(t),Br(w))),j=Gl(c,t,m,R,r,a),M=zl(e,t,a);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:ql(u,h),capability_family:Hl(u,h),description:c?.description??t.description(),usage:j.usage,intent:c?.description??C.intent,examples:c?[c.example]:C.examples,tips:c?[Xe(c.accepted_flags)]:C.tips,arguments:j.arguments,options:j.options,subcommands:j.subcommands,has_subcommands:j.subcommands.length>0,...M===void 0?{}:{command_aliases:M}}}async function pi(e,t,n){let o=z(t);if(!o.json)return!1;let r=P(t);if(!r.requested)return!1;let i=$l(e,r.commandPathTokens);if(!i){if(!o.quiet){let a=`unknown command '${r.commandPathTokens.join(" ")}'`,s=wn(a,e,n),l=lt(a,"help",Ie,f.USAGE,{...s,attemptedCommand:Ml(t),normalizedInvocationArgs:[...t],providedOptionFlags:K(t)});y(JSON.stringify(l,null,2))}return process.exitCode=f.USAGE,!0}if(!o.quiet){let a=Wl(e,i,t,r.commandPathTokens,n);Ao(`${JSON.stringify(a,null,2)}
|
|
26
|
+
`)}return process.exitCode=f.SUCCESS,!0}function Bl(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(`
|
|
27
|
+
`)}function Vl(e,t){if(t.options.length===0){e.push(" type options: none");return}e.push(" type options:");for(let n of t.options){let o=n.required?" (required)":"",r=n.aliases??[];e.push(` - ${n.key}${o}`),e.push(` values: ${n.values.length>0?n.values.join("|"):"any non-empty string"}`),e.push(` aliases: ${r.length>0?r.join("|"):"none"}`),n.description&&n.description.trim().length>0&&e.push(` description: ${n.description.trim()}`)}}function Kl(e,t){let n=e==="create"?new Set(["title","type"]):new Set,o=new Set(n);if(e==="create")for(let r of[...t.required_create_fields,...t.required_create_repeatables])o.add(r);return{progressive:n,strict:o}}function Jl(e,t,n,o){let r=new Set(n),i=o.filter(l=>!r.has(l)),a=l=>l.length>0?l.map(d=>Et("create",d)).join(", "):"none";e.push(` required in strict mode: ${a(i)}`);let s=i.map(Ko).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 Yl(e,t,n){let o=tr(n);if(!o)return Bl(e,t);let r=Xn(o,t);if(!r){let w=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${w}`].join(`
|
|
28
|
+
`)}let i=n.indexOf("--"),a=i<0?n:n.slice(0,i),s=a.findIndex(w=>w==="--create-mode"||w.startsWith("--create-mode=")),l=s<0?void 0:a[s]?.startsWith("--create-mode=")?a[s]?.slice(14):a[s+1],d=e==="create"&&l?.toLowerCase()==="strict",c=Kl(e,r),m=He(r,e,c.progressive),p=He(r,e,d?c.strict:c.progressive),u=w=>w.length>0?w.map(h=>Et(e,h)).join(", "):"none",g=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let w=He(r,e,c.strict);Jl(g,r,m.required,w.required)}return Vl(g,r),p.errors.length>0&&g.push(` config errors: ${p.errors.join("; ")}`),g.join(`
|
|
29
|
+
`)}function ui(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=Re(e,o);r&&r.addHelpText("after",Yl(o,t,n))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa92f987-990a-5159-8c45-f055d5a15da2")}catch{}})();async function fi(e,t,n,o){if(n)return null;let r=e.some(a=>a==="--for"||a.startsWith("--for=")),i=k(e)==="contracts"&&e.includes("--full");return r||i?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f947c7f0-adf8-59da-8bc7-9cd746b05839")}catch{}})();var Cn="PM_CLI_PACKAGE_ROOT",ut=Symbol.for("pm.readOutputInvocationProvenance");function Pn(e,t){let n=Reflect.get(e,ut);n!==void 0&&Reflect.set(t,ut,n)}function xi(e,t,n){let o=bo(t,n);if(!o)return;let r=e;for(;r.parent;)r=r.parent;let i=r.rawArgs,a=new Set(K(i.slice(2))),s=_o.find(c=>c.command===o),l=Object.values(s.dimensions).flatMap(c=>c.legacy_aliases.flatMap(m=>a.has(m.flag)?[m.flag]:[])),d=Reflect.get(n,ut);Reflect.set(n,ut,{canonical_include_modes:d?.canonical_include_modes??[],explicit_legacy_aliases:l,cli_invocation_observed:!0}),Pn(n,e)}function Zl(){return Kn(import.meta.url,["../.."])}(typeof process.env[Cn]!="string"||process.env[Cn]?.trim().length===0)&&(process.env[Cn]=Zl());var he=null,U=null;function Ql(e){he=e}function ec(e){O=e}var tc=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"]),nc=new Set(["parse","preflight","execute","unknown"]),oc=new Set(["usage","validation","conflict","runtime","unknown"]),Ne=null,oe=null,O=new Map,Nn=250,rc=new Set([f.USAGE,f.NOT_FOUND,f.CONFLICT]),ic=new Set(["1","true","yes","on"]),ac=ke(()=>import("./chunks/register-setup-D3ZFHY3L.js")),sc=ke(()=>import("./chunks/register-list-query-W2ZTOMKP.js")),lc=ke(()=>import("./chunks/register-mutation-RVND5NCG.js")),cc=ke(()=>import("./chunks/register-operations-TTROIVC4.js"));function pt(e){return A(e)}function vi(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=>ee(o)??o))];return n.length>0?n:void 0}function dc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=K(t),r=new Set(o.map(c=>ee(c)??c)),i=vi(e),a=t.find(c=>b.commands.some(m=>m.name()===c)),s=a?b.commands.find(c=>c.name()===a):void 0,l=new Set([...b.options,...s?.options??[]].flatMap(c=>c.flags.split(/[ ,|]+/).map(m=>ee(m)).filter(m=>m!==void 0))),d=i?.filter(c=>{let m=ee(c)??c;return r.has(m)?!1:l.has(m)||ln(t,a,m,O)!==void 0});return d&&d.length>0?d:void 0}function mc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],i=r?ee(r):void 0,a=e.find(p=>b.commands.some(u=>u.name()===p)),s=a?b.commands.find(p=>p.name()===a):void 0,l=i?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(i)):void 0,d=ln(e,a,i,O),c=i?l?.isBoolean()===!0||d===!1?[i]:[i,"<value>"]:[],m=i?pt([...e,...c]):t;return m===t?void 0:m}function pc(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","suggested_retry_args","allowed_values","candidate_commands","candidate_commands_total","candidate_commands_truncated","fallback_candidates","next_best_command"],n={};for(let o of t){let r=e[o];r!=null&&(n[o]=r)}return n}function uc(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,...pc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Ci(e,t,n){let o=Ve(t),r=o.includes("--explain"),i=e?.recovery,a=i&&o.includes("history-redact")?{...i,...i.attempted_command?{attempted_command:pt(o)}:{},...i.normalized_args?{normalized_args:[...o]}:{},...i.suggested_retry?{suggested_retry:pt(o)}:{},...i.suggested_retry_args?{suggested_retry_args:[...o]}:{}}:i;if(a?.recovery_mode==="compact"&&!r)return{...e,recovery:a};let s=pt(o),l=K(o),d=dc(n,o,a),c=mc(o,s,d,a),m=uc({invocationArgv:o,attemptedCommand:s,providedFields:l,inferredMissing:d,suggestedRetry:c,existingRecovery:a});return{...e,recovery:m}}function ge(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="string"){let r=o.trim();if(r.length>0)return r}}}function ki(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function Mn(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 Ei(e){if(!e)return;let t=e.trim().toLowerCase();if(tc.has(t))return t}function Si(e){if(!e)return;let t=e.trim().toLowerCase();if(nc.has(t))return t}function Ai(e){if(!e)return;let t=e.trim().toLowerCase();if(oc.has(t))return t}function Ti(e){let t=ge(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let a=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof a=="string")return a.trim()}if(ki(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=Mn(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let i=e?.run_results;if(Array.isArray(i)){let a=i.filter(s=>Ct(s)?.status==="failed").length;if(a>0)return`failed_runs:${a}`}}function Oi(e,t){if(!e)return t===f.USAGE?"invalid_command_usage":t===f.NOT_FOUND?"item_not_found":t===f.CONFLICT?"lock_conflict":t===f.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Ri(){let e=Ct(se()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=Mn(e,"exit_code","exitCode"),o=t??n??f.SUCCESS,r=Vo(o),i=ge(e,"error_code","errorCode")??Oi(r,o),a=Ai(ge(e,"error_category","errorCategory"))??(r?void 0:vt(i)),s=r?void 0:Ti(e)??`command_exit_${o}`,l=Ei(ge(e,"command_resolution","commandResolution"))??It({ok:r,errorCode:i,errorCategory:a}),d=Si(ge(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:i,error_category:a,command_resolution:l,resolution_stage:d}}async function Le(e){let t=U;U=null,await br(t,e);let n=he;if(he=null,!n){Ge();return}let o=[],r=po();try{await xr({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(i=>i.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await to(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:se(),affected:r}))}catch(i){o=[`afterCommand hooks failed: ${i instanceof Error?i.message:String(i)}`]}finally{Ge()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${D(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${D(o)}`)}async function Ii(){await Io()}function $i(e){return ic.has((process.env[e]??"").trim().toLowerCase())}function Pi(e){return $i("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!rc.has(Math.trunc(e))}async function ft(e){return Pi(e.exit_code)?(await Ii(),$o(e),!0):!1}async function Ni(e){let t=Z(e.error),n=Mr(t);e.bootstrapGlobal.json?y(JSON.stringify(Pr(t,f.GENERIC_FAILURE),null,2)):y(t),process.exitCode=f.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Ii(),Nt(e.error);let i=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:f.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=i.errorCategory,r=i.commandResolution,ve(!1,t,{error_code:n.code,error_category:o,exit_code:f.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to report error: ${Z(i)}`)}try{await Le({ok:!1,error:t,exit_code:f.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(i){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${Z(i)}`)}try{await Ce()}catch(i){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${Z(i)}`)}}function gi(e,t,n,o){xi(e,t,o);let r=n.outputInclude;if(r===void 0)return;let{selectors:i,modes:a}=Co(t,r,o);if(t==="get"&&typeof o.fields=="string"&&e.setOptionValueWithSource("fields",o.fields,"cli"),a.length===0)return;Pn(o,e);let s=vo(t);for(let d of a){let c=s.get(d),m=o[c];e.setOptionValueWithSource(c,m,"cli")}let l=i.length>0?i.join(","):void 0;l===void 0?delete n.outputInclude:n.outputInclude=l;for(let d=e;d;d=d.parent)d.setOptionValueWithSource("outputInclude",l,"cli");Dt(e,n)}function Me(e,t,n=[]){let r={...e.optsWithGlobals()};Pn(e,r),delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let i=mr(t);for(let[a,s]of Object.entries(i))r[a]===void 0&&(r[a]=s);if(n.length>0){let a=lr(n),s=Ze($(e)).map(d=>({long:d.flag,short:d.short,aliases:d.aliases})),l={...i};for(let d of a)r[d]!==void 0&&(l[d]=r[d]);return Wt(l,[...s,...n],$(e)),dr(r,n,i)}return r}function Sn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function gt(e,t,n){let o=Sn(e,t),r=[t],i=[];for(let a of n){if(a.startsWith("-"))break;r.push(a);let s=Sn(e,r.join(" "));s.length>0&&(i=s)}return i.length>0?i:o}function Dn(e){return e.arguments??[]}function hi(e){let t=Dn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function Mi(e,t){if(!e)return!1;let n=_(t);return e.importers.some(o=>_(`${o.importer} import`)===n)||e.exporters.some(o=>_(`${o.exporter} export`)===n)}function Di(e,t){let n=Dn(e),o=n.filter(l=>l.required).length,i=n.some(l=>l.variadic)?Number.POSITIVE_INFINITY:n.length,a=e.failure_hints??[],s=a.length>0?` ${a.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${hi(e)}${s}`,f.USAGE);if(t.length>i){let l=t.slice(i).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${l}. Usage: ${hi(e)}${s}`,f.USAGE)}}function fc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function gc(e,t,n){if(n.length>0){Wt(t,n,e.command);return}let o=Object.keys(t).filter(r=>t[r]!==void 0).sort();if(o.length!==0)throw new v(`Unknown option '${o.map(fc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,f.USAGE)}function Fi(e,t,n,o){e&&(Di(e,t),gc(e,n,o))}var hc={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"},kn=new Map;function An(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function Li(e,t){return e.options.some(n=>n.long===t)}function Ui(e,t){return e.options.some(n=>n.short===t)}function Tn(e,t,n,o){let r=t.trim();if(!r)return;let i=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(Ui(e,r))return;if(o){e.option(`${r} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${r} <value>`,i);return}let a=r.startsWith("--")?r:`--${r}`;if(!Li(e,a)){if(o){e.option(`${a} <value>`,`${i} (repeatable)`,Lt);return}e.option(`${a} <value>`,i)}}async function ji(e,t){let n=hc[e];if(!n)return[];let o=`${t}:${n}`,r=kn.get(o);if(r)return r;if(!await q(H(t)))return kn.set(o,[]),[];let i=await I(t),s=(Tt(i.schema).command_to_fields.get(n)??[]).flatMap(l=>[l.cli_flag,...l.cli_aliases].map(c=>({long:`--${c}`,type:An(l.type),value_type:An(l.type)})));return kn.set(o,s),s}async function qi(e,t){let n=z(t),o=E(process.cwd(),n.path);if(!await q(H(o)))return;let r=oe?.key===Un(o)?oe.snapshot:null,i=r===null?await I(o):r.settings,a=Tt(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 d=ue(e,l.path.split(" "));if(d)for(let c of a.command_to_fields.get(l.command)??[]){let m=c.description??"";Tn(d,c.cli_flag,m,c.repeatable);for(let p of c.cli_aliases)Tn(d,p,`Alias for --${c.cli_flag}`,c.repeatable)}}}async function Fn(e,t,n,o,r){let i=k(n);if(!(i!=="create"&&i!=="update"))try{let a=r??await I(t),s=J(a,o);ui(e,s,n)}catch{}}function On(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function Hi(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function Ln(e){return e.some(t=>t==="--profile")}function Un(e){return`pm-root:${e}`}function zi(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Ue(e){let t=_(e.commandPath??"");if(t.length===0)return[];let n=[t],o=t.split(" ").filter(r=>r.length>0);for(let r of zi(e.commandArgs))o.push(...r.split(" ").filter(i=>i.length>0)),n.push(o.join(" "));return[...new Set(n)]}function Gi(e,t){let n=_(e);if(n.length===0)return!1;let o=Ue(t);for(let r of o)if(r===n||r.startsWith(`${n} `))return!0;return t.allowCommandPrefixMatch===!0?o.some(r=>n.startsWith(`${r} `)):!1}function jn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...S(n.commands),...S(n.command_handlers),...S(n.command_overrides),...S(n.flag_commands),...S(n.parser_overrides),...yi(n.preflight_ownership),...yi(n.renderer_ownership)]:[]}function S(e){return e??[]}function yi(e){return S(e).flatMap(t=>t.commands)}function ht(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var Wi=new Set(["hooks","parser","preflight","renderers"]),Bi=new Set(["commands","schema","services","importers"]),yc=new Set(["reindex","search","search-advanced"]),wc=new Set(["--template"]);function De(e,t){for(let n of t)if(e.has(n))return!0;return!1}function Vi(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return yc.has(n??t)}function Ki(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 qn(e){return _(e.commandPath??"")==="create"&&Ki(e,wc)}function Ji(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function Rn(e,t){return e.some(n=>Gi(n,t))||qn(t)&&Ji(e)}function Yi(e){return[S(e.hooks).length,(e.preflight_overrides??0)-S(e.preflight_ownership).length,S(e.item_types).length,S(e.item_fields).length,S(e.relationship_kinds).length,S(e.service_overrides).length,S(e.assurance_providers).length,S(e.renderer_overrides).length-S(e.renderer_ownership).length].some(n=>n>0)}function Xi(e,t){let n=e.activation?.commands??[];if(n.length>0)return Rn(n,t);let o=jn(e);if(Rn(o,t)||ht(e).has("search")&&Vi(t.commandPath))return!0;if(e.contributions)return Yi(e.contributions)}function Hn(e,t){let n=Xi(e,t);if(n!==void 0)return n;let o=ht(e);return!!(De(o,Wi)||De(o,Bi))}function yt(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Hn(o,t)):e.effective.some(o=>{let r=ht(o);return jn(o).length>0||De(r,Wi)||De(r,Bi)||r.has("search")})}function zn(e){let t=Ue(e).filter(r=>r.split(" ").every(i=>!i.startsWith("-"))).sort((r,i)=>i.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=qn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function Zi(e){return zn(e)==="all"?void 0:t=>Hn(t,e)}function je(e){let t=P(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...i]=t.commandPathTokens;return{commandPath:r,commandArgs:i,allowCommandPrefixMatch:!0}}let n=Ae(e),o=n.findIndex(r=>r.trim().length>0&&!r.startsWith("-"));return o<0?{}:{commandPath:n[o],commandArgs:n.slice(o+1),allowCommandPrefixMatch:t.requested}}function Qi(e){let t=e.args.map(String);if(_($(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function In(e){for(let t of e)t.startsWith("settings_read_")&&y(`[pm] warning: ${t} \u2014 settings.json could not be loaded and pm fell back to defaults; run pm health for remediation.`)}function ea(e,t){e.profile&&(y(`profile:extensions loaded=${t.loadedCount} failed=${t.loadFailedCount} warnings=${t.loadWarnings.length} activation_failed=${t.activationFailedCount} hook_counts=before:${t.hooks.beforeCommand.length}|after:${t.hooks.afterCommand.length}|write:${t.hooks.onWrite.length}|read:${t.hooks.onRead.length}|index:${t.hooks.onIndex.length} command_overrides=${t.commands.overrides.length} command_handlers=${t.commands.handlers.length} parser_overrides=${t.parsers.overrides.length} preflight_overrides=${t.preflight.overrides.length} service_overrides=${t.services.overrides.length} renderer_overrides=${t.renderers.overrides.length}`),t.activationWarnings.length>0&&y(`profile:extensions activation_warnings=${D(t.activationWarnings)}`))}function wt(e,t,n){if(!e)return;let o=_(n.commandPath??"")||"<none>";y(`profile:extensions activation=skipped command=${o} effective=${t.discovery.effective.length} warnings=${t.discovery.warnings.length} discovery_ms=${t.discoveryMs}`)}async function _t(e,t=ce){let n=Un(e);if(oe?.key===n)return oe.snapshot;try{let o=Date.now(),{settings:r,warnings:i}=await t(e),a=await no({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:a,discoveryMs:Date.now()-o,settingsReadWarnings:[...i]};return oe={key:n,snapshot:s},s}catch{return oe={key:n,snapshot:null},null}}async function ye(e,t,n=I){let o=t?zn(t):"all",r=Hi(e,o);if(Ne?.key===r)return Ne.snapshot;try{let i=await n(e),a=await be({pmRoot:e,settings:i,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?Zi(t):void 0}),s=await xe({...a,loaded:a.loaded}),l=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,g)=>u.localeCompare(g)),d=Ur(s.registrations.flags),c=Fr(s.commands.handlers,s.registrations.commands),m=qr(l,s.registrations.commands,s.registrations.flags,c),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:d,commandDescriptors:m,commandAliases:c,loadWarnings:[...a.warnings],activationWarnings:[...s.warnings],loadedCount:a.loaded.length,loadFailedCount:a.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:a.loaded.map(({name:u,module:g})=>({name:u,module:g}))};return Ne={key:r,snapshot:p},p}catch{return Ne={key:r,snapshot:null},null}}async function ta(e){let t=Se(e);if(t.noExtensions){let a=E(process.cwd(),t.path);return await q(H(a))&&In((await ce(a)).warnings),null}let n=E(process.cwd(),t.path),o=await _t(n);if(!o)return null;In(o.settingsReadWarnings);let r={commandPath:$(e),commandArgs:Qi(e)};if(!yt(o.discovery,r))return wt(t.profile,o,r),null;let i=await ye(n,r);return i?(ea(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 na(e){let t=await ye(e);return t?new Map(t.commandDescriptors):O}async function oa(e,t){return(await Bo({pmRoot:t,migrations:e,author:"pm-extension-migration"})).migrations.filter(o=>o.outcome==="failed").map(o=>`extension_migration_failed:${o.layer}:${o.extension}:${o.id}`)}function ra(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return qo(e,Zo.forActiveExtensionHost({pmRoot:e,author:n}))}async function ia(e,t,n,o=[]){let r=$(e),i=Bt(e.args.map(String),o),a={...t},s={...n},l=E(process.cwd(),n.path),d=await We({command:r,args:i,options:a,global:s,pm_root:l});n.profile&&d.warnings.length>0&&y(`profile:extensions parser_warnings=${D(d.warnings)}`),i=d.context.args,a=d.context.options,s=d.context.global,Fi(O.get(_(r)),i,a,o),ae(void 0),ze({command:r,args:i,options:{...a},global:{...s},pm_root:l});let c=await At({command:r,args:i,options:a,global:s,pm_root:l,sdk:ra(l,s)});if(s.profile&&c.warnings.length>0&&y(`profile:extensions command_handler_warnings=${D(c.warnings)}`),!c.handled){if(c.warnings.length>0){let m=c.warnings[0],p=c.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,f.GENERIC_FAILURE,{code:c.errorCode??"command_failed",nextSteps:c.remediation?[c.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,f.NOT_FOUND)}return c.exitCode!==void 0&&(process.exitCode=c.exitCode),ae(c.result),c.result}var wi=Symbol("pm.wrappedActionHandler");function _c(e,t){let n=e[e.length-1];return n instanceof $n?n:t}function _i(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${D(n)}`)}function bc(e){let t=O.get(_(e.commandPath));if(!t||!Mi(e.activeRegistrations,e.commandPath))return;let n=Dn(t).length===0?pr(e.commandArgs):Bt(e.commandArgs,e.extensionFlagDefinitions);Di(t,n)}function xc(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 aa(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[wi]!==!0){let r=o._actionHandler;o._actionHandler=async function(...a){let s=_c(a,n),l=Date.now();Ft(s);let d=Se(s),c=$(s),m=E(process.cwd(),d.path),p=s.args.map(String),u=Y(),g=u?gt(u,c,p):[],w=await ji(c,m),h=Me(s,p,[...g,...w]),C=await We({command:c,args:p,options:h,global:d,pm_root:m});_i(d.profile,"parser_warnings",C.warnings),p=C.context.args,h=C.context.options,d=C.context.global,bc({activeRegistrations:u,commandPath:c,commandArgs:p,extensionFlagDefinitions:g}),d=await zo(d),Dt(s,d),xc(s,a,p),Qe(s,h),ae(void 0),ze({command:c,args:p,options:{...h},global:{...d},pm_root:m});let R=await At({command:c,args:p,options:h,global:d,pm_root:m,sdk:ra(m,d)});if(_i(d.profile,"command_handler_warnings",R.warnings),R.handled){ae(R.result),Rt(R.result,{...d,command:c,commandArgs:p,commandOptions:h,pmRoot:m}),d.profile&&y(`profile:command=${c} took_ms=${Date.now()-l}`);return}return await r.apply(this,a)},o[wi]=!0}for(let r of n.commands)t(r)};t(e)}async function mt(e){O=new Map,V({overrides:[]}),e&&await Fn(e.rootProgram,e.pmRoot,e.invocationArgv,Qn(),e.settings)}function vc(e,t,n,o){if(t?.flags&&t.flags.length>0){cn(e,t.flags);let r=dn(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}function sa(e,t,n){let o={core:0,standard:1,full:2,internal:3},r=(i,a)=>{let s=a.join(" "),l=[...n.entries()].filter(([c])=>c===s||c.startsWith(`${s} `)).map(([,c])=>c),d=l.length===0?"standard":l.reduce((c,m)=>o[m.tier]<o[c]?m.tier:c,"internal");fr(i,d);for(let c of i.commands)r(c,[...a,c.name()])};for(let i of e.commands)t.has(i.name())||r(i,[i.name()])}async function la(e,t){let n=z(t),o=E(process.cwd(),n.path);if(n.noExtensions){await mt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await _t(o),i=je(t);if(!r){await mt();return}if(!yt(r.discovery,i)){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),wt(Ln(t),r,i);return}let a=await ye(o,i);if(!a){await mt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}V(a.services),O=new Map(a.commandDescriptors),await Fn(e,o,t,a.registrations,a.settings);let s=Xr(e,a.commandHandlers,a.commandDescriptors,a.commandAliases,c=>Zr(a.activationWarnings,y,c)),l=new Set(e.commands.map(c=>c.name())),d=c=>{let m=c.split(" ").filter(R=>R.length>0),p=a.commandDescriptors.get(c),u=ue(e,m),g=a.commandFlagHelp.get(c),w=p?Kr(p):null;if(u){vc(u,p,g,w);return}let h=Yr(e,m);p?.description&&h.description(p.description);let C=g;p&&(Hr(h,p),p.flags.length>0&&(cn(h,p.flags),C=dn(h,p.flags)??void 0)),C&&h.addHelpText("after",C),w&&h.addHelpText("after",w),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...R)=>{let j=R[R.length-1],M=j instanceof $n?j:h,re=Se(M),xt=Date.now(),qe=gt(a.registrations,c,M.args.map(String)),we=Me(M,M.args.map(String),qe),ie=await ia(M,we,re,qe);await Go(re,ie),Rt(ie,{...re,command:c,commandArgs:M.args.map(String),commandOptions:we,pmRoot:o}),re.profile&&y(`profile:command=${c} took_ms=${Date.now()-xt}`)})};for(let c of s)d(c);sa(e,l,a.commandDescriptors)}var Fe=Jn(import.meta.url,["../.."])??"0.0.0",b=zt(Fe);function ca(e){e.hook("preAction",async(t,n)=>{he=null,U=null,Ge(),Ft(n);let o=n.optsWithGlobals(),r=Se(n),i=$(n),a=n.args.map(String),s=Me(n,a),l={...r};xo(i,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession,outputCursor:o.outputCursor}),gi(n,i,l,s),await Do(i,l);let d=E(process.cwd(),r.path),c=await ta(n);if(!c){he=oo({commandName:i,commandArgs:a,commandOptions:s,globalOptions:l,pmRoot:d}),U=await Mt({command:i,pm_version:Fe,args:a,options:s,global:l,pm_root:d}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i),await fn(i,s,d,On()),await un(i,a,s,l,d);return}ro(c.hooks),io(c.commands),ao(c.parsers),so(c.preflight),V(c.services),lo(c.renderers),co(c.registrations);let m=gt(c.registrations,i,a);s=Me(n,a,m),gi(n,i,l,s);let p=await We({command:i,args:a,options:s,global:l,pm_root:c.pmRoot});l.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${D(p.warnings)}`),a=p.context.args,s=p.context.options,l=p.context.global,Qe(n,s);let u=await uo({command:i,args:a,options:s,global:l,pm_root:c.pmRoot,decision:On()});l.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${D(u.warnings)}`),a=u.context.args,s=u.context.options,l=u.context.global,Qe(n,s);let g=u.decision;await fn(i,s,c.pmRoot,g),await un(i,a,s,l,c.pmRoot);let w=g.run_extension_migrations?await oa(c.registrations.migrations,c.pmRoot):[];l.profile&&w.length>0&&y(`profile:extensions migration_warnings=${D(w)}`);let h=ti(c.registrations.migrations);he={hooks:c.hooks,commandName:i,commandArgs:a,commandOptions:{...s},globalOptions:{...l},pmRoot:c.pmRoot,profileEnabled:!!l.profile,migrationBlockers:h},ae(void 0),ze({command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot}),U=await Mt({command:i,pm_version:Fe,args:a,options:s,global:l,pm_root:c.pmRoot}),$t(i,a,s,{source_context:U?.source_context,source_context_source:U?.source_context_source}),Pt(i);let C=await eo(c.hooks,{command:i,args:a,options:{...s},global:{...l},pm_root:c.pmRoot});l.profile&&C.length>0&&y(`profile:extensions hook_warnings=${D(C)}`),g.enforce_mandatory_migration_gate&&ni(i,s,h)}),e.hook("postAction",async()=>{let t=Ri();ve(t.ok,t.error,{error_code:t.error_code,error_category:t.error_category,exit_code:t.exit_code,command_resolution:t.command_resolution,resolution_stage:t.resolution_stage}),await Le(t)})}ca(b);var Cc=new Set(["--version","-V"]),kc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),da=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"]),ma=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Ec=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Sc=new Set(["claim","close-task","pause-task","release","start-task","test"]),En={setup:!0,listQuery:!0,mutation:!0,operation:!0},Ac=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 bt(e){return e.some(t=>Cc.has(t))}function pa(e){if(bt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||P(e).requested)return En;let t=k(e);if(!t)return En;let n=t.trim().toLowerCase();return kc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:da.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:ma.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Ec.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:En}function ua(e){return e.length===0||P(e).requested||e.includes("--explain")&&k(e)===void 0}var bi=Symbol("pmCliIdempotentTopLevelRegistration");function fa(e){let t=e;if(t[bi])return;t[bi]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let i=o.split(/\s+/u)[0];return e.commands.some(a=>a.name()===i||a.aliases().includes(i))?new $n(i):n(o,...r)})}async function Tc(e,t){if(fa(e),t.setup){let{registerSetupCommands:n}=await ac();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await sc(),o=typeof t.targetCommandName=="string"&&da.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await lc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await cc();n(e)}}function ga(e,t){return bt(t)?!1:de(t)||P(t).requested?!0:!!k(t)}function ha(e){if(bt(e))return!1;let t=k(e);return t?Ac.has(t):!1}function Oc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(d=>{let c=d.indexOf("=");return c>=0?d.slice(0,c):d}).find(d=>d==="--literal"||d==="--regex"||d==="--replacement"),i=r?e.argv.map(d=>{let c=d.indexOf("=");return(c>=0?d.slice(0,c):d)===o?c>=0?`${r}${d.slice(c)}`:r:d}):e.argv,a=Ve(i),s=r&&n>=0?`${o}=[redacted]`:t,l=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:a,normalizedDisplay:l,sourceDisplay:s}}function ya(e){let t=e.commandName;if(!t)return;let n=e.trace.find(d=>d.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(d=>d.length>0),r=o.length>0?o.join(" "):"the canonical flag",i=ma.has(t)||Sc.has(t),a=i?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=i?"mutating option":"option",l=Oc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${l.sourceDisplay} to ${l.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,f.USAGE,{code:a,examples:[A(l.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:l.argv,suggested_retry:A(l.argv)}})}function Rc(e){return async t=>{let n=vt(t.errorCode),o=It({ok:!1,errorCode:t.errorCode,errorCategory:n});return await Lo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Fe,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 wa(e){if(e.bootstrapGlobal.noExtensions)return;let t=je(e.invocationArgv),n=await _t(e.bootstrapPmRoot);if(n&&yt(n.discovery,t)){let o=await ye(e.bootstrapPmRoot,t);_a(o);return}n&&wt(Ln(e.invocationArgv),n,t),V({overrides:[]})}function _a(e){if(!e){V({overrides:[]});return}V(e.services)}async function Gn(e){ve(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Le({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 ba(){ve(!0,void 0,{exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Le({ok:!0,exit_code:f.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=f.SUCCESS}async function xa(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(qt(e.error)||!n))return!1;let o=Z(e.error),r=e.error instanceof v?e.error.exitCode:jt(t),i=e.error instanceof v?e.error.context:void 0,a=Ci(i,e.invocationArgv,o),s=Ir(o,a),l=e.bootstrapGlobal.lean?at(an(o,r,a)):an(o,r,a),d=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?So(l,u=>`${JSON.stringify(u,null,2)}
|
|
30
|
+
`):l,null,2):Rr(o,a);y(d);let{errorCategory:c,commandResolution:m}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:s.code,errorMessage:s.detail,exitCode:r,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"}),p=await ft({command:e.attemptedCommand,error_code:s.code,error_category:c,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:U?.source_context});return await Gn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:c,commandResolution:m,resolutionStage:"execute"}),p&&(Nt(Ht(e.error,o)),await Ce(Nn)),process.exitCode=r,!0}async function va(e,t){let n=hn(e.invocationArgv),o=`unknown command '${n}'`,r=E(process.cwd(),e.bootstrapGlobal.path),i=await na(r),a=je(e.invocationArgv),s=await vn(r,{},Ue(a)),l=await Pe({message:o},b,i,{failedExtensions:s}),d=sn(l.message,l.commandName,l.allowedTypes,{unknownCommandExamples:l.unknownCommandExamples,unknownCommandNextSteps:l.unknownCommandNextSteps,attemptedCommand:l.attemptedCommand,normalizedInvocationArgs:l.normalizedInvocationArgs,providedOptionFlags:l.providedOptionFlags,unknownOptionSuggestions:l.unknownOptionSuggestions,suggestedRetryCommand:l.suggestedRetryCommand,failedExtensions:s}),{errorCategory:c,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:d.code,errorMessage:d.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await ft({command:n,error_code:d.code,error_category:c,exit_code:f.USAGE,error_message:d.detail,command_resolution:m,resolution_stage:"parse"}),u=e.jsonErrors?await xn({message:o},b,i,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await bn({message:o},b,i,{failedExtensions:s}),g=gn(u,e.jsonErrors,s);await Gn({errorMessage:o,exitCode:f.USAGE,classificationCode:d.code,errorCategory:c,commandResolution:m,resolutionStage:"parse"}),y(g),p&&await Ce(Nn),process.exitCode=f.USAGE}async function Ca(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=P(e.invocationArgv);return r.requested&&!_n(b,r.commandPathTokens)?(await va(e,t),!0):(await ba(),!0)}async function ka(e,t){let n=await Pe(e.error,b,O),o=sn(n.message,n.commandName,n.allowedTypes,{unknownCommandExamples:n.unknownCommandExamples,unknownCommandNextSteps:n.unknownCommandNextSteps,attemptedCommand:n.attemptedCommand,normalizedInvocationArgs:n.normalizedInvocationArgs,providedOptionFlags:n.providedOptionFlags,unknownOptionSuggestions:n.unknownOptionSuggestions,suggestedRetryCommand:n.suggestedRetryCommand}),{errorCategory:r,commandResolution:i}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:f.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),a=await ft({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:f.USAGE,error_message:o.detail,command_resolution:i,resolution_stage:"parse",source_context:U?.source_context}),s=e.jsonErrors?await xn(e.error,b,O,e.bootstrapGlobal.lean===!0):await bn(e.error,b,O),l=await li(o.code,e.bootstrapPmRoot,{},Ue(je(e.invocationArgv))),d=gn(s,e.jsonErrors,l);await Gn({errorMessage:n.message,exitCode:f.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:i,resolutionStage:"parse"}),y(d),a&&await Ce(Nn),process.exitCode=f.USAGE}function Ea(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 Sa(e){let t=e.error.code,n=String(e.error.message??"");if(!await Ca(e,t,n)){if(t==="commander.version"){await ba();return}await ka(e,t)}}async function Wn(e){let t=z(e.invocationArgv),n=E(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Rc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await wa({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await xa(o,Ut(e.error))){if(Ea(e.error)){await Sa(o);return}await Ni({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function Ic(e){b=zt(Fe),ca(b),Ne=null,oe=null,O=new Map,mo();let t=[...e],n,o;try{let r=tt(e);t=r.argv;let i=[process.argv[0],process.argv[1],...t],a=t.length===0,s=z(t);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",f.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=rr(s.author),ya(r),o=er(t);let l=pa(t);if(await Tc(b,l),ua(t)&&_r(b,t),ga(b,t)?await la(b,t):(O=new Map,V({overrides:[]})),ha(t)&&await qi(b,t),aa(b),await pi(b,t,O))return;let m=P(t);if(m.requested&&!_n(b,m.commandPathTokens))throw new Xl(f.USAGE,"commander.helpDisplayed","(outputHelp)");if(a||de(t)&&k(t)===void 0){b.outputHelp();return}let p=await I(E(process.cwd(),s.path)),u=await fi(t,E(process.cwd(),s.path),s.noExtensions,ye);await Ho({pmRoot:E(process.cwd(),s.path),packages:u?.contextIntentPackages},()=>go(p.agent_identity.harness_signals,()=>b.parseAsync(i),{probesEnabled:p.agent_identity?.probes_enabled}))}catch(r){await Wn({error:r,invocationArgv:t})}finally{o?.(),n?.()}}async function cm(e=process.argv.slice(2)){try{await Uo(process.env,()=>Ic(e))}catch(t){await Wn({error:t,invocationArgv:[...e]})}}var dm={activationCommandMatchesProbe:Gi,applyDynamicExtensionRootHelpVisibility:sa,bootstrapProfileEnabled:Ln,buildBootstrapActivationProbe:je,buildPostActionTelemetryOutcome:Ri,buildPmCliRecoveryContext:Ci,buildRuntimeExtensionDiscoverySnapshotCacheKey:Un,buildRuntimeExtensionActivationScope:zn,buildRuntimeExtensionSnapshotCacheKey:Hi,buildRuntimeExtensionFilterForProbe:Zi,addRuntimeFieldOption:Tn,collectActivationCommandCandidates:Ue,collectExtensionFlagDefinitionsForCommand:Sn,collectExtensionFlagDefinitionsForInvocation:gt,collectLeadingCommandArgs:zi,collectParsedActivationCommandArgs:Qi,collectRuntimeFieldLooseFlagDefinitionsForCommand:ji,commandHasLongOption:Li,commandHasShortOption:Ui,commandPathNeedsSearchExtensions:Vi,commandPathNeedsTemplateExtensions:qn,describeUnknownError:Z,defaultPreflightDecision:On,discoveryNeedsActivationForProbe:yt,emitExtensionProfile:ea,emitExtensionSkippedProfile:wt,emitSettingsReadWarnings:In,ensureIdempotentTopLevelCommandRegistration:fa,enforceExplicitRetryForFlagTypos:ya,envFlagEnabled:$i,executeRegisteredRuntimeMigrations:oa,extractCommandScopedOptions:Me,extensionActivationCommands:jn,extensionCapabilities:ht,extensionNeedsActivationForProbe:Hn,extensionProvidesTemplatesRuntime:Ji,hasAnyCapability:De,hasGlobalExtensionContributions:Yi,handleGenericRunPmCliError:Ni,handleRunPmCliCommanderError:Sa,handleRunPmCliError:Wn,handleRunPmCliHelpDisplayError:Ca,handleRunPmCliKnownError:xa,handleRunPmCliCommanderUsageError:ka,handleUnknownHelpCommandError:va,inferMissingFieldsFromErrorMessage:vi,inferPostActionErrorCode:Oi,inferPostActionFailureMessage:Ti,invocationRequestsVersion:bt,isCommanderError:qt,loadRuntimeExtensionCommandDescriptorsForRecovery:na,loadRuntimeExtensionDiscoverySnapshot:_t,loadRuntimeExtensionSnapshot:ye,maybeLoadRuntimeExtensions:ta,maybeAttachCreateUpdatePolicyHelpText:Fn,maybeLogHandledCliErrorToSentry:ft,matchesStaticExtensionCommand:Rn,normalizeTelemetryCommandResolution:Ei,normalizeTelemetryErrorCategory:Ai,normalizeTelemetryResolutionStage:Si,normalizeThrownExitCode:jt,probeUsesAnyFlag:Ki,prepareExtensionServicesForRunPmCliError:wa,readRecordBoolean:ki,readRecordNumber:Mn,readRecordString:ge,recordCliReadOutputInvocationProvenance:xi,registerDynamicExtensionCommandPaths:la,registerRuntimeSchemaFieldFlags:qi,resolveCoreCommandRegistrationSelection:pa,resolveStaticExtensionActivationDecision:Xi,resolveUnknownHelpToken:hn,readThrownExitCode:Ut,runAndClearAfterCommandHooks:Le,runRequiredExtensionCommand:ia,shouldAttachRichHelpTextForInvocation:ua,shouldLogHandledErrorToSentry:Pi,shouldRegisterDynamicExtensionPaths:ga,shouldRegisterRuntimeSchemaFlags:ha,shouldHandleRunPmCliCommanderError:Ea,setActiveExtensionHookContextForTest:Ql,setActiveRuntimeExtensionCommandDescriptorsForTest:ec,setRecoveredExtensionServices:_a,toLooseFieldDefinitionType:An,isImporterOrExporterCommandPath:Mi,validateDynamicExtensionCommandInvocation:Fi,wrapProgramActionsForExtensionHandlers:aa,wrapThrownErrorForSentry:Ht};export{dm as _testOnly,cm as runPmCli};
|
|
31
31
|
//# sourceMappingURL=main.js.map
|