@unbrained/pm-cli 2026.9.15 → 2026.9.17
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 +58 -0
- package/dist/cli/error-guidance.d.ts +1 -1
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/register-setup.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +149 -149
- package/dist/cli-bundle/chunks/{chunk-3RB6Z7XE.js → chunk-5ZY4WE3F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UKLOSZV6.js → chunk-C3MFMGCR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-WLJJ4MAU.js → chunk-CPFBDM53.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YMMLKKEP.js → chunk-DN2RIHRN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5P5PYCZX.js → chunk-E67MIO3Z.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3AHONKLL.js → chunk-G2IJF244.js} +48 -48
- package/dist/cli-bundle/chunks/{chunk-RM2OGG65.js → chunk-LD2FH2YE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RKPUO75B.js → chunk-Q6KPZGMP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y2P3DSSO.js → chunk-T526C5DX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BOZ4HVYL.js → chunk-UF75LUAK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J4DRE3WN.js → chunk-UJSB6NO6.js} +76 -76
- package/dist/cli-bundle/chunks/{chunk-WDF7PP4P.js → chunk-YZXB4XGA.js} +4 -4
- package/dist/cli-bundle/chunks/{register-list-query-IWSPNFFD.js → register-list-query-ISM35VIX.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-3DVF4R64.js → register-mutation-KHMBJJS6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-LXP3MECQ.js → register-operations-HHDROJD6.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-KFQSNBDX.js → register-setup-YAURJMY5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-533DCWPY.js → chunk-267N774W.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZHX3433X.js → chunk-5FSGN4MP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-BMATJLPT.js → chunk-5KYHDFDN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SHF57M2H.js → chunk-7S7XWMXC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AXDAIBT3.js → chunk-7ZC4CKOX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JKJYXCT6.js → chunk-BFUXTNZU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PBJC2ZNA.js → chunk-G4TKJZ4A.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZOE2NSJB.js → chunk-GKSAMNBG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-63YRRGKX.js → chunk-IVWUQE7T.js} +51 -51
- package/dist/cli-bundle/focused-chunks/{chunk-6C3CUU2G.js → chunk-JZSLDLR4.js} +20 -20
- package/dist/cli-bundle/focused-chunks/{chunk-YBQTVE5S.js → chunk-LNM3BS45.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5SBU4QDC.js → chunk-NOK652OP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-OGGF2RBL.js → chunk-OCTTDZOU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MD7ADLME.js → chunk-OWDDVMAP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UACMCSCC.js → chunk-WUMGGQYN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4YTDKIPF.js → chunk-Z4PWEIMX.js} +21 -21
- package/dist/cli-bundle/main.js +11 -10
- 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 +2 -2
- 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 +40 -40
- 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/diagnostics/remediation.js +1 -1
- package/dist/core/store/tracker-preflight.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/init.d.ts +22 -1
- package/dist/sdk/init.js +1 -1
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/read-output-budget.d.ts +2 -0
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +4 -0
- package/dist/sdk/read-output-contracts.js +1 -1
- package/docs/MERGE_SAFETY.md +13 -2
- package/docs/PACKED_FIRST_RUN.md +46 -0
- package/docs/QUICKSTART.md +16 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +14 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
},
|
|
7
7
|
"metadata": {
|
|
8
8
|
"description": "Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.",
|
|
9
|
-
"version": "2026.9.
|
|
9
|
+
"version": "2026.9.17"
|
|
10
10
|
},
|
|
11
11
|
"plugins": [
|
|
12
12
|
{
|
|
13
13
|
"name": "pm-claude",
|
|
14
14
|
"source": "./plugins/pm-claude",
|
|
15
15
|
"description": "Native pm CLI integration for Claude Code — 28 MCP tools, 5 workflow skills, 14 slash commands, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.",
|
|
16
|
-
"version": "2026.9.
|
|
16
|
+
"version": "2026.9.17",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "unbrained",
|
|
19
19
|
"url": "https://github.com/unbraind/pm-cli"
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026.9.17 - 2026-09-17
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
|
|
7
|
+
- Keep merge driver launchers usable after runtime upgrades ([pm-rcjyft](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-rcjyft.toon))
|
|
8
|
+
|
|
9
|
+
## 2026.9.16 - 2026-09-16
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
|
|
13
|
+
- Preserve oversized standard item reads with a brief projection and explicit omission receipts ([pm-8eclqf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8eclqf.toon))
|
|
14
|
+
|
|
15
|
+
### Other
|
|
16
|
+
|
|
17
|
+
- As an agent on a minutes-old scratch project, pm init, quick-capture create, and next are near-zero ceremony and token-cheap at three-item scale ([pm-z436](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-z436.toon))
|
|
18
|
+
|
|
3
19
|
## 2026.9.15 - 2026-09-15
|
|
4
20
|
|
|
5
21
|
### Fixed
|
|
@@ -1003,6 +1019,7 @@
|
|
|
1003
1019
|
|
|
1004
1020
|
### Other
|
|
1005
1021
|
|
|
1022
|
+
- As a coding agent, every pm command I run costs the fewest tokens that still fully answer my question, and I can see what I spent ([pm-g3n00m](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-g3n00m.toon))
|
|
1006
1023
|
- Self-reported token accounting: any command can report the token cost of its own output so budget spend is attributable at runtime and in CI ([pm-t5dt4z](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-t5dt4z.toon))
|
|
1007
1024
|
|
|
1008
1025
|
## 2026.8.1 - 2026-08-01
|
|
@@ -1352,6 +1369,7 @@
|
|
|
1352
1369
|
- SDK reference documentation for promoted primitives + migration notes for the CLI-on-SDK layering ([pm-ds3b](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-ds3b.toon))
|
|
1353
1370
|
- SDK authoring DX polish: manifest-drift guard in scaffold tests, expectation key naming, repeated --capability, define\* index signatures ([pm-llrp](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-llrp.toon))
|
|
1354
1371
|
- Extension install should scaffold newly required item-type folders (pm health ok:false after installing pm-kanban until pm init) ([pm-l98s](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-l98s.toon))
|
|
1372
|
+
- As a platform developer, I can build a non-PM domain system (e.g. a git-like VCS or a company's business workflows) using only pm SDK primitives ([pm-8ngt](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-8ngt.toon))
|
|
1355
1373
|
- Cursor fingerprints: replace per-command presentation-flag deny-lists with contract-declared semantic classification in sdk/pagination ([pm-fgih](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-fgih.toon))
|
|
1356
1374
|
|
|
1357
1375
|
## 2026.7.23 - 2026-07-23
|
|
@@ -1477,6 +1495,10 @@
|
|
|
1477
1495
|
|
|
1478
1496
|
- CodeQL alert 27: js/polynomial-redos in sdk/test/linked-command-detection.ts trailing-dash prefix trim ([pm-8og4](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8og4.toon))
|
|
1479
1497
|
|
|
1498
|
+
### Other
|
|
1499
|
+
|
|
1500
|
+
- As an agent, I can traverse why an item exists, what it affects, what blocks it, and its evidence chain from one bounded graph query ([pm-8xr8](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-8xr8.toon))
|
|
1501
|
+
|
|
1480
1502
|
## 2026.7.17 - 2026-07-17
|
|
1481
1503
|
|
|
1482
1504
|
### Added
|
|
@@ -1769,6 +1791,8 @@
|
|
|
1769
1791
|
|
|
1770
1792
|
### Added
|
|
1771
1793
|
|
|
1794
|
+
- As a coding agent, I want keyword, semantic, and hybrid search with inline field filters, so that I can find relevant prior context before creating new work and never duplicate an item ([pm-nnro](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-nnro.toon))
|
|
1795
|
+
- As a new teammate or onboarding agent, I want accurate docs, one-command onboarding, and automated date-based releases, so that I can become productive quickly and ship safely ([pm-ixm6](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-ixm6.toon))
|
|
1772
1796
|
- Architecture boundary ratchet: prevent new CLI/MCP private core imports while SDK promotion shrinks the baseline ([pm-8778](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-8778.toon))
|
|
1773
1797
|
- Lock contention auto-retry: bounded jittered wait before lock_conflict so parallel agent mutations self-heal ([pm-2muu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-2muu.toon))
|
|
1774
1798
|
|
|
@@ -1785,11 +1809,21 @@
|
|
|
1785
1809
|
- Backfill full-context bodies (and comments/deps/risk) on all active items so context is rebuildable from pm CLI alone ([pm-o043](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-o043.toon))
|
|
1786
1810
|
- 2026-07-04 full pm-backlog audit: reconcile pm items with entire ecosystem (code, tests, docs, ideas, decisions) ([pm-y904](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-y904.toon))
|
|
1787
1811
|
- 2026-07-04 ecosystem audit \#4: coverage matrix, governance capability epic & relationship modeling ([pm-osea](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-osea.toon))
|
|
1812
|
+
- As a future maintainer, I want every significant architectural decision recorded as an ADR with context, decision, and consequences, so that I can understand why the system is built the way it is ([pm-xugp](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-xugp.toon))
|
|
1813
|
+
- As an MCP-connected agent, I want narrow pm\_\* tools kept in lockstep with the CLI via machine-readable contracts, so that I get drift-free, discoverable operations over the same primitives ([pm-wo7x](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-wo7x.toon))
|
|
1814
|
+
- As an agent gating on tracker quality, I want pm validate and pm health to surface every data-quality gap with a machine-executable remediation, so that I can keep context trustworthy and rebuild it from pm alone ([pm-tra4](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-tra4.toon))
|
|
1815
|
+
- As a maintainer extending pm with agents, I want CodeFactor A+ enforced by ratcheted static gates, so that the codebase stays maintainable no matter how many agents contribute ([pm-r0z2](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-r0z2.toon))
|
|
1788
1816
|
- Bundle GH-433 self-parent guard, Windows nightly lock proof, and pnpm 11 bootstrap hardening ([pm-q1ke](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-q1ke.toon))
|
|
1817
|
+
- As a coding agent, I want every pm command to be self-describing and to never block without a machine-actionable recovery path, so that I can operate the full item lifecycle with zero out-of-band context ([pm-nh73](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-nh73.toon))
|
|
1818
|
+
- As one of many parallel agents, I want atomic claim and lock semantics with bounded auto-retry, so that we each get distinct work and never corrupt shared tracker state ([pm-miju](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-miju.toon))
|
|
1819
|
+
- As a third-party author, I want an SDK to compose, validate, test, and ship a pm extension or package, so that pm can be customized and optimized for any project without forking ([pm-m2kl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-m2kl.toon))
|
|
1789
1820
|
- Inventory the CLI-to-core call graph: map every command to core modules and classify logic for SDK promotion ([pm-lodl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-lodl.toon))
|
|
1821
|
+
- As a coding agent, I want every mutation to be atomic and fully replayable from an append-only history, so that I can trust the tracker's state and recover any prior context at any time ([pm-hu11](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-hu11.toon))
|
|
1822
|
+
- As a maintainer, I want consent-aware local telemetry and health diagnostics, so that I can observe how pm is used and detect problems without leaking any project data ([pm-gnya](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-gnya.toon))
|
|
1790
1823
|
- Sandbox audit fixes: package describe accepts npm package name; pm context <id\> routes to pm get ([pm-ayn7](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-ayn7.toon))
|
|
1791
1824
|
- SDK testing-helper input validation: runRegisteredCommandForTest positional misuse crashes; createExtensionTestHarness accepts non-extension module silently ([pm-2exf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-2exf.toon))
|
|
1792
1825
|
- GH-426: reduce complex method in compatibility-check.spec runCurrentPmCommand ([pm-24o5](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-24o5.toon))
|
|
1826
|
+
- As a coding agent bootstrapping any project, I want to define custom item types, statuses, fields, workflows, and profiles via config, so that pm fits the project's domain without code changes ([pm-0zuv](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-0zuv.toon))
|
|
1793
1827
|
|
|
1794
1828
|
## 2026.7.4 - 2026-07-04
|
|
1795
1829
|
|
|
@@ -1920,21 +1954,27 @@
|
|
|
1920
1954
|
- Built-in MCP actions are now extension-aware: pm_profile/pm_list/pm_schema activate workspace extensions like the CLI ([pm-zumn](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-zumn.toon))
|
|
1921
1955
|
- Sub-agent lane: source, tests, docs, and command-surface coverage map ([pm-xezi](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-xezi.toon))
|
|
1922
1956
|
- pm profile list/show/apply merges extension-registered profiles with source labels ([pm-vpwt](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-vpwt.toon))
|
|
1957
|
+
- Audit (2026-06-07): CLI surface & schema/config ([pm-srex](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-srex.toon))
|
|
1923
1958
|
- Package scaffolds declare current SDK compatibility floor ([pm-sf08](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-sf08.toon))
|
|
1924
1959
|
- ADR: profile lint severity model — errors break apply, warnings flag suspicious-but-valid cross-references ([pm-qcdu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/decisions/pm-qcdu.toon))
|
|
1925
1960
|
- Docs: SDK.md/EXTENSIONS.md document api.registerProfile + regenerate contracts/full.json ([pm-ol8j](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-ol8j.toon))
|
|
1926
1961
|
- Sub-agent lane: SDK, packages, MCP, and universal customization backlog ([pm-o578](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-o578.toon))
|
|
1962
|
+
- Audit (2026-06-07): observability / telemetry / health ([pm-lzrq](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-lzrq.toon))
|
|
1927
1963
|
- SDK profile parity: assertRegisteredProfile + composeExtension blueprint.profiles + deriveExtensionCapabilities + describe ([pm-l8fl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-l8fl.toon))
|
|
1928
1964
|
- Sub-agent lane: tracker taxonomy, hierarchy, and duplicate hygiene ([pm-klpw](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-klpw.toon))
|
|
1965
|
+
- Docs & CI/CD audit 2026-06-12 ([pm-gpea](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-gpea.toon))
|
|
1929
1966
|
- Action-scoped MCP parameter descriptions: split shared name/target description per action (schema vs profile) ([pm-fq80](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-fq80.toon))
|
|
1930
1967
|
- ADR: offline BM25 lexical provider + relevance eval harness for search quality ([pm-f2al](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/decisions/pm-f2al.toon))
|
|
1931
1968
|
- ADR: explicit pm_format_version front-matter field for storage schema evolution ([pm-eeai](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/decisions/pm-eeai.toon))
|
|
1969
|
+
- Audit (2026-06-07): MCP + SDK/extensions/packages ([pm-b4cp](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-b4cp.toon))
|
|
1932
1970
|
- ADR: dependency-aware actionability for pm next — ready = active leaf with no open blocked_by; reuse compareCriticalItems + shared blocked_by resolver ([pm-9x6k](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/decisions/pm-9x6k.toon))
|
|
1933
1971
|
- registerProfile core registration surface: ExtensionApi + registry + loader gate + capability-usage + policy surface ([pm-6oox](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-6oox.toon))
|
|
1934
1972
|
- First-party package manifests declare current SDK compatibility floor ([pm-6d7q](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-6d7q.toon))
|
|
1973
|
+
- Audit (2026-06-07): docs/onboarding/release/CI + tests/coverage ([pm-5dbn](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-5dbn.toon))
|
|
1935
1974
|
- Refresh Sentry release and telemetry dependencies ([pm-4dz7](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-4dz7.toon))
|
|
1936
1975
|
- Decompose cli-contracts.ts monolith into flag-contracts + tool-schema sibling modules ([pm-3wue](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-3wue.toon))
|
|
1937
1976
|
- Sub-agent lane: release, GitHub, Sentry, telemetry, and live-ops evidence ([pm-3whx](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-3whx.toon))
|
|
1977
|
+
- Audit (2026-06-07): storage/history + search/semantic ([pm-34gb](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-34gb.toon))
|
|
1938
1978
|
|
|
1939
1979
|
## 2026.6.24 - 2026-06-24
|
|
1940
1980
|
|
|
@@ -2024,6 +2064,7 @@
|
|
|
2024
2064
|
|
|
2025
2065
|
### Other
|
|
2026
2066
|
|
|
2067
|
+
- Package scaffold generates a runnable sample test, .gitignore, and npm test script ([pm-4ltc](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-4ltc.toon))
|
|
2027
2068
|
- Code quality & perf audit 2026-06-12 ([pm-nimu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-nimu.toon))
|
|
2028
2069
|
- SDK testing helper for registerFlags registrations ([pm-oveq](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-oveq.toon))
|
|
2029
2070
|
|
|
@@ -2226,6 +2267,9 @@
|
|
|
2226
2267
|
- Literal 100% all-source test coverage & module-mirrored test reorganization ([pm-xau3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/epics/pm-xau3.toon))
|
|
2227
2268
|
- Coverage to 100%: packages, plugins, and docs examples ([pm-6tch](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-6tch.toon))
|
|
2228
2269
|
- Coverage to 100%: build, release, and smoke scripts ([pm-f2ne](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-f2ne.toon))
|
|
2270
|
+
- pm context power-user projection: --depth full, --fields, --parent subtree (GH-156, pm-ds0m, GH-154) ([pm-kp1d](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-kp1d.toon))
|
|
2271
|
+
- GH-212: type-default estimate backfill via validate --auto-fix --fix-scope estimates ([pm-s3hl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-s3hl.toon))
|
|
2272
|
+
- GH-210: missing_linked_path_rows owner attribution in validate --check-files ([pm-z36m](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-z36m.toon))
|
|
2229
2273
|
- pm validate: --all-affected-ids flag + never truncate ID lists in JSON mode (GH-224) ([pm-o0d2](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-o0d2.toon))
|
|
2230
2274
|
- pm aggregate: explicit (unassigned)/(none) labels for blank group keys in all output modes (GH-225) ([pm-zcx9](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-zcx9.toon))
|
|
2231
2275
|
- pm stats: --by-assignee/--by-tag/--by-priority breakdowns + --metadata-coverage + lifecycle/type adoption (GH-213/218/219) ([pm-gq27](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-gq27.toon))
|
|
@@ -2429,6 +2473,8 @@
|
|
|
2429
2473
|
|
|
2430
2474
|
### Other
|
|
2431
2475
|
|
|
2476
|
+
- As a maintainer tuning relevance, I want a golden-query eval harness, so that I can catch ranking regressions before release ([pm-fhsg](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-fhsg.toon))
|
|
2477
|
+
- As a PM with large item bodies, I want to raise the semantic corpus character limit, so that search indexes my full content instead of truncating it ([pm-tnk5](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-tnk5.toon))
|
|
2432
2478
|
- Config-driven optional close reason via governance.require_close_reason ([pm-peyv](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-peyv.toon))
|
|
2433
2479
|
- PR \#123 review: make governance hook sidecar logging fail-open ([pm-mzlu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-mzlu.toon))
|
|
2434
2480
|
- Publish pm-github starter package as a community reference (credential-requiring pattern) ([pm-zw0n](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-zw0n.toon))
|
|
@@ -2444,6 +2490,9 @@
|
|
|
2444
2490
|
|
|
2445
2491
|
### Added
|
|
2446
2492
|
|
|
2493
|
+
- Add operator-facing stale-lock cleanup to pm gc (locks scope) ([pm-gbbn](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-gbbn.toon))
|
|
2494
|
+
- As a new teammate, I want a single ONBOARDING.md, so that I become productive in two hours without accidentally triggering a release or corrupting the tracker ([pm-10ml](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-10ml.toon))
|
|
2495
|
+
- Add pm history --diff --field: filter the audit diff to one field's transitions ([pm-g94b](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-g94b.toon))
|
|
2447
2496
|
- Add AGENTS.md/README workflow-update checkbox to the PR template ([pm-0sqs](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-0sqs.toon))
|
|
2448
2497
|
- Add Claude Code rows to docs read-path and README start-here tables ([pm-pwdx](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-pwdx.toon))
|
|
2449
2498
|
- Add markdown broken-link check to the docs CI gate ([pm-mp6c](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-mp6c.toon))
|
|
@@ -2456,6 +2505,7 @@
|
|
|
2456
2505
|
|
|
2457
2506
|
### Changed
|
|
2458
2507
|
|
|
2508
|
+
- As a contributor closing items, I want documented changelog classification, so that my change appears in the correct CHANGELOG section without reading the generator source ([pm-ijd9](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-ijd9.toon))
|
|
2459
2509
|
- Generate pm_run action-list description from PM_TOOL_ACTIONS to end prose/enum drift ([pm-fd8n](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-fd8n.toon))
|
|
2460
2510
|
- Export PM_TOOL_PARAMETERS_SCHEMA_VERSION constant and bind all assertion sites ([pm-r9sz](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-r9sz.toon))
|
|
2461
2511
|
|
|
@@ -2473,6 +2523,7 @@
|
|
|
2473
2523
|
- MCP & contract platform maturity PR (pm-5k4v): narrow tools pm_notes/pm_learnings/pm_deps + schema-base hardening + action-list drift-gen + schema-version constant + handshake tests ([pm-at83](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/plans/pm-at83.toon))
|
|
2474
2524
|
- Evaluate commander 15.0.0 major upgrade (current 14.0.3) ([pm-7j8t](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-7j8t.toon))
|
|
2475
2525
|
- Drift-lock the .agents/plugins/marketplace.json (pm-local) manifest in the plugin contract test ([pm-g3xl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-g3xl.toon))
|
|
2526
|
+
- As a coding agent, I want narrow MCP tools for notes/learnings/deps, so that I can self-document and inspect dependencies with the same ergonomics as pm_comments ([pm-77t3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-77t3.toon))
|
|
2476
2527
|
- Clean up stale closed tracker-item references in docs/ header lines ([pm-e376](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-e376.toon))
|
|
2477
2528
|
- Document changelog classifier keyword routing for contributors ([pm-5vsv](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-5vsv.toon))
|
|
2478
2529
|
- Telemetry schema versioning/negotiation preparation ([pm-t4wb](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-t4wb.toon))
|
|
@@ -2488,6 +2539,7 @@
|
|
|
2488
2539
|
- Add generic create/update setter for extension item fields ([pm-qvdj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-qvdj.toon))
|
|
2489
2540
|
- pm list --updated-after/--created-after incremental date filters ([pm-y138](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-y138.toon))
|
|
2490
2541
|
- Reusable external npm package ecosystem smoke harness ([pm-vnjh](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-vnjh.toon))
|
|
2542
|
+
- As an agile/ops/research team, I want pm init --type-preset, so that my domain's item types are registered instantly without manual add-type calls ([pm-vhd9](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-vhd9.toon))
|
|
2491
2543
|
- pm schema list / pm schema show: inspect registered custom and built-in types ([pm-qq69](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-qq69.toon))
|
|
2492
2544
|
- pm close-many: bulk-close matched items with shared reason and validate-close semantics ([pm-i17g](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-i17g.toon))
|
|
2493
2545
|
- Per-type workflow / allowed-transitions config (schema/workflows.json) ([pm-f4r1](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-f4r1.toon))
|
|
@@ -2501,6 +2553,7 @@
|
|
|
2501
2553
|
### Changed
|
|
2502
2554
|
|
|
2503
2555
|
- 2026-06-02 commander SDK custom-field and extension-output hardening ([pm-lwtx](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-lwtx.toon))
|
|
2556
|
+
- As a long-running coding agent, I want to list only items changed since my last context window, so that my context stays focused without scanning 900+ items ([pm-ankr](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-ankr.toon))
|
|
2504
2557
|
|
|
2505
2558
|
### Fixed
|
|
2506
2559
|
|
|
@@ -2519,8 +2572,13 @@
|
|
|
2519
2572
|
- Agent context & bulk-ops primitives: incremental date filters, search --status, --ids targeting, close-many ([pm-j2ig](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/plans/pm-j2ig.toon))
|
|
2520
2573
|
- SDK extension hook context and manifest capability guardrails ([pm-e9ut](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-e9ut.toon))
|
|
2521
2574
|
- 2026-06-02 latest-main ecosystem dogfood and SDK review ([pm-kddw](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-kddw.toon))
|
|
2575
|
+
- As an agent gating on pm health/validate, I want machine-executable remediation commands, so that I can auto-repair findings without hardcoding warning-code mappings ([pm-sz6w](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-sz6w.toon))
|
|
2522
2576
|
- After-command hook affected item transition context ([pm-qzv2](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-qzv2.toon))
|
|
2577
|
+
- As a coding agent bootstrapping a custom-typed project, I want pm schema list/show, so that I can confirm my types registered before pm create ([pm-mt7k](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-mt7k.toon))
|
|
2578
|
+
- As a third-party package author, I want first-party capability exemplars and pm_min_version models, so that I can copy working patterns for importers/hooks/search and version compat ([pm-izsi](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-izsi.toon))
|
|
2523
2579
|
- Sentry gate expected handled CLI classifier refresh ([pm-flbo](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-flbo.toon))
|
|
2580
|
+
- As a coding agent, I want search to scope to open work by default-able status filter, so that I'm not distracted by closed history ([pm-arew](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-arew.toon))
|
|
2581
|
+
- As a coding agent doing sprint closeout, I want to close all matched items in one audited command, so that I don't issue 20 individual closes or bypass close validation ([pm-9mjw](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/stories/pm-9mjw.toon))
|
|
2524
2582
|
- Surface settings_read_invalid_schema warning proactively on affected commands ([pm-7tcw](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-7tcw.toon))
|
|
2525
2583
|
|
|
2526
2584
|
## 2026.6.2 - 2026-06-02
|
|
@@ -172,7 +172,7 @@ declare function buildCommanderRecoveryPayload(context: CommanderGuidanceContext
|
|
|
172
172
|
declare function appendIfMissing(entries: string[], value: string | undefined): string[];
|
|
173
173
|
/** Synthesize a copy-pasteable retry for the unquoted linked-test value shape `pm test <id> --add command npm test -- parser` by re-joining the shell-split value tokens into the documented quoted `key=value` form. Only fires when the item id already precedes the flag (so trailing tokens unambiguously belong to the value) and the token after `--add`/`--remove` is an entry-identity key. */
|
|
174
174
|
export declare function buildLinkedTestQuotedRetryCommand(argv: string[] | undefined): string | undefined;
|
|
175
|
-
/**
|
|
175
|
+
/** Render concise initialization recovery or the bounded diagnostic for other failures. */
|
|
176
176
|
export declare function formatPmCliErrorForDisplay(rawMessage: string, context?: PmCliErrorContext): string;
|
|
177
177
|
/** Implements classify pm cli error for the public runtime surface of this module. */
|
|
178
178
|
export declare function classifyPmCliError(rawMessage: string, context?: PmCliErrorContext): ErrorClassification;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="536f01c0-0dbf-5ef3-ab29-51212f6db36e")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){const normalizedArgs=message.recovery?.normalized_args??[];const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??inferCommandNameFromRecovery(message.recovery)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode)},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery;const hasActionableRecovery=Boolean(recovery?.suggested_retry)||Boolean(recovery?.suggested_retry_args?.length)||Boolean(recovery?.allowed_values?.length)||Boolean(recovery?.candidate_commands?.length)||Boolean(guidance.nextSteps?.length);return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function dedupeStrings(values){const seen=new Set;const result=[];for(const value of values){if(seen.has(value)){continue}seen.add(value);result.push(value)}return result}function inferCommandNameFromRecovery(recovery){return resolveRecoveryCommandName(recovery?.normalized_args)}function inferAllowedValuesFromMessage(message){const match=message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);if(!match){return[]}return match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry))}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args;const fields=recovery?.provided_fields;const replacement=allowedValues[0];if(!Array.isArray(args)||!Array.isArray(fields)||!replacement){return void 0}for(const field of fields){const index=args.findIndex(arg=>arg===field);if(index>=0&&index<args.length-1&&!args[index+1]?.startsWith("-")){const nextArgs=[...args];nextArgs[index+1]=replacement;return renderPmCommand(nextArgs)}}return void 0}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0){return void 0}if(firstLine.length<=120){return firstLine}return`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value==="string"&&value.trim().length>0?value.trim():fallback}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context){return guidance}const normalizedRawMessage=normalizeMessage(rawMessage);const code=normalizeContextValue(context.code,guidance.code);const type=normalizeContextValue(context.type,errorType(code));const examples=normalizeContextList(context.examples)??guidance.examples;const nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps;const verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors;const fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0;const contextRecovery=normalizeRecoveryPayload(context.recovery);const recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,tombstone:context.tombstone,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized){return null}const attemptedRoot=trackerNotInitialized[1];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,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 ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[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.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound){return null}const badId=itemNotFound[1];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;const nextSteps=isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,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.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,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"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,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."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){if(!message.startsWith("No update flags provided")){return null}return applyPmCliErrorContext(makeGuidanceMessage({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."]}),rawMessage,context)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);const guidance=buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context);if(guidance){return guidance}return applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,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"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove"){continue}const key=argv[index+1];if(typeof key!=="string"||!LINKED_TEST_RETRY_KEYS.has(key)){return void 0}const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2){break}valueTokens.push(candidate)}if(valueTokens.length<2){return void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument){return null}const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} 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:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){return{}}const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption){return null}const guidanceContext=context??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.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:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" 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:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} 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:[...retryCommand?[retryCommand]:[],'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:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=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"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({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 "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} 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:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,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."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,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 classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d05107ef-b5c6-5620-b47c-30689680e893")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){const normalizedArgs=message.recovery?.normalized_args??[];const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??inferCommandNameFromRecovery(message.recovery)??"command",...rejectedValue!==void 0?{rejected_value:rejectedValue}:{},...message.recovery?.allowed_values?.length?{legal_domain:message.recovery.allowed_values}:{},exit_code:exitCode}}function guidanceToJsonEnvelope(message,exitCode){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode)},message)}function projectJsonErrorGuidance(guidance,exitCode){const recovery=guidance.recovery;const hasActionableRecovery=Boolean(recovery?.suggested_retry)||Boolean(recovery?.suggested_retry_args?.length)||Boolean(recovery?.allowed_values?.length)||Boolean(recovery?.candidate_commands?.length)||Boolean(guidance.nextSteps?.length);return projectPmDiagnosticOutput(guidanceToJsonEnvelope(guidance,exitCode),{diagnosticClass:hasActionableRecovery?"recovery_bundle":"error"})}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required},message)}function normalizeMessage(message){return message.replace(/\(outputHelp\)/g,"").trim()}function isModuleResolutionErrorMessage(message){const normalized=message.toLowerCase();return normalized.includes("cannot find module")||normalized.includes("cannot find package")||normalized.includes("err_module_not_found")||normalized.includes("module_not_found")}function normalizeContextList(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function dedupeStrings(values){const seen=new Set;const result=[];for(const value of values){if(seen.has(value)){continue}seen.add(value);result.push(value)}return result}function inferCommandNameFromRecovery(recovery){return resolveRecoveryCommandName(recovery?.normalized_args)}function inferAllowedValuesFromMessage(message){const match=message.match(/\bmust be one of:?\s+([A-Za-z0-9_.|,\- ]+)/i);if(!match){return[]}return match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry))}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args;const fields=recovery?.provided_fields;const replacement=allowedValues[0];if(!Array.isArray(args)||!Array.isArray(fields)||!replacement){return void 0}for(const field of fields){const index=args.findIndex(arg=>arg===field);if(index>=0&&index<args.length-1&&!args[index+1]?.startsWith("-")){const nextArgs=[...args];nextArgs[index+1]=replacement;return renderPmCommand(nextArgs)}}return void 0}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0){return void 0}if(firstLine.length<=120){return firstLine}return`${firstLine.slice(0,117)}...`}function normalizeContextValue(value,fallback){return typeof value==="string"&&value.trim().length>0?value.trim():fallback}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context){return guidance}const normalizedRawMessage=normalizeMessage(rawMessage);const code=normalizeContextValue(context.code,guidance.code);const type=normalizeContextValue(context.type,errorType(code));const examples=normalizeContextList(context.examples)??guidance.examples;const nextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps;const verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors;const fallbackTitle=guidance.code==="command_failed"&&context.code?buildFallbackTitleFromMessage(normalizedRawMessage):void 0;const contextRecovery=normalizeRecoveryPayload(context.recovery);const recovery=contextRecovery&&guidance.recovery?normalizeRecoveryPayload({...guidance.recovery,...contextRecovery}):contextRecovery??guidance.recovery;return{...guidance,code,type,title:fallbackTitle??guidance.title,happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,verificationErrors,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,tombstone:context.tombstone,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized){return null}const attemptedRoot=trackerNotInitialized[1];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,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 ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[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.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound){return null}const badId=itemNotFound[1];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;const nextSteps=isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,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.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,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"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,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."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){if(!message.startsWith("No update flags provided")){return null}return applyPmCliErrorContext(makeGuidanceMessage({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."]}),rawMessage,context)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);const guidance=buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context);if(guidance){return guidance}return applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,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"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove"){continue}const key=argv[index+1];if(typeof key!=="string"||!LINKED_TEST_RETRY_KEYS.has(key)){return void 0}const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2){break}valueTokens.push(candidate)}if(valueTokens.length<2){return void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument){return null}const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} 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:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){return{}}const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption){return null}const guidanceContext=context??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.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:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" 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:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} 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:[...retryCommand?[retryCommand]:[],'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:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=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"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({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 "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} 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:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);if((context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args){return[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join("\n")}return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,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."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,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 classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
|
|
2
2
|
//# sourceMappingURL=error-guidance.js.map
|