@unbrained/pm-cli 2026.8.13 → 2026.8.14
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 +141 -112
- package/dist/cli/main.js +39 -3
- package/dist/cli-bundle/bundle-manifest.json +144 -176
- package/dist/cli-bundle/chunks/{chunk-DEDU3DG7.js → chunk-BBOFSVAK.js} +66 -65
- package/dist/cli-bundle/chunks/chunk-BFALV3YP.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-Q47C67TQ.js → chunk-FIW4P64F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QGTUPEU5.js → chunk-G5JUB66K.js} +41 -41
- package/dist/cli-bundle/chunks/{chunk-3ZMOWAFM.js → chunk-SBRKH6OR.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TMJ7URWS.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-F7FJYGK3.js → chunk-TXMEUUUY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YLBAPY22.js → chunk-XAVMOK6B.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TF3TPKPR.js → chunk-YAMTJL6Y.js} +33 -33
- package/dist/cli-bundle/chunks/{chunk-IMGIN7R6.js → chunk-YSVSMJ2B.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-4HIZ7EA3.js → register-list-query-T3EHHNNV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-W64FZ5HN.js → register-mutation-E27WCLSZ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-C44ET7R5.js → register-operations-4R6I7CPY.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-634MFRXU.js → register-setup-3YXZ444E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OOYYKQWX.js → chunk-4DQ2YERC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-F43TT2QQ.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2RI2FESN.js → chunk-K7RWWOAG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KFSZ3BP6.js +16 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3DJSGWVB.js → chunk-KSEDUWVZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NFHFZH2Z.js → chunk-KYUQGTSB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IIS2FRKL.js → chunk-LZ4MV3RH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PGXJQLCT.js +155 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E3AVJ655.js → chunk-PPFGQDSI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Q4YY3XNF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QK753U3U.js +46 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QDZUABWL.js → chunk-QUMB2J27.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SM7MTG27.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-I75MANL7.js → chunk-WCVE2NIG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XDNAW5OI.js +18 -0
- package/dist/cli-bundle/focused-chunks/{chunk-2JP7W7GO.js → chunk-YOOI3UZX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZM6TZVHC.js +2 -0
- package/dist/cli-bundle/main.js +13 -13
- 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 +44 -41
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +109 -1
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/history/drift-scan.d.ts +6 -0
- package/dist/core/history/drift-scan.js +74 -50
- package/dist/core/history/workspace-history.d.ts +59 -0
- package/dist/core/history/workspace-history.js +197 -10
- package/dist/core/output/output.js +12 -4
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +155 -60
- package/dist/sdk/cli-program.js +3 -3
- package/dist/sdk/context-relevance.js +12 -4
- package/dist/sdk/governance/assurance.js +4 -4
- package/dist/sdk/governance/health.js +15 -3
- package/dist/sdk/governance/validate-history-drift.d.ts +7 -0
- package/dist/sdk/governance/validate-history-drift.js +68 -0
- package/dist/sdk/governance/validate.js +4 -46
- package/dist/sdk/graph/assembly.d.ts +23 -0
- package/dist/sdk/graph/assembly.js +54 -2
- package/dist/sdk/graph/durable-cache.js +50 -20
- package/dist/sdk/graph/governance-contracts.d.ts +1 -1
- package/dist/sdk/graph/governance-contracts.js +4 -2
- package/dist/sdk/graph/governance.d.ts +21 -1
- package/dist/sdk/graph/governance.js +94 -32
- package/dist/sdk/graph/index.d.ts +2 -2
- package/dist/sdk/graph/index.js +4 -4
- package/dist/sdk/graph/mutation-advisory.js +15 -7
- package/dist/sdk/graph/remediation.js +12 -2
- package/dist/sdk/history-read.d.ts +8 -0
- package/dist/sdk/history-read.js +2 -2
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +3 -3
- package/dist/sdk/query/history.js +20 -3
- package/dist/sdk/read-output-budget.d.ts +2 -0
- package/dist/sdk/read-output-budget.js +12 -5
- package/dist/sdk/read-output-contracts.d.ts +61 -5
- package/dist/sdk/read-output-contracts.js +210 -28
- package/dist/sdk/read-output-rows.d.ts +11 -0
- package/dist/sdk/read-output-rows.js +47 -2
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +3 -3
- package/dist/sdk/runtime.js +5 -3
- package/docs/ASSURANCE.md +10 -1
- package/docs/COMMANDS.md +31 -2
- package/docs/READ_OUTPUT_CONTRACTS.md +44 -8
- package/docs/RELATIONSHIP_GRAPH.md +20 -5
- package/docs/SDK.md +12 -5
- package/docs/SDK_CONTEXT_INTEGRITY.md +32 -1
- package/docs/TESTING.md +23 -1
- package/docs/performance/sdk-entrypoint-import-costs.md +20 -13
- package/marketplace.json +2 -2
- package/package.json +6 -6
- package/packages/pm-beads/extensions/beads/index.ts +1 -0
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/extensions/digital-twin/index.ts +7 -0
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/extensions/governance-audit/index.ts +4 -0
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/extensions/guide-shell/index.ts +5 -0
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/index.ts +6 -0
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/extensions/search-advanced/index.ts +2 -0
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/extensions/templates/index.ts +4 -0
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/extensions/todos/index.ts +2 -0
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/extensions/vcs/index.ts +7 -0
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/bundle-cli.mjs +17 -4
- package/sdk/public-surface.json +209 -29
- package/dist/cli-bundle/chunks/chunk-DL5M5J3V.js +0 -13
- package/dist/cli-bundle/chunks/chunk-HIUZVCMN.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-27N23W6M.js +0 -31
- package/dist/cli-bundle/focused-chunks/chunk-3BNVU6LC.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-6MLIRBLV.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-6XYLENDV.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-CP4K4WFS.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-EBTNSFYE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-HC2OL2H2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-OGC4XSBC.js +0 -17
- package/dist/cli-bundle/focused-chunks/chunk-PKPOZXLL.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QQX5TDFT.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-TEZIXMTH.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-WEH6NSL6.js +0 -18
package/dist/cli-bundle/main.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as q,d as
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function qo(e,t){return t==="detailed"?ii(e):ai(e)}function F(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var si={cal:"calendar",ctx:"context"};function ci(e,t){return e.commands.find(n=>n.name()===t)??null}function li(e,t){let n=e;for(let o of t){let r=ci(n,o);if(!r)return null;n=r}return n}function di(e,t,n,o){let r=li(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",qo(n,o))}function Nt(e){return e.includes("--explain")?"detailed":"compact"}var zo={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."]}},Ft={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 mi(e){let t=F(e??"");return t?si[t]??t:""}function pi(e){let t=mi(e);return t?zo[t]??Ft:Ft}function Ho(e,t){let n=pi(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:jo(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Go(e,t=process.argv.slice(2)){let n=Nt(t);e.addHelpText("after",qo(Ft,n));for(let[o,r]of Object.entries(zo))di(e,o,r,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function Wo(e,t){await lo(e,{ok:t.ok,error:t.error,result:ge(),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 Bo(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await O(e.pmRoot);await bo({pmRoot:e.pmRoot,author:Le(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function L(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function Y(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return L(t)}function X(e){let t=new Set,n=[];for(let o of e){let r=Y(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]="9ec35c35-f2dc-5f86-a166-cf0c80eab1bd")}catch{}})();function Ke(e){let{required:t,why:n,title:o,...r}=e;return r}var ui=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Qo(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!ui.has(e.code)}function Zo(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:Zo(e.code)}}var re={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Vo={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Ko={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Be={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},fi={guide:re,shell:re,completion:re,"completion-statuses":re,"completion-tags":re,"completion-types":re,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Vo,cal:Vo,reindex:Ko,"search-advanced":Ko,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Be,"dedupe-audit":Be,"dedupe-merge":Be,normalize:Be};function gi(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return fi[t]}function Jo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function hi(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 yi(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 Mt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function B(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=hi(n);o&&(e[t]=o)}function Je(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Mt(t,"attempted_command",e.attempted_command),B(t,"normalized_args",e.normalized_args),B(t,"parsed_positionals",e.parsed_positionals),B(t,"provided_fields",e.provided_fields),B(t,"missing",e.missing),B(t,"missing_required_fields",e.missing_required_fields),B(t,"suggested_flags",e.suggested_flags),B(t,"allowed_values",e.allowed_values),B(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),Mt(t,"suggested_retry",e.suggested_retry),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=yi(e.fallback_candidates);return n&&(t.fallback_candidates=n),Mt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Lt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function wi(e){let t=Je(e);if(!t)return[];let n=["Recovery bundle:"];if(Lt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),Lt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Lt(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 er(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Jo("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Jo("Next steps:",e.nextSteps)));let n=wi(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
5
|
-
`)}function Ut(e,t){let n={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t};return Qo(e)&&(n.why=e.why),e.examples&&e.examples.length>0&&(n.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(n.next_steps=e.nextSteps),e.recovery&&(n.recovery=e.recovery),n}function jt(e){let t={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required};return Qo(e)&&(t.why=e.why),e.examples&&e.examples.length>0&&(t.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(t.next_steps=e.nextSteps),e.recovery&&(t.recovery=e.recovery),t}function Ye(e){return e.replace(/\(outputHelp\)/g,"").trim()}function _i(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 ae(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 Yo(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function xi(e){return Oo(e?.normalized_args)}function bi(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 vi(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,R(s)}}}function Ci(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ve(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function z(e,t,n){if(!n)return e;let o=Ye(t),r=Ve(n.code,e.code),a=Ve(n.type,Zo(r)),i=ae(n.examples)??e.examples,s=ae(n.nextSteps)??e.nextSteps,c=e.code==="command_failed"&&n.code?Ci(o):void 0,l=Je(n.recovery)??e.recovery;return{...e,code:r,type:a,title:c??e.title,happened:o.length>0?o:e.happened,required:Ve(n.required,e.required),why:Ve(n.why,e.why),examples:i,nextSteps:s,recovery:l}}function ki(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. Run pm init first\.$/);if(!o)return null;let r=o[1],a=Fn(process.cwd(),r);return z(b(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Ei(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return z(b({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list-open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list-open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Si(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:z(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Ai(e,t,n){return t.includes("is locked")?z(b({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 Ti(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return z(b({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Oi(e,t,n){return t.startsWith("No update flags provided")?z(b({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function Ri(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Je(n?.recovery),r=xi(o),a=r?`pm ${r} --help`:"pm <command> --help",i=bi(t),s=vi(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return z(b({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function qt(e,t){let n=Ye(e),o=ki(e,n,t)??Ei(e,n,t)??Si(e,n,t)??Ai(e,n,t)??Ti(e,n,t)??Oi(e,n,t)??Ri(e,n,t);return o||z(b({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Ii(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 $i(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Pi(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function zt(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 N(e,t={}){let n=zt(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Pi(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Je({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Dt(e,t){return!t||e.includes(t)?e:[...e,t]}var Fi=new Set(["--add","--add-json","--remove"]),Ni=new Set(["command","cmd","path"]);function Mi(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(Fi.has(o))return o}}function Li(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Ni.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return R(c)}}function Di(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=$i(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=zt(o?.providedOptionFlags),l=[a],d=Ii(t,a,n),m=s?Dt(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Dt(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Dt(u,`Already provided options: ${c.join(", ")}`):u;return b({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:N(o,{missing:l})})}function Ui(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return b({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:N(n,{missing:[r]})})}function ji(e,t,n){return b({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:N(t,{suggested_flags:n})})}function qi(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},a=o[1],i=zt(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(a==="--file"||a==="--doc"))return ji(a,n,i);let c=ae(r.unknownOptionOtherCommands)??[],l=r.unknownOptionOtherCommandsTotal??c.length,d=c.slice(0,3),m=l-d.length,p="";m>0&&(p=` and ${String(m)} more command path(s)`);let u=["Run command help to confirm the exact option contracts for this command path.",i.length?`Nearest supported options: ${i.join(", ")}`:void 0,d.length?`${a} is accepted by ${d.join(", ")}${p}. Inspect those command contracts only if you intended a different operation.`:void 0,s?`Replay with suggested correction: ${s}`:void 0].filter(h=>typeof h=="string"),f=[s,`pm ${t??"<command>"} --help`].filter(h=>typeof h=="string");return b({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:"Use supported options only, or move option to the correct subcommand.",why:"Option contracts are command-specific and intentionally validated.",examples:f,nextSteps:u,recovery:N(n,{suggested_flags:i.length>0?i:void 0,candidate_commands:c,candidate_commands_total:l||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated})})}function zi(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:Yo([t.installCommand,...n]),nextSteps:Yo([a,...i]),recovery:N(r)})}function Hi(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ae(t?.unknownCommandExamples),a=ae(t?.unknownCommandNextSteps),i=gi(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?zi(o,i,s,c,t):b({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:N(t)})}function Gi(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ae(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return b({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:N(e,{allowed_values:o,suggested_retry:r})})}function Wi(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Mi(o);if(!r)return null;let a=Li(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:N(n,a?{suggested_retry:a}:{})})}var Bi=new Set(["comments","docs","files","learnings","notes","test"]);function Vi(e,t,n){if(!/too many arguments/i.test(e)||!Bi.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>l===t),a=o[r+1],i=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!i||i.startsWith("-")||!s||s.toLowerCase()!==i.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:N(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var Ki=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"]),Xo=new Set(["context","ctx"]);function Ji(e,t,n){if(!/too many arguments/i.test(e)||!Xo.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>Xo.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(Ki.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:N(n,{suggested_retry:c})})}function Ht(e,t,n,o){let r=Ye(e),a=Di(r,t,n,o)??Ui(r,t,o)??qi(r,t,o)??Hi(r,o)??Gi(o)??Vi(r,t,o)??Wi(r,t,o)??Ji(r,t,o);return a||b({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:N(o)})}function tr(e,t){return er(qt(e,t))}function nr(e,t){return jt(qt(e,t))}function Gt(e,t,n){return Ut(qt(e,n),t)}function or(e,t,n,o){return er(Ht(e,t,n,o))}function Wt(e,t,n,o){return jt(Ht(e,t,n,o))}function Xe(e,t,n,o,r){return Ut(Ht(e,t,n,r),o)}function rr(e,t){let n=ar(e);return Ut(n,t)}function ar(e){let t=Ye(e);return _i(t)?b({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):b({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function ir(e){return jt(ar(e))}import{Option as Yi}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function cr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=_(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function Bt(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return Qe(i).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function H(e){return typeof e=="boolean"?e:void 0}function Qe(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||H(e.required)===!0||H(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Xi(e){if(H(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=A(e.value_name),i=a?` <${a}>`:"",s=A(e.description)??"Extension-provided option.",c=[];H(e.required)===!0&&c.push("required"),H(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function lr(e){let t=[...new Set(e.map(Xi).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
2
|
+
import{c as q,d as So,e as M,f as Ao,g as k,h as To,m as He,n as Oo,o as Ro,q as Io,r as J,s as At,t as Tt,u as Ot,v as Rt,w as $o,x as It,z as Po}from"./chunks/chunk-YSVSMJ2B.js";import{Za as Eo,f as ho,u as yo}from"./chunks/chunk-G5JUB66K.js";import"./chunks/chunk-FIW4P64F.js";import"./chunks/chunk-BFALV3YP.js";import{Kb as ko,lb as Co}from"./chunks/chunk-YAMTJL6Y.js";import{Ha as bo,k as R,l as ze,qa as xo}from"./chunks/chunk-XAVMOK6B.js";import{vb as vo}from"./chunks/chunk-TMJ7URWS.js";import"./chunks/chunk-WYRZZ5ZE.js";import{$ as ut,$b as ue,$c as yt,$k as je,Ac as Ne,Af as to,Ai as we,Al as P,C as g,Cf as wt,D as mt,De,Df as y,Di as lo,E as v,Eb as Mn,G as pe,Ga as ft,Gc as ht,Gi as mo,Hc as Me,Ic as Jn,Ja as V,Jc as Yn,K as pt,Kb as Ln,Kd as Xn,La as Fn,Li as Ct,Ma as Pe,Mb as Dn,Mi as po,Ni as uo,Oi as fo,Ol as _o,Pa as gt,Qa as Nn,Ra as C,Sd as Le,Ua as j,Z as On,_ as Rn,_b as Un,_k as go,bc as fe,c as U,cc as jn,ci as ao,da as In,di as _t,ea as $n,ei as xt,fh as no,fi as bt,ga as Pn,gf as Qn,gh as oe,gi as he,hh as O,hi as vt,if as Zn,ih as oo,ii as io,ji as ye,lc as qn,mc as zn,mi as so,nc as Hn,ni as co,oc as Gn,ol as qe,pc as W,pl as kt,qc as Wn,ql as Et,rc as Bn,rl as _e,sc as K,sl as I,tc as Vn,tl as wo,uc as Fe,ul as St,vc as ne,wc as ge,wh as Ue,xh as ro,zc as Kn,zf as eo}from"./chunks/chunk-BBOFSVAK.js";import{Command as yn}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 Xa=new Set(["__proto__","prototype","constructor"]),Fo=Symbol("looseOptionOccurrences");function xe(e){return e.trim().toLowerCase().replaceAll(/-([a-z0-9])/g,(n,o)=>o.toUpperCase())}function Qa(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 $t(e,t){let n=e[t];if(!n.startsWith("-")||n==="-"||n==="--")return null;if(!n.startsWith("--")){let i=n.indexOf("=");if(i>=0)return{consumed:1,key:n.slice(1,i).trim(),value:n.slice(i+1)};let s=n.slice(1).trim(),c=e[t+1];return typeof c=="string"&&!c.startsWith("-")?{consumed:2,key:s,value:c}:{consumed:1,key:s,value:!0}}let o=n.indexOf("=");if(o>=0)return{consumed:1,key:n.slice(2,o).trim(),value:n.slice(o+1)};if(n.startsWith("--no-"))return{consumed:1,key:n.slice(5).trim(),value:!1};let r=n.slice(2).trim(),a=e[t+1];return typeof a=="string"&&!a.startsWith("-")?{consumed:2,key:r,value:a}:{consumed:1,key:r,value:!0}}function Ge(e){return Xa.has(e)}function No(e){let t=(typeof e.value_type=="string"?e.value_type:void 0)??(typeof e.type=="string"?e.type:void 0);return On(t)}function be(e){let t=[],n=typeof e.long=="string"?e.long.trim():"",o=typeof e.short=="string"?e.short.trim():"";if(n.startsWith("--")){let r=xe(n.slice(2));r.length>0&&!Ge(r)&&t.push(r)}if(o.startsWith("-")&&!o.startsWith("--")){let r=xe(o.slice(1));r.length>0&&!Ge(r)&&t.push(r)}return[...new Set(t)]}function Mo(e){let t=new Set;for(let n of e)for(let o of be(n))t.add(o);return t}function Za(e){let t=typeof e.long=="string"?e.long.trim():"";if(t.startsWith("--")){let n=xe(t.slice(2));if(n.length>0&&!Ge(n))return n}return be(e)[0]??null}function ei(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 Pt(e,t,n){if(t.length===0)return;let o=new Set,r=new Map,a=[],i=[];for(let s of t){let c=be(s),l=ei(s);l!==null&&i.push(l);for(let d of c)o.add(d),s.enabled===!1&&r.set(d,l);s.required===!0&&s.enabled!==!1&&c.length>0&&a.push({keys:c,label:l})}for(let s of Object.keys(e)){if(!o.has(s)){let l=i.length>0?` Expected one of: ${[...new Set(i)].join(", ")}.`:"";throw new v(`Unknown option '--${s}' for extension command '${n}'.${l}`,g.USAGE)}let c=r.get(s);if(c)throw new v(`Option '${c}' is disabled for extension command '${n}'.`,g.USAGE)}for(let s of a)if(!s.keys.some(c=>Object.hasOwn(e,c)))throw new v(`Missing required option '${s.label}' for extension command '${n}'.`,g.USAGE)}function ti(e){return typeof e=="string"||e==null?e:String(e)}function ni(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 oi(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 ri={string:ti,number:ni,boolean:oi};function We(e,t){return Array.isArray(e)?e.map(n=>We(n,t)):ri[t](e)}function Lo(e,t,n){let o=n?(Array.isArray(e)?e.flat(1/0):[e]).filter(r=>r!=null&&r!==""):Rn(e);return t?o.map(r=>We(r,t)):o}function ai(e,t,n,o){return n?Lo(e,t,o):t?We(e,t):e}function ii(e,t,n){let o=e[Fo];if(!o||o.length===0)return n;let r=new Set(t);return o.filter(a=>r.has(a.key)).map(a=>a.value)}function Do(e,t,n=e){if(t.length===0)return e;let o=Object.create(null);for(let[r,a]of Object.entries(e))o[r]=a;for(let r of t){let a=Za(r);if(!a)continue;let i=r.list===!0,s=be(r);for(let d of s)if(!(d===a||!Object.hasOwn(o,d))){if(Object.hasOwn(o,a)){if(!i){delete o[d];continue}let m=o[a],p=o[d];o[a]=[...Array.isArray(m)?m:[m],...Array.isArray(p)?p:[p]].filter(u=>u!=null),delete o[d];continue}o[a]=o[d],delete o[d]}let c=No(r),l=r.repeatable===!0;if(!Object.hasOwn(o,a)){r.default!==void 0&&(o[a]=ai(r.default,c,i,l));continue}if(i){o[a]=Lo(ii(n,s,o[a]),c,l);continue}c&&(o[a]=We(o[a],c))}return o}function Uo(e){let t=Object.create(null),n=[];Object.defineProperty(t,Fo,{value:n});let o=0;for(;o<e.length;){let r=$t(e,o);if(!r){o+=1;continue}let a=xe(r.key);if(a.length===0||Ge(a)){o+=r.consumed;continue}Qa(t,a,r.value),n.push({...r,key:a}),o+=r.consumed}return t}function jo(e){let t=[],n=0;for(;n<e.length;){if(e[n]==="--"){t.push(...e.slice(n+1));break}let o=$t(e,n);if(o){n+=Math.max(1,o.consumed);continue}t.push(e[n]),n+=1}return t}function Ft(e,t){if(t.length===0)return[...e];let n=new Set,o=new Set;for(let i of t){let s=No(i);for(let c of be(i))n.add(c),s==="boolean"&&o.add(c)}if(n.size===0)return[...e];let r=[],a=0;for(;a<e.length;){if(e[a]==="--"){r.push(...e.slice(a+1));break}let i=$t(e,a);if(i){let s=xe(i.key);if(n.has(s)){let c=e[a],l=o.has(s)&&!c.includes("=")?1:i.consumed;a+=l;continue}}r.push(e[a]),a+=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]="a97a61f2-df10-5c2b-8497-f8de17a6222d")}catch{}})();function qo(e){return e.length>0?[e[0]]:[]}function si(e){let t=["","Intent:",` ${e.why}`],n=qo(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 ci(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 zo(e,t){return t==="detailed"?ci(e):si(e)}function F(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}var li={cal:"calendar",ctx:"context"};function di(e,t){return e.commands.find(n=>n.name()===t)??null}function mi(e,t){let n=e;for(let o of t){let r=di(n,o);if(!r)return null;n=r}return n}function pi(e,t,n,o){let r=mi(e,t.split(" ").filter(a=>a.length>0));r&&r.addHelpText("after",zo(n,o))}function Mt(e){return e.includes("--explain")?"detailed":"compact"}var Ho={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."]}},Nt={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 ui(e){let t=F(e??"");return t?li[t]??t:""}function fi(e){let t=ui(e);return t?Ho[t]??Nt:Nt}function Go(e,t){let n=fi(e);return{intent:n.why,examples:t==="detailed"?[...n.examples]:qo(n.examples),tips:t==="detailed"?[...n.tips??[]]:[],detail_mode:t}}function Wo(e,t=process.argv.slice(2)){let n=Mt(t);e.addHelpText("after",zo(Nt,n));for(let[o,r]of Object.entries(Ho))pi(e,o,r,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1944833a-5d9b-514d-99d0-50cdad5db8f4")}catch{}})();async function Bo(e,t){await po(e,{ok:t.ok,error:t.error,result:ge(),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 Vo(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1")return;let t=await O(e.pmRoot);await vo({pmRoot:e.pmRoot,author:Le(e.author,t.author_default),itemIds:e.itemIds,intent:e.intent})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1b6eea75-9da4-5cc1-9e26-dde9fcb863d1")}catch{}})();function L(e){return`--${e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`}function Y(e){if(!e.startsWith("--"))return;let t=e.includes("=")?e.slice(0,e.indexOf("=")):e;return L(t)}function X(e){let t=new Set,n=[];for(let o of e){let r=Y(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]="9ec35c35-f2dc-5f86-a166-cf0c80eab1bd")}catch{}})();function Ke(e){let{required:t,why:n,title:o,...r}=e;return r}var gi=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function Zo(e){return!e.why||e.recovery?.recovery_mode==="compact"?!1:!gi.has(e.code)}function er(e){return`urn:pm-cli:error:${e}`}function b(e){return{...e,type:er(e.code)}}var re={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"},Ko={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},Jo={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},Be={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},hi={guide:re,shell:re,completion:re,"completion-statuses":re,"completion-tags":re,"completion-types":re,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:Ko,cal:Ko,reindex:Jo,"search-advanced":Jo,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":Be,"dedupe-audit":Be,"dedupe-merge":Be,normalize:Be};function yi(e){let t=e.trim().split(/\s+/)[0]?.toLowerCase();if(t)return hi[t]}function Yo(e,t){return t.length===0?[]:[e,...t.map(n=>` - ${n}`)]}function wi(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 _i(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 Lt(e,t,n){typeof n=="string"&&n.trim().length>0&&(e[t]=n.trim())}function B(e,t,n){if(t==="parsed_positionals"){if(!Array.isArray(n))return;let r=n.map(a=>({role:typeof a?.role=="string"?a.role.trim():"",value:typeof a?.value=="string"?a.value.trim():""})).filter(a=>a.role.length>0&&a.value.length>0);r.length>0&&(e.parsed_positionals=r);return}let o=wi(n);o&&(e[t]=o)}function Je(e){if(!e||typeof e!="object")return;let t={};e.recovery_mode==="compact"&&(t.recovery_mode="compact"),Lt(t,"attempted_command",e.attempted_command),B(t,"normalized_args",e.normalized_args),B(t,"parsed_positionals",e.parsed_positionals),B(t,"provided_fields",e.provided_fields),B(t,"missing",e.missing),B(t,"missing_required_fields",e.missing_required_fields),B(t,"suggested_flags",e.suggested_flags),B(t,"allowed_values",e.allowed_values),B(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),Lt(t,"suggested_retry",e.suggested_retry),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=_i(e.fallback_candidates);return n&&(t.fallback_candidates=n),Lt(t,"next_best_command",e.next_best_command),Object.keys(t).length>0?t:void 0}function Dt(e,t,n){n&&e.push(` ${t}: ${n}`)}function Q(e,t,n,o){n&&n.length>0&&e.push(` ${t}: ${n.join(o)}`)}function xi(e){let t=Je(e);if(!t)return[];let n=["Recovery bundle:"];if(Dt(n,"attempted_command",t.attempted_command),Q(n,"normalized_args",t.normalized_args," "),t.parsed_positionals&&t.parsed_positionals.length>0){n.push(" parsed_positionals:");for(let o of t.parsed_positionals)n.push(` - ${o.role}: ${o.value}`)}if(Q(n,"provided_fields",t.provided_fields,", "),Q(n,"missing",t.missing,", "),Q(n,"missing_required_fields",t.missing_required_fields,", "),Q(n,"suggested_flags",t.suggested_flags,", "),Q(n,"allowed_values",t.allowed_values,", "),Q(n,"candidate_commands",t.candidate_commands,", "),typeof t.candidate_commands_total=="number"&&n.push(` candidate_commands_total: ${String(t.candidate_commands_total)}`),t.candidate_commands_truncated===!0&&n.push(" candidate_commands_truncated: true"),Dt(n,"suggested_retry",t.suggested_retry),typeof t.retry_after_ms=="number"&&n.push(` retry_after_ms: ${t.retry_after_ms}`),Dt(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 tr(e){let t=[`Error: ${e.title}`,"","What happened:",` ${e.happened}`,"","What is required:",` ${e.required}`];e.why&&(t.push("","Why:"),t.push(` ${e.why}`)),e.examples&&e.examples.length>0&&(t.push(""),t.push(...Yo("Examples:",e.examples))),e.nextSteps&&e.nextSteps.length>0&&(t.push(""),t.push(...Yo("Next steps:",e.nextSteps)));let n=xi(e.recovery);return n.length>0&&(t.push(""),t.push(...n)),t.join(`
|
|
5
|
+
`)}function jt(e,t){let n={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required,exit_code:t};return Zo(e)&&(n.why=e.why),e.examples&&e.examples.length>0&&(n.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(n.next_steps=e.nextSteps),e.recovery&&(n.recovery=e.recovery),n}function qt(e){let t={type:e.type,code:e.code,title:e.title,detail:e.happened,required:e.required};return Zo(e)&&(t.why=e.why),e.examples&&e.examples.length>0&&(t.examples=e.examples),e.nextSteps&&e.nextSteps.length>0&&(t.next_steps=e.nextSteps),e.recovery&&(t.recovery=e.recovery),t}function Ye(e){return e.replace(/\(outputHelp\)/g,"").trim()}function bi(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 ae(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 Xo(e){let t=new Set,n=[];for(let o of e)t.has(o)||(t.add(o),n.push(o));return n}function vi(e){return Ro(e?.normalized_args)}function Ci(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 ki(e,t){let n=e?.normalized_args,o=e?.provided_fields,r=t[0];if(!(!Array.isArray(n)||!Array.isArray(o)||!r))for(let a of o){let i=n.findIndex(s=>s===a);if(i>=0&&i<n.length-1&&!n[i+1]?.startsWith("-")){let s=[...n];return s[i+1]=r,R(s)}}}function Ei(e){let t=e.split(/\r?\n/)[0].trim();if(t.length!==0)return t.length<=120?t:`${t.slice(0,117)}...`}function Ve(e,t){return typeof e=="string"&&e.trim().length>0?e.trim():t}function z(e,t,n){if(!n)return e;let o=Ye(t),r=Ve(n.code,e.code),a=Ve(n.type,er(r)),i=ae(n.examples)??e.examples,s=ae(n.nextSteps)??e.nextSteps,c=e.code==="command_failed"&&n.code?Ei(o):void 0,l=Je(n.recovery)??e.recovery;return{...e,code:r,type:a,title:c??e.title,happened:o.length>0?o:e.happened,required:Ve(n.required,e.required),why:Ve(n.why,e.why),examples:i,nextSteps:s,recovery:l}}function Si(e,t,n){let o=t.match(/^Tracker is not initialized at (.+)\. Run pm init first\.$/);if(!o)return null;let r=o[1],a=Nn(process.cwd(),r);return z(b(a?{code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${r}, but found a tracker at ${a}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${a} <command>`,`PM_PATH=${a} pm <command>`],nextSteps:[`Re-run with "--pm-path ${a}" or export PM_PATH=${a}.`]}:{code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${o[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),e,n)}function Ai(e,t,n){let o=t.match(/^Item ([^ ]+) not found$/);if(!o)return null;let r=o[1],a=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(r),i=a?`The item ID "${r}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${r}" exists in the active tracker scope.`;return z(b({code:"item_not_found",title:"Item ID not found",happened:i,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list-open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps:a?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list-open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."]}),e,n)}function Ti(e,t,n){return!t.includes("is assigned to")||!t.includes("Use --force to override")?null:z(b({code:"ownership_conflict",title:"Ownership conflict",happened:t,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),e,n)}function Oi(e,t,n){return t.includes("is locked")?z(b({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 Ri(e,t,n){let o=t.match(/^Missing required option /),r=t.match(/^Missing required options /);if(!o&&!r)return null;let a=!!r,i=a?null:t.replace(/^Missing required option\s+/,"").trim(),s=i??"",c=i?`Pass ${i} with a valid value before running the command.`:"Provide the required option for this command invocation.";return z(b({code:"missing_required_option",title:a?"Missing required options":`Missing required option ${s}`,happened:t,required:a?"Provide every required option for this command invocation.":c,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),e,n)}function Ii(e,t,n){return t.startsWith("No update flags provided")?z(b({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),e,n):null}function $i(e,t,n){if(!t.startsWith("Invalid ")&&!t.includes(" must be ")&&!t.includes(" requires "))return null;let o=Je(n?.recovery),r=vi(o),a=r?`pm ${r} --help`:"pm <command> --help",i=Ci(t),s=ki(o,i),c=s?[s,a]:[a,"pm contracts --command <command> --flags-only --json"],l=i.length>0?[`Allowed values: ${i.join("|")}`,`Run "${a}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return z(b({code:"invalid_argument_value",title:"Invalid argument value",happened:t,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples:c,nextSteps:l}),e,n)}function zt(e,t){let n=Ye(e),o=Si(e,n,t)??Ai(e,n,t)??Ti(e,n,t)??Oi(e,n,t)??Ri(e,n,t)??Ii(e,n,t)??$i(e,n,t);return o||z(b({code:"command_failed",title:"Command failed",happened:n,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),e,t)}function Pi(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 Fi(e){let t=e.trim();return t.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??t}function Ni(e){if(!(!Array.isArray(e)||e.length===0))return R(e)}function Ht(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 N(e,t={}){let n=Ht(e?.providedOptionFlags),o=Array.isArray(e?.normalizedInvocationArgs)&&e?.normalizedInvocationArgs.length>0?e.normalizedInvocationArgs:void 0,r=typeof e?.attemptedCommand=="string"?e.attemptedCommand:Ni(o),a=typeof e?.suggestedRetryCommand=="string"?e.suggestedRetryCommand:void 0;return Je({attempted_command:r,normalized_args:o,provided_fields:n,suggested_retry:a,...t})}function Ut(e,t){return!t||e.includes(t)?e:[...e,t]}var Mi=new Set(["--add","--add-json","--remove"]),Li=new Set(["command","cmd","path"]);function Di(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(Mi.has(o))return o}}function Ui(e){if(!Array.isArray(e))return;let t=e.indexOf("test");if(t<0)return;let n=e[t+1];if(!(typeof n!="string"||n.startsWith("-")))for(let o=t+2;o<e.length;o+=1){let r=e[o];if(r!=="--add"&&r!=="--remove")continue;let a=e[o+1];if(typeof a!="string"||!Li.has(a))return;let i=[];for(let l=o+2;l<e.length;l+=1){let d=e[l];if(d.startsWith("--")&&d.length>2)break;i.push(d)}if(i.length<2)return;let s=`${a}=${i.join(" ")}`,c=[...e.slice(0,o+1),s,...e.slice(o+2+i.length)];return R(c)}}function ji(e,t,n,o){let r=e.match(/required option '([^']+)' not specified/);if(!r)return null;let a=Fi(r[1]),i=a.startsWith("--type"),s=o?.suggestedRetryCommand,c=Ht(o?.providedOptionFlags),l=[a],d=Pi(t,a,n),m=s?Ut(d,s):d,p=i?[`Allowed type values: ${n}`,`Run "pm ${t??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${t??"<command>"} --help" for required option guidance.`],u=s?Ut(p,`Replay with preserved arguments: ${s}`):p,f=c&&c.length>0?Ut(u,`Already provided options: ${c.join(", ")}`):u;return b({code:"missing_required_option",title:`Missing required option ${a}`,happened:`Commander rejected the command because ${a} was not provided.`,required:`Pass ${a} with a valid value before running the command.`,why:i?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:m,nextSteps:f,recovery:N(o,{missing:l})})}function qi(e,t,n){let o=e.match(/missing required argument '([^']+)'/);if(!o)return null;let r=o[1];return b({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:N(n,{missing:[r]})})}function zi(e,t,n){return b({code:"unsupported_update_option",title:`Unsupported option ${e} for update`,happened:`pm update does not accept ${e} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:N(t,{suggested_flags:n})})}function Hi(e,t,n){let o=e.match(/unknown option '([^']+)'/);if(!o)return null;let r=n??{},a=o[1],i=Ht(r.unknownOptionSuggestions)??[],s=r.suggestedRetryCommand;if(t==="update"&&(a==="--file"||a==="--doc"))return zi(a,n,i);let c=ae(r.unknownOptionOtherCommands)??[],l=r.unknownOptionOtherCommandsTotal??c.length,d=c.slice(0,3),m=l-d.length,p="";m>0&&(p=` and ${String(m)} more command path(s)`);let u=["Run command help to confirm the exact option contracts for this command path.",i.length?`Nearest supported options: ${i.join(", ")}`:void 0,d.length?`${a} is accepted by ${d.join(", ")}${p}. Inspect those command contracts only if you intended a different operation.`:void 0,s?`Replay with suggested correction: ${s}`:void 0].filter(h=>typeof h=="string"),f=[s,`pm ${t??"<command>"} --help`].filter(h=>typeof h=="string");return b({code:"unknown_option",title:`Unknown option ${a}`,happened:`Commander does not recognize option ${a} for this command path.`,required:"Use supported options only, or move option to the correct subcommand.",why:"Option contracts are command-specific and intentionally validated.",examples:f,nextSteps:u,recovery:N(n,{suggested_flags:i.length>0?i:void 0,candidate_commands:c,candidate_commands_total:l||void 0,candidate_commands_truncated:r.unknownOptionOtherCommandsTruncated})})}function Gi(e,t,n,o,r){let a=`"${e}" is provided by the ${t.packageName} package. Install it with: ${t.installCommand}`,i=o.filter(s=>!s.endsWith(`: ${t.installCommand}`));return b({code:"unknown_command",title:`Unknown command ${e}`,happened:`pm does not expose command path "${e}" in current runtime configuration. It is shipped by the optional ${t.packageName} package.`,required:`Install the ${t.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:Xo([t.installCommand,...n]),nextSteps:Xo([a,...i]),recovery:N(r)})}function Wi(e,t){let n=e.match(/unknown command '([^']+)'/);if(!n)return null;let o=n[1],r=ae(t?.unknownCommandExamples),a=ae(t?.unknownCommandNextSteps),i=yi(o),s=r??["pm --help"],c=a??["Verify spelling and active extensions, then rerun."],l=new Set(t?.failedExtensions?.map(m=>m.name.trim().toLowerCase())),d=i?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return i&&(!d||!l.has(d))?Gi(o,i,s,c,t):b({code:"unknown_command",title:`Unknown command ${o}`,happened:`pm does not expose command path "${o}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:s,nextSteps:c,recovery:N(t)})}function Bi(e){let t=e?.unknownSubcommandPath?.trim(),n=e?.unknownSubcommandToken?.trim(),o=ae(e?.unknownSubcommandAllowedValues);if(!t||!n||!o)return null;let r=e?.suggestedRetryCommand;return b({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:N(e,{allowed_values:o,suggested_retry:r})})}function Vi(e,t,n){if(!/too many arguments/i.test(e)||t!=="test")return null;let o=n?.normalizedInvocationArgs,r=Di(o);if(!r)return null;let a=Ui(o);return b({code:"linked_test_value_not_quoted",title:`Linked-test ${r} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${r} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${r} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...a?[a]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...a?[`Replay with the value re-joined into one argument: ${a}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:N(n,a?{suggested_retry:a}:{})})}var Ki=new Set(["comments","docs","files","learnings","notes","test"]);function Ji(e,t,n){if(!/too many arguments/i.test(e)||!Ki.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>l===t),a=o[r+1],i=o[r+2],s=n?.verifiedCollectionItemId?.trim();if(a?.toLowerCase()!=="add"||!i||i.startsWith("-")||!s||s.toLowerCase()!==i.toLowerCase())return null;let c=`pm ${t} ${s} --add <value>`;return b({code:"collection_transposed_subcommand",title:`Transposed ${t} add syntax`,happened:`The positional token "add" occupied the item-id role and "${s}" occupied the next positional role. pm ${t} does not use an add subcommand.`,required:`Place the item id immediately after ${t}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[c,`pm ${t} --help`],recovery:N(n,{parsed_positionals:[{role:"transposed_subcommand",value:a},{role:"item_id",value:s}],suggested_retry:c})})}var Yi=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"]),Qo=new Set(["context","ctx"]);function Xi(e,t,n){if(!/too many arguments/i.test(e)||!Qo.has(t??""))return null;let o=n?.normalizedInvocationArgs??[],r=o.findIndex(l=>Qo.has(l)),a=r===-1?1:r+1,i=e.match(/got \d+:\s*(\S+)/i),s=i?i[1].replace(/\.$/,""):void 0;if(s===void 0){let l=!1;for(let d of o.slice(a)){if(l){l=!1;continue}let m=d.split("=")[0];if(Yi.has(m)){l=!d.includes("=");continue}if(!d.startsWith("-")){s=d;break}}}if(!s)return null;let c=`pm get ${s}`;return b({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${s}".`,required:`Use ${c} for one item's full details, or pm context --parent ${s} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[c,`pm context --parent ${s}`],recovery:N(n,{suggested_retry:c})})}function Gt(e,t,n,o){let r=Ye(e),a=ji(r,t,n,o)??qi(r,t,o)??Hi(r,t,o)??Wi(r,o)??Bi(o)??Ji(r,t,o)??Vi(r,t,o)??Xi(r,t,o);return a||b({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:N(o)})}function nr(e,t){return tr(zt(e,t))}function or(e,t){return qt(zt(e,t))}function Wt(e,t,n){return jt(zt(e,n),t)}function rr(e,t,n,o){return tr(Gt(e,t,n,o))}function Bt(e,t,n,o){return qt(Gt(e,t,n,o))}function Xe(e,t,n,o,r){return jt(Gt(e,t,n,r),o)}function ar(e,t){let n=ir(e);return jt(n,t)}function ir(e){let t=Ye(e);return bi(t)?b({code:"module_import_failed",title:"Module import failed",happened:t,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]}):b({code:"unknown_error",title:"Unhandled error",happened:t,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function sr(e){return qt(ir(e))}import{Option as Qi}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="45f3bebb-c075-5573-97bc-b573ae4d2d76")}catch{}})();function _(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function lr(e,t){let n=new Map;for(let o of e){let r=_(o.command);for(let a of t){if(a.layer!==o.layer||a.name!==o.name)continue;let i=_(a.command),s=i.split(" "),c=s.at(-1),l=s.slice(1).join(" "),d=l?`${s[0]}-${c} ${l}`:`${s[0]}-${c}`;if(c&&r===d){n.set(r,i);break}}}return n}function Vt(e,t,n,o){if(!t||!n)return;let r,a=0;for(let[s,c]of e.entries()){if(c!==t)continue;let l=e.slice(s);for(let[d,m]of o.entries()){let p=d.split(" ");p.length>a&&p.every((u,f)=>l[f]===u)&&(r=m,a=p.length)}}let i=r?.flags.find(s=>s.long===n||s.short===n);if(i)return Qe(i).takesValue}function A(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function H(e){return typeof e=="boolean"?e:void 0}function Qe(e){let t=A(e.value_type)??A(e.type),n=A(e.value_name),o=t!=="boolean"&&(n!==null||t!==null||H(e.required)===!0||H(e.list)===!0);return{takesValue:o,valueName:o?n??"value":null}}function Zi(e){if(H(e.visible)===!1)return null;let n=A(e.long);if(!n||!n.startsWith("--")||n.length<3)return null;let o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?`${o}, `:"",a=A(e.value_name),i=a?` <${a}>`:"",s=A(e.description)??"Extension-provided option.",c=[];H(e.required)===!0&&c.push("required"),H(e.enabled)===!1&&c.push("disabled");let l=c.length>0?` [${c.join(", ")}]`:"";return`${r}${n}${i} ${s}${l}`}function dr(e){let t=[...new Set(e.map(Zi).filter(n=>n!==null))].sort((n,o)=>n.localeCompare(o));return t.length===0?null:`
|
|
6
6
|
Extension-provided flags:
|
|
7
7
|
${t.join(`
|
|
8
|
-
`)}`}function
|
|
8
|
+
`)}`}function mr(e){let t=new Map;for(let r of e){let a=_(r.target_command);if(a.length===0)continue;let i=t.get(a)??[];i.push(...r.flags),t.set(a,i)}let n=[...t.entries()].sort(([r],[a])=>r.localeCompare(a)),o=new Map;for(let[r,a]of n){let i=dr(a);i&&o.set(r,i)}return o}function pr(e,t){return typeof t!="string"||t.trim().length===0?e.replace(/\s+/g,"-"):t.trim().toLowerCase()}function cr(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 es(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 ts(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,a=typeof n.intent=="string"&&n.intent.trim().length>0?n.intent.trim():void 0;t.set(o,{command:o,action:pr(o,n.action),description:r,intent:a,examples:cr(n.examples),failure_hints:cr(n.failure_hints),arguments:es(n.arguments),flags:[],source:{layer:n.layer,name:n.name,package:n.source_package}})}return t}function ns(e){let t=new Map;for(let n of e){let o=_(n.target_command);if(o.length===0)continue;let r=t.get(o)??[];r.push(...n.flags),t.set(o,r)}return t}function os(e,t,n){let o=new Set;for(let r of e){let a=_(r);a.length>0&&o.add(a)}for(let r of t.keys())o.add(r);for(let r of n.keys())o.add(r);return o}function rs(e,t,n){let o=n.get(e);return o?t.get(o):void 0}function ur(e,t,n,o=new Map){let r=ts(t),a=ns(n),i=os(e,r,a),s=new Map,c=[...i].sort((l,d)=>l.localeCompare(d));for(let l of c){let d=rs(l,r,o)??r.get(l),m=a.get(l)??(d?a.get(d.command):void 0)??[];if(d){s.set(l,{...d,command:l,flags:m});continue}s.set(l,{command:l,action:pr(l,void 0),examples:[],failure_hints:[],arguments:[],flags:m})}return s}function as(e){let t=e.variadic?"...":"";return e.required?`<${e.name}${t}>`:`[${e.name}${t}]`}function fr(e,t){for(let n of t.arguments)e.argument(as(n),n.description??"Extension argument.")}function gr(e){if(H(e.visible)===!1)return null;let n=A(e.long),o=A(e.short),r=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,a=n&&n.startsWith("--")&&n.length>2?n:null,i=[r,a].filter(s=>s!==null);return i.length>0?i:null}function is(e){let t=gr(e);if(!t)return null;let{valueName:n}=Qe(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function ss(e){let t=gr(e);if(!t)return null;let{valueName:n}=Qe(e),o=n?` <${n}>`:"";return`${t.join(", ")}${o}`}function hr(e){let t=A(e.description)??"Extension-provided option.",n=[];H(e.required)===!0&&n.push("required"),H(e.enabled)===!1&&n.push("disabled");let o=n.length>0?` [${n.join(", ")}]`:"";return`${t}${o}`}function yr(e,t){let n=A(t.long),o=A(t.short);return e.options.some(r=>{let a=r;return n!==null&&a.long===n||o!==null&&a.short===o})}function Kt(e,t){for(let n of t){if(yr(e,n))continue;let o=ss(n);if(!o)continue;let r=hr(n);if(n.list!==!0){e.option(o,r);continue}e.addOption(new Qi(o,r).argParser((a,i=[])=>[...Array.isArray(i)?i:[i],a]))}}function Jt(e,t){return dr(t.filter(n=>!yr(e,n)))}function cs(e){let t=is(e);if(!t)return null;let n=A(e.long),o=A(e.short),r=n&&n.startsWith("--")&&n.length>2?n:null,a=o&&o.startsWith("-")&&!o.startsWith("--")?o:null,{takesValue:i,valueName:s}=Qe(e),c=H(e.required)===!0;return{flags:t,long:r,short:a,description:hr(e),takes_value:i,value_required:i,value_name:s,variadic:!1,required:c,aliases:[],alias_for:null}}function wr(e){if(!e)return[];let t=[],n=new Set;for(let o of e.flags){let r=cs(o);!r||n.has(r.flags)||(n.add(r.flags),t.push(r))}return t}function _r(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 xr(e){let t=[];if(e.intent&&t.push(`Intent: ${e.intent}`),e.action&&t.push(`Action contract: ${e.action}`),e.examples.length>0){t.push("Examples:");for(let n of e.examples)t.push(` - ${n}`)}if(e.failure_hints.length>0){t.push("Common failure hints:");for(let n of e.failure_hints)t.push(` - ${n}`)}return t.length===0?null:`
|
|
9
9
|
Extension command metadata:
|
|
10
10
|
${t.join(`
|
|
11
|
-
`)}`}function
|
|
11
|
+
`)}`}function Yt(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 ve(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:Yt(o).includes(n))??null}function ie(e,t){let n=e;for(let o of t){let r=ve(n,o);if(!r)return null;n=r}return n}var br=new WeakSet;function vr(e,t){if(t.length===0)return null;let n=e;for(let o=0;o<t.length;o+=1){let r=t[o],a=ve(n,r);if(a){n=a;continue}let i=n.command(r);br.add(i),o<t.length-1?(i.description("Extension-provided command group."),i.action(()=>{i.help()})):i.description("Extension-provided command path."),n=i}return n}function ls(e,t){let n=e,o=[];for(let r of t){let a=ve(n,r);if(!a)return null;if(o.push(r),!br.has(a))return{core_path:o.join(" "),extension_path:t.join(" ")};n=a}return null}function ds(e,t,n,o){let r=t.split(" ").filter(s=>s.length>0),a=ls(e,r);if(!a||a.core_path===t&&!n.has(t))return null;let i=o?.source?.package??o?.source?.name??"unknown-extension";return`extension_command_collision:${a.extension_path}:core_owner=pm-cli:${a.core_path}:extension_owner=${i}`}function Cr(e,t,n,o,r){return[...new Set([...t,...n.keys()])].filter(a=>a.trim().length>0).sort((a,i)=>a.localeCompare(i)).filter(a=>{let i=ds(e,a,o,n.get(a));return i?(r(i),!1):!0})}function kr(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]="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]="33842ea7-43c9-52a3-a9ec-75f190a5fd6f")}catch{}})();function ms(e,t){let n=pe(e.id);return n||`migration-${String(t+1).padStart(3,"0")}`}function ps(e){return pe(e.status)?.toLowerCase()??"pending"}function us(e){return e.mandatory===!0}function fs(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 Ar(e){let t=[];return e.forEach((n,o)=>{if(!us(n.definition))return;let r=ps(n.definition);r!=="applied"&&t.push({layer:n.layer,name:n.name,id:ms(n.definition,o),status:r})}),t.sort(fs),t}function Er(e){return Array.isArray(e)&&e.length>0}var gs=new Set(["create","beads import","todos import"]),hs=new Set(["restore","update","close","delete","append","claim","release"]),ys=new Set(["comments","notes","learnings"]),ws=new Set(["files","docs","test"]),_s=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 Xt(e,t){let n=t.force===!0;return gs.has(e)?{isMutation:!0,forceCapable:!1,forceRequested:!1}:hs.has(e)?{isMutation:!0,forceCapable:!0,forceRequested:n}:ys.has(e)?{isMutation:typeof t.add=="string",forceCapable:!0,forceRequested:n}:ws.has(e)?{isMutation:Er(t.add)||Er(t.remove),forceCapable:!0,forceRequested:n}:{isMutation:!1,forceCapable:!1,forceRequested:!1}}function xs(e,t,n){if(Xt(e,n).isMutation)return!0;let o=e.trim().toLowerCase();return co(o)?["close-many","close-task","copy","delete","discover","focus","pause-task","start-task","update-many"].includes(o)?!0:t.some(r=>_s.has(r.trim().toLowerCase())):!1}function Sr(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function bs(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(pe(t[1])||r.push("source"),pe(n.to)||r.push("--to"),r.length!==0)throw new v(`Schema migration requires ${r.join(", ")}.`,g.USAGE,{code:"schema_migration_input_required",required:r.join(","),why:"Schema migrations require a source and target. A workspace-bound stable migration id is derived automatically when --migration-id is omitted.",recovery:{recovery_mode:"compact",missing_required_fields:r,suggested_flags:r.filter(a=>a.startsWith("--")),suggested_retry:`pm schema ${o} <source> --to <target>`}})}async function vs(e,t,n,o,r){if(e.trim().toLowerCase()!=="update"||typeof n.status!="string"||Sr(n.status)!==Sr(r.schema.workflow.in_progress_status))return;let a=t[0];if(!a)return;let i=V(r,K()),s=await Ue(o,a,r.id_prefix,r.item_format,i.type_to_folder);if(!s)return;let c=await ro(s,{schema:r.schema}),l=typeof n.assignee=="string"?n.assignee.trim():void 0;(l===void 0?c.document.metadata.assignee?.trim():!["","none","null","undefined"].includes(l.toLowerCase())&&l)||y(`warning:in_progress_item_unclaimed:${s.id}:claim_with=pm claim ${s.id}`)}async function Qt(e,t,n,o,r){if(!xs(e,t,n)||(bs(e,t,n),!await U(j(r))))return;let a=await oe(r);o.json!==!0&&await vs(e,t,n,r,a.settings);let i=so({author:Le(o.author,a.settings.author_default),payload:{command:e,args:t,options:n},settings:a.settings.mutation_guard,force:o.force===!0||n.force===!0});for(let s of i.warnings)y(`warning:${s}`)}function Tr(e,t,n){if(n.length===0)return;let o=Xt(e,t);if(!o.isMutation||o.forceCapable&&o.forceRequested)return;let r=n.map(i=>`extension_migration_blocking:${i.layer}:${i.name}:${i.id}:${i.status}`),a=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(",")}). ${a}`,g.CONFLICT)}async function Zt(e,t,n,o){if(!Xt(e,t).isMutation||!o.enforce_item_format_gate&&!o.run_preflight_item_format_sync||!await U(j(n)))return;let{settings:a,metadata:i,warnings:s}=await oe(n);for(let c of s)y(`warning:${c}`);if(o.enforce_item_format_gate&&!i.has_explicit_item_format&&(no(a),await oo(n,a,"item_format:auto_select_default")),o.run_preflight_item_format_sync){let c=V(a,K());await lo(n,a.item_format,"item_format:pre_mutation_sync",c.type_to_folder,a.schema)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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]="05cf369c-7529-57ab-984a-f5505cc9c0c9")}catch{}})();var Ce=Pn.join("|"),Cs={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"},ks={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"]}},Or=["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 Es(e,t){let n=ks[e];if(!n)return[];let o=L(t);for(let[r,a]of Object.entries(n))if(L(r)===o)return a;return[]}function en(e,t,n){if(n.length===0)return e;if(t){let i=n.find(s=>s.declared_command_match===!0);return JSON.stringify({...JSON.parse(e),...i?{extension_command_failure:{code:"extension_command_activation_failed",extension:i.name,layer:i.layer,error:i.error,recovery_commands:i.recovery_commands??[]}}:{},failed_extensions:n},null,2)}let o=n.map(i=>`- ${i.layer}:${i.name}: ${i.error}`).join(`
|
|
12
12
|
`),r=n.find(i=>i.declared_command_match===!0);if(!r)return`${e}
|
|
13
13
|
Extension activation failures:
|
|
14
14
|
${o}`;let a=(r.recovery_commands??[]).map(i=>`- ${i}`).join(`
|
|
@@ -19,11 +19,11 @@ ${a}`:""}
|
|
|
19
19
|
|
|
20
20
|
${e}
|
|
21
21
|
Extension activation failures:
|
|
22
|
-
${o}`}function
|
|
23
|
-
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Ls(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 Ds(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function Pr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=Ds(n,r);if(!a)return o;o=!0,n=a}return o}async function Us(e,t,n,o){try{let r=C(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Ce};let a=await O(r),i=e.noExtensions?void 0:K(),s=V(a,i),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await Ue(r,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ce,pmRoot:r,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ce}}}function js(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?$r([...Cs(t,n[1]),...As(n[1],et(t))]):void 0;return{match:n,suggestions:o,otherCommands:n?Rs(n[1],t):[]}}function qs(e,t,n){if(!t||!n||n.length===0)return;let o=Is(e,t[1],n[0]);return o?tn(o):void 0}function zs(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Ls(Ms(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return Ro(t,r,[o])}function Hs(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=So(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let a=`${o}-${r}`;if(!Tr.includes(a))return;let i=[...t.slice(0,n+1),a,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Tr],suggestedRetryCommand:tn(i)}}async function ke(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=He(process.argv.slice(2)).argv,s=q(i),c=k(i),l=tn(i),d=X(i),m=await Us(s,a,i,c),p=m.allowedTypes,u=nn(a,t,n),f=js(a,c),h=Hs(a,i),w=h?.suggestedRetryCommand??qs(i,f.match,f.suggestions)??zs(a,i);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,suggestedRetryCommand:w,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function on(e,t,n,o={}){let r=await ke(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownSubcommandPath:S,unknownSubcommandToken:D,unknownSubcommandAllowedValues:G,suggestedRetryCommand:ee,verifiedCollectionItemId:dt,failedExtensions:$e}=r,me=or(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownSubcommandPath:S,unknownSubcommandToken:D,unknownSubcommandAllowedValues:G,suggestedRetryCommand:ee,verifiedCollectionItemId:dt,failedExtensions:$e}),te=await Jn("help_format",{message:me,command:i,allowed_types:s});return te.handled&&typeof te.result=="string"?te.result:me}async function rn(e,t,n,o=!1,r={}){let a=await ke(e,t,n,r),i=Xe(a.message,a.commandName,a.allowedTypes,g.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:a.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:a.unknownOptionOtherCommandsTruncated,unknownSubcommandPath:a.unknownSubcommandPath,unknownSubcommandToken:a.unknownSubcommandToken,unknownSubcommandAllowedValues:a.unknownSubcommandAllowedValues,suggestedRetryCommand:a.suggestedRetryCommand,verifiedCollectionItemId:a.verifiedCollectionItemId,failedExtensions:a.failedExtensions});return JSON.stringify(o?Ke(i):i,null,2)}import se 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 an(e,t={},n=[]){let o={readSettings:O,loadExtensions:ue,activateExtensions:fe,resolveImplicitPmRoot:gt,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(F).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(F),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function Fr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await an(t,n,o),a={readSettings:O,loadExtensions:ue,activateExtensions:fe,resolveImplicitPmRoot:gt,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(se.resolve(i)===se.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${se.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${se.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${se.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${se.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]="42b9782e-2151-54b0-98ce-8c5ae810c424")}catch{}})();function Gs(e,t){if(t.length===0)return e;let n=ie(e,t);if(n)return n;let o=t.join(" ");if(!De.some(r=>r===o)&&!uo(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ie(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function Ws(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Nr(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 Bs(e){let t=new Map;for(let n of e){let o=n,r=Nr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function Vs(e){return R(e)}function Ks(e){let t=e.options??[],n=Bs(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Nr(o),l=(s?n.get(s)??[]:[]).filter(w=>w!==r.long).map(w=>w.trim()).filter(w=>w.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),f=u||a.includes("["),h={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:f,value_required:u,value_name:Ws(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function Js(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Ys(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0,variadic:o.variadic===!0,description:a}})}function Xs(e){return e.commands.map(t=>({name:t.name().trim(),aliases:Jt(t),description:t.description().trim()})).sort((t,n)=>t.name.localeCompare(n.name))}function Qs(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 Zs(e,t,n,o,r){let a=Nt(n),i=F(I(t)),s=F(o.join(" ")),c=s.length>i.length?s:i,l=c.length>0?c:void 0,d=Ho(l,a),m=l?r.get(l):void 0,p=Qs(a,d,m),u=Js(wr(Ks(t),yr(m))),f=Xs(t);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:c.length>0?c:e.name(),description:t.description(),usage:t.usage(),intent:p.intent,examples:p.examples,tips:p.tips,arguments:Ys(t),options:u,subcommands:f,has_subcommands:f.length>0}}async function Mr(e,t,n){let o=q(t);if(!o.json)return!1;let r=M(t);if(!r.requested)return!1;let a=Gs(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=nn(i,e,n),c=Xe(i,"help",Ce,g.USAGE,{...s,attemptedCommand:Vs(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)});y(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let i=Zs(e,a,t,r.commandPathTokens,n);Zn(`${JSON.stringify(i,null,2)}
|
|
24
|
-
`)}return process.exitCode=g.SUCCESS,!0}function
|
|
25
|
-
`)}function
|
|
26
|
-
`)}let a=n.indexOf("--"),i=a<0?n:n.slice(0,a),s=i.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:i[s]?.startsWith("--create-mode=")?i[s]?.slice(14):i[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=
|
|
27
|
-
`)}function Lr(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=ve(e,o);r&&r.addHelpText("after",rc(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 Dr(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=k(e)==="contracts"&&e.includes("--full");return r||a?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8aed7a8b-4c51-5aba-b27e-80f87f8f3d35")}catch{}})();var sn="PM_CLI_PACKAGE_ROOT";function ac(){return Rn(import.meta.url,["../.."])}(typeof process.env[sn]!="string"||process.env[sn]?.trim().length===0)&&(process.env[sn]=ac());var le=null,$=null;function ic(e){le=e}function sc(e){T=e}var cc=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"]),lc=new Set(["parse","preflight","execute","unknown"]),dc=new Set(["usage","validation","conflict","runtime","unknown"]),Ee=null,Z=null,T=new Map,yn=250,mc=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),pc=new Set(["1","true","yes","on"]),uc=we(()=>import("./chunks/register-setup-634MFRXU.js")),fc=we(()=>import("./chunks/register-list-query-4HIZ7EA3.js")),gc=we(()=>import("./chunks/register-mutation-W64FZ5HN.js")),hc=we(()=>import("./chunks/register-operations-C44ET7R5.js"));function nt(e){return R(e)}function Gr(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=>Y(o)??o))];return n.length>0?n:void 0}function yc(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),r=new Set(o.map(d=>Y(d)??d)),a=Gr(e),i=t.find(d=>x.commands.some(m=>m.name()===d)),s=i?x.commands.find(d=>d.name()===i):void 0,c=new Set([...x.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>Y(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=Y(d)??d;return r.has(m)?!1:c.has(m)||Bt(t,i,m,T)!==void 0});return l&&l.length>0?l:void 0}function wc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?Y(r):void 0,i=e.find(p=>x.commands.some(u=>u.name()===p)),s=i?x.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=Bt(e,i,a,T),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?nt([...e,...d]):t;return m===t?void 0:m}function _c(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","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 xc(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,..._c(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Wr(e,t,n){let o=ze(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:nt(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:nt(o)}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=nt(o),c=X(o),l=yc(n,o,i),d=wc(o,s,l,i),m=xc({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function ce(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 Br(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function wn(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 Vr(e){if(!e)return;let t=e.trim().toLowerCase();if(cc.has(t))return t}function Kr(e){if(!e)return;let t=e.trim().toLowerCase();if(lc.has(t))return t}function Jr(e){if(!e)return;let t=e.trim().toLowerCase();if(dc.has(t))return t}function Yr(e){let t=ce(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(Br(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=wn(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>pt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Xr(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function Qr(){let e=pt(ge()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=wn(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=vo(o),a=ce(e,"error_code","errorCode")??Xr(r,o),i=Jr(ce(e,"error_category","errorCategory"))??(r?void 0:mt(a)),s=r?void 0:Yr(e)??`command_exit_${o}`,c=Vr(ce(e,"command_resolution","commandResolution"))??_t({ok:r,errorCode:a,errorCategory:i}),l=Kr(ce(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Oe(e){let t=$;$=null,await Wo(t,e);let n=le;if(le=null,!n){Ne();return}let o=[],r=Vn();try{await Bo({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Ln(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:ge(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Ne()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${P(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${P(o)}`)}async function Zr(){await oo()}function ea(e){return pc.has((process.env[e]??"").trim().toLowerCase())}function ta(e){return ea("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!mc.has(Math.trunc(e))}async function ot(e){return ta(e.exit_code)?(await Zr(),ro(e),!0):!1}async function na(e){let t=J(e.error),n=ir(t);e.bootstrapGlobal.json?y(JSON.stringify(rr(t,g.GENERIC_FAILURE),null,2)):y(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await Zr(),vt(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,he(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to report error: ${J(a)}`)}try{await Oe({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${J(a)}`)}try{await ye()}catch(a){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${J(a)}`)}}function Se(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=Do(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=No(n),s=je(I(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return $t(c,[...s,...n],I(e)),Lo(r,n,a)}return r}function dn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function rt(e,t,n){let o=dn(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=dn(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function _n(e){return e.arguments??[]}function Ur(e){let t=_n(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function oa(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 ra(e,t){let n=_n(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${Ur(e)}${s}`,g.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${Ur(e)}${s}`,g.USAGE)}}function bc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function vc(e,t,n){if(n.length>0){$t(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(bc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function aa(e,t,n,o){e&&(ra(e,t),vc(e,n,o))}var Cc={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"},cn=new Map;function mn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function ia(e,t){return e.options.some(n=>n.long===t)}function sa(e,t){return e.options.some(n=>n.short===t)}function pn(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(sa(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,Et);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!ia(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,Et);return}e.option(`${i} <value>`,a)}}async function ca(e,t){let n=Cc[e];if(!n)return[];let o=`${t}:${n}`,r=cn.get(o);if(r)return r;if(!await U(j(t)))return cn.set(o,[]),[];let a=await O(t),s=(yt(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:mn(c.type),value_type:mn(c.type)})));return cn.set(o,s),s}async function la(e,t){let n=q(t),o=C(process.cwd(),n.path);if(!await U(j(o)))return;let r=Z?.key===vn(o)?Z.snapshot:null,a=r===null?await O(o):r.settings,i=yt(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ie(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";pn(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)pn(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function xn(e,t,n,o,r){let a=k(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await O(t),s=V(i,o);Lr(e,s,n)}catch{}}function un(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function da(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function bn(e){return e.some(t=>t==="--profile")}function vn(e){return`pm-root:${e}`}function ma(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Re(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 ma(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function pa(e,t){let n=_(e);if(n.length===0)return!1;let o=Re(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 Cn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...E(n.commands),...E(n.command_handlers),...E(n.command_overrides),...E(n.flag_commands),...E(n.parser_overrides),...jr(n.preflight_ownership),...jr(n.renderer_ownership)]:[]}function E(e){return e??[]}function jr(e){return E(e).flatMap(t=>t.commands)}function at(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var ua=new Set(["hooks","parser","preflight","renderers"]),fa=new Set(["commands","schema","services","importers"]),kc=new Set(["reindex","search","search-advanced"]),Ec=new Set(["--template"]);function Ae(e,t){for(let n of t)if(e.has(n))return!0;return!1}function ga(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return kc.has(n??t)}function ha(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 kn(e){return _(e.commandPath??"")==="create"&&ha(e,Ec)}function ya(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function fn(e,t){return e.some(n=>pa(n,t))||kn(t)&&ya(e)}function wa(e){return[E(e.hooks).length,(e.preflight_overrides??0)-E(e.preflight_ownership).length,E(e.item_types).length,E(e.item_fields).length,E(e.relationship_kinds).length,E(e.service_overrides).length,E(e.assurance_providers).length,E(e.renderer_overrides).length-E(e.renderer_ownership).length].some(n=>n>0)}function _a(e,t){let n=e.activation?.commands??[];if(n.length>0)return fn(n,t);let o=Cn(e);if(fn(o,t)||at(e).has("search")&&ga(t.commandPath))return!0;if(e.contributions)return wa(e.contributions)}function En(e,t){let n=_a(e,t);if(n!==void 0)return n;let o=at(e);return!!(Ae(o,ua)||Ae(o,fa))}function it(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>En(o,t)):e.effective.some(o=>{let r=at(o);return Cn(o).length>0||Ae(r,ua)||Ae(r,fa)||r.has("search")})}function Sn(e){let t=Re(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=kn(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function xa(e){return Sn(e)==="all"?void 0:t=>En(t,e)}function Ie(e){let t=M(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=Eo(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 ba(e){let t=e.args.map(String);if(_(I(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function gn(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 va(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=${P(t.activationWarnings)}`))}function st(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 ct(e,t=oe){let n=vn(e);if(Z?.key===n)return Z.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Dn({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return Z={key:n,snapshot:s},s}catch{return Z={key:n,snapshot:null},null}}async function de(e,t,n=O){let o=t?Sn(t):"all",r=da(e,o);if(Ee?.key===r)return Ee.snapshot;try{let a=await n(e),i=await ue({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?xa(t):void 0}),s=await fe({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=dr(s.registrations.flags),d=cr(s.commands.handlers,s.registrations.commands),m=pr(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Ee={key:r,snapshot:p},p}catch{return Ee={key:r,snapshot:null},null}}async function Ca(e){let t=_e(e);if(t.noExtensions){let i=C(process.cwd(),t.path);return await U(j(i))&&gn((await oe(i)).warnings),null}let n=C(process.cwd(),t.path),o=await ct(n);if(!o)return null;gn(o.settingsReadWarnings);let r={commandPath:I(e),commandArgs:ba(e)};if(!it(o.discovery,r))return st(t.profile,o,r),null;let a=await de(n,r);return a?(va(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function ka(e){let t=await de(e);return t?new Map(t.commandDescriptors):T}async function Ea(e,t){return(await xo({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 Sa(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return fo(e,ko.forActiveExtensionHost({pmRoot:e,author:n}))}async function Aa(e,t,n,o=[]){let r=I(e),a=Pt(e.args.map(String),o),i={...t},s={...n},c=C(process.cwd(),n.path),l=await Me({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&y(`profile:extensions parser_warnings=${P(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,aa(T.get(_(r)),a,i,o),ne(void 0),Fe({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await ht({command:r,args:a,options:i,global:s,pm_root:c,sdk:Sa(c,s)});if(s.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${P(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ne(d.result),d.result}var qr=Symbol("pm.wrappedActionHandler");function Sc(e,t){let n=e[e.length-1];return n instanceof hn?n:t}function zr(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${P(n)}`)}function Ac(e){let t=T.get(_(e.commandPath));if(!t||!oa(e.activeRegistrations,e.commandPath))return;let n=_n(t).length===0?Uo(e.commandArgs):Pt(e.commandArgs,e.extensionFlagDefinitions);ra(t,n)}function Tc(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 Ta(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[qr]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=Sc(i,n),c=Date.now();kt(s);let l=_e(s),d=I(s),m=C(process.cwd(),l.path),p=s.args.map(String),u=K(),f=u?rt(u,d,p):[],h=await ca(d,m),w=Se(s,p,[...f,...h]),S=await Me({command:d,args:p,options:w,global:l,pm_root:m});zr(l.profile,"parser_warnings",S.warnings),p=S.context.args,w=S.context.options,l=S.context.global,Ac({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:f}),l=await yo(l),ho(s,l),Tc(s,i,p),qe(s,w),ne(void 0),Fe({command:d,args:p,options:{...w},global:{...l},pm_root:m});let D=await ht({command:d,args:p,options:w,global:l,pm_root:m,sdk:Sa(m,l)});if(zr(l.profile,"command_handler_warnings",D.warnings),D.handled){ne(D.result),wt(D.result,{...l,command:d,commandArgs:p,commandOptions:w,pmRoot:m}),l.profile&&y(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[qr]=!0}for(let r of n.commands)t(r)};t(e)}async function tt(e){T=new Map,W({overrides:[]}),e&&await xn(e.rootProgram,e.pmRoot,e.invocationArgv,Nn(),e.settings)}function Oc(e,t,n,o){if(t?.flags&&t.flags.length>0){Vt(e,t.flags);let r=Kt(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function Oa(e,t){let n=q(t),o=C(process.cwd(),n.path);if(n.noExtensions){await tt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await ct(o),a=Ie(t);if(!r){await tt();return}if(!it(r.discovery,a)){await tt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),st(bn(t),r,a);return}let i=await de(o,a);if(!i){await tt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}W(i.services),T=new Map(i.commandDescriptors),await xn(e,o,t,i.registrations,i.settings);let s=vr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>Cr(i.activationWarnings,y,l)),c=l=>{let d=l.split(" ").filter(S=>S.length>0),m=i.commandDescriptors.get(l),p=ie(e,d),u=i.commandFlagHelp.get(l),f=m?_r(m):null;if(p){Oc(p,m,u,f);return}let h=br(e,d);m?.description&&h.description(m.description);let w=u;m&&(ur(h,m),m.flags.length>0&&(Vt(h,m.flags),w=Kt(h,m.flags)??void 0)),w&&h.addHelpText("after",w),f&&h.addHelpText("after",f),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...S)=>{let D=S[S.length-1],G=D instanceof hn?D:h,ee=_e(G),dt=Date.now(),$e=rt(i.registrations,l,G.args.map(String)),me=Se(G,G.args.map(String),$e),te=await Aa(G,me,ee,$e);await wo(ee,te),wt(te,{...ee,command:l,commandArgs:G.args.map(String),commandOptions:me,pmRoot:o}),ee.profile&&y(`profile:command=${l} took_ms=${Date.now()-dt}`)})};for(let l of s)c(l)}var Te=In(import.meta.url,["../.."])??"0.0.0",x=Rt(Te);function Ra(e){e.hook("preAction",async(t,n)=>{le=null,$=null,Ne(),kt(n);let o=n.optsWithGlobals(),r=_e(n),a=I(n),i=n.args.map(String),s=Se(n,i),c={...r};Xn(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession}),await co(a,c);let l=C(process.cwd(),r.path),d=await Ca(n);if(!d){le=Un({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),$=await Ct({command:a,pm_version:Te,args:i,options:s,global:c,pm_root:l}),xt(a,i,s,{source_context:$?.source_context,source_context_source:$?.source_context_source}),bt(a),await Qt(a,s,l,un()),await Xt(a,i,s,c,l);return}jn(d.hooks),qn(d.commands),zn(d.parsers),Hn(d.preflight),W(d.services),Gn(d.renderers),Wn(d.registrations);let m=rt(d.registrations,a,i);s=Se(n,i,m);let p=await Me({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${P(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,qe(n,s);let u=await Kn({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:un()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${P(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,qe(n,s);let f=u.decision;await Qt(a,s,d.pmRoot,f),await Xt(a,i,s,c,d.pmRoot);let h=f.run_extension_migrations?await Ea(d.registrations.migrations,d.pmRoot):[];c.profile&&h.length>0&&y(`profile:extensions migration_warnings=${P(h)}`);let w=Sr(d.registrations.migrations);le={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:w},ne(void 0),Fe({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),$=await Ct({command:a,pm_version:Te,args:i,options:s,global:c,pm_root:d.pmRoot}),xt(a,i,s,{source_context:$?.source_context,source_context_source:$?.source_context_source}),bt(a);let S=await Mn(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&S.length>0&&y(`profile:extensions hook_warnings=${P(S)}`),f.enforce_mandatory_migration_gate&&Ar(a,s,w)}),e.hook("postAction",async()=>{let t=Qr();he(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 Oe(t)})}Ra(x);var Rc=new Set(["--version","-V"]),Ic=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Ia=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"]),$a=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),$c=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Pc=new Set(["claim","close-task","pause-task","release","start-task","test"]),ln={setup:!0,listQuery:!0,mutation:!0,operation:!0},Fc=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function lt(e){return e.some(t=>Rc.has(t))}function Pa(e){if(lt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||M(e).requested)return ln;let t=k(e);if(!t)return ln;let n=t.trim().toLowerCase();return Ic.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Ia.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:$a.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:$c.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:ln}function Fa(e){return e.length===0||M(e).requested}var Hr=Symbol("pmCliIdempotentTopLevelRegistration");function Na(e){let t=e;if(t[Hr])return;t[Hr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new hn(a):n(o,...r)})}async function Nc(e,t){if(Na(e),t.setup){let{registerSetupCommands:n}=await uc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await fc(),o=typeof t.targetCommandName=="string"&&Ia.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await gc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await hc();n(e)}}function Ma(e,t){return lt(t)?!1:M(t).requested?!0:!!k(t)}function La(e){if(lt(e))return!1;let t=k(e);return t?Fc.has(t):!1}function Mc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=ze(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function Da(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=$a.has(t)||Pc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=Mc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:i,examples:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function Lc(e){return async t=>{let n=mt(t.errorCode),o=_t({ok:!1,errorCode:t.errorCode,errorCategory:n});return await mo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Te,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 Ua(e){if(e.bootstrapGlobal.noExtensions)return;let t=Ie(e.invocationArgv),n=await ct(e.bootstrapPmRoot);if(n&&it(n.discovery,t)){let o=await de(e.bootstrapPmRoot,t);ja(o);return}n&&st(bn(e.invocationArgv),n,t),W({overrides:[]})}function ja(e){if(!e){W({overrides:[]});return}W(e.services)}async function An(e){he(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Oe({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 qa(){he(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Oe({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function za(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(Tt(e.error)||!n))return!1;let o=J(e.error),r=e.error instanceof v?e.error.exitCode:At(t),a=e.error instanceof v?e.error.context:void 0,i=Wr(a,e.invocationArgv,o),s=nr(o,i),c=e.bootstrapGlobal.lean?Ke(Gt(o,r,i)):Gt(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?Qn(c,u=>`${JSON.stringify(u,null,2)}
|
|
28
|
-
`):c,null,2):
|
|
22
|
+
${o}`}function tn(e){return M(e).commandPathTokens[0]??k(e)??"<command>"}function Ss(e,t){let n=new Set,o=[...e.commands];for(;o.length>0;){let r=o.shift();if(!r)continue;let a=F(I(r)),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a),o.push(...r.commands)}for(let r of t.keys()){let a=F(r),i=a.split(" ").some(s=>s.startsWith("_"));a.length>0&&!i&&n.add(a)}return[...n].sort((r,a)=>r.localeCompare(a))}function Rr(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 a=o.length>=5?2:1,i=Number.POSITIVE_INFINITY;for(let s of r){let c=ut(s,o,a);c!==null&&(i=Math.min(i,c))}return Number.isFinite(i)?4+i:Number.POSITIVE_INFINITY}function Ir(e){return L(e).slice(2).replace(/-/g,"")}function nn(e){return R(e)}function As(e){let t=e.split(" ")[0]?.trim().toLowerCase();if(!t)return null;let n=Cs[t];return n?`If this command comes from an optional package, install it with: pm install ${n}`:null}function $r(e){let t=xo(e);for(let n of["@unbrained/","builtin-","pm-"])t.startsWith(n)&&(t=t.slice(n.length));return t}function Ts(e,t){let n=$r(e);if(n.length===0)return[];let o=[];for(let r of t.values()){let a=new Set,i=r.source;if(i)for(let c of[i.name,i.package]){let l=$r(c??"");l.length>0&&a.add(l)}if(a.size===0)continue;[...a].some(c=>c===n||c.includes(n)||n.includes(c))&&o.push(r.command)}return[...new Set(o)].sort((r,a)=>r.localeCompare(a))}function et(e,t){let n=new Set,o=t??je(e);for(let r of o){r.flag.startsWith("--")&&n.add(L(r.flag));for(let a of r.aliases??[])a.startsWith("--")&&n.add(L(a))}return[...n].sort((r,a)=>r.localeCompare(a))}function Os(e,t){if(!e.startsWith("--"))return[];let n=Ir(e);if(n.length===0)return[];let o=n.length>=8?2:1,r=[];for(let a of t){let i=Ir(a);if(i===n)continue;if(n.length>=3&&i.startsWith(n)){r.push({flag:a,rank:0,distance:i.length-n.length});continue}let s=ut(n,i,o);s===null||s<=0||r.push({flag:a,rank:1,distance:s})}return r.sort((a,i)=>a.rank!==i.rank?a.rank-i.rank:a.distance!==i.distance?a.distance-i.distance:a.flag.localeCompare(i.flag)).map(a=>a.flag).slice(0,3)}var Ze,Rs=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 Is(){if(Ze)return Ze;let e=new Map;for(let t of De)if(!Rs.has(t))for(let n of et(t)){let o=e.get(n)??[];o.push(t),e.set(n,o)}return Ze=e,Ze}function $s(e,t){if(!e.startsWith("--"))return[];let n=Is().get(L(e));if(!n)return[];let o=t?.trim().toLowerCase(),r=new Set(et(o));return n.filter(a=>a!==o).map(a=>({command:a,sharedFlagCount:et(a).filter(i=>r.has(i)).length})).sort((a,i)=>a.sharedFlagCount!==i.sharedFlagCount?i.sharedFlagCount-a.sharedFlagCount:a.command.localeCompare(i.command)).map(({command:a})=>a)}function Ps(e,t,n){for(let o=0;o<e.length;o+=1){let r=e[o];if(!r.startsWith("--"))continue;let a=r.indexOf("="),i=a>=0?r.slice(0,a):r;if(L(i)!==L(t))continue;let s=[...e];return s[o]=a>=0?`${n}${r.slice(a)}`:n,s}}function Fs(e){let t=new Set(e.commandPaths),n=a=>Math.min(Rr(a,e.normalizedUnknown),e.primaryToken!==e.normalizedUnknown?Rr(a,e.primaryToken):Number.POSITIVE_INFINITY),o=new Map,r=(a,i)=>{if(!Number.isFinite(i)||!t.has(a))return;let s=o.get(a);(s===void 0||i<s)&&o.set(a,i)};for(let a of e.commandPaths)r(a,n(a));for(let[a,i]of Object.entries(fo))a!=="read"&&r(i,n(a));return[...o.entries()].sort(([a,i],[s,c])=>i!==c?i-c:a.localeCompare(s)).map(([a])=>a)}function Ns(e){let t=Po(e.commandPaths,e.primaryToken),n=Fs(e),o=Ts(e.primaryToken,e.extensionDescriptors).filter(r=>e.commandPaths.includes(r));return Pr([...t,...n,...o])}function Ms(e){return[...new Set(e.map(n=>n.split(" ")[0]).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function Ls(e,t){let n=e.map(o=>`pm ${o} --help`);return t?[...new Set([...n,"pm --help"])]:[...new Set(["pm --help",...n])]}function on(e,t,n){let o=e.match(/unknown command '([^']+)'/i);if(!o||typeof o[1]!="string")return;let r=F(o[1]);if(r.length===0)return;let a=Ss(t,n);if(a.length===0)return;let i=r.split(" ")[0],s=Ns({commandPaths:a,normalizedUnknown:r,primaryToken:i,extensionDescriptors:n}),c=Ms(a),l=(s.length>0?s:c).slice(0,3),d=Ls(l,s.length>0),m=As(r),p=s.length>0?`Did you mean: ${l.join(", ")}?`:null;return{unknownCommandExamples:d,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 Pr(e){return Array.from(new Set(e))}function Ds(e){let t="";for(let n of e){if(n===" "||n===" "||n===`
|
|
23
|
+
`||n==="\r"||n==="\f"||n==="\v")break;t+=n}return t}function Us(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 js(e,t){let n=t.trim().toLowerCase();return e.commands.find(o=>o.name().trim().toLowerCase()===n?!0:(typeof o.aliases=="function"?o.aliases():[]).some(a=>a.trim().toLowerCase()===n))}function Fr(e,t){if(t.length===0)return!0;let n=e,o=!1;for(let r of t){let a=js(n,r);if(!a)return o;o=!0,n=a}return o}async function qs(e,t,n,o){try{let r=C(process.cwd(),e.path);if(!await U(j(r)))return{allowedTypes:Ce};let a=await O(r),i=e.noExtensions?void 0:K(),s=V(a,i),c;if(/too many arguments/i.test(t)&&["comments","docs","files","learnings","notes","test"].includes(o??"")){let l=n.findIndex(m=>m===o),d=n[l+2];if(n[l+1]?.toLowerCase()==="add"&&d!==void 0&&!d.startsWith("-"))try{c=(await Ue(r,d,a.id_prefix,a.item_format,s.type_to_folder))?.id}catch{}}return{allowedTypes:s.types.length>0?s.types.join("|"):Ce,pmRoot:r,settings:a,typeToFolder:s.type_to_folder,verifiedCollectionItemId:c}}catch{return{allowedTypes:Ce}}}function zs(e,t){let n=e.match(/unknown option '([^']+)'/i),o=n&&t?Pr([...Es(t,n[1]),...Os(n[1],et(t))]):void 0;return{match:n,suggestions:o,otherCommands:n?$s(n[1],t):[]}}function Hs(e,t,n){if(!t||!n||n.length===0)return;let o=Ps(e,t[1],n[0]);return o?nn(o):void 0}function Gs(e,t){let n=e.match(/required option '([^']+)' not specified/i),o=n?.[1]?Us(Ds(n[1].trim())):void 0;if(!o?.startsWith("--"))return;let r=k(t);if(r)return Io(t,r,[o])}function Ws(e,t){if(!/too many arguments/i.test(e)||k(t)!=="schema")return;let n=Ao(t),o=t[n+1]?.trim().toLowerCase(),r=t[n+2]?.trim().toLowerCase();if(!o||!r)return;let a=`${o}-${r}`;if(!Or.includes(a))return;let i=[...t.slice(0,n+1),a,...t.slice(n+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${o} ${r}`,unknownSubcommandAllowedValues:[...Or],suggestedRetryCommand:nn(i)}}async function ke(e,t,n,o={}){let a=(typeof e=="object"&&e!==null?e.message:void 0)??"Invalid command usage",i=He(process.argv.slice(2)).argv,s=q(i),c=k(i),l=nn(i),d=X(i),m=await qs(s,a,i,c),p=m.allowedTypes,u=on(a,t,n),f=zs(a,c),h=Ws(a,i),w=h?.suggestedRetryCommand??Hs(i,f.match,f.suggestions)??Gs(a,i);return{message:a,commandName:c,allowedTypes:p,attemptedCommand:l,normalizedInvocationArgs:[...i],providedOptionFlags:d,unknownOptionSuggestions:f.suggestions,unknownOptionOtherCommands:f.otherCommands.length>0?f.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:f.otherCommands.length>0?f.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:f.otherCommands.length>12||void 0,suggestedRetryCommand:w,verifiedCollectionItemId:m.verifiedCollectionItemId,...h,...u,...o}}async function rn(e,t,n,o={}){let r=await ke(e,t,n,o),{message:a,commandName:i,allowedTypes:s,unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownSubcommandPath:S,unknownSubcommandToken:D,unknownSubcommandAllowedValues:G,suggestedRetryCommand:ee,verifiedCollectionItemId:dt,failedExtensions:$e}=r,me=rr(a,i,s,{unknownCommandExamples:c,unknownCommandNextSteps:l,attemptedCommand:d,normalizedInvocationArgs:m,providedOptionFlags:p,unknownOptionSuggestions:u,unknownOptionOtherCommands:f,unknownOptionOtherCommandsTotal:h,unknownOptionOtherCommandsTruncated:w,unknownSubcommandPath:S,unknownSubcommandToken:D,unknownSubcommandAllowedValues:G,suggestedRetryCommand:ee,verifiedCollectionItemId:dt,failedExtensions:$e}),te=await Yn("help_format",{message:me,command:i,allowed_types:s});return te.handled&&typeof te.result=="string"?te.result:me}async function an(e,t,n,o=!1,r={}){let a=await ke(e,t,n,r),i=Xe(a.message,a.commandName,a.allowedTypes,g.USAGE,{unknownCommandExamples:a.unknownCommandExamples,unknownCommandNextSteps:a.unknownCommandNextSteps,attemptedCommand:a.attemptedCommand,normalizedInvocationArgs:a.normalizedInvocationArgs,providedOptionFlags:a.providedOptionFlags,unknownOptionSuggestions:a.unknownOptionSuggestions,unknownOptionOtherCommands:a.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:a.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:a.unknownOptionOtherCommandsTruncated,unknownSubcommandPath:a.unknownSubcommandPath,unknownSubcommandToken:a.unknownSubcommandToken,unknownSubcommandAllowedValues:a.unknownSubcommandAllowedValues,suggestedRetryCommand:a.suggestedRetryCommand,verifiedCollectionItemId:a.verifiedCollectionItemId,failedExtensions:a.failedExtensions});return JSON.stringify(o?Ke(i):i,null,2)}import se 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 sn(e,t={},n=[]){let o={readSettings:O,loadExtensions:ue,activateExtensions:fe,resolveImplicitPmRoot:gt,...t};try{let r=await o.readSettings(e),a=await o.loadExtensions({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),i=await o.activateExtensions(a);return[...a.failed,...i.failed].map(s=>{let c=(a.effective??[]).find(p=>p.layer===s.layer&&p.name===s.name),l=[...c?.contributions?.commands??[],...c?.contributions?.command_handlers??[],...c?.activation?.commands??[]].map(F).filter((p,u,f)=>p.length>0&&f.indexOf(p)===u).sort((p,u)=>p.localeCompare(u)),d=n.map(F),m=l.some(p=>d.some(u=>u===p||u.startsWith(`${p} `)));return{layer:s.layer,name:s.name,error:s.error,...l.length>0?{declared_commands:l}:{},...m?{declared_command_match:!0,recovery_commands:["pm package doctor --project --detail deep","pm package install <package-or-path> --project"]}:{}}})}catch(r){return[{layer:"runtime",name:"extension-loader",error:r instanceof Error?r.message:String(r)}]}}async function Nr(e,t,n={},o=[]){if(e!=="unknown_command")return[];let r=await sn(t,n,o),a={readSettings:O,loadExtensions:ue,activateExtensions:fe,resolveImplicitPmRoot:gt,...n};try{let i=a.resolveImplicitPmRoot(process.cwd());if(se.resolve(i)===se.resolve(t))return r;let[s,c]=await Promise.all([a.readSettings(t),a.readSettings(i)]),[l,d]=await Promise.all([a.loadExtensions({pmRoot:t,settings:s,cwd:process.cwd(),noExtensions:!1}),a.loadExtensions({pmRoot:i,settings:c,cwd:process.cwd(),noExtensions:!1})]),m=new Set(l.loaded.flatMap(u=>u.activation?.commands??[])),p=[...new Set(d.loaded.flatMap(u=>u.activation?.commands??[]))].filter(u=>!m.has(u)).sort((u,f)=>u.localeCompare(f));if(p.length===0)return r;r.push({layer:"runtime",name:"extension-root-relocation",error:`storage_root=${se.resolve(t)} extension_discovery_root=${l.roots.project}; cwd_storage_root=${se.resolve(i)} cwd_extension_discovery_root=${d.roots.project}; the selected --pm-path runtime is missing ${p.length} workspace command path(s): ${p.slice(0,8).join(", ")}${p.length>8?", ...":""}. --pm-path selects extension discovery as well as item storage; omit it, point --pm-path at ${se.resolve(i)}, or install the extension into the selected tracker with "pm --pm-path ${se.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]="42b9782e-2151-54b0-98ce-8c5ae810c424")}catch{}})();function Bs(e,t){if(t.length===0)return e;let n=ie(e,t);if(n)return n;let o=t.join(" ");if(!De.some(r=>r===o)&&!go(o))return null;for(let r=t.length-1;r>0;r-=1){let a=ie(e,t.slice(0,r));if(a)return a}return t.length===1?e:null}function Vs(e){let t=e.match(/[<[]([^>\]]+)[>\]]/);if(!t)return null;let n=t[1]?.trim();return n&&n.length>0?n:null}function Mr(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 Ks(e){let t=new Map;for(let n of e){let o=n,r=Mr(n);if(!r||typeof o.long!="string"||o.long.trim().length===0)continue;let a=t.get(r)??[];a.push(o.long.trim()),t.set(r,a)}for(let[n,o]of t.entries())t.set(n,[...new Set(o.map(r=>r.trim()).filter(r=>r.length>0))].sort((r,a)=>r.localeCompare(a)));return t}function Js(e){return R(e)}function Ys(e){let t=e.options??[],n=Ks(t);return t.map(o=>{let r=o,a=typeof r.flags=="string"?r.flags.trim():"",i=typeof r.description=="string"?r.description.trim():"",s=Mr(o),l=(s?n.get(s)??[]:[]).filter(w=>w!==r.long).map(w=>w.trim()).filter(w=>w.length>0),d=i.match(/^Alias for ([^ ]+)/i),m=d&&d[1]?d[1].trim():null,p=r.mandatory===!0||i.includes("[required]")||i.toLowerCase().includes("required;"),u=a.includes("<"),f=u||a.includes("["),h={flags:a,long:typeof r.long=="string"?r.long:null,short:typeof r.short=="string"?r.short:null,description:i,takes_value:f,value_required:u,value_name:Vs(a),variadic:r.variadic===!0,required:p,aliases:l,alias_for:m};return r.defaultValue!==void 0&&(h.default_value=r.defaultValue),h})}function Xs(e){let t=new Map,n=[];for(let o of e){if(o.alias_for&&o.long){n.push(o);continue}o.long&&t.set(o.long,o)}for(let o of n){let r=o.alias_for,a=t.get(r);if(!a)continue;let i=o.long,s=new Set([...a.aliases??[],i]);a.aliases=[...s].sort((c,l)=>c.localeCompare(l))}return e.filter(o=>!o.alias_for||!o.long?!0:!t.has(o.alias_for))}function Qs(e){let t=e;return(Array.isArray(t.registeredArguments)?t.registeredArguments:Array.isArray(t._args)?t._args:[]).map(o=>{let r=typeof o.name=="function"?o.name():typeof o.name=="string"?o.name:"argument",a=typeof o.description=="string"&&o.description.trim().length>0?o.description.trim():null;return{name:r.trim(),required:o.required===!0,variadic:o.variadic===!0,description:a}})}function Zs(e){return e.commands.map(t=>({name:t.name().trim(),aliases:Yt(t),description:t.description().trim()})).sort((t,n)=>t.name.localeCompare(n.name))}function ec(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 tc(e,t,n,o,r){let a=Mt(n),i=F(I(t)),s=F(o.join(" ")),c=s.length>i.length?s:i,l=c.length>0?c:void 0,d=Go(l,a),m=l?r.get(l):void 0,p=ec(a,d,m),u=Xs(_r(Ys(t),wr(m))),f=Zs(t);return{format:"pm_help_v1",detail_mode:a,root_command:e.name(),requested_path:o,resolved_path:c.length>0?c:e.name(),description:t.description(),usage:t.usage(),intent:p.intent,examples:p.examples,tips:p.tips,arguments:Qs(t),options:u,subcommands:f,has_subcommands:f.length>0}}async function Lr(e,t,n){let o=q(t);if(!o.json)return!1;let r=M(t);if(!r.requested)return!1;let a=Bs(e,r.commandPathTokens);if(!a){if(!o.quiet){let i=`unknown command '${r.commandPathTokens.join(" ")}'`,s=on(i,e,n),c=Xe(i,"help",Ce,g.USAGE,{...s,attemptedCommand:Js(t),normalizedInvocationArgs:[...t],providedOptionFlags:X(t)});y(JSON.stringify(c,null,2))}return process.exitCode=g.USAGE,!0}if(!o.quiet){let i=tc(e,a,t,r.commandPathTokens,n);to(`${JSON.stringify(i,null,2)}
|
|
24
|
+
`)}return process.exitCode=g.SUCCESS,!0}function nc(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(`
|
|
25
|
+
`)}function oc(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 rc(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 ac(e,t,n,o){let r=new Set(n),a=o.filter(c=>!r.has(c)),i=c=>c.length>0?c.map(l=>ft("create",l)).join(", "):"none";e.push(` required in strict mode: ${i(a)}`);let s=a.map(ko).filter(c=>c!==void 0);e.push(` explicit empty assertion: ${s.length>0?s.join(", "):"none"}`),["Reminder","Meeting","Event"].includes(t.name)&&(e.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy."),e.push(" strict parity remains available via --create-mode strict."))}function ic(e,t,n){let o=Oo(n);if(!o)return nc(e,t);let r=Fn(o,t);if(!r){let h=t.types.join("|");return["",`Type-aware option policies: type "${o}" is not in the active registry.`,` active type values: ${h}`].join(`
|
|
26
|
+
`)}let a=n.indexOf("--"),i=a<0?n:n.slice(0,a),s=i.findIndex(h=>h==="--create-mode"||h.startsWith("--create-mode=")),c=s<0?void 0:i[s]?.startsWith("--create-mode=")?i[s]?.slice(14):i[s+1],l=e==="create"&&c?.toLowerCase()==="strict",d=rc(e,r),m=Pe(r,e,d.progressive),p=Pe(r,e,l?d.strict:d.progressive),u=h=>h.length>0?h.map(w=>ft(e,w)).join(", "):"none",f=["",`Type-aware option policies for ${r.name}:`,` required: ${u(p.required)}`,` disabled: ${u(p.disabled)}`,` hidden: ${u(p.hidden)}`];if(e==="create"){let h=Pe(r,e,d.strict);ac(f,r,m.required,h.required)}return oc(f,r),p.errors.length>0&&f.push(` config errors: ${p.errors.join("; ")}`),f.join(`
|
|
27
|
+
`)}function Dr(e,t,n){let o=k(n);if(o!=="create"&&o!=="update")return;let r=ve(e,o);r&&r.addHelpText("after",ic(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 Ur(e,t,n,o){if(n)return null;let r=e.some(i=>i==="--for"||i.startsWith("--for=")),a=k(e)==="contracts"&&e.includes("--full");return r||a?await o(t):null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c8924d43-556d-5041-9fe3-7c5c944531ae")}catch{}})();var cn="PM_CLI_PACKAGE_ROOT";function sc(){return In(import.meta.url,["../.."])}(typeof process.env[cn]!="string"||process.env[cn]?.trim().length===0)&&(process.env[cn]=sc());var le=null,$=null;function cc(e){le=e}function lc(e){T=e}var dc=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"]),mc=new Set(["parse","preflight","execute","unknown"]),pc=new Set(["usage","validation","conflict","runtime","unknown"]),Ee=null,Z=null,T=new Map,wn=250,uc=new Set([g.USAGE,g.NOT_FOUND,g.CONFLICT]),fc=new Set(["1","true","yes","on"]),gc=we(()=>import("./chunks/register-setup-3YXZ444E.js")),hc=we(()=>import("./chunks/register-list-query-T3EHHNNV.js")),yc=we(()=>import("./chunks/register-mutation-E27WCLSZ.js")),wc=we(()=>import("./chunks/register-operations-4R6I7CPY.js"));function nt(e){return R(e)}function Br(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=>Y(o)??o))];return n.length>0?n:void 0}function _c(e,t,n){if(n?.suggested_retry||e.includes("failed in extension handler (")||!/\b(?:missing|required|requires)\b/i.test(e))return;let o=X(t),r=new Set(o.map(d=>Y(d)??d)),a=Br(e),i=t.find(d=>x.commands.some(m=>m.name()===d)),s=i?x.commands.find(d=>d.name()===i):void 0,c=new Set([...x.options,...s?.options??[]].flatMap(d=>d.flags.split(/[ ,|]+/).map(m=>Y(m)).filter(m=>m!==void 0))),l=a?.filter(d=>{let m=Y(d)??d;return r.has(m)?!1:c.has(m)||Vt(t,i,m,T)!==void 0});return l&&l.length>0?l:void 0}function xc(e,t,n,o){if(o?.suggested_retry)return o.suggested_retry;let r=n?.[0],a=r?Y(r):void 0,i=e.find(p=>x.commands.some(u=>u.name()===p)),s=i?x.commands.find(p=>p.name()===i):void 0,c=a?s?.options.find(p=>p.flags.split(/[ ,|]+/).includes(a)):void 0,l=Vt(e,i,a,T),d=a?c?.isBoolean()===!0||l===!1?[a]:[a,"<value>"]:[],m=a?nt([...e,...d]):t;return m===t?void 0:m}function bc(e){if(!e)return{};let t=["recovery_mode","missing_required_fields","suggested_flags","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 vc(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,...bc(t),...e.suggestedRetry?{suggested_retry:e.suggestedRetry}:{}}}function Vr(e,t,n){let o=ze(t),r=o.includes("--explain"),a=e?.recovery,i=a&&o.includes("history-redact")?{...a,...a.attempted_command?{attempted_command:nt(o)}:{},...a.normalized_args?{normalized_args:[...o]}:{},...a.suggested_retry?{suggested_retry:nt(o)}:{}}:a;if(i?.recovery_mode==="compact"&&!r)return{...e,recovery:i};let s=nt(o),c=X(o),l=_c(n,o,i),d=xc(o,s,l,i),m=vc({invocationArgv:o,attemptedCommand:s,providedFields:c,inferredMissing:l,suggestedRetry:d,existingRecovery:i});return{...e,recovery:m}}function ce(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 Kr(e,...t){if(e)for(let n of t){let o=e[n];if(typeof o=="boolean")return o}}function _n(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 Jr(e){if(!e)return;let t=e.trim().toLowerCase();if(dc.has(t))return t}function Yr(e){if(!e)return;let t=e.trim().toLowerCase();if(mc.has(t))return t}function Xr(e){if(!e)return;let t=e.trim().toLowerCase();if(pc.has(t))return t}function Qr(e){let t=ce(e,"error","message");if(t)return t;let n=e?.warnings;if(Array.isArray(n)){let i=n.find(s=>typeof s=="string"&&s.trim().length>0);if(typeof i=="string")return i.trim()}if(Kr(e,"fail_on_skipped_triggered","failOnSkippedTriggered"))return"linked_test_fail_on_skipped_triggered";let r=_n(e,"failed");if(typeof r=="number"&&r>0)return`failed_runs:${r}`;let a=e?.run_results;if(Array.isArray(a)){let i=a.filter(s=>pt(s)?.status==="failed").length;if(i>0)return`failed_runs:${i}`}}function Zr(e,t){if(!e)return t===g.USAGE?"invalid_command_usage":t===g.NOT_FOUND?"item_not_found":t===g.CONFLICT?"lock_conflict":t===g.DEPENDENCY_FAILED?"dependency_failed":"command_failed"}function ea(){let e=pt(ge()),t=typeof process.exitCode=="number"&&Number.isFinite(process.exitCode)?Math.max(0,Math.trunc(process.exitCode)):void 0,n=_n(e,"exit_code","exitCode"),o=t??n??g.SUCCESS,r=Co(o),a=ce(e,"error_code","errorCode")??Zr(r,o),i=Xr(ce(e,"error_category","errorCategory"))??(r?void 0:mt(a)),s=r?void 0:Qr(e)??`command_exit_${o}`,c=Jr(ce(e,"command_resolution","commandResolution"))??_t({ok:r,errorCode:a,errorCategory:i}),l=Yr(ce(e,"resolution_stage","resolutionStage"))??"execute";return{ok:r,error:s,exit_code:o,error_code:a,error_category:i,command_resolution:c,resolution_stage:l}}async function Oe(e){let t=$;$=null,await Bo(t,e);let n=le;if(le=null,!n){Ne();return}let o=[],r=Kn();try{await Vo({pmRoot:n.pmRoot,author:n.globalOptions.author,itemIds:e.ok?r?.map(a=>a.id)??[]:[],intent:n.commandName})}catch{o.push("context_usage_feedback_write_failed")}try{o.push(...await Dn(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:ge(),affected:r}))}catch(a){o=[`afterCommand hooks failed: ${a instanceof Error?a.message:String(a)}`]}finally{Ne()}!n.globalOptions.json&&o.length>0&&y(`[pm] warning: afterCommand hook_warnings=${P(o)}`),n.profileEnabled&&o.length>0&&y(`profile:extensions hook_warnings=${P(o)}`)}async function ta(){await ao()}function na(e){return fc.has((process.env[e]??"").trim().toLowerCase())}function oa(e){return na("PM_SENTRY_CAPTURE_EXPECTED_ERRORS")?!0:!uc.has(Math.trunc(e))}async function ot(e){return oa(e.exit_code)?(await ta(),io(e),!0):!1}async function ra(e){let t=J(e.error),n=sr(t);e.bootstrapGlobal.json?y(JSON.stringify(ar(t,g.GENERIC_FAILURE),null,2)):y(t),process.exitCode=g.GENERIC_FAILURE;let o="runtime",r="runtime_failed";try{await ta(),vt(e.error);let a=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:n.code,errorMessage:n.detail,exitCode:g.GENERIC_FAILURE,options:{bootstrap_global_options:e.bootstrapGlobal},resolutionStage:"execute"});o=a.errorCategory,r=a.commandResolution,he(!1,t,{error_code:n.code,error_category:o,exit_code:g.GENERIC_FAILURE,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to report error: ${J(a)}`)}try{await Oe({ok:!1,error:t,exit_code:g.GENERIC_FAILURE,error_code:n.code,error_category:o,command_resolution:r,resolution_stage:"execute"})}catch(a){e.bootstrapGlobal.json||y(`Failed to run error hooks: ${J(a)}`)}try{await ye()}catch(a){e.bootstrapGlobal.json||y(`Failed to flush error reporting: ${J(a)}`)}}function jr(e,t,n,o){let r=n.outputInclude;if(r===void 0)return;let a={},{selectors:i,modes:s}=Zn(t,r,a);if(s.length===0)return;for(let[l,d]of Object.entries(a))o[l]=d,e.setOptionValueWithSource(l,d,"cli");let c=i.length>0?i.join(","):void 0;c===void 0?delete n.outputInclude:n.outputInclude=c;for(let l=e;l;l=l.parent)l.setOptionValueWithSource("outputInclude",c,"cli");kt(e,n)}function Se(e,t,n=[]){let r={...e.optsWithGlobals()};delete r.json,delete r.quiet,delete r.path,delete r.pmPath,delete r.noExtensions,delete r.extensions,delete r.profile,delete r.pager,delete r.changedFields,delete r.fullChangedFields,delete r.idOnly,delete r.lean,delete r.tokenAccounting,delete r.outputInclude,delete r.outputLimit,delete r.outputBudget,delete r.outputFormat,delete r.outputSession;let a=Uo(t);for(let[i,s]of Object.entries(a))r[i]===void 0&&(r[i]=s);if(n.length>0){let i=Mo(n),s=je(I(e)).map(l=>({long:l.flag,short:l.short,aliases:l.aliases})),c={...a};for(let l of i)r[l]!==void 0&&(c[l]=r[l]);return Pt(c,[...s,...n],I(e)),Do(r,n,a)}return r}function mn(e,t){let n=_(t);return n.length===0?[]:e.flags.filter(o=>_(o.target_command)===n).flatMap(o=>o.flags)}function rt(e,t,n){let o=mn(e,t),r=[t],a=[];for(let i of n){if(i.startsWith("-"))break;r.push(i);let s=mn(e,r.join(" "));s.length>0&&(a=s)}return a.length>0?a:o}function xn(e){return e.arguments??[]}function qr(e){let t=xn(e).map(n=>{let o=n.variadic?`${n.name}...`:n.name;return n.required?`<${o}>`:`[${o}]`}).join(" ");return`pm ${e.command}${t?` ${t}`:""}`}function aa(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 ia(e,t){let n=xn(e),o=n.filter(c=>c.required).length,a=n.some(c=>c.variadic)?Number.POSITIVE_INFINITY:n.length,i=e.failure_hints??[],s=i.length>0?` ${i.join(" ")}`:"";if(t.length<o)throw new v(`Missing required argument for extension command '${e.command}'. Usage: ${qr(e)}${s}`,g.USAGE);if(t.length>a){let c=t.slice(a).join(" ");throw new v(`Too many arguments for extension command '${e.command}': ${c}. Usage: ${qr(e)}${s}`,g.USAGE)}}function Cc(e){return`--${e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}`}function kc(e,t,n){if(n.length>0){Pt(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(Cc).join(", ")}' for extension command '${e.command}'. This command does not define extension flags.`,g.USAGE)}function sa(e,t,n,o){e&&(ia(e,t),kc(e,n,o))}var Ec={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"},ln=new Map;function pn(e){return e==="number"?"number":e==="boolean"?"boolean":"string"}function ca(e,t){return e.options.some(n=>n.long===t)}function la(e,t){return e.options.some(n=>n.short===t)}function un(e,t,n,o){let r=t.trim();if(!r)return;let a=n.length>0?n:`Runtime schema field (${t})`;if(r.startsWith("-")&&!r.startsWith("--")){if(la(e,r))return;if(o){e.option(`${r} <value>`,`${a} (repeatable)`,St);return}e.option(`${r} <value>`,a);return}let i=r.startsWith("--")?r:`--${r}`;if(!ca(e,i)){if(o){e.option(`${i} <value>`,`${a} (repeatable)`,St);return}e.option(`${i} <value>`,a)}}async function da(e,t){let n=Ec[e];if(!n)return[];let o=`${t}:${n}`,r=ln.get(o);if(r)return r;if(!await U(j(t)))return ln.set(o,[]),[];let a=await O(t),s=(yt(a.schema).command_to_fields.get(n)??[]).flatMap(c=>[c.cli_flag,...c.cli_aliases].map(d=>({long:`--${d}`,type:pn(c.type),value_type:pn(c.type)})));return ln.set(o,s),s}async function ma(e,t){let n=q(t),o=C(process.cwd(),n.path);if(!await U(j(o)))return;let r=Z?.key===Cn(o)?Z.snapshot:null,a=r===null?await O(o):r.settings,i=yt(a.schema),s=[{path:"create",command:"create"},{path:"update",command:"update"},{path:"update-many",command:"update_many"},{path:"list",command:"list"},{path:"list-all",command:"list"},{path:"list-draft",command:"list"},{path:"list-open",command:"list"},{path:"list-in-progress",command:"list"},{path:"list-blocked",command:"list"},{path:"list-closed",command:"list"},{path:"list-canceled",command:"list"},{path:"search",command:"search"},{path:"calendar",command:"calendar"},{path:"context",command:"context"},{path:"templates save",command:"create"}];for(let c of s){let l=ie(e,c.path.split(" "));if(l)for(let d of i.command_to_fields.get(c.command)??[]){let m=d.description??"";un(l,d.cli_flag,m,d.repeatable);for(let p of d.cli_aliases)un(l,p,`Alias for --${d.cli_flag}`,d.repeatable)}}}async function bn(e,t,n,o,r){let a=k(n);if(!(a!=="create"&&a!=="update"))try{let i=r??await O(t),s=V(i,o);Dr(e,s,n)}catch{}}function fn(){return{enforce_item_format_gate:!0,run_preflight_item_format_sync:!0,run_extension_migrations:!0,enforce_mandatory_migration_gate:!0}}function pa(e,t="all"){return t==="all"?`pm-root:${e}`:`pm-root:${e}:activation:${t}`}function vn(e){return e.some(t=>t==="--profile")}function Cn(e){return`pm-root:${e}`}function ua(e){let t=[];for(let n of e??[]){if(n.startsWith("-"))break;let o=_(n);o.length!==0&&t.push(o)}return t}function Re(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 ua(e.commandArgs))o.push(...r.split(" ").filter(a=>a.length>0)),n.push(o.join(" "));return[...new Set(n)]}function fa(e,t){let n=_(e);if(n.length===0)return!1;let o=Re(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 kn(e){let t=e.activation?.commands;if(t)return t;let n=e.contributions;return n?[...E(n.commands),...E(n.command_handlers),...E(n.command_overrides),...E(n.flag_commands),...E(n.parser_overrides),...zr(n.preflight_ownership),...zr(n.renderer_ownership)]:[]}function E(e){return e??[]}function zr(e){return E(e).flatMap(t=>t.commands)}function at(e){return new Set((e.capabilities??[]).map(t=>t.trim().toLowerCase()))}var ga=new Set(["hooks","parser","preflight","renderers"]),ha=new Set(["commands","schema","services","importers"]),Sc=new Set(["reindex","search","search-advanced"]),Ac=new Set(["--template"]);function Ae(e,t){for(let n of t)if(e.has(n))return!0;return!1}function ya(e){let t=_(e??"");if(t.length===0)return!1;let[n]=t.split(" ");return Sc.has(n??t)}function wa(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 En(e){return _(e.commandPath??"")==="create"&&wa(e,Ac)}function _a(e){return e.some(t=>{let n=_(t);return n==="templates"||n.startsWith("templates ")})}function gn(e,t){return e.some(n=>fa(n,t))||En(t)&&_a(e)}function xa(e){return[E(e.hooks).length,(e.preflight_overrides??0)-E(e.preflight_ownership).length,E(e.item_types).length,E(e.item_fields).length,E(e.relationship_kinds).length,E(e.service_overrides).length,E(e.assurance_providers).length,E(e.renderer_overrides).length-E(e.renderer_ownership).length].some(n=>n>0)}function ba(e,t){let n=e.activation?.commands??[];if(n.length>0)return gn(n,t);let o=kn(e);if(gn(o,t)||at(e).has("search")&&ya(t.commandPath))return!0;if(e.contributions)return xa(e.contributions)}function Sn(e,t){let n=ba(e,t);if(n!==void 0)return n;let o=at(e);return!!(Ae(o,ga)||Ae(o,ha))}function it(e,t){return e.effective.length===0?!1:_(t.commandPath??"").length>0?e.effective.some(o=>Sn(o,t)):e.effective.some(o=>{let r=at(o);return kn(o).length>0||Ae(r,ga)||Ae(r,ha)||r.has("search")})}function An(e){let t=Re(e).filter(r=>r.split(" ").every(a=>!a.startsWith("-"))).sort((r,a)=>a.length-r.length)[0]??_(e.commandPath??"");if(t.length===0)return"all";let n=En(e)?"--template":"";return`${e.allowCommandPrefixMatch===!0?"prefix":"exact"}:${t}:${n}`}function va(e){return An(e)==="all"?void 0:t=>Sn(t,e)}function Ie(e){let t=M(e);if(t.requested&&t.commandPathTokens.length>0){let[r,...a]=t.commandPathTokens;return{commandPath:r,commandArgs:a,allowCommandPrefixMatch:!0}}let n=So(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 Ca(e){let t=e.args.map(String);if(_(I(e))==="create"){let o=e.optsWithGlobals();typeof o.template=="string"&&o.template.trim().length>0&&t.push("--template")}return t}function hn(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 ka(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=${P(t.activationWarnings)}`))}function st(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 ct(e,t=oe){let n=Cn(e);if(Z?.key===n)return Z.snapshot;try{let o=Date.now(),{settings:r,warnings:a}=await t(e),i=await Un({pmRoot:e,settings:r,cwd:process.cwd(),noExtensions:!1}),s={pmRoot:e,settings:r,discovery:i,discoveryMs:Date.now()-o,settingsReadWarnings:[...a]};return Z={key:n,snapshot:s},s}catch{return Z={key:n,snapshot:null},null}}async function de(e,t,n=O){let o=t?An(t):"all",r=pa(e,o);if(Ee?.key===r)return Ee.snapshot;try{let a=await n(e),i=await ue({pmRoot:e,settings:a,cwd:process.cwd(),noExtensions:!1,extensionFilter:t?va(t):void 0}),s=await fe({...i,loaded:i.loaded}),c=[...new Set(s.commands.handlers.map(u=>_(u.command)))].filter(u=>u.length>0).sort((u,f)=>u.localeCompare(f)),l=mr(s.registrations.flags),d=lr(s.commands.handlers,s.registrations.commands),m=ur(c,s.registrations.commands,s.registrations.flags,d),p={hooks:s.hooks,commands:s.commands,parsers:s.parsers,preflight:s.preflight,services:s.services,renderers:s.renderers,registrations:s.registrations,pmRoot:e,settings:a,commandHandlers:c,commandFlagHelp:l,commandDescriptors:m,commandAliases:d,loadWarnings:[...i.warnings],activationWarnings:[...s.warnings],loadedCount:i.loaded.length,loadFailedCount:i.failed.length,activationFailedCount:s.failed.length,contextIntentPackages:i.loaded.map(({name:u,module:f})=>({name:u,module:f}))};return Ee={key:r,snapshot:p},p}catch{return Ee={key:r,snapshot:null},null}}async function Ea(e){let t=_e(e);if(t.noExtensions){let i=C(process.cwd(),t.path);return await U(j(i))&&hn((await oe(i)).warnings),null}let n=C(process.cwd(),t.path),o=await ct(n);if(!o)return null;hn(o.settingsReadWarnings);let r={commandPath:I(e),commandArgs:Ca(e)};if(!it(o.discovery,r))return st(t.profile,o,r),null;let a=await de(n,r);return a?(ka(t,a),{hooks:a.hooks,commands:a.commands,parsers:a.parsers,preflight:a.preflight,services:a.services,renderers:a.renderers,registrations:a.registrations,pmRoot:n}):null}async function Sa(e){let t=await de(e);return t?new Map(t.commandDescriptors):T}async function Aa(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 Ta(e,t){let n=typeof t.author=="string"&&t.author.trim()?t.author.trim():"pm-extension";return ho(e,Eo.forActiveExtensionHost({pmRoot:e,author:n}))}async function Oa(e,t,n,o=[]){let r=I(e),a=Ft(e.args.map(String),o),i={...t},s={...n},c=C(process.cwd(),n.path),l=await Me({command:r,args:a,options:i,global:s,pm_root:c});n.profile&&l.warnings.length>0&&y(`profile:extensions parser_warnings=${P(l.warnings)}`),a=l.context.args,i=l.context.options,s=l.context.global,sa(T.get(_(r)),a,i,o),ne(void 0),Fe({command:r,args:a,options:{...i},global:{...s},pm_root:c});let d=await ht({command:r,args:a,options:i,global:s,pm_root:c,sdk:Ta(c,s)});if(s.profile&&d.warnings.length>0&&y(`profile:extensions command_handler_warnings=${P(d.warnings)}`),!d.handled){if(d.warnings.length>0){let m=d.warnings[0],p=d.errorMessage?.trim(),u=p?` ${p}`:"";throw new v(`Command "${r}" failed in extension handler (${m}).${u}`,g.GENERIC_FAILURE,{code:d.errorCode??"command_failed",nextSteps:d.remediation?[d.remediation]:void 0})}throw new v(`Command "${r}" is provided by extensions and is not currently available.`,g.NOT_FOUND)}return d.exitCode!==void 0&&(process.exitCode=d.exitCode),ne(d.result),d.result}var Hr=Symbol("pm.wrappedActionHandler");function Tc(e,t){let n=e[e.length-1];return n instanceof yn?n:t}function Gr(e,t,n){e&&n.length>0&&y(`profile:extensions ${t}=${P(n)}`)}function Oc(e){let t=T.get(_(e.commandPath));if(!t||!aa(e.activeRegistrations,e.commandPath))return;let n=xn(t).length===0?jo(e.commandArgs):Ft(e.commandArgs,e.extensionFlagDefinitions);ia(t,n)}function Rc(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 Ra(e){let t=n=>{let o=n;if(typeof o._actionHandler=="function"&&o[Hr]!==!0){let r=o._actionHandler;o._actionHandler=async function(...i){let s=Tc(i,n),c=Date.now();Et(s);let l=_e(s),d=I(s),m=C(process.cwd(),l.path),p=s.args.map(String),u=K(),f=u?rt(u,d,p):[],h=await da(d,m),w=Se(s,p,[...f,...h]),S=await Me({command:d,args:p,options:w,global:l,pm_root:m});Gr(l.profile,"parser_warnings",S.warnings),p=S.context.args,w=S.context.options,l=S.context.global,Oc({activeRegistrations:u,commandPath:d,commandArgs:p,extensionFlagDefinitions:f}),l=await wo(l),kt(s,l),Rc(s,i,p),qe(s,w),ne(void 0),Fe({command:d,args:p,options:{...w},global:{...l},pm_root:m});let D=await ht({command:d,args:p,options:w,global:l,pm_root:m,sdk:Ta(m,l)});if(Gr(l.profile,"command_handler_warnings",D.warnings),D.handled){ne(D.result),wt(D.result,{...l,command:d,commandArgs:p,commandOptions:w,pmRoot:m}),l.profile&&y(`profile:command=${d} took_ms=${Date.now()-c}`);return}return await r.apply(this,i)},o[Hr]=!0}for(let r of n.commands)t(r)};t(e)}async function tt(e){T=new Map,W({overrides:[]}),e&&await bn(e.rootProgram,e.pmRoot,e.invocationArgv,Mn(),e.settings)}function Ic(e,t,n,o){if(t?.flags&&t.flags.length>0){Kt(e,t.flags);let r=Jt(e,t.flags);r&&e.addHelpText("after",r)}else n&&e.addHelpText("after",n);o&&e.addHelpText("after",o)}async function Ia(e,t){let n=q(t),o=C(process.cwd(),n.path);if(n.noExtensions){await tt({rootProgram:e,pmRoot:o,invocationArgv:t});return}let r=await ct(o),a=Ie(t);if(!r){await tt();return}if(!it(r.discovery,a)){await tt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings}),st(vn(t),r,a);return}let i=await de(o,a);if(!i){await tt({rootProgram:e,pmRoot:o,invocationArgv:t,settings:r.settings});return}W(i.services),T=new Map(i.commandDescriptors),await bn(e,o,t,i.registrations,i.settings);let s=Cr(e,i.commandHandlers,i.commandDescriptors,i.commandAliases,l=>kr(i.activationWarnings,y,l)),c=l=>{let d=l.split(" ").filter(S=>S.length>0),m=i.commandDescriptors.get(l),p=ie(e,d),u=i.commandFlagHelp.get(l),f=m?xr(m):null;if(p){Ic(p,m,u,f);return}let h=vr(e,d);m?.description&&h.description(m.description);let w=u;m&&(fr(h,m),m.flags.length>0&&(Kt(h,m.flags),w=Jt(h,m.flags)??void 0)),w&&h.addHelpText("after",w),f&&h.addHelpText("after",f),h.allowUnknownOption(!0).allowExcessArguments(!0).action(async(...S)=>{let D=S[S.length-1],G=D instanceof yn?D:h,ee=_e(G),dt=Date.now(),$e=rt(i.registrations,l,G.args.map(String)),me=Se(G,G.args.map(String),$e),te=await Oa(G,me,ee,$e);await _o(ee,te),wt(te,{...ee,command:l,commandArgs:G.args.map(String),commandOptions:me,pmRoot:o}),ee.profile&&y(`profile:command=${l} took_ms=${Date.now()-dt}`)})};for(let l of s)c(l)}var Te=$n(import.meta.url,["../.."])??"0.0.0",x=It(Te);function $a(e){e.hook("preAction",async(t,n)=>{le=null,$=null,Ne(),Et(n);let o=n.optsWithGlobals(),r=_e(n),a=I(n),i=n.args.map(String),s=Se(n,i),c={...r};Qn(a,{...s,outputInclude:o.outputInclude,outputLimit:o.outputLimit,outputBudget:o.outputBudget,outputFormat:o.outputFormat,outputSession:o.outputSession}),jr(n,a,c,s),await mo(a,c);let l=C(process.cwd(),r.path),d=await Ea(n);if(!d){le=jn({commandName:a,commandArgs:i,commandOptions:s,globalOptions:c,pmRoot:l}),$=await Ct({command:a,pm_version:Te,args:i,options:s,global:c,pm_root:l}),xt(a,i,s,{source_context:$?.source_context,source_context_source:$?.source_context_source}),bt(a),await Zt(a,s,l,fn()),await Qt(a,i,s,c,l);return}qn(d.hooks),zn(d.commands),Hn(d.parsers),Gn(d.preflight),W(d.services),Wn(d.renderers),Bn(d.registrations);let m=rt(d.registrations,a,i);s=Se(n,i,m),jr(n,a,c,s);let p=await Me({command:a,args:i,options:s,global:c,pm_root:d.pmRoot});c.profile&&p.warnings.length>0&&y(`profile:extensions parser_warnings=${P(p.warnings)}`),i=p.context.args,s=p.context.options,c=p.context.global,qe(n,s);let u=await Jn({command:a,args:i,options:s,global:c,pm_root:d.pmRoot,decision:fn()});c.profile&&u.warnings.length>0&&y(`profile:extensions preflight_warnings=${P(u.warnings)}`),i=u.context.args,s=u.context.options,c=u.context.global,qe(n,s);let f=u.decision;await Zt(a,s,d.pmRoot,f),await Qt(a,i,s,c,d.pmRoot);let h=f.run_extension_migrations?await Aa(d.registrations.migrations,d.pmRoot):[];c.profile&&h.length>0&&y(`profile:extensions migration_warnings=${P(h)}`);let w=Ar(d.registrations.migrations);le={hooks:d.hooks,commandName:a,commandArgs:i,commandOptions:{...s},globalOptions:{...c},pmRoot:d.pmRoot,profileEnabled:!!c.profile,migrationBlockers:w},ne(void 0),Fe({command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot}),$=await Ct({command:a,pm_version:Te,args:i,options:s,global:c,pm_root:d.pmRoot}),xt(a,i,s,{source_context:$?.source_context,source_context_source:$?.source_context_source}),bt(a);let S=await Ln(d.hooks,{command:a,args:i,options:{...s},global:{...c},pm_root:d.pmRoot});c.profile&&S.length>0&&y(`profile:extensions hook_warnings=${P(S)}`),f.enforce_mandatory_migration_gate&&Tr(a,s,w)}),e.hook("postAction",async()=>{let t=ea();he(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 Oe(t)})}$a(x);var $c=new Set(["--version","-V"]),Pc=new Set(["config","extension","init","install","package","packages","templates","upgrade"]),Pa=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"]),Fa=new Set(["append","close","close-many","comments","delete","deps","discover","docs","files","learnings","notes","plan","restore","update","update-many","create"]),Fc=new Set(["claim","close-task","contracts","duplicates","gc","health","pause-task","release","start-task","stats","test","test-all","test-runs","test-runs-worker","validate"]),Nc=new Set(["claim","close-task","pause-task","release","start-task","test"]),dn={setup:!0,listQuery:!0,mutation:!0,operation:!0},Mc=new Set(["create","update","update-many","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","search","calendar","context","templates"]);function lt(e){return e.some(t=>$c.has(t))}function Na(e){if(lt(e))return{setup:!1,listQuery:!1,mutation:!1,operation:!1};if(e.length===0||M(e).requested)return dn;let t=k(e);if(!t)return dn;let n=t.trim().toLowerCase();return Pc.has(n)?{setup:!0,listQuery:!1,mutation:!1,operation:!1,targetCommandName:n}:Pa.has(n)?{setup:!1,listQuery:!0,mutation:!1,operation:!1,targetCommandName:n}:Fa.has(n)?{setup:!1,listQuery:!1,mutation:!0,operation:!1,targetCommandName:n}:Fc.has(n)?{setup:!1,listQuery:!1,mutation:!1,operation:!0,targetCommandName:n}:dn}function Ma(e){return e.length===0||M(e).requested}var Wr=Symbol("pmCliIdempotentTopLevelRegistration");function La(e){let t=e;if(t[Wr])return;t[Wr]=!0;let n=e.command.bind(e);e.command=((o,...r)=>{let a=o.split(/\s+/u)[0];return e.commands.some(i=>i.name()===a||i.aliases().includes(a))?new yn(a):n(o,...r)})}async function Lc(e,t){if(La(e),t.setup){let{registerSetupCommands:n}=await gc();n(e)}if(t.listQuery){let{registerListQueryCommands:n}=await hc(),o=typeof t.targetCommandName=="string"&&Pa.has(t.targetCommandName)?new Set([t.targetCommandName]):void 0;n(e,o?{commandFilter:o}:void 0)}if(t.mutation){let{registerMutationCommands:n}=await yc();n(e,{targetCommandName:t.targetCommandName})}if(t.operation){let{registerOperationCommands:n}=await wc();n(e)}}function Da(e,t){return lt(t)?!1:M(t).requested?!0:!!k(t)}function Ua(e){if(lt(e))return!1;let t=k(e);return t?Mc.has(t):!1}function Dc(e){let t=String(e.rawFrom??""),n=t.indexOf("="),o=n>=0?t.slice(0,n):t,r=e.normalizedTokens.map(l=>{let d=l.indexOf("=");return d>=0?l.slice(0,d):l}).find(l=>l==="--literal"||l==="--regex"||l==="--replacement"),a=r?e.argv.map(l=>{let d=l.indexOf("=");return(d>=0?l.slice(0,d):l)===o?d>=0?`${r}${l.slice(d)}`:r:l}):e.argv,i=ze(a),s=r&&n>=0?`${o}=[redacted]`:t,c=r&&e.normalizedDisplay.includes("=")?`${r}=[redacted]`:e.normalizedDisplay;return{argv:i,normalizedDisplay:c,sourceDisplay:s}}function ja(e){let t=e.commandName;if(!t)return;let n=e.trace.find(l=>l.reason==="flag_typo");if(!n)return;let o=Array.isArray(n.to)?n.to:[String(n.to??"")].filter(l=>l.length>0),r=o.length>0?o.join(" "):"the canonical flag",a=Fa.has(t)||Nc.has(t),i=a?"mutating_flag_typo_requires_retry":"flag_typo_requires_retry",s=a?"mutating option":"option",c=Dc({argv:e.argv,normalizedDisplay:r,normalizedTokens:o,rawFrom:n.from});throw new v(`Refusing to auto-correct ${s} ${c.sourceDisplay} to ${c.normalizedDisplay}. Retry with the canonical flag so the command is explicit.`,g.USAGE,{code:i,examples:[R(c.argv)],nextSteps:["Retry the command with the canonical flag shown in examples."],recovery:{normalized_args:c.argv,suggested_retry:R(c.argv)}})}function Uc(e){return async t=>{let n=mt(t.errorCode),o=_t({ok:!1,errorCode:t.errorCode,errorCategory:n});return await uo({command:t.command,args:e.invocationArgv,options:t.options,global:e.bootstrapGlobal,pm_version:Te,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 qa(e){if(e.bootstrapGlobal.noExtensions)return;let t=Ie(e.invocationArgv),n=await ct(e.bootstrapPmRoot);if(n&&it(n.discovery,t)){let o=await de(e.bootstrapPmRoot,t);za(o);return}n&&st(vn(e.invocationArgv),n,t),W({overrides:[]})}function za(e){if(!e){W({overrides:[]});return}W(e.services)}async function Tn(e){he(!1,e.errorMessage,{error_code:e.classificationCode,error_category:e.errorCategory,exit_code:e.exitCode,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage}),await Oe({ok:!1,error:e.errorMessage,exit_code:e.exitCode,error_code:e.classificationCode,error_category:e.errorCategory,command_resolution:e.commandResolution,resolution_stage:e.resolutionStage})}async function Ha(){he(!0,void 0,{exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),await Oe({ok:!0,exit_code:g.SUCCESS,command_resolution:"success",resolution_stage:"parse"}),process.exitCode=g.SUCCESS}async function Ga(e,t){let n=typeof t=="number"&&Number.isFinite(t);if(!(e.error instanceof v)&&(Ot(e.error)||!n))return!1;let o=J(e.error),r=e.error instanceof v?e.error.exitCode:Tt(t),a=e.error instanceof v?e.error.context:void 0,i=Vr(a,e.invocationArgv,o),s=or(o,i),c=e.bootstrapGlobal.lean?Ke(Wt(o,r,i)):Wt(o,r,i),l=e.jsonErrors?JSON.stringify(e.bootstrapGlobal.tokenAccounting?eo(c,u=>`${JSON.stringify(u,null,2)}
|
|
28
|
+
`):c,null,2):nr(o,i);y(l);let{errorCategory:d,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 ot({command:e.attemptedCommand,error_code:s.code,error_category:d,exit_code:r,error_message:s.detail,command_resolution:m,resolution_stage:"execute",source_context:$?.source_context});return await Tn({errorMessage:o,exitCode:r,classificationCode:s.code,errorCategory:d,commandResolution:m,resolutionStage:"execute"}),p&&(vt(Rt(e.error,o)),await ye(wn)),process.exitCode=r,!0}async function Wa(e,t){let n=tn(e.invocationArgv),o=`unknown command '${n}'`,r=C(process.cwd(),e.bootstrapGlobal.path),a=await Sa(r),i=Ie(e.invocationArgv),s=await sn(r,{},Re(i)),c=await ke({message:o},x,a,{failedExtensions:s}),l=Bt(c.message,c.commandName,c.allowedTypes,{unknownCommandExamples:c.unknownCommandExamples,unknownCommandNextSteps:c.unknownCommandNextSteps,attemptedCommand:c.attemptedCommand,normalizedInvocationArgs:c.normalizedInvocationArgs,providedOptionFlags:c.providedOptionFlags,unknownOptionSuggestions:c.unknownOptionSuggestions,suggestedRetryCommand:c.suggestedRetryCommand,failedExtensions:s}),{errorCategory:d,commandResolution:m}=await e.emitTelemetryCommandError({command:n,errorCode:l.code,errorMessage:l.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t??"commander.helpDisplayed"},resolutionStage:"parse"}),p=await ot({command:n,error_code:l.code,error_category:d,exit_code:g.USAGE,error_message:l.detail,command_resolution:m,resolution_stage:"parse",source_context:$?.source_context}),u=e.jsonErrors?await an({message:o},x,a,e.bootstrapGlobal.lean===!0,{failedExtensions:s}):await rn({message:o},x,a,{failedExtensions:s}),f=en(u,e.jsonErrors,s);await Tn({errorMessage:o,exitCode:g.USAGE,classificationCode:l.code,errorCategory:d,commandResolution:m,resolutionStage:"parse"}),y(f),p&&await ye(wn),process.exitCode=g.USAGE}async function Ba(e,t,n){if(!(t==="commander.helpDisplayed"||t==="commander.help"||t==="commander.helpCommand")&&!n.includes("(outputHelp)"))return!1;let r=M(e.invocationArgv);return r.requested&&!Fr(x,r.commandPathTokens)?(await Wa(e,t),!0):(await Ha(),!0)}async function Va(e,t){let n=await ke(e.error,x,T),o=Bt(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:a}=await e.emitTelemetryCommandError({command:e.attemptedCommand,errorCode:o.code,errorMessage:o.detail,exitCode:g.USAGE,options:{bootstrap_global_options:e.bootstrapGlobal,commander_code:t},resolutionStage:"parse"}),i=await ot({command:e.attemptedCommand,error_code:o.code,error_category:r,exit_code:g.USAGE,error_message:o.detail,command_resolution:a,resolution_stage:"parse",source_context:$?.source_context}),s=e.jsonErrors?await an(e.error,x,T,e.bootstrapGlobal.lean===!0):await rn(e.error,x,T),c=await Nr(o.code,e.bootstrapPmRoot,{},Re(Ie(e.invocationArgv))),l=en(s,e.jsonErrors,c);await Tn({errorMessage:n.message,exitCode:g.USAGE,classificationCode:o.code,errorCategory:r,commandResolution:a,resolutionStage:"parse"}),y(l),i&&await ye(wn),process.exitCode=g.USAGE}function Ka(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 Ja(e){let t=e.error.code,n=String(e.error.message??"");if(!await Ba(e,t,n)){if(t==="commander.version"){await Ha();return}await Va(e,t)}}async function Ya(e){let t=q(e.invocationArgv),n=C(process.cwd(),t.path),o={error:e.error,invocationArgv:e.invocationArgv,bootstrapGlobal:t,jsonErrors:t.json,bootstrapPmRoot:n,attemptedCommand:k(e.invocationArgv)??"<unknown>",emitTelemetryCommandError:Uc({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n})};if(await qa({invocationArgv:e.invocationArgv,bootstrapGlobal:t,bootstrapPmRoot:n}),!await Ga(o,At(e.error))){if(Ka(e.error)){await Ja(o);return}await ra({error:e.error,attemptedCommand:o.attemptedCommand,bootstrapGlobal:t,emitTelemetryCommandError:o.emitTelemetryCommandError})}}async function cd(e=process.argv.slice(2)){x=It(Te),$a(x),Ee=null,Z=null,T=new Map,Vn();let t=[...e],n,o;try{let r=He(e);t=r.argv;let a=[process.argv[0],process.argv[1],...t],i=t.length===0,s=q(t);if(s.authorMissingValue)throw new v("--author requires a non-empty value.",g.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});n=$o(s.author),ja(r),o=To(t);let c=Na(t);if(await Lc(x,c),Ma(t)&&Wo(x,t),Da(x,t)?await Ia(x,t):(T=new Map,W({overrides:[]})),Ua(t)&&await ma(x,t),Ra(x),await Lr(x,t,T))return;if(i){x.outputHelp();return}let m=await O(C(process.cwd(),s.path)),p=await Ur(t,C(process.cwd(),s.path),s.noExtensions,de);await yo({pmRoot:C(process.cwd(),s.path),packages:p?.contextIntentPackages},()=>Xn(m.agent_identity.harness_signals,()=>x.parseAsync(a),{probesEnabled:m.agent_identity?.probes_enabled}))}catch(r){await Ya({error:r,invocationArgv:t})}finally{o?.(),n?.()}}var ld={activationCommandMatchesProbe:fa,bootstrapProfileEnabled:vn,buildBootstrapActivationProbe:Ie,buildPostActionTelemetryOutcome:ea,buildPmCliRecoveryContext:Vr,buildRuntimeExtensionDiscoverySnapshotCacheKey:Cn,buildRuntimeExtensionActivationScope:An,buildRuntimeExtensionSnapshotCacheKey:pa,buildRuntimeExtensionFilterForProbe:va,addRuntimeFieldOption:un,collectActivationCommandCandidates:Re,collectExtensionFlagDefinitionsForCommand:mn,collectExtensionFlagDefinitionsForInvocation:rt,collectLeadingCommandArgs:ua,collectParsedActivationCommandArgs:Ca,collectRuntimeFieldLooseFlagDefinitionsForCommand:da,commandHasLongOption:ca,commandHasShortOption:la,commandPathNeedsSearchExtensions:ya,commandPathNeedsTemplateExtensions:En,describeUnknownError:J,defaultPreflightDecision:fn,discoveryNeedsActivationForProbe:it,emitExtensionProfile:ka,emitExtensionSkippedProfile:st,emitSettingsReadWarnings:hn,ensureIdempotentTopLevelCommandRegistration:La,enforceExplicitRetryForFlagTypos:ja,envFlagEnabled:na,executeRegisteredRuntimeMigrations:Aa,extractCommandScopedOptions:Se,extensionActivationCommands:kn,extensionCapabilities:at,extensionNeedsActivationForProbe:Sn,extensionProvidesTemplatesRuntime:_a,hasAnyCapability:Ae,hasGlobalExtensionContributions:xa,handleGenericRunPmCliError:ra,handleRunPmCliCommanderError:Ja,handleRunPmCliError:Ya,handleRunPmCliHelpDisplayError:Ba,handleRunPmCliKnownError:Ga,handleRunPmCliCommanderUsageError:Va,handleUnknownHelpCommandError:Wa,inferMissingFieldsFromErrorMessage:Br,inferPostActionErrorCode:Zr,inferPostActionFailureMessage:Qr,invocationRequestsVersion:lt,isCommanderError:Ot,loadRuntimeExtensionCommandDescriptorsForRecovery:Sa,loadRuntimeExtensionDiscoverySnapshot:ct,loadRuntimeExtensionSnapshot:de,maybeLoadRuntimeExtensions:Ea,maybeAttachCreateUpdatePolicyHelpText:bn,maybeLogHandledCliErrorToSentry:ot,matchesStaticExtensionCommand:gn,normalizeTelemetryCommandResolution:Jr,normalizeTelemetryErrorCategory:Xr,normalizeTelemetryResolutionStage:Yr,normalizeThrownExitCode:Tt,probeUsesAnyFlag:wa,prepareExtensionServicesForRunPmCliError:qa,readRecordBoolean:Kr,readRecordNumber:_n,readRecordString:ce,registerDynamicExtensionCommandPaths:Ia,registerRuntimeSchemaFieldFlags:ma,resolveCoreCommandRegistrationSelection:Na,resolveStaticExtensionActivationDecision:ba,resolveUnknownHelpToken:tn,readThrownExitCode:At,runAndClearAfterCommandHooks:Oe,runRequiredExtensionCommand:Oa,shouldAttachRichHelpTextForInvocation:Ma,shouldLogHandledErrorToSentry:oa,shouldRegisterDynamicExtensionPaths:Da,shouldRegisterRuntimeSchemaFlags:Ua,shouldHandleRunPmCliCommanderError:Ka,setActiveExtensionHookContextForTest:cc,setActiveRuntimeExtensionCommandDescriptorsForTest:lc,setRecoveredExtensionServices:za,toLooseFieldDefinitionType:pn,isImporterOrExporterCommandPath:aa,validateDynamicExtensionCommandInvocation:sa,wrapProgramActionsForExtensionHandlers:Ra,wrapThrownErrorForSentry:Rt};export{ld as _testOnly,cd as runPmCli};
|
|
29
29
|
//# sourceMappingURL=main.js.map
|