@unbrained/pm-cli 2026.9.10 → 2026.9.12
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 +53 -11
- package/dist/cli/command-namespaces.d.ts +2 -2
- package/dist/cli/command-namespaces.js +1 -1
- package/dist/cli/error-guidance.d.ts +10 -0
- package/dist/cli/error-guidance.js +1 -1
- package/dist/cli/extension-command-help.js +3 -3
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +2 -2
- package/dist/cli/option-values.d.ts +3 -0
- package/dist/cli/option-values.js +2 -0
- package/dist/cli/register-history-maintenance.js +2 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-mutation.d.ts +5 -0
- package/dist/cli/register-mutation.js +2 -16
- package/dist/cli/schema/registration.d.ts +4 -0
- package/dist/cli/schema/registration.js +16 -0
- package/dist/cli-bundle/bundle-manifest.json +156 -156
- package/dist/cli-bundle/chunks/{chunk-NKOYVKFM.js → chunk-2JAY4LFI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-I6XT3DLQ.js → chunk-3ZJDGTYC.js} +53 -53
- package/dist/cli-bundle/chunks/chunk-67H4PKQ5.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-EOCKPCEY.js → chunk-7H33WPDF.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-7KF6HCRC.js +20 -0
- package/dist/cli-bundle/chunks/chunk-DEGRLB6Y.js +235 -0
- package/dist/cli-bundle/chunks/chunk-GKY655T7.js +6 -0
- package/dist/cli-bundle/chunks/chunk-I6VQUHK6.js +8 -0
- package/dist/cli-bundle/chunks/chunk-PTX2JRFR.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-PYUITRSV.js → chunk-TAGDYARO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-X6POOZKD.js +29 -0
- package/dist/cli-bundle/chunks/{chunk-4SFBH77G.js → chunk-YU75JRTW.js} +156 -142
- package/dist/cli-bundle/chunks/{register-list-query-CUIW7SSE.js → register-list-query-KEZPDR6X.js} +6 -6
- package/dist/cli-bundle/chunks/register-mutation-HEXA3ZDM.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-XIZPLPQY.js → register-operations-TEZT65JF.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-JVGPCAIL.js → register-setup-IIL74WUG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZAWAL2CG.js → chunk-2BQ4JSJQ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-5CRND7UA.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-5PSYV3AT.js +164 -0
- package/dist/cli-bundle/focused-chunks/{chunk-SL5YVVPV.js → chunk-7EKXAUKF.js} +53 -52
- package/dist/cli-bundle/focused-chunks/chunk-BIOWOU6S.js +30 -0
- package/dist/cli-bundle/focused-chunks/chunk-EIXGDI77.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-GAKFECOQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-HFAW3FJQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-U5SHHU7E.js → chunk-IURELABV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KK7KSXUP.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZDNAWWQI.js → chunk-LWJBBM6X.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-MFVABYEU.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7N5MRONP.js → chunk-PERRTPIY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-FHUARRMA.js → chunk-SDQOOL34.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-M36SF4GE.js → chunk-TTRB47KM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-VWMP6W7Y.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-YNBACVQ2.js +2 -0
- package/dist/cli-bundle/main.js +21 -21
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- 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 +42 -42
- 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 +10 -10
- package/dist/core/history/digest.d.ts +12 -0
- package/dist/core/history/digest.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history.d.ts +5 -3
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/operation-contract.d.ts +30 -0
- package/dist/core/history/operation-contract.js +2 -0
- package/dist/core/history/replay.d.ts +3 -2
- package/dist/core/history/replay.js +1 -1
- package/dist/core/history/tombstone.d.ts +3 -0
- package/dist/core/history/tombstone.js +2 -0
- package/dist/core/item/id.d.ts +8 -7
- package/dist/core/item/id.js +1 -1
- package/dist/core/output/mutation-projection.d.ts +1 -0
- package/dist/core/output/mutation-projection.js +1 -1
- package/dist/core/shared/command-line.d.ts +10 -0
- package/dist/core/shared/command-line.js +2 -0
- package/dist/core/shared/errors.d.ts +13 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/store/item-store.d.ts +5 -1
- package/dist/core/store/item-store.js +1 -1
- package/dist/core/telemetry/runtime.d.ts +1 -0
- package/dist/core/telemetry/runtime.js +2 -2
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/agent/item-addressing.js +1 -1
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
- package/dist/sdk/agent-capability-contracts.js +1 -1
- package/dist/sdk/cli-bootstrap.d.ts +2 -1
- package/dist/sdk/cli-bootstrap.js +1 -1
- package/dist/sdk/cli-contracts/command-aliases.d.ts +2 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -1
- package/dist/sdk/command-line.d.ts +1 -6
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/comments.js +1 -1
- package/dist/sdk/completion.d.ts +2 -0
- package/dist/sdk/completion.js +26 -14
- package/dist/sdk/contracts.d.ts +2 -0
- package/dist/sdk/contracts.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/governance/storage-integrity.js +1 -1
- package/dist/sdk/governance/workflow-completeness.js +1 -1
- package/dist/sdk/governance/workflow-policy.js +2 -2
- package/dist/sdk/governance.d.ts +3 -0
- package/dist/sdk/governance.js +1 -1
- package/dist/sdk/history/attestation-command.d.ts +22 -0
- package/dist/sdk/history/attestation-command.js +3 -0
- package/dist/sdk/history/attestation-contract.d.ts +103 -0
- package/dist/sdk/history/attestation-contract.js +2 -0
- package/dist/sdk/history/attestation-scan.d.ts +16 -0
- package/dist/sdk/history/attestation-scan.js +2 -0
- package/dist/sdk/history/attestation.d.ts +8 -0
- package/dist/sdk/history/attestation.js +2 -0
- package/dist/sdk/history/salvage.js +1 -1
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-read.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +3 -1
- package/dist/sdk/index.js +1 -1
- package/dist/sdk/learnings.js +1 -1
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -1
- package/dist/sdk/lifecycle/mcp-actions.d.ts +4 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -1
- package/dist/sdk/lifecycle/task-composition.d.ts +2 -0
- package/dist/sdk/lifecycle/task-composition.js +1 -1
- package/dist/sdk/merge/reconcile.js +1 -1
- package/dist/sdk/merge/three-way.js +2 -2
- package/dist/sdk/notes.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output-budget.d.ts +4 -10
- package/dist/sdk/read-output-budget.js +1 -1
- package/dist/sdk/read-output-contracts.d.ts +1 -1
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +1 -1
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime.d.ts +3 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/types.d.ts +5 -1
- package/dist/types.js +1 -1
- package/docs/AGENT_UX_CONTRACTS.md +8 -0
- package/docs/ARCHITECTURE.md +7 -0
- package/docs/CLI_GRAMMAR.md +23 -0
- package/docs/HISTORY_ATTESTATION.md +164 -0
- package/docs/HISTORY_OPERATIONS.md +46 -0
- package/docs/HISTORY_RECOVERY.md +27 -2
- package/docs/LIFECYCLE_COMMANDS.md +19 -2
- package/docs/MERGE_SAFETY.md +64 -3
- package/docs/README.md +1 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +13 -0
- package/docs/WORKFLOW_POLICIES.md +47 -3
- package/docs/generated/AGENT_CAPABILITY_ROUTING.md +4 -4
- package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -0
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +10 -7
- package/marketplace.json +2 -2
- package/package.json +4 -4
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/README.md +31 -7
- package/packages/pm-governance-audit/extensions/governance-audit/index.ts +6 -3
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/extensions/guide-shell/runtime.ts +7 -19
- 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/README.md +9 -5
- package/packages/pm-search-advanced/extensions/search-advanced/index.ts +3 -2
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/dist/cli-bundle/chunks/chunk-74RGSPLL.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7WIHZI2M.js +0 -5
- package/dist/cli-bundle/chunks/chunk-GLQMKUGP.js +0 -2
- package/dist/cli-bundle/chunks/chunk-MACGGTLQ.js +0 -29
- package/dist/cli-bundle/chunks/chunk-P6BEYAON.js +0 -8
- package/dist/cli-bundle/chunks/chunk-TSWEX72T.js +0 -20
- package/dist/cli-bundle/chunks/chunk-YKQTETJI.js +0 -235
- package/dist/cli-bundle/chunks/register-mutation-5F5CYUWZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-26O2WB73.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-5YU75QLV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-B2CMFYRZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CRY5MHEI.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-F6WKFXBT.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-OROZM37I.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-PNGYYQY7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-TPOL4TWE.js +0 -9
- package/dist/cli-bundle/focused-chunks/chunk-XSMA2W6Q.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-ZJHYQOTM.js +0 -20
|
@@ -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.12"
|
|
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.12",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "unbrained",
|
|
19
19
|
"url": "https://github.com/unbraind/pm-cli"
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,47 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2026.9.12 - 2026-09-12
|
|
4
|
+
|
|
5
|
+
### Changed
|
|
6
|
+
|
|
7
|
+
- Verify complete merge documents across branch permutations and merge directions ([pm-1tns7o](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-1tns7o.toon))
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- Two items created independently on two branches with the same id merge into one document carrying two create entries, and storage integrity only notices when the types differ ([pm-qx95lz](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-qx95lz.toon))
|
|
12
|
+
- Isolate merge reconciliation receipt discovery from unrelated invocation workspaces ([pm-q5grv5](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-q5grv5.toon))
|
|
13
|
+
- The immutable history op vocabulary is ungoverned: 71 op literals across five naming conventions, with the same operation spelled two ways in one file, are written permanently with no enum, no contract, and no gate ([pm-0elqjj](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-0elqjj.toon))
|
|
14
|
+
- Read surfaces give no tombstone signal for a deleted id: pm get returns a bare not-found, so an agent cannot tell never-existed from deleted-and-recoverable ([pm-nb4zwz](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-nb4zwz.toon))
|
|
15
|
+
- CI assurance receipts must explicitly request complete evidence beyond interactive output ceilings ([pm-yrio0m](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-yrio0m.toon))
|
|
16
|
+
- GH-1231: Expose non-vacuous lifecycle completeness evidence ([pm-khd2fd](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-khd2fd.toon))
|
|
17
|
+
- GH-1232: Normalize policy authoring ids with actionable mismatch recovery ([pm-ycv2cz](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-ycv2cz.toon))
|
|
18
|
+
- GH-1233: Make strict ownership recovery executable for annotation writes ([pm-nrkjik](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-nrkjik.toon))
|
|
19
|
+
|
|
20
|
+
### Other
|
|
21
|
+
|
|
22
|
+
- Streamline agent triage and schema command discovery ([pm-gdi7](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-gdi7.toon))
|
|
23
|
+
- Compact compound lifecycle receipts without losing SDK results ([pm-r1f9f1](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-r1f9f1.toon))
|
|
24
|
+
|
|
25
|
+
## 2026.9.11 - 2026-09-11
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
|
|
29
|
+
- Portable integrity attestation: compare recorded history with independently retained proof bundles ([pm-3z0k](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/features/pm-3z0k.toon))
|
|
30
|
+
|
|
31
|
+
### Fixed
|
|
32
|
+
|
|
33
|
+
- The history integrity chain hard-codes SHA-256 with no algorithm identifier, so the proof it produces has no migration path across the decades it claims to cover ([pm-bbk8we](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-bbk8we.toon))
|
|
34
|
+
- Optional undefined result fields silently drop telemetry completion events ([pm-rqaqfp](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-rqaqfp.toon))
|
|
35
|
+
- GH-1229: preserve bounded HTTP process-tree cleanup when POSIX liveness returns EPERM ([pm-qn9zxu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-qn9zxu.toon))
|
|
36
|
+
|
|
37
|
+
### Other
|
|
38
|
+
|
|
39
|
+
- Refresh jscpd 5.2 and MCP Apps 2 development contracts ([pm-qs5iiq](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-qs5iiq.toon))
|
|
40
|
+
- Register advanced retrieval as a search facet ([pm-wfskfn](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-wfskfn.toon))
|
|
41
|
+
- Consolidate duplicate governance under item operations ([pm-fmy9ih](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-fmy9ih.toon))
|
|
42
|
+
- Declare item copy and workspace merge command destinations ([pm-m6g87m](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-m6g87m.toon))
|
|
43
|
+
- Refresh Sentry 10.74 with history attestation consumer verification ([pm-2us1yv](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-2us1yv.toon))
|
|
44
|
+
|
|
3
45
|
## 2026.9.10 - 2026-09-10
|
|
4
46
|
|
|
5
47
|
### Changed
|
|
@@ -160,29 +202,29 @@
|
|
|
160
202
|
|
|
161
203
|
### Fixed
|
|
162
204
|
|
|
205
|
+
- A read whose result was omitted for budget still records those items as served and included, so the usage-affinity signal learns from context the agent never received ([pm-wv47pf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wv47pf.toon))
|
|
206
|
+
- Shape-qualified scale baselines drifted from current CLI/SDK output contracts and supported runtime ([pm-r8yytk](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-r8yytk.toon))
|
|
163
207
|
- Context recency is computed from updated_at, so every governance write the project mandates erases the freshness signal it ranks on ([pm-07pt16](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-07pt16.toon))
|
|
164
208
|
|
|
165
209
|
### Security
|
|
166
210
|
|
|
167
211
|
- OSSF Scorecard alert \#29: qs denial-of-service advisories in the MCP Apps development dependency tree ([pm-mlpn91](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-mlpn91.toon))
|
|
168
212
|
|
|
213
|
+
### Other
|
|
214
|
+
|
|
215
|
+
- Refresh compatible 2026-09-01 jscpd 5.1.1 tooling ([pm-ur4swu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-ur4swu.toon))
|
|
216
|
+
- Refresh Sentry 10.73 and TypeScript-ESLint 8.69 with exact coverage ([pm-92tp12](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-92tp12.toon))
|
|
217
|
+
|
|
169
218
|
## 2026.9.2 - 2026-09-02
|
|
170
219
|
|
|
171
220
|
### Fixed
|
|
172
221
|
|
|
173
|
-
- A read whose result was omitted for budget still records those items as served and included, so the usage-affinity signal learns from context the agent never received ([pm-wv47pf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-wv47pf.toon))
|
|
174
|
-
- Shape-qualified scale baselines drifted from current CLI/SDK output contracts and supported runtime ([pm-r8yytk](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-r8yytk.toon))
|
|
175
222
|
- GH-1174: Windows Node 24 receipt traversal negative control must fail closed portably ([pm-r97901](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-r97901.toon))
|
|
176
223
|
|
|
177
224
|
### Security
|
|
178
225
|
|
|
179
226
|
- GH-1173: make merge-receipt evidence diagnostics source-stable and record-addressable ([pm-dn8rwl](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-dn8rwl.toon))
|
|
180
227
|
|
|
181
|
-
### Other
|
|
182
|
-
|
|
183
|
-
- Refresh compatible 2026-09-01 jscpd 5.1.1 tooling ([pm-ur4swu](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-ur4swu.toon))
|
|
184
|
-
- Refresh Sentry 10.73 and TypeScript-ESLint 8.69 with exact coverage ([pm-92tp12](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-92tp12.toon))
|
|
185
|
-
|
|
186
228
|
## 2026.9.1 - 2026-09-01
|
|
187
229
|
|
|
188
230
|
### Added
|
|
@@ -197,6 +239,10 @@
|
|
|
197
239
|
- GH-1104: health must not certify pending lossless merge receipts as reconciled ([pm-baksix](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-baksix.toon))
|
|
198
240
|
- GH-1135: item_hash_version 2 still masks writer hash divergence as corruption ([pm-2qahia](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-2qahia.toon))
|
|
199
241
|
|
|
242
|
+
### Security
|
|
243
|
+
|
|
244
|
+
- Refresh compatible GitHub Actions and tsx tooling dependencies ([pm-k47gdd](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-k47gdd.toon))
|
|
245
|
+
|
|
200
246
|
### Other
|
|
201
247
|
|
|
202
248
|
- Document the measured canonical agent cold-start across docs and generated guidance ([pm-ka6d](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-ka6d.toon))
|
|
@@ -216,10 +262,6 @@
|
|
|
216
262
|
- The local preflight token-budget gate is red on a workstation and green in hosted CI for the same commit again, because the earlier remediation closed the one ambient channel that had bitten instead of closing the fixture's environment ([pm-4o7tlx](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-4o7tlx.toon))
|
|
217
263
|
- The bounded legacy MCP compatibility set stops one revision short of the spec's own legacy boundary, so every current host is refused at initialize and the dual-era guarantee is unmet ([pm-edywqn](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-edywqn.toon))
|
|
218
264
|
|
|
219
|
-
### Security
|
|
220
|
-
|
|
221
|
-
- Refresh compatible GitHub Actions and tsx tooling dependencies ([pm-k47gdd](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/chores/pm-k47gdd.toon))
|
|
222
|
-
|
|
223
265
|
### Deprecated
|
|
224
266
|
|
|
225
267
|
- The project's own agent-facing documentation and skills instruct deprecated command spellings, so the alias-usage signal that decides when a spelling can be retired is manufactured by the instructions rather than observed from callers ([pm-q2n4vd](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-q2n4vd.toon))
|
|
@@ -5,5 +5,5 @@
|
|
|
5
5
|
* actual node preserves its parser, action closure, flags, and nested verbs.
|
|
6
6
|
*/
|
|
7
7
|
import type { Command } from "commander";
|
|
8
|
-
/**
|
|
9
|
-
export declare function installCommandNamespaces(program: Command): void;
|
|
8
|
+
/** Relocate existing handlers; the early pass moves only parents needed by package facets. */
|
|
9
|
+
export declare function installCommandNamespaces(program: Command, parentsOnly?: boolean): void;
|
|
@@ -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]="
|
|
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]="9914cd35-65dc-58f4-8a4d-69cd5d7c6849")}catch(e2){}})();import{PM_RELOCATED_COMMAND_ALIASES}from"../sdk/cli-contracts/command-aliases.js";function installCommandNamespaces(program,parentsOnly=false){if(!program.commands.some(command=>command.name()==="ops"))program.command("ops").description("Discover workspace diagnostics and maintenance operations.");for(const{alias,canonical,canonical_argv:tokens}of PM_RELOCATED_COMMAND_ALIASES){if(parentsOnly&&!PM_RELOCATED_COMMAND_ALIASES.some(entry=>entry.canonical.startsWith(`${canonical} `)))continue;const sourceIndex=program.commands.findIndex(command=>command.name()===alias);if(sourceIndex<0)continue;const source=program.commands[sourceIndex];let parent=program;for(const noun of tokens.slice(0,-1)){if(parent!==program)parent.enablePositionalOptions();parent=parent.commands.find(command=>command.name()===noun)??parent.command(noun).description(`Discover ${noun} operations.`)}const verb=tokens[tokens.length-1];if(parent.commands.some(command=>command.name()===verb)){throw new Error(`Cannot install canonical command ${canonical}: destination already exists.`)}program.commands.splice(sourceIndex,1);source.name(verb);parent.enablePositionalOptions();parent.addCommand(source)}}export{installCommandNamespaces};
|
|
2
2
|
//# sourceMappingURL=command-namespaces.js.map
|
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
import { type PmCliErrorContext, type PmCliErrorRecoveryPayload } from "../sdk/runtime-primitives.js";
|
|
7
7
|
import { type PmDiagnosticOutputReceipt, type PmProjectedDiagnostic } from "../sdk/cli-contracts/agent-output-contracts.js";
|
|
8
8
|
interface GuidanceMessage {
|
|
9
|
+
itemId?: string;
|
|
10
|
+
tombstone?: PmCliErrorContext["tombstone"];
|
|
9
11
|
code: string;
|
|
10
12
|
type: string;
|
|
11
13
|
title: string;
|
|
@@ -34,6 +36,10 @@ export interface PmRefusalEnvelope {
|
|
|
34
36
|
}
|
|
35
37
|
/** Documents the json error envelope payload exchanged by command, SDK, and package integrations. */
|
|
36
38
|
export interface JsonErrorEnvelope {
|
|
39
|
+
/** Exact item identity attached to a storage diagnostic. */
|
|
40
|
+
item_id?: string;
|
|
41
|
+
/** Verified retained deletion and its recoverable version. */
|
|
42
|
+
tombstone?: PmCliErrorContext["tombstone"];
|
|
37
43
|
/** Schema type that determines the shape and validation rules for this value. */
|
|
38
44
|
type: string;
|
|
39
45
|
/** Value that configures or reports code for this contract. */
|
|
@@ -75,6 +81,10 @@ export type ProjectedJsonErrorEnvelope = PmProjectedDiagnostic<JsonErrorEnvelope
|
|
|
75
81
|
export declare function projectLeanErrorEnvelope(envelope: ProjectedJsonErrorEnvelope): ProjectedJsonErrorEnvelope;
|
|
76
82
|
/** Documents the error classification payload exchanged by command, SDK, and package integrations. */
|
|
77
83
|
export interface ErrorClassification {
|
|
84
|
+
/** Exact item identity attached to a storage diagnostic. */
|
|
85
|
+
item_id?: string;
|
|
86
|
+
/** Verified retained deletion and its recoverable version. */
|
|
87
|
+
tombstone?: PmCliErrorContext["tombstone"];
|
|
78
88
|
/** Schema type that determines the shape and validation rules for this value. */
|
|
79
89
|
type: string;
|
|
80
90
|
/** Value that configures or reports code for this contract. */
|
|
@@ -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]="a2919889-aa1a-54a6-8a2f-95d4484b9e65")}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";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.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(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,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??"<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]="f7a3a881-2a9b-5c10-b0e7-3a4434f6dcbf")}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";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.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??"<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};
|
|
2
2
|
//# sourceMappingURL=error-guidance.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
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]="
|
|
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]="cd9e5ba1-3a9b-5891-8617-9922574872fe")}catch(e2){}})();import{Option}from"commander";import{PM_RELOCATED_COMMAND_ALIASES}from"../sdk/cli-contracts/command-aliases.js";function normalizeExtensionCommandPath(commandPath){return commandPath.trim().toLowerCase().split(/\s+/).filter(part=>part.length>0).join(" ")}function buildCanonicalExtensionAliases(handlers,definitions){const aliases=new Map;for(const handler of handlers){const alias=normalizeExtensionCommandPath(handler.command);for(const definition of definitions){if(definition.layer!==handler.layer||definition.name!==handler.name){continue}const canonical=normalizeExtensionCommandPath(definition.command);const parts=canonical.split(" ");const action=parts.at(-1);const suffix=parts.slice(1).join(" ");const expectedAlias=suffix?`${parts[0]}-${action} ${suffix}`:`${parts[0]}-${action}`;if(action&&alias===expectedAlias){aliases.set(alias,canonical);break}}}return aliases}function extensionFlagTakesValueForInvocation(invocationArgv,commandName,normalizedMissing,descriptors){if(!commandName||!normalizedMissing){return void 0}let descriptor;let matchedTokenCount=0;for(const[index,token]of invocationArgv.entries()){if(token!==commandName){continue}const commandTokens=invocationArgv.slice(index);for(const[path,candidate]of descriptors.entries()){const pathTokens=path.split(" ");if(pathTokens.length>matchedTokenCount&&pathTokens.every((pathToken,pathIndex)=>commandTokens[pathIndex]===pathToken)){descriptor=candidate;matchedTokenCount=pathTokens.length}}}const flag=descriptor?.flags.find(candidate=>candidate.long===normalizedMissing||candidate.short===normalizedMissing);if(!flag){return void 0}return resolveExtensionFlagArity(flag).takesValue}function toNonEmptyFlagString(value){if(typeof value!=="string"){return null}const trimmed=value.trim();return trimmed.length>0?trimmed:null}function toOptionalBoolean(value){return typeof value==="boolean"?value:void 0}function resolveExtensionFlagArity(definition){const valueType=toNonEmptyFlagString(definition.value_type)??toNonEmptyFlagString(definition.type);const declaredValueName=toNonEmptyFlagString(definition.value_name);const takesValue=valueType!=="boolean"&&(declaredValueName!==null||valueType!==null||toOptionalBoolean(definition.required)===true||toOptionalBoolean(definition.list)===true);return{takesValue,valueName:takesValue?declaredValueName??"value":null}}function formatDynamicExtensionFlagHelpLine(definition){const visible=toOptionalBoolean(definition.visible);if(visible===false){return null}const longName=toNonEmptyFlagString(definition.long);if(!longName||!longName.startsWith("--")||longName.length<3){return null}const shortName=toNonEmptyFlagString(definition.short);const shortPrefix=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?`${shortName}, `:"";const valueName=toNonEmptyFlagString(definition.value_name);const valueSuffix=valueName?` <${valueName}>`:"";const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.";const markers=[];if(toOptionalBoolean(definition.required)===true){markers.push("required")}if(toOptionalBoolean(definition.enabled)===false){markers.push("disabled")}const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"";return`${shortPrefix}${longName}${valueSuffix} ${description}${markerSuffix}`}function buildDynamicExtensionFlagHelp(definitions){const lines=[...new Set(definitions.map(formatDynamicExtensionFlagHelpLine).filter(line=>line!==null))].sort((left,right)=>left.localeCompare(right));if(lines.length===0){return null}return`
|
|
2
2
|
Extension-provided flags:
|
|
3
|
-
${lines.join("\n ")}`}function collectDynamicExtensionFlagHelpByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0){continue}const existing=grouped.get(commandPath)??[];existing.push(...registration.flags);grouped.set(commandPath,existing)}const entries=[...grouped.entries()].sort(([left],[right])=>left.localeCompare(right));const helpByCommand=new Map;for(const[commandPath,definitions]of entries){const helpText=buildDynamicExtensionFlagHelp(definitions);if(!helpText){continue}helpByCommand.set(commandPath,helpText)}return helpByCommand}function normalizeExtensionCommandAction(commandPath,action){if(typeof action!=="string"||action.trim().length===0){return commandPath.replace(/\s+/g,"-")}return action.trim().toLowerCase()}function normalizeExtensionCommandStringList(values){if(!Array.isArray(values)){return[]}const normalized=[];const seen=new Set;for(const value of values){if(typeof value!=="string"){continue}const trimmed=value.trim();if(trimmed.length===0||seen.has(trimmed)){continue}seen.add(trimmed);normalized.push(trimmed)}return normalized}function normalizeExtensionCommandArguments(values){if(!Array.isArray(values)){return[]}return values.map(value=>{const name=typeof value.name==="string"?value.name.trim():"";if(name.length===0){return null}const normalized={name,required:value.required===true,variadic:value.variadic===true};if(typeof value.description==="string"&&value.description.trim().length>0){normalized.description=value.description.trim()}return normalized}).filter(entry=>entry!==null)}function collectExtensionDefinitionsByCommand(commandDefinitions){const definitionsByCommand=new Map;for(const definition of commandDefinitions){const commandPath=normalizeExtensionCommandPath(definition.command);if(commandPath.length===0){continue}const description=typeof definition.description==="string"&&definition.description.trim().length>0?definition.description.trim():void 0;const intent=typeof definition.intent==="string"&&definition.intent.trim().length>0?definition.intent.trim():void 0;definitionsByCommand.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,definition.action),description,intent,examples:normalizeExtensionCommandStringList(definition.examples),failure_hints:normalizeExtensionCommandStringList(definition.failure_hints),arguments:normalizeExtensionCommandArguments(definition.arguments),flags:[],tier:definition.tier??"standard",family:definition.family??"extensions",source:{layer:definition.layer,name:definition.name,package:definition.source_package}})}return definitionsByCommand}function collectExtensionFlagsByCommand(flagRegistrations){const flagsByCommand=new Map;for(const registration of flagRegistrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0){continue}const existing=flagsByCommand.get(commandPath)??[];existing.push(...registration.flags);flagsByCommand.set(commandPath,existing)}return flagsByCommand}function collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand){const commandSet=new Set;for(const commandPath of commandHandlers){const normalized=normalizeExtensionCommandPath(commandPath);if(normalized.length>0){commandSet.add(normalized)}}for(const commandPath of definitionsByCommand.keys()){commandSet.add(commandPath)}for(const commandPath of flagsByCommand.keys()){commandSet.add(commandPath)}return commandSet}function resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases){const canonical=canonicalAliases.get(commandPath);return canonical?definitionsByCommand.get(canonical):void 0}function collectExtensionCommandHelpDescriptors(commandHandlers,commandDefinitions,flagRegistrations,canonicalAliases=new Map){const definitionsByCommand=collectExtensionDefinitionsByCommand(commandDefinitions);const flagsByCommand=collectExtensionFlagsByCommand(flagRegistrations);const commandSet=collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand);const descriptors=new Map;const sortedCommands=[...commandSet].sort((left,right)=>left.localeCompare(right));for(const commandPath of sortedCommands){const definition=resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases)??definitionsByCommand.get(commandPath);const flags=flagsByCommand.get(commandPath)??(definition?flagsByCommand.get(definition.command):void 0)??[];if(definition){descriptors.set(commandPath,{...definition,command:commandPath,flags});continue}descriptors.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,void 0),examples:[],failure_hints:[],arguments:[],flags,tier:"standard",family:"extensions"})}return descriptors}function buildExtensionArgumentToken(argument){const variadicSuffix=argument.variadic?"...":"";if(argument.required){return`<${argument.name}${variadicSuffix}>`}return`[${argument.name}${variadicSuffix}]`}function applyDynamicExtensionArguments(command,descriptor){for(const argument of descriptor.arguments){command.argument(buildExtensionArgumentToken(argument),argument.description??"Extension argument.")}}function normalizeDynamicExtensionOptionNames(definition){const visible=toOptionalBoolean(definition.visible);if(visible===false){return null}const longName=toNonEmptyFlagString(definition.long);const shortName=toNonEmptyFlagString(definition.short);const normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null;const normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null;const optionNames=[normalizedShort,normalizedLong].filter(entry=>entry!==null);return optionNames.length>0?optionNames:null}function formatDynamicExtensionOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames){return null}const{valueName}=resolveExtensionFlagArity(definition);const optionValueSuffix=valueName?` <${valueName}>`:"";return`${optionNames.join(", ")}${optionValueSuffix}`}function formatDynamicExtensionParseOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames){return null}const{valueName}=resolveExtensionFlagArity(definition);const valueSuffix=valueName?` <${valueName}>`:"";return`${optionNames.join(", ")}${valueSuffix}`}function formatDynamicExtensionOptionDescription(definition){const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.";const markers=[];if(toOptionalBoolean(definition.required)===true){markers.push("required")}if(toOptionalBoolean(definition.enabled)===false){markers.push("disabled")}const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"";return`${description}${markerSuffix}`}function commandAlreadyHasOption(command,definition){const longName=toNonEmptyFlagString(definition.long);const shortName=toNonEmptyFlagString(definition.short);return command.options.some(option=>{const optionWithNames=option;return longName!==null&&optionWithNames.long===longName||shortName!==null&&optionWithNames.short===shortName})}function applyDynamicExtensionFlagOptions(command,definitions){for(const definition of definitions){if(commandAlreadyHasOption(command,definition)){continue}const flags=formatDynamicExtensionParseOptionFlags(definition);if(!flags){continue}const description=formatDynamicExtensionOptionDescription(definition);if(definition.list!==true){command.option
|
|
3
|
+
${lines.join("\n ")}`}function collectDynamicExtensionFlagHelpByCommand(registrations){const grouped=new Map;for(const registration of registrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0){continue}const existing=grouped.get(commandPath)??[];existing.push(...registration.flags);grouped.set(commandPath,existing)}const entries=[...grouped.entries()].sort(([left],[right])=>left.localeCompare(right));const helpByCommand=new Map;for(const[commandPath,definitions]of entries){const helpText=buildDynamicExtensionFlagHelp(definitions);if(!helpText){continue}helpByCommand.set(commandPath,helpText)}return helpByCommand}function normalizeExtensionCommandAction(commandPath,action){if(typeof action!=="string"||action.trim().length===0){return commandPath.replace(/\s+/g,"-")}return action.trim().toLowerCase()}function normalizeExtensionCommandStringList(values){if(!Array.isArray(values)){return[]}const normalized=[];const seen=new Set;for(const value of values){if(typeof value!=="string"){continue}const trimmed=value.trim();if(trimmed.length===0||seen.has(trimmed)){continue}seen.add(trimmed);normalized.push(trimmed)}return normalized}function normalizeExtensionCommandArguments(values){if(!Array.isArray(values)){return[]}return values.map(value=>{const name=typeof value.name==="string"?value.name.trim():"";if(name.length===0){return null}const normalized={name,required:value.required===true,variadic:value.variadic===true};if(typeof value.description==="string"&&value.description.trim().length>0){normalized.description=value.description.trim()}return normalized}).filter(entry=>entry!==null)}function collectExtensionDefinitionsByCommand(commandDefinitions){const definitionsByCommand=new Map;for(const definition of commandDefinitions){const commandPath=normalizeExtensionCommandPath(definition.command);if(commandPath.length===0){continue}const description=typeof definition.description==="string"&&definition.description.trim().length>0?definition.description.trim():void 0;const intent=typeof definition.intent==="string"&&definition.intent.trim().length>0?definition.intent.trim():void 0;definitionsByCommand.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,definition.action),description,intent,examples:normalizeExtensionCommandStringList(definition.examples),failure_hints:normalizeExtensionCommandStringList(definition.failure_hints),arguments:normalizeExtensionCommandArguments(definition.arguments),flags:[],tier:definition.tier??"standard",family:definition.family??"extensions",source:{layer:definition.layer,name:definition.name,package:definition.source_package}})}return definitionsByCommand}function collectExtensionFlagsByCommand(flagRegistrations){const flagsByCommand=new Map;for(const registration of flagRegistrations){const commandPath=normalizeExtensionCommandPath(registration.target_command);if(commandPath.length===0){continue}const existing=flagsByCommand.get(commandPath)??[];existing.push(...registration.flags);flagsByCommand.set(commandPath,existing)}return flagsByCommand}function collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand){const commandSet=new Set;for(const commandPath of commandHandlers){const normalized=normalizeExtensionCommandPath(commandPath);if(normalized.length>0){commandSet.add(normalized)}}for(const commandPath of definitionsByCommand.keys()){commandSet.add(commandPath)}for(const commandPath of flagsByCommand.keys()){commandSet.add(commandPath)}return commandSet}function resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases){const canonical=canonicalAliases.get(commandPath);return canonical?definitionsByCommand.get(canonical):void 0}function collectExtensionCommandHelpDescriptors(commandHandlers,commandDefinitions,flagRegistrations,canonicalAliases=new Map){const definitionsByCommand=collectExtensionDefinitionsByCommand(commandDefinitions);const flagsByCommand=collectExtensionFlagsByCommand(flagRegistrations);const commandSet=collectExtensionHelpCommandSet(commandHandlers,definitionsByCommand,flagsByCommand);const descriptors=new Map;const sortedCommands=[...commandSet].sort((left,right)=>left.localeCompare(right));for(const commandPath of sortedCommands){const definition=resolveFlattenedAliasDescriptor(commandPath,definitionsByCommand,canonicalAliases)??definitionsByCommand.get(commandPath);const flags=flagsByCommand.get(commandPath)??(definition?flagsByCommand.get(definition.command):void 0)??[];if(definition){descriptors.set(commandPath,{...definition,command:commandPath,flags});continue}descriptors.set(commandPath,{command:commandPath,action:normalizeExtensionCommandAction(commandPath,void 0),examples:[],failure_hints:[],arguments:[],flags,tier:"standard",family:"extensions"})}return descriptors}function buildExtensionArgumentToken(argument){const variadicSuffix=argument.variadic?"...":"";if(argument.required){return`<${argument.name}${variadicSuffix}>`}return`[${argument.name}${variadicSuffix}]`}function applyDynamicExtensionArguments(command,descriptor){for(const argument of descriptor.arguments){command.argument(buildExtensionArgumentToken(argument),argument.description??"Extension argument.")}}function normalizeDynamicExtensionOptionNames(definition){const visible=toOptionalBoolean(definition.visible);if(visible===false){return null}const longName=toNonEmptyFlagString(definition.long);const shortName=toNonEmptyFlagString(definition.short);const normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null;const normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null;const optionNames=[normalizedShort,normalizedLong].filter(entry=>entry!==null);return optionNames.length>0?optionNames:null}function formatDynamicExtensionOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames){return null}const{valueName}=resolveExtensionFlagArity(definition);const optionValueSuffix=valueName?` <${valueName}>`:"";return`${optionNames.join(", ")}${optionValueSuffix}`}function formatDynamicExtensionParseOptionFlags(definition){const optionNames=normalizeDynamicExtensionOptionNames(definition);if(!optionNames){return null}const{valueName}=resolveExtensionFlagArity(definition);const valueSuffix=valueName?` <${valueName}>`:"";return`${optionNames.join(", ")}${valueSuffix}`}function formatDynamicExtensionOptionDescription(definition){const description=toNonEmptyFlagString(definition.description)??"Extension-provided option.";const markers=[];if(toOptionalBoolean(definition.required)===true){markers.push("required")}if(toOptionalBoolean(definition.enabled)===false){markers.push("disabled")}const markerSuffix=markers.length>0?` [${markers.join(", ")}]`:"";return`${description}${markerSuffix}`}function commandAlreadyHasOption(command,definition){const longName=toNonEmptyFlagString(definition.long);const shortName=toNonEmptyFlagString(definition.short);return command.options.some(option=>{const optionWithNames=option;return longName!==null&&optionWithNames.long===longName||shortName!==null&&optionWithNames.short===shortName})}function applyDynamicExtensionFlagOptions(command,definitions){for(const definition of definitions){if(commandAlreadyHasOption(command,definition)){continue}const flags=formatDynamicExtensionParseOptionFlags(definition);if(!flags){continue}const description=formatDynamicExtensionOptionDescription(definition);const option=new Option(flags,description);option.negate=false;if(definition.list!==true){command.addOption(option);continue}command.addOption(option.argParser((value,previous=[])=>[...Array.isArray(previous)?previous:[previous],value]))}}function buildResidualDynamicExtensionFlagHelp(command,definitions){return buildDynamicExtensionFlagHelp(definitions.filter(definition=>!commandAlreadyHasOption(command,definition)))}function buildDynamicExtensionHelpOptionSummary(definition){const flags=formatDynamicExtensionOptionFlags(definition);if(!flags){return null}const longName=toNonEmptyFlagString(definition.long);const shortName=toNonEmptyFlagString(definition.short);const normalizedLong=longName&&longName.startsWith("--")&&longName.length>2?longName:null;const normalizedShort=shortName&&shortName.startsWith("-")&&!shortName.startsWith("--")?shortName:null;const{takesValue,valueName}=resolveExtensionFlagArity(definition);const required=toOptionalBoolean(definition.required)===true;return{flags,long:normalizedLong,short:normalizedShort,description:formatDynamicExtensionOptionDescription(definition),takes_value:takesValue,value_required:takesValue,value_name:valueName,variadic:false,required,aliases:[],alias_for:null}}function buildDynamicExtensionHelpOptionSummaries(descriptor){if(!descriptor){return[]}const summaries=[];const seen=new Set;for(const definition of descriptor.flags){const summary=buildDynamicExtensionHelpOptionSummary(definition);if(!summary||seen.has(summary.flags)){continue}seen.add(summary.flags);summaries.push(summary)}return summaries}function mergeHelpOptionSummaries(base,extension){if(extension.length===0){return base}const merged=[...base];const seen=new Set(base.map(entry=>entry.flags));for(const entry of extension){if(seen.has(entry.flags)){continue}seen.add(entry.flags);merged.push(entry)}return merged}function buildDynamicExtensionCommandMetadataHelp(descriptor){const lines=[];if(descriptor.intent){lines.push(`Intent: ${descriptor.intent}`)}if(descriptor.action){lines.push(`Action contract: ${descriptor.action}`)}if(descriptor.examples.length>0){lines.push("Examples:");for(const example of descriptor.examples){lines.push(` - ${example}`)}}if(descriptor.failure_hints.length>0){lines.push("Common failure hints:");for(const hint of descriptor.failure_hints){lines.push(` - ${hint}`)}}if(lines.length===0){return null}return`
|
|
4
4
|
Extension command metadata:
|
|
5
|
-
${lines.join("\n ")}`}function commandAliases(command){const commandRecord=command;if(typeof commandRecord.aliases==="function"){return commandRecord.aliases().map(value=>value.trim().toLowerCase()).filter(value=>value.length>0)}if(typeof commandRecord.alias==="function"){const alias=commandRecord.alias();if(typeof alias==="string"&&alias.trim().length>0){return[alias.trim().toLowerCase()]}}if(Array.isArray(commandRecord._aliases)){return commandRecord._aliases.map(value=>value.trim().toLowerCase()).filter(value=>value.length>0)}return[]}function findDirectChildCommand(parent,name){const normalizedTarget=name.trim().toLowerCase();return parent.commands.find(entry=>{if(entry.name().trim().toLowerCase()===normalizedTarget){return true}return commandAliases(entry).includes(normalizedTarget)})??null}function findCommandByPath(root,pathParts){let current=root;for(const part of pathParts){const next=findDirectChildCommand(current,part);if(!next){return null}current=next}return current}const extensionCreatedCommands=new WeakSet;function ensureCommandPath(root,pathParts){if(pathParts.length===0){return null}let current=root;for(let index=0;index<pathParts.length;index+=1){const part=pathParts[index];const existing=findDirectChildCommand(current,part);if(existing){current=existing;continue}const created=current.command(part);extensionCreatedCommands.add(created);if(index<pathParts.length-1){created.description("Extension-provided command group.");created.action(()=>{created.help()})}else{created.description("Extension-provided command path.")}current=created}return current}function findExtensionCommandPathCollision(root,pathParts){let current=root;const traversed=[];for(const part of pathParts){const existing=findDirectChildCommand(current,part);if(!existing){return null}traversed.push(part);if(!extensionCreatedCommands.has(existing)){return{core_path:traversed.join(" "),extension_path:pathParts.join(" ")}}current=existing}return null}function buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptor){const pathParts=commandPath.split(" ").filter(part=>part.length>0);const collision=findExtensionCommandPathCollision(root,pathParts);if(!collision||collision.core_path===commandPath&&!aliases.has(commandPath)){return null}const extensionOwner=descriptor?.source?.package??descriptor?.source?.name??"unknown-extension";return`extension_command_collision:${collision.extension_path}:core_owner=pm-cli:${collision.core_path}:extension_owner=${extensionOwner}`}function collectSafeExtensionCommandPaths(root,commandHandlers,descriptors,aliases,onCollision){return[...new Set([...commandHandlers,...descriptors.keys()])].filter(commandPath=>commandPath.trim().length>0).sort((left,right)=>left.localeCompare(right)).filter(commandPath=>{const warning=buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptors.get(commandPath));if(!warning)return true;onCollision(warning);return false})}function reportExtensionCommandCollision(activationWarnings,report,warning){activationWarnings.push(warning);report(`[pm] warning: ${warning}; core command preserved. Rename or namespace the extension command alias.`)}export{applyDynamicExtensionArguments,applyDynamicExtensionFlagOptions,buildCanonicalExtensionAliases,buildDynamicExtensionCommandMetadataHelp,buildDynamicExtensionHelpOptionSummaries,buildExtensionCommandCollisionWarning,buildResidualDynamicExtensionFlagHelp,collectDynamicExtensionFlagHelpByCommand,collectExtensionCommandHelpDescriptors,collectSafeExtensionCommandPaths,commandAliases,ensureCommandPath,extensionFlagTakesValueForInvocation,findCommandByPath,findDirectChildCommand,findExtensionCommandPathCollision,mergeHelpOptionSummaries,normalizeExtensionCommandPath,reportExtensionCommandCollision,resolveExtensionFlagArity};
|
|
5
|
+
${lines.join("\n ")}`}function commandAliases(command){const commandRecord=command;if(typeof commandRecord.aliases==="function"){return commandRecord.aliases().map(value=>value.trim().toLowerCase()).filter(value=>value.length>0)}if(typeof commandRecord.alias==="function"){const alias=commandRecord.alias();if(typeof alias==="string"&&alias.trim().length>0){return[alias.trim().toLowerCase()]}}if(Array.isArray(commandRecord._aliases)){return commandRecord._aliases.map(value=>value.trim().toLowerCase()).filter(value=>value.length>0)}return[]}function findDirectChildCommand(parent,name){const normalizedTarget=name.trim().toLowerCase();return parent.commands.find(entry=>{if(entry.name().trim().toLowerCase()===normalizedTarget){return true}return commandAliases(entry).includes(normalizedTarget)})??null}function findCommandByPath(root,pathParts){let current=root;for(const part of pathParts){const next=findDirectChildCommand(current,part);if(!next){return null}current=next}return current}const extensionCreatedCommands=new WeakSet;function ensureCommandPath(root,pathParts){if(pathParts.length===0){return null}let current=root;for(let index=0;index<pathParts.length;index+=1){const part=pathParts[index];if(index>0&&PM_RELOCATED_COMMAND_ALIASES.some(entry=>entry.canonical===pathParts.join(" ")))current.enablePositionalOptions();const existing=findDirectChildCommand(current,part);if(existing){current=existing;continue}const created=current.command(part);extensionCreatedCommands.add(created);if(index<pathParts.length-1){created.description("Extension-provided command group.");created.action(()=>{created.help()})}else{created.description("Extension-provided command path.")}current=created}return current}function findExtensionCommandPathCollision(root,pathParts){let current=root;const traversed=[];for(const part of pathParts){const existing=findDirectChildCommand(current,part);if(!existing){return null}traversed.push(part);if(!extensionCreatedCommands.has(existing)){return{core_path:traversed.join(" "),extension_path:pathParts.join(" ")}}current=existing}return null}function buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptor){const pathParts=commandPath.split(" ").filter(part=>part.length>0);const collision=findExtensionCommandPathCollision(root,pathParts);const declaredFacet=PM_RELOCATED_COMMAND_ALIASES.some(alias=>alias.canonical===commandPath&&alias.alias===descriptor?.action);if(!collision||collision.core_path===commandPath&&!aliases.has(commandPath)||declaredFacet&&!aliases.has(commandPath)){return null}const extensionOwner=descriptor?.source?.package??descriptor?.source?.name??"unknown-extension";return`extension_command_collision:${collision.extension_path}:core_owner=pm-cli:${collision.core_path}:extension_owner=${extensionOwner}`}function collectSafeExtensionCommandPaths(root,commandHandlers,descriptors,aliases,onCollision){return[...new Set([...commandHandlers,...descriptors.keys()])].filter(commandPath=>commandPath.trim().length>0).sort((left,right)=>left.localeCompare(right)).filter(commandPath=>{const warning=buildExtensionCommandCollisionWarning(root,commandPath,aliases,descriptors.get(commandPath));if(!warning)return true;onCollision(warning);return false})}function reportExtensionCommandCollision(activationWarnings,report,warning){activationWarnings.push(warning);report(`[pm] warning: ${warning}; core command preserved. Rename or namespace the extension command alias.`)}export{applyDynamicExtensionArguments,applyDynamicExtensionFlagOptions,buildCanonicalExtensionAliases,buildDynamicExtensionCommandMetadataHelp,buildDynamicExtensionHelpOptionSummaries,buildExtensionCommandCollisionWarning,buildResidualDynamicExtensionFlagHelp,collectDynamicExtensionFlagHelpByCommand,collectExtensionCommandHelpDescriptors,collectSafeExtensionCommandPaths,commandAliases,ensureCommandPath,extensionFlagTakesValueForInvocation,findCommandByPath,findDirectChildCommand,findExtensionCommandPathCollision,mergeHelpOptionSummaries,normalizeExtensionCommandPath,reportExtensionCommandCollision,resolveExtensionFlagArity};
|
|
6
6
|
//# sourceMappingURL=extension-command-help.js.map
|
package/dist/cli/main.d.ts
CHANGED
|
@@ -92,7 +92,9 @@ declare function handleGenericRunPmCliError(params: {
|
|
|
92
92
|
commandResolution: TelemetryCommandResolution;
|
|
93
93
|
}>;
|
|
94
94
|
}): Promise<void>;
|
|
95
|
+
/** Separate handler options from global controls, then validate and coerce contributed flags against the command's declared schema. */
|
|
95
96
|
declare function extractCommandScopedOptions(command: Command, commandArgs: string[], extensionFlagDefinitions?: LooseCommandFlagDefinition[]): Record<string, unknown>;
|
|
97
|
+
/** Join contributed flags by stable operation identity so canonical and compatibility command paths share the same schema. */
|
|
96
98
|
declare function collectExtensionFlagDefinitionsForCommand(registrations: ReturnType<typeof createEmptyExtensionRegistrationRegistry>, commandPath: string): FlagDefinition[];
|
|
97
99
|
declare function collectExtensionFlagDefinitionsForInvocation(registrations: ReturnType<typeof createEmptyExtensionRegistrationRegistry>, commandPath: string, commandArgs: string[]): FlagDefinition[];
|
|
98
100
|
/**
|
|
@@ -134,7 +136,9 @@ declare function hasGlobalExtensionContributions(contributions: NonNullable<Exte
|
|
|
134
136
|
/** Resolve an exact activation verdict from declared commands and contributions. */
|
|
135
137
|
declare function resolveStaticExtensionActivationDecision(extension: ExtensionDiscoveryResult["effective"][number], probe: RuntimeExtensionActivationProbe): boolean | undefined;
|
|
136
138
|
declare function extensionNeedsActivationForProbe(extension: ExtensionDiscoveryResult["effective"][number], probe: RuntimeExtensionActivationProbe): boolean;
|
|
139
|
+
/** Decide whether installed providers must activate for a targeted invocation or complete command discovery. */
|
|
137
140
|
declare function discoveryNeedsActivationForProbe(discovery: ExtensionDiscoveryResult, probe: RuntimeExtensionActivationProbe): boolean;
|
|
141
|
+
/** Build a deterministic activation scope; completion and unconstrained discovery include every installed command provider. */
|
|
138
142
|
declare function buildRuntimeExtensionActivationScope(probe: RuntimeExtensionActivationProbe): string;
|
|
139
143
|
declare function buildRuntimeExtensionFilterForProbe(probe: RuntimeExtensionActivationProbe): ((extension: ExtensionDiscoveryResult["effective"][number]) => boolean) | undefined;
|
|
140
144
|
declare function buildBootstrapActivationProbe(invocationArgv: string[]): RuntimeExtensionActivationProbe;
|