@unbrained/pm-cli 2026.9.28 → 2026.9.29

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.
Files changed (101) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +2 -2
  5. package/CHANGELOG.md +17 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  10. package/dist/cli/runtime/invocation-options.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +153 -153
  12. package/dist/cli-bundle/chunks/{chunk-OYCCWPBM.js → chunk-2AQKVJMW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-UT7GRGHY.js → chunk-4DOL43PF.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-GLH2LNRH.js → chunk-5KEPG36D.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-YERBAGQD.js → chunk-D32HVIB2.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-A2G5OG6W.js → chunk-GP6QTYSD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-CPOWTIIS.js → chunk-OTLIM22J.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-PLNNUAFZ.js → chunk-P75SO5HO.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-PR4UAMI5.js → chunk-PJSQAWWQ.js} +60 -60
  20. package/dist/cli-bundle/chunks/{chunk-VMJLM7P2.js → chunk-S5A2UIRV.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-ZFHJP7YD.js → chunk-SC6JHXFT.js} +31 -29
  22. package/dist/cli-bundle/chunks/{chunk-NBDB3SRC.js → chunk-SEJ53XDN.js} +48 -48
  23. package/dist/cli-bundle/chunks/{chunk-35DME35A.js → chunk-SJI55O65.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-NEUIVBFO.js → chunk-U3QJGJYN.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-list-query-N6RP6PSP.js → register-list-query-R3ELWWPY.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-mutation-CY7JGQE6.js → register-mutation-WHXJXIHJ.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-operations-53HAD3QP.js → register-operations-7ASWBYQG.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-setup-NVX6374E.js → register-setup-FDRTUG54.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-YZB7IPR6.js → chunk-2O3QFI3G.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-Y5Z3XNGY.js → chunk-4A4DO5ZT.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-K7GSZ7YZ.js → chunk-5MC57KRC.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-IWLMQLBO.js → chunk-6OXJVE74.js} +17 -17
  33. package/dist/cli-bundle/focused-chunks/{chunk-6IVQPNYN.js → chunk-7URX7FMY.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-5KJXX2TZ.js → chunk-AVP5C674.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-DTLRXY77.js → chunk-AZE7KUHG.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-V7OPZRL6.js → chunk-DZVOCJFY.js} +14 -14
  37. package/dist/cli-bundle/focused-chunks/{chunk-AZA4AEOR.js → chunk-FBIRNSYP.js} +6 -6
  38. package/dist/cli-bundle/focused-chunks/{chunk-A5O3VYWV.js → chunk-IFBA3ZAT.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-ONDNR3VU.js → chunk-K3AIMRIK.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-ZMQTIS3L.js → chunk-KLKKCHWM.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-BRLXKRI2.js → chunk-MRH4A542.js} +4 -4
  42. package/dist/cli-bundle/focused-chunks/{chunk-IJXZQE3D.js → chunk-NXQZMKW5.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-BGWF6CMP.js → chunk-NY6FLQTN.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-OVVCXTIE.js → chunk-T4H6Q44B.js} +2 -2
  45. package/dist/cli-bundle/main.js +22 -22
  46. package/dist/cli-bundle/sdk-authoring.js +1 -1
  47. package/dist/cli-bundle/sdk-contracts.js +1 -1
  48. package/dist/cli-bundle/sdk-core.js +22 -21
  49. package/dist/cli-bundle/sdk-governance.js +1 -1
  50. package/dist/cli-bundle/sdk-graph.js +1 -1
  51. package/dist/cli-bundle/sdk-merge.js +28 -28
  52. package/dist/cli-bundle/sdk-query.js +1 -1
  53. package/dist/cli-bundle/sdk-runtime.js +1 -1
  54. package/dist/cli-bundle/sdk-testing.js +1 -1
  55. package/dist/cli-bundle/sdk.js +2 -2
  56. package/dist/core/history/replay.js +1 -1
  57. package/dist/core/output/mutation-projection.js +1 -1
  58. package/dist/core/telemetry/runtime.js +2 -2
  59. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  60. package/dist/sdk/index.d.ts +1 -0
  61. package/dist/sdk/index.js +1 -1
  62. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  63. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  64. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  65. package/dist/sdk/lifecycle/plan.js +1 -1
  66. package/dist/sdk/linked-artifacts.js +1 -1
  67. package/dist/sdk/public-surface.json +1 -1
  68. package/dist/sdk/runtime/actions.js +1 -1
  69. package/dist/sdk/runtime-input.d.ts +2 -0
  70. package/dist/sdk/runtime-input.js +1 -1
  71. package/dist/sdk/runtime.js +1 -1
  72. package/dist/sdk/similarity-scoring.js +1 -1
  73. package/dist/sdk/telemetry.d.ts +2 -0
  74. package/dist/sdk/telemetry.js +3 -1
  75. package/docs/CLI_GRAMMAR.md +18 -1
  76. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  77. package/docs/README.md +1 -0
  78. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  79. package/docs/agent-task-token-baseline.json +28 -2
  80. package/docs/agent-task-transcripts.json +137 -14
  81. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  82. package/marketplace.json +2 -2
  83. package/package.json +1 -1
  84. package/packages/pm-beads/package.json +1 -1
  85. package/packages/pm-calendar/package.json +1 -1
  86. package/packages/pm-command-kit/package.json +1 -1
  87. package/packages/pm-digital-twin/package.json +1 -1
  88. package/packages/pm-governance-audit/package.json +1 -1
  89. package/packages/pm-guide-shell/package.json +1 -1
  90. package/packages/pm-kanban/package.json +1 -1
  91. package/packages/pm-lifecycle-hooks/package.json +1 -1
  92. package/packages/pm-linked-test-adapters/package.json +1 -1
  93. package/packages/pm-search-advanced/package.json +1 -1
  94. package/packages/pm-templates/package.json +1 -1
  95. package/packages/pm-todos/package.json +1 -1
  96. package/packages/pm-vcs/package.json +1 -1
  97. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  98. package/plugins/pm-claude/package.json +2 -2
  99. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  100. package/plugins/pm-codex/package.json +2 -2
  101. package/plugins/pm-codex/plugin.json +1 -1
@@ -10,7 +10,7 @@ and [docs/DEPENDENCY_KIND_CONTRACT.md](../../../../docs/DEPENDENCY_KIND_CONTRACT
10
10
  Authoritative at runtime:
11
11
 
12
12
  ```bash
13
- pm contracts --json --full | jq '.relationship_kind_contracts'
13
+ pm contracts --json --full --output-budget unbounded | jq '.relationship_kind_contracts'
14
14
  ```
15
15
 
16
16
  | Kind | Meaning | Ordering | Hierarchy |
@@ -47,11 +47,12 @@ Rules that prevent damage:
47
47
  - `--dep-remove` with a bare id deletes **every** row for that id. Always pass
48
48
  `kind=` unless removing all of them is the intent.
49
49
  - Never record both `A blocks B` and `B blocked_by A`. They are inverse
50
- spellings of one edge, and recording both creates a cycle.
50
+ spellings of one edge; storing both creates redundant evidence and can confuse ordering analyses.
51
51
  - Never add an edge to satisfy a count. Each edge should cite durable text, a
52
52
  history event, or a linked artifact.
53
- - A placeholder or misspelled id passes `create` silently. Verify with
54
- `pm deps <ID>` after adding.
53
+ - Local targets must exist: create/update reject missing IDs. Deliberate staged
54
+ imports require `--allow-unresolved-deps` and a retained warning receipt.
55
+ Verify the resulting neighborhood with `pm deps <ID>` after adding.
55
56
 
56
57
  ## Reading The Graph
57
58
 
@@ -60,13 +61,13 @@ pm deps <ID> # tree view of one item's neighborhood
60
61
  pm deps <ID> --format context --direction both --kind implements,verifies
61
62
  pm graph analyze # layers, critical path, components, hubs
62
63
  pm graph audit # findings, coverage, edge composition
63
- pm graph impact <ID> --direction downstream
64
+ pm graph impact <ID> --direction incoming
64
65
  pm graph ancestors <ID> / descendants <ID>
65
66
  pm graph paths <A> <B>
66
67
  pm graph dominators <ID> # what must pass through this node
67
68
  pm graph articulation # single points of failure
68
69
  pm graph communities / centrality / slack / redundancy
69
- pm graph plan # critical path method over the ordering DAG
70
+ pm graph plan # dry-run relationship remediation plan
70
71
  ```
71
72
 
72
73
  `pm graph impact` and the traversal verbs are directional. Pass `--direction`
@@ -67,7 +67,7 @@ pm update <ID> --dep "id=<prerequisite>,kind=blocked_by"
67
67
  ```
68
68
 
69
69
  Do not record the inverse `blocks` edge as well — the pair is one relationship
70
- and recording both creates a cycle.
70
+ and recording both duplicates the same ordering evidence.
71
71
 
72
72
  ## Closing Well
73
73
 
@@ -14,10 +14,14 @@ pm context --limit 10 --for orient
14
14
  pm search "<request keywords>" --limit 10 # hybrid when semantic search is configured, keyword otherwise
15
15
  pm list --status open --limit 20
16
16
  pm list --status in_progress --limit 20
17
- pm list --all --no-truncate --full --include-body --strict-read --json
17
+ pm list --all --no-truncate --full --include-body --strict-read --json --output-budget unbounded > items.json
18
18
  pm events --full --limit 1000
19
19
  ```
20
20
 
21
+ The complete snapshot command is for an explicitly authorized exhaustive review.
22
+ Keep its output outside the prompt and use a bounded streaming consumer for
23
+ million-item workspaces; an unbounded collection is not a normal agent loop.
24
+
21
25
  Stream large results to an analysis consumer instead of loading them into the
22
26
  agent's context. Certify the list's total, completeness, truncation, and omission
23
27
  receipt. For events, parse the terminal `pm.stream.trailer`, retain every event's
@@ -26,10 +30,10 @@ false. Record the snapshot cutoff: a concurrent workspace can change during a
26
30
  read, and new events belong to a subsequent delta. Event collection is not an
27
31
  independent hash-chain verification.
28
32
 
29
- Read `pm get <ID> --full --json` and the item's history before changing its
33
+ Read `pm get <ID> --full --json --output-budget unbounded` and the item's history before changing its
30
34
  meaning or making a status claim. A closed implementation remains completed
31
35
  when its encompassing outcome still has work left. Read the full contract only
32
- when enumerating the surface: `pm contracts --full --json`; its default summary
36
+ when enumerating the surface: `pm contracts --full --json --output-budget unbounded`; its default summary
33
37
  does not contain the complete flag, action, SDK, and MCP catalog.
34
38
 
35
39
  ## Inspect Meaning and Coverage
@@ -93,3 +97,22 @@ timestamp; a closed substrate does not prove its proposed extensions shipped.
93
97
  After terminal metadata changes, regenerate and check the package-owned
94
98
  changelog, preserving historical release attribution. Release claims when the
95
99
  batch ends; keep unfinished programmes open with exact residual scope.
100
+
101
+ ## Keep annotation inputs plain
102
+
103
+ Use `pm notes <ID> --add "prose"` and `pm comments <ID> --add "prose"`
104
+ for text. Do not JSON-encode a `{ "text": "..." }` object into these plain-text
105
+ arguments: it becomes a literal wrapper in the stored annotation. Use
106
+ `pm notes <ID> --add-json` only for an intentional JSON event. Correct a wrapped
107
+ annotation with `--edit <index> --add "prose"` so history records the correction.
108
+
109
+ ## Interpret verification precisely
110
+
111
+ A configured embedding model and a successful reindex prove availability, not
112
+ retrieval quality. Run keyword, semantic and hybrid judgments independently and
113
+ inspect each query beside aggregate scores. At cutoff k, a query with more than
114
+ k relevant records cannot attain recall 1. Record feasible per-query floors.
115
+
116
+ A recovered release does not erase the failed automatic attempt. Preserve the
117
+ original run, same-version recovery, registry identity and each installed-consumer
118
+ verdict separately. Historical fields without recoverable evidence stay unknown.
@@ -5,13 +5,13 @@
5
5
  "url": "https://github.com/unbraind/pm-cli"
6
6
  },
7
7
  "description": "Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.",
8
- "version": "2026.9.28",
8
+ "version": "2026.9.29",
9
9
  "plugins": [
10
10
  {
11
11
  "name": "pm-claude",
12
12
  "source": "./plugins/pm-claude",
13
13
  "description": "Native pm CLI integration for Claude Code — 32 MCP tools, 14 workflow skills with slash invocations, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.",
14
- "version": "2026.9.28",
14
+ "version": "2026.9.29",
15
15
  "author": {
16
16
  "name": "unbrained",
17
17
  "url": "https://github.com/unbraind/pm-cli"
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.9.29 - 2026-09-29
4
+
5
+ ### Fixed
6
+
7
+ - GH-1340: pm duplicates treats UTF-8 prose as a 0.99 issue-code match ([pm-1ieq24](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-1ieq24.toon))
8
+ - Persist revised linked evidence notes while preserving idempotent retries ([pm-zqxlfs](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-zqxlfs.toon))
9
+ - Bound Plan mutation receipts while preserving full inspection ([pm-hqy7lr](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-hqy7lr.toon))
10
+
11
+ ### Deprecated
12
+
13
+ - Alias-usage counters: measure deprecated-spelling hits so grammar-freeze removals are evidence-based ([pm-0mox](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-0mox.toon))
14
+ - Extension activation attributes canonical full-list projection to deprecated --full ([pm-8uwigr](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-8uwigr.toon))
15
+
16
+ ### Other
17
+
18
+ - Replay each history state once: reuse the previous entry's digest as the next before-hash, stop at the first matching hash epoch, and drop the second document clone ([pm-hen0t6](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-hen0t6.toon))
19
+
3
20
  ## 2026.9.28 - 2026-09-28
4
21
 
5
22
  ### Fixed
@@ -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]="10506b96-211c-5174-aeb0-0e5301e21e34")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){if(message.policyViolations?.length){return{surface:`policy:${message.policyViolations.map(policy=>policy.policy_id).join(",")}`,policies:message.policyViolations,policy_violation_count:message.policyViolationCount,missing_fields:[...new Set(message.policyViolations.flatMap(policy=>policy.missing_fields))],exit_code:exitCode}}const invocationArgs=stripGlobalBootstrapTokens(message.recovery?.normalized_args??[]);const namespaced=findPmNamespacedCommand(invocationArgs);const normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs;const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??resolveRecoveryCommandName(normalizedArgs)??"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,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:context.flag,value:context.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,tombstone:context.tombstone,availableDependencies:context.available_dependencies,recovery}}function buildTrackerNotInitializedGuidance(rawMessage,message,context){const trackerNotInitialized=message.match(/^Tracker is not initialized at (.+)\. (?:Run pm init first|Tracker root does not exist\. Run pm init first)\.$/);if(!trackerNotInitialized){return null}const attemptedRoot=trackerNotInitialized[1];const nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);if(nearbyRoot){return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker exists at a custom path",happened:`pm did not find initialized metadata at ${attemptedRoot}, but found a tracker at ${nearbyRoot}.`,required:"Select the existing tracker root explicitly.",why:"Implicit discovery checks the default .agents/pm layout and ancestor root-layout trackers, while custom nested roots require an explicit path.",examples:[`pm --pm-path ${nearbyRoot} <command>`,`PM_PATH=${nearbyRoot} pm <command>`],nextSteps:[`Re-run with "--pm-path ${nearbyRoot}" or export PM_PATH=${nearbyRoot}.`]}),rawMessage,context)}return applyPmCliErrorContext(makeGuidanceMessage({code:"tracker_not_initialized",title:"Tracker is not initialized",happened:`pm data path does not contain initialized tracker metadata (${trackerNotInitialized[1]}).`,required:"Select an existing tracker with --pm-path/PM_PATH, or initialize the default .agents/pm storage.",why:"Most commands require settings in an explicitly selected root, an ancestor root-layout tracker, or the default .agents/pm directory.",examples:["pm init","pm init acme"],nextSteps:['Run "pm init", then rerun your original command.']}),rawMessage,context)}function buildItemNotFoundGuidance(rawMessage,message,context){const itemNotFound=message.match(/^Item ([^ ]+) not found$/);if(!itemNotFound){return null}const badId=itemNotFound[1];const isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId);const happened=isPlaceholder?`The item ID "${badId}" looks like a placeholder or unresolved variable. Ensure the ID argument is resolved before calling pm.`:`No item with id "${badId}" exists in the active tracker scope.`;const nextSteps=isPlaceholder?["Check that the variable holding the item ID is defined before passing it to pm.",'Use "pm list --status open --limit 20" to find valid IDs.']:["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",happened,required:"Use an existing item ID from current tracker data.",why:"Mutation and read commands operate only on known IDs.",examples:["pm list --status open --limit 20",'pm search "<keyword>" --limit 10'],nextSteps}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){if(!message.includes("is assigned to")||!message.includes("Use --force to override")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"ownership_conflict",title:"Ownership conflict",happened:message,required:"Run as the assigned owner, claim the item when appropriate, or use --force only for an approved override.",why:"Ownership checks prevent accidental concurrent mutations on claimed items and protect against conflicting writes.",examples:["pm claim pm-a1b2","pm update pm-a1b2 --status in_progress --force"],nextSteps:["Use --force for approved systematic metadata updates performed by leads or maintainers.","Use --force when correcting known stale metadata after coordinating ownership changes.",'For non-terminal reassignment, prefer "pm claim <ID>" before running other mutations.']}),rawMessage,context)}function buildLockConflictGuidance(rawMessage,message,context){if(!message.includes("is locked")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, or use --force where supported if lock is stale and safe to override.",why:"Locking protects item files from concurrent write races.",examples:["pm update pm-a1b2 --status in_progress --force"]}),rawMessage,context)}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /);const missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions){return null}const plural=Boolean(missingRequiredOptions);const missingOptionFlag=!plural?message.replace(/^Missing required option\s+/,"").trim():null;const missingOptionLabel=missingOptionFlag??"";const missingOptionRequired=missingOptionFlag?`Pass ${missingOptionFlag} with a valid value before running the command.`:"Provide the required option for this command invocation.";return applyPmCliErrorContext(makeGuidanceMessage({code:"missing_required_option",title:plural?"Missing required options":`Missing required option ${missingOptionLabel}`,happened:message,required:plural?"Provide every required option for this command invocation.":missingOptionRequired,why:"Required options define command intent and enforce deterministic write contracts.",examples:['pm create --title "Task title" --description "Task details" --type Task --create-mode progressive','pm create --title "Task title" --description "Task details" --type Task --status open --priority 1 --message "Create task" --dep "id=pm-epic01,kind=parent,created_at=now" --comment "created_at=now,text=Why this task exists." --note "created_at=now,text=Initial implementation note." --learning "created_at=now,text=Durable lesson placeholder." --file "path=src/example.ts,scope=project" --test "command=node scripts/run-tests.mjs test,scope=project,timeout_seconds=240" --doc "path=README.md,scope=project"'],nextSteps:['Run "pm <command> --help" to view required and recommended flags.',"For staged triage without placeholder linkage values, use --create-mode progressive."]}),rawMessage,context)}function buildNoUpdateFieldsGuidance(rawMessage,message,context){if(!message.startsWith("No update flags provided")){return null}return applyPmCliErrorContext(makeGuidanceMessage({code:"no_update_fields",title:"No update fields supplied",happened:"The update command was called without any field-changing flags.",required:"Provide at least one field-changing flag such as --status, --priority, --title, --tags, --description, or --body. Use --message only to label a real mutation.",why:"pm update mutates existing item fields; no-op invocations are rejected to avoid ambiguous history.",examples:['pm update pm-a1b2 --status in_progress --message "Start implementation"','pm update pm-a1b2 --description "Clarified implementation scope" --message "Clarify task intent"','pm append pm-a1b2 --body "Detailed progress notes" --message "Append progress notes"'],nextSteps:["Choose the item field you intend to change, then pair that change with --message for history context.","Use pm comments, pm notes, pm learnings, or pm append when you only need to add narrative context."]}),rawMessage,context)}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!message.startsWith("Invalid ")&&!message.includes(" must be ")&&!message.includes(" requires ")){return null}const recovery=normalizeRecoveryPayload(context?.recovery);const commandName=inferCommandNameFromRecovery(recovery);const helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help";const allowedValues=inferAllowedValuesFromMessage(message);const enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues});const retryExample=buildAllowedValueRetryCommand(recovery,allowedValues);const examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"];const nextSteps=allowedValues.length>0?[`Allowed values: ${allowedValues.join("|")}`,`Run "${helpExample}" to confirm command-specific constraints.`]:["Check allowed values in command help, then rerun with corrected input."];return applyPmCliErrorContext(makeGuidanceMessage({code:"invalid_argument_value",title:"Invalid argument value",happened:message,required:"Use values that match documented command constraints.",why:"Validation protects data consistency and deterministic behavior across commands.",examples,nextSteps,recovery:enrichedRecovery}),rawMessage,context)}function buildPmCliErrorGuidance(rawMessage,context){const message=normalizeMessage(rawMessage);const guidance=buildTrackerNotInitializedGuidance(rawMessage,message,context)??buildItemNotFoundGuidance(rawMessage,message,context)??buildOwnershipConflictGuidance(rawMessage,message,context)??buildLockConflictGuidance(rawMessage,message,context)??buildPmMissingRequiredOptionGuidance(rawMessage,message,context)??buildNoUpdateFieldsGuidance(rawMessage,message,context)??buildInvalidArgumentGuidance(rawMessage,message,context);if(guidance){return guidance}return applyPmCliErrorContext(makeGuidanceMessage({code:"command_failed",title:"Command failed",happened:message,required:"Adjust command input or tracker state and retry.",why:"pm enforces explicit, deterministic contracts for data and command semantics.",examples:["pm --help","pm <command> --help"]}),rawMessage,context)}function commandExampleForRequiredOption(commandName,optionFlag,allowedTypes){if(commandName==="create"&&optionFlag.startsWith("--type")){const firstAllowed=allowedTypes.split("|")[0]||"Task";return[`pm create --title "Example title" --description "Example description" --type ${firstAllowed} --status open --priority 1 --message "Create item" --create-mode progressive`]}if(commandName==="update"){return['pm update pm-a1b2 --status in_progress --message "Start implementation"']}return[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();const firstLongFlag=normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0];return firstLongFlag??normalized}function renderPmCommandFromArgs(argv){if(!Array.isArray(argv)||argv.length===0){return void 0}return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values)){return void 0}const normalized=values.map(value=>value.trim()).filter(value=>value.length>0);return normalized.length>0?normalized:void 0}function buildCommanderRecoveryPayload(context,overrides={}){const providedFields=normalizeOptionFlags(context?.providedOptionFlags);const normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0;const attemptedCommand=typeof context?.attemptedCommand==="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs);const retryCommand=typeof context?.suggestedRetryCommand==="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,...overrides})}function appendIfMissing(entries,value){if(!value||entries.includes(value)){return entries}return[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]);const LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(!Array.isArray(argv)){return void 0}for(const token of argv){if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag)){return flag}}return void 0}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv)){return void 0}const commandIndex=argv.indexOf("test");if(commandIndex<0){return void 0}const idToken=argv[commandIndex+1];if(typeof idToken!=="string"||idToken.startsWith("-")){return void 0}for(let index=commandIndex+2;index<argv.length;index+=1){const token=argv[index];if(token!=="--add"&&token!=="--remove"){continue}const key=argv[index+1];if(typeof key!=="string"||!LINKED_TEST_RETRY_KEYS.has(key)){return void 0}const valueTokens=[];for(let cursor=index+2;cursor<argv.length;cursor+=1){const candidate=argv[cursor];if(candidate.startsWith("--")&&candidate.length>2){break}valueTokens.push(candidate)}if(valueTokens.length<2){return void 0}const merged=`${key}=${valueTokens.join(" ")}`;const rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}return void 0}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption){return null}const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]);const isType=optionFlag.startsWith("--type");const retryCommand=context?.suggestedRetryCommand;const providedFlags=normalizeOptionFlags(context?.providedOptionFlags);const missing=[optionFlag];const examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes);const examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples;const nextStepsBase=isType?[`Allowed type values: ${allowedTypes}`,`Run "pm ${commandName??"create"} --help --type <value>" for type-aware policy details.`]:[`Run "pm ${commandName??"<command>"} --help" for required option guidance.`];const nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase;const nextSteps=providedFlags&&providedFlags.length>0?appendIfMissing(nextStepsWithRetry,`Already provided options: ${providedFlags.join(", ")}`):nextStepsWithRetry;return makeGuidanceMessage({code:"missing_required_option",title:`Missing required option ${optionFlag}`,happened:`Commander rejected the command because ${optionFlag} was not provided.`,required:`Pass ${optionFlag} with a valid value before running the command.`,why:isType?"--type selects item contract and policy routing, including required/disabled option rules.":"Required flags define mandatory command intent and prevent ambiguous execution.",examples:examplesWithRetry,nextSteps,recovery:buildCommanderRecoveryPayload(context,{missing})})}function buildMissingRequiredArgumentGuidance(message,commandName,context){const missingArgument=message.match(/missing required argument '([^']+)'/);if(!missingArgument){return null}const argumentName=missingArgument[1];return makeGuidanceMessage({code:"missing_required_argument",title:`Missing required argument ${argumentName}`,happened:`Command invocation omitted positional argument ${argumentName}.`,required:`Provide ${argumentName} in the expected command position.`,why:"Positional arguments identify the target entity or action context for the command.",examples:[`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context,{missing:[argumentName]})})}function buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions){return makeGuidanceMessage({code:"unsupported_update_option",title:`Unsupported option ${optionName} for update`,happened:`pm update does not accept ${optionName} for linked artifact mutations.`,required:"Use dedicated linked-artifact commands instead of pm update for files/docs changes.",why:"pm update manages scalar item metadata, while linked files/docs are managed by pm files and pm docs.",examples:['pm files pm-a1b2 --add "path=src/cli/main.ts,scope=project,note=implementation surface"','pm docs pm-a1b2 --add "path=README.md,scope=project,note=user-facing contract"'],nextSteps:['Run "pm files --help" and "pm docs --help" for add/remove payload formats.'],recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions})})}const UNKNOWN_OPTION_REQUIRED_BY_SCOPE={declared_elsewhere:"Use an option declared on this path, or move the declared option to one of its accepting command paths.",declared_on_path:"Use the option with the value and syntax declared by this command path.",declared_nowhere:"Use a declared option on this command path; this spelling exists nowhere in the command lexicon."};function resolveUnknownOptionCandidateContext(context){const otherCommands=normalizeContextList(context.unknownOptionOtherCommands)??[];return{otherCommands,optionScope:context.unknownOptionScope??(otherCommands.length>0?"declared_elsewhere":"declared_nowhere"),candidateTotal:context.unknownOptionOtherCommandsTotal??otherCommands.length}}function buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand){const proseCommands=candidateContext.otherCommands.slice(0,3);const proseRemainder=candidateContext.candidateTotal-proseCommands.length;const proseRemainderText=proseRemainder>0?` and ${String(proseRemainder)} more command path(s)`:"";return["Run command help to confirm the exact option contracts for this command path.",suggestions.length?`Nearest supported options: ${suggestions.join(", ")}`:void 0,proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,candidateContext.optionScope==="declared_nowhere"?`${optionName} is not declared on any command path. Use a nearest supported option on ${commandName??"the attempted command"}, or inspect that command's help.`:void 0,retryCommand?`Replay with suggested correction: ${retryCommand}`:void 0].filter(entry=>typeof entry==="string")}function resolveUnknownOptionRetry(context,optionName){if(context.suggestedRetryCommand!==void 0){return{retryCommand:context.suggestedRetryCommand}}const normalizedArgs=context.normalizedInvocationArgs;if(normalizedArgs===void 0)return{};if(normalizedArgs.filter(argument=>argument===optionName||argument.startsWith(`${optionName}=`)).length!==1){return{}}const optionIndex=normalizedArgs.findIndex(argument=>argument===optionName||argument.startsWith(`${optionName}=`));if(optionIndex<0||normalizedArgs.includes("--")||!normalizedArgs[optionIndex]?.includes("=")&&optionIndex!==normalizedArgs.length-1&&normalizedArgs[optionIndex+1]?.startsWith("-")!==true){return{}}const suggestedRetryArgs=stripGlobalBootstrapTokens(normalizedArgs.filter((_,index)=>index!==optionIndex));return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function buildUnknownOptionGuidance(message,commandName,context){const unknownOption=message.match(/unknown option '([^']+)'/);if(!unknownOption){return null}const guidanceContext=context??{};const optionName=unknownOption[1];const suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[];const{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc")){return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions)}const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext);const nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${resolvePmCommandAlias(commandPath)?.canonical??commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);if((context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args){return[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join("\n")}return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
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]="2e3d63ed-ae76-5027-af01-066f60e8070a")}catch(e2){}})();import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{projectPmDiagnosticOutput,projectPmDiagnosticText}from"../sdk/cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./argv-utils.js";import{discoverNearbyPmRoot}from"../sdk/tracker-root-discovery.js";import{stripGlobalBootstrapTokens}from"../sdk/cli-bootstrap.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";function projectLeanErrorEnvelope(envelope){const{why:_why,title:_title,...actionable}=envelope;return actionable}const STRUCTURED_WHY_SUPPRESSION_CODES=new Set(["unknown_command","unknown_option","missing_required_option","missing_required_argument","invalid_argument_value","invalid_command_usage","command_failed"]);function includeWhyInStructuredGuidance(message){if(!message.why){return false}if(message.recovery?.recovery_mode==="compact"){return false}return!STRUCTURED_WHY_SUPPRESSION_CODES.has(message.code)}function errorType(code){return`urn:pm-cli:error:${code}`}function makeGuidanceMessage(params){return{...params,type:errorType(params.code)}}const GUIDE_SHELL_HINT={packageName:"@unbrained/pm-guide-shell",installCommand:"pm install guide-shell"};const CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"};const SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"};const GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"};const KNOWN_PACKAGE_COMMAND_HINTS={guide:GUIDE_SHELL_HINT,shell:GUIDE_SHELL_HINT,completion:GUIDE_SHELL_HINT,"completion-statuses":GUIDE_SHELL_HINT,"completion-tags":GUIDE_SHELL_HINT,"completion-types":GUIDE_SHELL_HINT,templates:{packageName:"@unbrained/pm-templates",installCommand:"pm install templates"},calendar:CALENDAR_HINT,cal:CALENDAR_HINT,reindex:SEARCH_ADVANCED_HINT,"search-advanced":SEARCH_ADVANCED_HINT,"test-runs":{packageName:"@unbrained/pm-linked-test-adapters",installCommand:"pm install linked-test-adapters"},"comments-audit":GOVERNANCE_AUDIT_HINT,"dedupe-audit":GOVERNANCE_AUDIT_HINT,"dedupe-merge":GOVERNANCE_AUDIT_HINT,normalize:GOVERNANCE_AUDIT_HINT};function resolveKnownPackageCommandHint(commandToken){const primary=commandToken.trim().split(/\s+/)[0]?.toLowerCase();if(!primary){return void 0}return KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){if(entries.length===0){return[]}return[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values)){return void 0}const normalized=values.filter(entry=>typeof entry==="string").map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length>0?normalized:void 0}function normalizeRecoveryCandidates(candidates){if(!Array.isArray(candidates)){return void 0}const normalized=candidates.map(entry=>({source:typeof entry?.source==="string"?entry.source.trim():"",command:typeof entry?.command==="string"?entry.command.trim():"",reason:typeof entry?.reason==="string"?entry.reason.trim():""})).filter(entry=>entry.source.length>0&&entry.command.length>0&&entry.reason.length>0);return normalized.length>0?normalized:void 0}function assignRecoveryString(normalized,key,value){if(typeof value==="string"&&value.trim().length>0){normalized[key]=value.trim()}}function assignRecoveryCollection(normalized,key,value){if(key==="parsed_positionals"){if(!Array.isArray(value))return;const parsedPositionals=value.map(entry=>({role:typeof entry?.role==="string"?entry.role.trim():"",value:typeof entry?.value==="string"?entry.value.trim():""})).filter(entry=>entry.role.length>0&&entry.value.length>0);if(parsedPositionals.length>0){normalized.parsed_positionals=parsedPositionals}return}const values=normalizeStringArray(value);if(values){normalized[key]=values}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!=="object"){return void 0}const normalized={};if(payload.recovery_mode==="compact"){normalized.recovery_mode="compact"}assignRecoveryString(normalized,"attempted_command",payload.attempted_command);assignRecoveryCollection(normalized,"normalized_args",payload.normalized_args);assignRecoveryCollection(normalized,"parsed_positionals",payload.parsed_positionals);assignRecoveryCollection(normalized,"provided_fields",payload.provided_fields);assignRecoveryCollection(normalized,"missing",payload.missing);assignRecoveryCollection(normalized,"missing_required_fields",payload.missing_required_fields);assignRecoveryCollection(normalized,"suggested_flags",payload.suggested_flags);assignRecoveryCollection(normalized,"allowed_values",payload.allowed_values);assignRecoveryCollection(normalized,"candidate_commands",payload.candidate_commands);if(typeof payload.candidate_commands_total==="number"&&Number.isSafeInteger(payload.candidate_commands_total)&&payload.candidate_commands_total>=0){normalized.candidate_commands_total=payload.candidate_commands_total}if(payload.candidate_commands_truncated===true){normalized.candidate_commands_truncated=true}if(payload.option_scope==="declared_on_path"||payload.option_scope==="declared_elsewhere"||payload.option_scope==="declared_nowhere"){normalized.option_scope=payload.option_scope}assignRecoveryString(normalized,"suggested_retry",payload.suggested_retry);assignRecoveryCollection(normalized,"suggested_retry_args",payload.suggested_retry_args);if(typeof payload.retry_after_ms==="number"&&Number.isSafeInteger(payload.retry_after_ms)&&payload.retry_after_ms>=0){normalized.retry_after_ms=payload.retry_after_ms}const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);if(fallbackCandidates){normalized.fallback_candidates=fallbackCandidates}assignRecoveryString(normalized,"next_best_command",payload.next_best_command);return Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){if(value){lines.push(` ${label}: ${value}`)}}function appendRecoveryListLine(lines,label,values,separator){if(values&&values.length>0){lines.push(` ${label}: ${values.join(separator)}`)}}function renderRecoveryBundle(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized){return[]}const lines=["Recovery bundle:"];appendRecoveryTextLine(lines,"suggested_retry",normalized.suggested_retry);appendRecoveryTextLine(lines,"attempted_command",normalized.attempted_command);appendRecoveryListLine(lines,"normalized_args",normalized.attempted_command?void 0:normalized.normalized_args," ");if(normalized.parsed_positionals&&normalized.parsed_positionals.length>0){lines.push(" parsed_positionals:");for(const positional of normalized.parsed_positionals){lines.push(` - ${positional.role}: ${positional.value}`)}}appendRecoveryListLine(lines,"provided_fields",normalized.provided_fields,", ");appendRecoveryListLine(lines,"missing",normalized.missing,", ");appendRecoveryListLine(lines,"missing_required_fields",normalized.missing_required_fields,", ");appendRecoveryListLine(lines,"suggested_flags",normalized.suggested_flags,", ");appendRecoveryListLine(lines,"allowed_values",normalized.allowed_values,", ");appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", ");if(typeof normalized.candidate_commands_total==="number"){lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`)}if(normalized.candidate_commands_truncated===true){lines.push(" candidate_commands_truncated: true")}if(normalized.option_scope!==void 0){lines.push(` option_scope: ${normalized.option_scope}`)}if(typeof normalized.retry_after_ms==="number"){lines.push(` retry_after_ms: ${normalized.retry_after_ms}`)}appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command);if(normalized.fallback_candidates&&normalized.fallback_candidates.length>0){lines.push(" fallback_candidates:");for(const candidate of normalized.fallback_candidates){lines.push(` - ${candidate.source}: ${candidate.command} (${candidate.reason})`)}}return lines}function renderGuidanceMessage(message){const lines=[`Error: ${message.title}`,"","What is required:",` ${message.required}`];if(message.nextSteps&&message.nextSteps.length>0){lines.push("");lines.push(...renderList("Next steps:",message.nextSteps))}lines.push("","What happened:",` ${message.happened}`);if(message.why){lines.push("","Why:");lines.push(` ${message.why}`)}if(message.examples&&message.examples.length>0){lines.push("");lines.push(...renderList("Examples:",message.examples))}if(message.verificationErrors&&message.verificationErrors.length>0){lines.push("");lines.push(...renderList("Verification errors:",message.verificationErrors))}const recoveryLines=renderRecoveryBundle(message.recovery);if(recoveryLines.length>0){lines.push("");lines.push(...recoveryLines)}return lines.join("\n")}function attachStructuredGuidanceDetails(payload,message){if(message.tombstone!==void 0){payload.tombstone=message.tombstone;payload.item_id=message.itemId}if(includeWhyInStructuredGuidance(message)){payload.why=message.why}if(message.examples&&message.examples.length>0){payload.examples=message.examples}if(message.nextSteps&&message.nextSteps.length>0){payload.next_steps=message.nextSteps}if(message.verificationErrors&&message.verificationErrors.length>0){payload.verification_errors=message.verificationErrors}if(message.flag!==void 0)payload.flag=message.flag;if(message.value!==void 0)payload.value=message.value;if(message.unmatchedSelectors!==void 0)payload.unmatched_selectors=message.unmatchedSelectors;if(message.availableDependencies!==void 0)payload.available_dependencies=message.availableDependencies;if(message.recovery){payload.recovery=message.recovery}return payload}function resolveRefusalCandidateFlag(message,normalizedArgs){if(message.flag)return message.flag;const isAdmissibleCandidate=flag=>{const canonicalFlag=flag.split("=",1)[0];return stripGlobalBootstrapTokens([canonicalFlag]).length>0&&!["--help","--no-changed-fields","--version"].includes(canonicalFlag)&&normalizedArgs.some(argument=>argument===canonicalFlag||argument.startsWith(`${canonicalFlag}=`))};const mentionedFlag=[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag));if(mentionedFlag)return mentionedFlag;return message.recovery?.provided_fields?.map(field=>field.split("=",1)[0]).find(field=>isAdmissibleCandidate(field))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(candidateFlag){const candidateArgument=normalizedArgs.find(argument=>argument===candidateFlag||argument.startsWith(`${candidateFlag}=`));if(candidateArgument?.startsWith(`${candidateFlag}=`)){return candidateArgument.slice(candidateFlag.length+1)}const candidateIndex=normalizedArgs.indexOf(candidateFlag);return candidateIndex>=0?normalizedArgs[candidateIndex+1]:void 0}const allowedValues=message.recovery?.allowed_values;if(!allowedValues?.length)return void 0;return normalizedArgs.find((argument,index)=>index>0&&!argument.startsWith("-")&&!allowedValues.includes(argument))}function buildRefusalEnvelope(message,exitCode){if(message.policyViolations?.length){return{surface:`policy:${message.policyViolations.map(policy=>policy.policy_id).join(",")}`,policies:message.policyViolations,policy_violation_count:message.policyViolationCount,missing_fields:[...new Set(message.policyViolations.flatMap(policy=>policy.missing_fields))],exit_code:exitCode}}const invocationArgs=stripGlobalBootstrapTokens(message.recovery?.normalized_args??[]);const namespaced=findPmNamespacedCommand(invocationArgs);const normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs;const candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs);const rejectedValue=resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag);return{surface:candidateFlag??message.recovery?.missing?.[0]??resolveRecoveryCommandName(normalizedArgs)??"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,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,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(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0])){return{}}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);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0])){nextSteps.push("The requested preview is unavailable on this path. Inspect the item with a read-only command or use a command that declares this option; do not replay this mutation without preview intent.")}const examples=[retryCommand,`pm ${commandName?resolvePmCommandAlias(commandName)?.canonical??commandName:"<command>"} --help`].filter(entry=>typeof entry==="string");return makeGuidanceMessage({code:"unknown_option",title:`Unknown option ${optionName}`,happened:`Commander does not recognize option ${optionName} for this command path.`,required:UNKNOWN_OPTION_REQUIRED_BY_SCOPE[candidateContext.optionScope],why:"Option contracts are command-specific and intentionally validated.",flag:optionName,value:optionName,examples,nextSteps,recovery:buildCommanderRecoveryPayload(context,{suggested_flags:suggestions.length>0?suggestions:void 0,suggested_retry:retryCommand,suggested_retry_args:suggestedRetryArgs,candidate_commands:candidateContext.otherCommands,candidate_commands_total:candidateContext.candidateTotal||void 0,candidate_commands_truncated:guidanceContext.unknownOptionOtherCommandsTruncated,option_scope:candidateContext.optionScope})})}function buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context){const installStep=`"${commandToken}" is provided by the ${packageHint.packageName} package. Install it with: ${packageHint.installCommand}`;const nextSteps=baseNextSteps.filter(step=>!step.endsWith(`: ${packageHint.installCommand}`));return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration. It is shipped by the optional ${packageHint.packageName} package.`,required:`Install the ${packageHint.packageName} package, or use a valid command name or subcommand path.`,why:"Command registry includes core commands plus active extension command handlers; package-provided commands appear only after the package is installed.",examples:dedupeStrings([packageHint.installCommand,...baseExamples]),nextSteps:dedupeStrings([installStep,...nextSteps]),recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownCommandGuidance(message,context){const unknownCommand=message.match(/unknown command '([^']+)'/);if(!unknownCommand){return null}const commandToken=unknownCommand[1];const runtimeExamples=normalizeContextList(context?.unknownCommandExamples);const runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps);const packageHint=resolveKnownPackageCommandHint(commandToken);const baseExamples=runtimeExamples??["pm --help"];const baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."];const failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase()));const hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();if(packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))){return buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context)}return makeGuidanceMessage({code:"unknown_command",title:`Unknown command ${commandToken}`,happened:`pm does not expose command path "${commandToken}" in current runtime configuration.`,required:"Use a valid command name or subcommand path.",why:"Command registry includes core commands plus active extension command handlers.",examples:baseExamples,nextSteps:baseNextSteps,recovery:buildCommanderRecoveryPayload(context)})}function buildUnknownSubcommandGuidance(context){const commandPath=context?.unknownSubcommandPath?.trim();const token=context?.unknownSubcommandToken?.trim();const allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed){return null}const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,happened:`The positional token sequence "${token}" is not a declared ${commandPath} subcommand.`,required:`Use one of: ${allowed.join(", ")}.`,why:"Subcommands are single positional tokens; multi-word action names use hyphens.",examples:[...retryCommand?[retryCommand]:[],`pm ${resolvePmCommandAlias(commandPath)?.canonical??commandPath} --help`],nextSteps:retryCommand?[`Retry with the declared hyphenated action: ${retryCommand}`]:["Choose one value from recovery.allowed_values."],recovery:buildCommanderRecoveryPayload(context,{allowed_values:allowed,suggested_retry:retryCommand})})}function buildLinkedTestValueNotQuotedGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||commandName!=="test"){return null}const argv=context?.normalizedInvocationArgs;const mutationFlag=findLinkedTestMutationFlag(argv);if(!mutationFlag){return null}const retryCommand=buildLinkedTestQuotedRetryCommand(argv);return makeGuidanceMessage({code:"linked_test_value_not_quoted",title:`Linked-test ${mutationFlag} value must be one argument`,happened:`Commander saw extra positional tokens after the item id \u2014 usually a ${mutationFlag} value containing spaces (for example a command with " -- ") that the shell split into multiple tokens.`,required:`Quote the whole ${mutationFlag} value as a single argument. Accepted forms: --add "command=npm test -- parser", --add command "npm test -- parser" (two-token form with the value quoted), or --add-json for complex commands.`,why:"The shell splits unquoted values before pm can see them, so pm cannot reassemble the intended command unambiguously.",examples:[...retryCommand?[retryCommand]:[],'pm test pm-a1b2 --add "command=npm test -- parser"','pm test pm-a1b2 --add command "npm test -- parser"',`pm test pm-a1b2 --add-json '{"command":"npm test -- parser"}'`],nextSteps:[...retryCommand?[`Replay with the value re-joined into one argument: ${retryCommand}`]:[],"Prefer --add-json for commands containing commas, equals signs, or quotes.",'Run "pm test --help" for linked-test entry contracts.'],recovery:buildCommanderRecoveryPayload(context,retryCommand?{suggested_retry:retryCommand}:{})})}const TRANSPOSED_COLLECTION_COMMANDS=new Set(["comments","docs","files","learnings","notes","test"]);function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>token===commandName);const action=argv[commandIndex+1];const parsedItemId=argv[commandIndex+2];const itemId=context?.verifiedCollectionItemId?.trim();if(action?.toLowerCase()!=="add"||!parsedItemId||parsedItemId.startsWith("-")||!itemId||itemId.toLowerCase()!==parsedItemId.toLowerCase()){return null}const suggestedRetry=`pm ${commandName} ${itemId} --add <value>`;return makeGuidanceMessage({code:"collection_transposed_subcommand",title:`Transposed ${commandName} add syntax`,happened:`The positional token "add" occupied the item-id role and "${itemId}" occupied the next positional role. pm ${commandName} does not use an add subcommand.`,required:`Place the item id immediately after ${commandName}, then use --add for the value.`,why:"Collection mutations use object-first grammar: pm <collection> <item-id> --add <value>.",examples:[suggestedRetry,`pm ${commandName} --help`],recovery:buildCommanderRecoveryPayload(context,{parsed_positionals:[{role:"transposed_subcommand",value:action},{role:"item_id",value:itemId}],suggested_retry:suggestedRetry})})}const CONTEXT_GUIDANCE_VALUE_FLAGS=new Set(["--activity-limit","--assignee","--assignee-filter","--date","--depth","--fields","--format","--from","--limit","--parent","--path","--pm-path","--priority","--release","--section","--sprint","--stale-threshold","--tag","--to","--type"]);const CONTEXT_GUIDANCE_COMMAND_NAMES=new Set(["context","ctx"]);function buildContextItemArgumentGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!CONTEXT_GUIDANCE_COMMAND_NAMES.has(commandName??"")){return null}const argv=context?.normalizedInvocationArgs??[];const commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token));const searchIndex=commandIndex===-1?1:commandIndex+1;const match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=false;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=false;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(token.startsWith("-")){continue}positional=token;break}}if(!positional){return null}const getCommand=`pm get ${positional}`;return makeGuidanceMessage({code:"context_takes_no_item_argument",title:"pm context takes no item argument",happened:`pm context renders a workspace-level snapshot and received the positional argument "${positional}".`,required:`Use ${getCommand} for one item's full details, or pm context --parent ${positional} to scope the snapshot to that item's subtree.`,why:"Item-level detail (pm get) and workspace-level context (pm context) are separate projections.",examples:[getCommand,`pm context --parent ${positional}`],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:getCommand})})}function buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context){const message=normalizeMessage(rawMessage);const guidance=buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context)??buildMissingRequiredArgumentGuidance(message,commandName,context)??buildUnknownOptionGuidance(message,commandName,context)??buildUnknownCommandGuidance(message,context)??buildUnknownSubcommandGuidance(context)??buildTransposedCollectionActionGuidance(message,commandName,context)??buildLinkedTestValueNotQuotedGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context);if(guidance){return guidance}return makeGuidanceMessage({code:"invalid_command_usage",title:"Invalid command usage",happened:message,required:"Use the command with valid arguments and options.",why:"Commander validates CLI contracts before execution.",examples:["pm --help",`pm ${commandName??"<command>"} --help`],recovery:buildCommanderRecoveryPayload(context)})}function formatPmCliErrorForDisplay(rawMessage,context){const guidance=buildPmCliErrorGuidance(rawMessage,context);if((context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args){return[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join("\n")}return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyPmCliError(rawMessage,context){return guidanceToClassification(buildPmCliErrorGuidance(rawMessage,context))}function formatPmCliErrorForJson(rawMessage,exitCode,context){return projectJsonErrorGuidance(buildPmCliErrorGuidance(rawMessage,context),exitCode)}function formatCommanderErrorForDisplay(rawMessage,commandName,allowedTypes,context){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return projectPmDiagnosticText(renderGuidanceMessage(guidance),guidance.required).output}function classifyCommanderError(rawMessage,commandName,allowedTypes,context){return guidanceToClassification(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context))}function formatCommanderErrorForJson(rawMessage,commandName,allowedTypes,exitCode,context){return projectJsonErrorGuidance(buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context),exitCode)}function formatUnknownErrorForJson(rawMessage,exitCode){const guidance=buildUnknownErrorGuidance(rawMessage);return projectJsonErrorGuidance(guidance,exitCode)}function buildUnknownErrorGuidance(rawMessage){const message=normalizeMessage(rawMessage);if(isModuleResolutionErrorMessage(message)){return makeGuidanceMessage({code:"module_import_failed",title:"Module import failed",happened:message,required:"Ensure the active checkout is built and any package or extension entry file exists before retrying.",why:"Node could not resolve an imported module. In pm this usually means an extension/package entrypoint, build artifact, or dependency is missing from the active runtime.",examples:["pnpm build","pm package manage --doctor --project","pm health --check-only --json"],nextSteps:["Rebuild the checkout or package that provides the missing module.","Run package doctor for installed extensions when the failure follows package installation or activation.","Rerun the original pm command after the runtime files are present."]})}return makeGuidanceMessage({code:"unknown_error",title:"Unhandled error",happened:message,required:"Inspect command input and runtime state, then retry.",why:"Unexpected runtime failures can occur from environment or extension-level issues.",examples:["pm --help","pm health --json"]})}function classifyUnknownError(rawMessage){return guidanceToClassification(buildUnknownErrorGuidance(rawMessage))}const _testOnly={applyPmCliErrorContext,appendIfMissing,buildCommanderRecoveryPayload,buildFallbackTitleFromMessage,commandExampleForRequiredOption,dedupeStrings,guidanceToClassification,guidanceToJsonEnvelope,normalizeRecoveryPayload,renderList,resolveKnownPackageCommandHint};export{_testOnly,buildLinkedTestQuotedRetryCommand,classifyCommanderError,classifyPmCliError,classifyUnknownError,formatCommanderErrorForDisplay,formatCommanderErrorForJson,formatPmCliErrorForDisplay,formatPmCliErrorForJson,formatUnknownErrorForJson,projectLeanErrorEnvelope,renderGuidanceMessage};
2
2
  //# sourceMappingURL=error-guidance.js.map
@@ -1,5 +1,5 @@
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]="a0e4b3f7-ace2-5190-8e60-83d67109e95d")}catch(e2){}})();import{hasSubcommandFlagContractsForCommand,PM_COMMAND_ALIAS_CONTRACTS,PM_CORE_COMMAND_NAMES,resolvePmCommandOperation}from"../sdk/cli-contracts.js";import{commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveTypeDefinition,EXIT_CODE,writeStderr,writeStdout}from"../sdk/runtime-primitives.js";import{buildDynamicExtensionHelpOptionSummaries,mergeHelpOptionSummaries,findCommandByPath,findDirectChildCommand,commandAliases}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier,isFullHelpDiscovery,normalizeHelpCommandPath,resolveHelpBundleForPath,resolveHelpDetailMode,resolveHelpNarrative,ROOT_HELP_BUNDLE}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapCommandName,parseBootstrapTypeValue}from"./bootstrap-args.js";import{extractProvidedOptionFlags,renderPmCommand}from"./argv-utils.js";import{formatCommanderErrorForJson}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES,buildUnknownCommandGuidanceFromRuntime,isKnownHelpCommandPath}from"./commander-usage.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip,PM_POSITIONAL_ACTION_CONTRACTS,resolvePmPositionalActionContract}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"../sdk/agent-capability-contracts.js";const EXTENSION_TIER_ORDER={core:0,standard:1,full:2,internal:3};function resolveExtensionCommandSurface(commandPath,descriptors,allowDescendants=true){const exact=descriptors.get(resolvePmCommandOperation(commandPath));if(exact)return exact;if(!allowDescendants)return void 0;const descendants=[...descriptors.entries()].filter(([path])=>path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);if(descendants.length===0)return void 0;const tier=descendants.reduce((selected,descriptor)=>EXTENSION_TIER_ORDER[descriptor.tier]<EXTENSION_TIER_ORDER[selected]?descriptor.tier:selected,"internal");const families=new Set(descendants.map(({family})=>family));return{tier,family:families.size===1?descendants[0].family:"extensions"}}function resolveCommandFromPathTokens(root,pathTokens){if(pathTokens.length===0){return root}const exactCommand=findCommandByPath(root,pathTokens);if(exactCommand){return exactCommand}const requestedPath=pathTokens.join(" ");if(resolvePmCommandOperation(requestedPath)!==requestedPath)return null;if(!PM_CORE_COMMAND_NAMES.some(commandName=>commandName===requestedPath)&&!hasSubcommandFlagContractsForCommand(requestedPath)&&!resolvePmPositionalActionContract(requestedPath)&&!isKnownHelpCommandPath(root,pathTokens)){return null}for(let length=pathTokens.length-1;length>0;length-=1){const positionalParent=findCommandByPath(root,pathTokens.slice(0,length));if(positionalParent){return positionalParent}}return pathTokens.length===1?root:null}function extractOptionValueName(flags){const match=flags.match(/[<[]([^>\]]+)[>\]]/);if(!match){return null}const value=match[1]?.trim();return value&&value.length>0?value:null}function readOptionAttributeName(option){const optionRecord=option;if(typeof optionRecord.attributeName==="function"){const value=optionRecord.attributeName();return typeof value==="string"&&value.trim().length>0?value.trim():null}if(typeof optionRecord.attributeName==="string"&&optionRecord.attributeName.trim().length>0){return optionRecord.attributeName.trim()}return null}function buildOptionAliasMap(options){const aliasMap=new Map;for(const option of options){const optionRecord=option;const attributeName=readOptionAttributeName(option);if(!attributeName||typeof optionRecord.long!=="string"||optionRecord.long.trim().length===0){continue}const existing=aliasMap.get(attributeName)??[];existing.push(optionRecord.long.trim());aliasMap.set(attributeName,existing)}for(const[attributeName,values]of aliasMap.entries()){aliasMap.set(attributeName,[...new Set(values.map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right)))}return aliasMap}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function buildHelpOptionSummaries(command){const options=command.options??[];const optionAliasMap=buildOptionAliasMap(options);return options.map(option=>{const optionRecord=option;const flags=typeof optionRecord.flags==="string"?optionRecord.flags.trim():"";const description=typeof optionRecord.description==="string"?optionRecord.description.trim():"";const attributeName=readOptionAttributeName(option);const aliasCandidates=attributeName?optionAliasMap.get(attributeName)??[]:[];const aliases=aliasCandidates.filter(entry=>entry!==optionRecord.long).map(entry=>entry.trim()).filter(entry=>entry.length>0);const aliasForMatch=description.match(/^Alias for ([^ ]+)/i);const aliasFor=aliasForMatch&&aliasForMatch[1]?aliasForMatch[1].trim():null;const required=optionRecord.mandatory===true||description.includes("[required]")||description.toLowerCase().includes("required;");const valueRequired=flags.includes("<");const takesValue=valueRequired||flags.includes("[");const summary={flags,long:typeof optionRecord.long==="string"?optionRecord.long:null,short:typeof optionRecord.short==="string"?optionRecord.short:null,description,takes_value:takesValue,value_required:valueRequired,value_name:extractOptionValueName(flags),variadic:optionRecord.variadic===true,required,aliases,alias_for:aliasFor};if(optionRecord.defaultValue!==void 0){summary.default_value=optionRecord.defaultValue}return summary})}function compactHelpOptionAliases(options){const canonicalByLong=new Map;const aliasOptions=[];for(const option of options){if(option.alias_for&&option.long){aliasOptions.push(option);continue}if(option.long){canonicalByLong.set(option.long,option)}}for(const aliasOption of aliasOptions){const aliasFor=aliasOption.alias_for;const canonical=canonicalByLong.get(aliasFor);if(!canonical){continue}const aliasLong=aliasOption.long;const aliases=new Set([...canonical.aliases??[],aliasLong]);canonical.aliases=[...aliases].sort((left,right)=>left.localeCompare(right))}return options.filter(option=>{if(!option.alias_for||!option.long){return true}return!canonicalByLong.has(option.alias_for)})}function buildHelpArgumentSummaries(command){const commandRecord=command;const argumentsList=Array.isArray(commandRecord.registeredArguments)?commandRecord.registeredArguments:Array.isArray(commandRecord._args)?commandRecord._args:[];return argumentsList.map(argument=>{const rawName=typeof argument.name==="function"?argument.name():typeof argument.name==="string"?argument.name:"argument";const description=typeof argument.description==="string"&&argument.description.trim().length>0?argument.description.trim():null;return{name:rawName.trim(),required:argument.required===true||description?.toLowerCase().startsWith("required;")===true,variadic:argument.variadic===true,description}})}function buildHelpSubcommandSummaries(command,extensionDescriptors=new Map,includeAll=false){const visible=command.createHelp().visibleCommands(command);const candidates=includeAll?[...new Set([...visible,...command.commands])]:visible;return candidates.filter(entry=>entry.name()!=="help"||command.parent===null).filter(entry=>!includeAll||(getPmCommandHelpVisibilityTier(entry)??resolvePmCommandVisibilityTier(entry.name()))!=="internal").map(entry=>{const commandPath=normalizeHelpCommandPath(getCommandPath(entry));const rootCommand=commandPath;const declaredTier=getPmCommandHelpVisibilityTier(entry);const extensionDescriptor=resolveExtensionCommandSurface(commandPath,extensionDescriptors,declaredTier!==void 0);const aliasContract=PM_COMMAND_ALIAS_CONTRACTS.find(({alias})=>alias===commandPath);return{name:entry.name().trim(),aliases:commandAliases(entry),description:entry.description().trim(),tier:extensionDescriptor?.tier??declaredTier??resolvePmCommandVisibilityTier(rootCommand),family:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommand),...aliasContract?{alias_for:aliasContract.canonical,alias_lifecycle:aliasContract.lifecycle,...aliasContract.lifecycle==="deprecated"?{deprecated:true}:{}}:{}}}).sort((left,right)=>left.name.localeCompare(right.name))}function buildJsonHelpNarrative(detailMode,fallbackNarrative,extensionDescriptor){if(!extensionDescriptor){return fallbackNarrative}const extensionExamples=extensionDescriptor.examples??[];const extensionFailureHints=extensionDescriptor.failure_hints??[];return{intent:extensionDescriptor.intent??extensionDescriptor.description??fallbackNarrative.intent,examples:detailMode==="detailed"?extensionExamples.length>0?[...extensionExamples]:[...fallbackNarrative.examples]:extensionExamples.length>0?[extensionExamples[0]]:[...fallbackNarrative.examples],tips:detailMode==="detailed"?extensionFailureHints.length>0?[...extensionFailureHints]:[...fallbackNarrative.tips]:[],detail_mode:detailMode}}function resolveJsonHelpNarrative(commandPath,commandDescription,detailMode,extensionDescriptor,hasPositionalAction){const isRootFallback=commandPath!==void 0&&resolveHelpBundleForPath(commandPath)===ROOT_HELP_BUNDLE;const fallback=isRootFallback?{intent:commandDescription,examples:[`pm ${commandPath} --help`],tips:[],detail_mode:detailMode}:resolveHelpNarrative(commandPath,detailMode);const intentSource=hasPositionalAction?"positional_action":extensionDescriptor?.intent||extensionDescriptor?.description?"extension":isRootFallback?commandDescription?"command_description":"unavailable":commandPath?"help_bundle":"root_help_bundle";return{narrative:buildJsonHelpNarrative(detailMode,fallback,extensionDescriptor),intentSource}}function resolveJsonHelpVisibilityTier(rootCommandPath,extensionDescriptor){if(rootCommandPath===void 0)return null;return extensionDescriptor?.tier??resolvePmCommandVisibilityTier(rootCommandPath)}function resolveJsonHelpCapabilityFamily(rootCommandPath,extensionDescriptor){if(rootCommandPath===void 0)return null;return extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommandPath)}function projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery){if(targetCommand!==rootProgram||!fullDiscovery)return void 0;return PM_COMMAND_ALIAS_CONTRACTS.map(contract=>({alias:contract.alias,canonical:contract.canonical,canonical_argv:[...contract.canonical_argv],lifecycle:contract.lifecycle,hidden:contract.hidden,deprecated:contract.lifecycle==="deprecated"}))}function buildPositionalActionHelpProjection(action,targetCommand,resolvedPath,allOptions,extensionDescriptors=new Map,includeAll=false){if(!action){const argumentsList=buildHelpArgumentSummaries(targetCommand);const registeredSubcommands=buildHelpSubcommandSummaries(targetCommand,extensionDescriptors,includeAll);const registeredSubcommandNames=new Set(registeredSubcommands.map(({name})=>name));return{arguments:argumentsList,options:allOptions,subcommands:[...registeredSubcommands,...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent,action:name})=>parent===resolvedPath&&!registeredSubcommandNames.has(name)).map(({action:name,description})=>({name,aliases:[],description,tier:resolvePmCommandVisibilityTier(resolvedPath.split(" ")[0]),family:resolvePmCommandCapabilityFamily(resolvedPath.split(" ")[0])}))].sort((left,right)=>left.name.localeCompare(right.name)),usage:[resolvedPath,argumentsList.reduce((usage,argument)=>argument.required?usage.replace(`[${argument.name}${argument.variadic?"...":""}]`,`<${argument.name}${argument.variadic?"...":""}>`):usage,targetCommand.usage())].filter(token=>token.length>0).join(" ")}}const acceptedFlags=new Set(action.accepted_flags);return{arguments:action.slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>({name,required,variadic,description:polymorphic?`Polymorphic ${valueKind} value; inspect the action contract before mutation.`:`${valueKind.replaceAll("_"," ")} value.`})),options:allOptions.filter(({long,aliases})=>long!==null&&acceptedFlags.has(long)||aliases.some(alias=>acceptedFlags.has(alias))),subcommands:[],usage:[action.command,...action.slots.map(({name,required,variadic})=>{const token=variadic?`${name}...`:name;return required?`<${token}>`:`[${token}]`})].join(" ")}}function buildJsonHelpPayload(rootProgram,targetCommand,argv,requestedPath,extensionDescriptors){const detailMode=resolveHelpDetailMode(argv);const fullDiscovery=isFullHelpDiscovery(argv);const commanderPath=normalizeHelpCommandPath(getCommandPath(targetCommand));const requestedCommandPath=normalizeHelpCommandPath(requestedPath.join(" "));const resolvedPath=requestedCommandPath.length>commanderPath.length?requestedCommandPath:commanderPath;const positionalAction=resolvePmPositionalActionContract(resolvedPath);const projectedPath=positionalAction?.command??commanderPath;const commandPath=projectedPath.length>0?projectedPath:void 0;const rootCommandPath=commandPath;const extensionDescriptor=commandPath?extensionDescriptors.get(resolvePmCommandOperation(commandPath)):void 0;const extensionSurface=commandPath?resolveExtensionCommandSurface(commandPath,extensionDescriptors,getPmCommandHelpVisibilityTier(targetCommand)!==void 0):void 0;const{narrative,intentSource}=resolveJsonHelpNarrative(commandPath,targetCommand.description().trim(),detailMode,extensionDescriptor,positionalAction!==void 0);const allOptionSummaries=compactHelpOptionAliases(mergeHelpOptionSummaries(buildHelpOptionSummaries(targetCommand),buildDynamicExtensionHelpOptionSummaries(extensionDescriptor)));const projection=buildPositionalActionHelpProjection(positionalAction,targetCommand,projectedPath,allOptionSummaries,extensionDescriptors,fullDiscovery);const fullCommandAliases=projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery);return{format:"pm_help_v1",detail_mode:detailMode,root_command:rootProgram.name(),requested_path:requestedPath,resolved_path:projectedPath.length>0?projectedPath:rootProgram.name(),visibility_tier:resolveJsonHelpVisibilityTier(rootCommandPath,extensionSurface),capability_family:resolveJsonHelpCapabilityFamily(rootCommandPath,extensionSurface),description:positionalAction?.description??targetCommand.description(),usage:projection.usage,intent:positionalAction?.description??narrative.intent,intent_source:intentSource,examples:positionalAction?[positionalAction.example]:narrative.examples,tips:positionalAction?[formatPmPositionalActionFlagTip(positionalAction.accepted_flags)]:narrative.tips,arguments:projection.arguments,options:projection.options,subcommands:projection.subcommands,has_subcommands:projection.subcommands.length>0,...fullCommandAliases===void 0?{}:{command_aliases:fullCommandAliases}}}async function maybeRenderBootstrapJsonHelp(rootProgram,argv,extensionDescriptors,requestedArgv=argv){const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!bootstrapGlobal.json){return false}const helpRequest=parseBootstrapHelpRequest(argv);if(!helpRequest.requested){return false}const targetCommand=resolveCommandFromPathTokens(rootProgram,helpRequest.commandPathTokens);if(!targetCommand){if(!bootstrapGlobal.quiet){const unknownMessage=`unknown command '${resolvePmCommandOperation(helpRequest.commandPathTokens.join(" "))}'`;const runtimeContext=buildUnknownCommandGuidanceFromRuntime(unknownMessage,rootProgram,extensionDescriptors);const envelope=formatCommanderErrorForJson(unknownMessage,"help",BUILTIN_TYPE_HELP_VALUES,EXIT_CODE.USAGE,{...runtimeContext,attemptedCommand:renderAttemptedCommand(argv),normalizedInvocationArgs:[...argv],providedOptionFlags:extractProvidedOptionFlags(argv)});const output=bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(envelope,value=>`${JSON.stringify(value,null,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]="6fa59b21-fcd4-5056-ae4c-379d57bb7757")}catch(e2){}})();import{hasSubcommandFlagContractsForCommand,PM_COMMAND_ALIAS_CONTRACTS,PM_CORE_COMMAND_NAMES,resolvePmCommandAlias,resolvePmCommandOperation}from"../sdk/cli-contracts.js";import{commandOptionFlagLabel,resolveCommandOptionPolicyState,resolveTypeDefinition,EXIT_CODE,writeStderr,writeStdout}from"../sdk/runtime-primitives.js";import{buildDynamicExtensionHelpOptionSummaries,mergeHelpOptionSummaries,findCommandByPath,findDirectChildCommand,commandAliases}from"./extension-command-help.js";import{getPmCommandHelpVisibilityTier,isFullHelpDiscovery,normalizeHelpCommandPath,resolveHelpBundleForPath,resolveHelpDetailMode,resolveHelpNarrative,ROOT_HELP_BUNDLE}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapCommandName,parseBootstrapTypeValue}from"./bootstrap-args.js";import{extractProvidedOptionFlags,renderPmCommand}from"./argv-utils.js";import{formatCommanderErrorForJson}from"./error-guidance.js";import{BUILTIN_TYPE_HELP_VALUES,buildUnknownCommandGuidanceFromRuntime,isKnownHelpCommandPath}from"./commander-usage.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{resolveCreateExplicitEmptyFlag}from"../sdk/agent/create-option-policy.js";import{formatPmPositionalActionFlagTip,PM_POSITIONAL_ACTION_CONTRACTS,resolvePmPositionalActionContract}from"../sdk/cli-contracts/grammar-contracts.js";import{resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"../sdk/agent-capability-contracts.js";const EXTENSION_TIER_ORDER={core:0,standard:1,full:2,internal:3};function resolveExtensionCommandSurface(commandPath,descriptors,allowDescendants=true){const exact=descriptors.get(resolvePmCommandOperation(commandPath));if(exact)return exact;if(!allowDescendants)return void 0;const descendants=[...descriptors.entries()].filter(([path])=>path.startsWith(`${commandPath} `)).map(([,descriptor])=>descriptor);if(descendants.length===0)return void 0;const tier=descendants.reduce((selected,descriptor)=>EXTENSION_TIER_ORDER[descriptor.tier]<EXTENSION_TIER_ORDER[selected]?descriptor.tier:selected,"internal");const families=new Set(descendants.map(({family})=>family));return{tier,family:families.size===1?descendants[0].family:"extensions"}}function resolveCommandFromPathTokens(root,pathTokens){if(pathTokens.length===0){return root}const exactCommand=findCommandByPath(root,pathTokens);if(exactCommand){return exactCommand}const requestedPath=pathTokens.join(" ");if(resolvePmCommandOperation(requestedPath)!==requestedPath)return null;if(!PM_CORE_COMMAND_NAMES.some(commandName=>commandName===requestedPath)&&!hasSubcommandFlagContractsForCommand(requestedPath)&&!resolvePmPositionalActionContract(requestedPath)&&!isKnownHelpCommandPath(root,pathTokens)){return null}for(let length=pathTokens.length-1;length>0;length-=1){const positionalParent=findCommandByPath(root,pathTokens.slice(0,length));if(positionalParent){return positionalParent}}return pathTokens.length===1?root:null}function extractOptionValueName(flags){const match=flags.match(/[<[]([^>\]]+)[>\]]/);if(!match){return null}const value=match[1]?.trim();return value&&value.length>0?value:null}function readOptionAttributeName(option){const optionRecord=option;if(typeof optionRecord.attributeName==="function"){const value=optionRecord.attributeName();return typeof value==="string"&&value.trim().length>0?value.trim():null}if(typeof optionRecord.attributeName==="string"&&optionRecord.attributeName.trim().length>0){return optionRecord.attributeName.trim()}return null}function buildOptionAliasMap(options){const aliasMap=new Map;for(const option of options){const optionRecord=option;const attributeName=readOptionAttributeName(option);if(!attributeName||typeof optionRecord.long!=="string"||optionRecord.long.trim().length===0){continue}const existing=aliasMap.get(attributeName)??[];existing.push(optionRecord.long.trim());aliasMap.set(attributeName,existing)}for(const[attributeName,values]of aliasMap.entries()){aliasMap.set(attributeName,[...new Set(values.map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right)))}return aliasMap}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function buildHelpOptionSummaries(command){const options=command.options??[];const optionAliasMap=buildOptionAliasMap(options);return options.map(option=>{const optionRecord=option;const flags=typeof optionRecord.flags==="string"?optionRecord.flags.trim():"";const description=typeof optionRecord.description==="string"?optionRecord.description.trim():"";const attributeName=readOptionAttributeName(option);const aliasCandidates=attributeName?optionAliasMap.get(attributeName)??[]:[];const aliases=aliasCandidates.filter(entry=>entry!==optionRecord.long).map(entry=>entry.trim()).filter(entry=>entry.length>0);const aliasForMatch=description.match(/^Alias for ([^ ]+)/i);const aliasFor=aliasForMatch&&aliasForMatch[1]?aliasForMatch[1].trim():null;const required=optionRecord.mandatory===true||description.includes("[required]")||description.toLowerCase().includes("required;");const valueRequired=flags.includes("<");const takesValue=valueRequired||flags.includes("[");const summary={flags,long:typeof optionRecord.long==="string"?optionRecord.long:null,short:typeof optionRecord.short==="string"?optionRecord.short:null,description,takes_value:takesValue,value_required:valueRequired,value_name:extractOptionValueName(flags),variadic:optionRecord.variadic===true,required,aliases,alias_for:aliasFor};if(optionRecord.defaultValue!==void 0){summary.default_value=optionRecord.defaultValue}return summary})}function compactHelpOptionAliases(options){const canonicalByLong=new Map;const aliasOptions=[];for(const option of options){if(option.alias_for&&option.long){aliasOptions.push(option);continue}if(option.long){canonicalByLong.set(option.long,option)}}for(const aliasOption of aliasOptions){const aliasFor=aliasOption.alias_for;const canonical=canonicalByLong.get(aliasFor);if(!canonical){continue}const aliasLong=aliasOption.long;const aliases=new Set([...canonical.aliases??[],aliasLong]);canonical.aliases=[...aliases].sort((left,right)=>left.localeCompare(right))}return options.filter(option=>{if(!option.alias_for||!option.long){return true}return!canonicalByLong.has(option.alias_for)})}function buildHelpArgumentSummaries(command){const commandRecord=command;const argumentsList=Array.isArray(commandRecord.registeredArguments)?commandRecord.registeredArguments:Array.isArray(commandRecord._args)?commandRecord._args:[];return argumentsList.map(argument=>{const rawName=typeof argument.name==="function"?argument.name():typeof argument.name==="string"?argument.name:"argument";const description=typeof argument.description==="string"&&argument.description.trim().length>0?argument.description.trim():null;return{name:rawName.trim(),required:argument.required===true||description?.toLowerCase().startsWith("required;")===true,variadic:argument.variadic===true,description}})}function buildHelpSubcommandSummaries(command,extensionDescriptors=new Map,includeAll=false){const visible=command.createHelp().visibleCommands(command);const candidates=includeAll?[...new Set([...visible,...command.commands])]:visible;return candidates.filter(entry=>entry.name()!=="help"||command.parent===null).filter(entry=>!includeAll||(getPmCommandHelpVisibilityTier(entry)??resolvePmCommandVisibilityTier(entry.name()))!=="internal").map(entry=>{const commandPath=normalizeHelpCommandPath(getCommandPath(entry));const rootCommand=commandPath;const declaredTier=getPmCommandHelpVisibilityTier(entry);const extensionDescriptor=resolveExtensionCommandSurface(commandPath,extensionDescriptors,declaredTier!==void 0);const aliasContract=PM_COMMAND_ALIAS_CONTRACTS.find(({alias})=>alias===commandPath);return{name:entry.name().trim(),aliases:commandAliases(entry),description:entry.description().trim(),tier:extensionDescriptor?.tier??declaredTier??resolvePmCommandVisibilityTier(rootCommand),family:extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommand),...aliasContract?{alias_for:aliasContract.canonical,alias_lifecycle:aliasContract.lifecycle,...aliasContract.lifecycle==="deprecated"?{deprecated:true}:{}}:{}}}).sort((left,right)=>left.name.localeCompare(right.name))}function buildJsonHelpNarrative(detailMode,fallbackNarrative,extensionDescriptor){if(!extensionDescriptor){return fallbackNarrative}const extensionExamples=extensionDescriptor.examples??[];const extensionFailureHints=extensionDescriptor.failure_hints??[];return{intent:extensionDescriptor.intent??extensionDescriptor.description??fallbackNarrative.intent,examples:detailMode==="detailed"?extensionExamples.length>0?[...extensionExamples]:[...fallbackNarrative.examples]:extensionExamples.length>0?[extensionExamples[0]]:[...fallbackNarrative.examples],tips:detailMode==="detailed"?extensionFailureHints.length>0?[...extensionFailureHints]:[...fallbackNarrative.tips]:[],detail_mode:detailMode}}function resolveJsonHelpNarrative(commandPath,commandDescription,detailMode,extensionDescriptor,hasPositionalAction){const isRootFallback=commandPath!==void 0&&resolveHelpBundleForPath(commandPath)===ROOT_HELP_BUNDLE;const fallback=isRootFallback?{intent:commandDescription,examples:[`pm ${commandPath} --help`],tips:[],detail_mode:detailMode}:resolveHelpNarrative(commandPath,detailMode);const intentSource=hasPositionalAction?"positional_action":extensionDescriptor?.intent||extensionDescriptor?.description?"extension":isRootFallback?commandDescription?"command_description":"unavailable":commandPath?"help_bundle":"root_help_bundle";return{narrative:buildJsonHelpNarrative(detailMode,fallback,extensionDescriptor),intentSource}}function resolveJsonHelpVisibilityTier(rootCommandPath,extensionDescriptor){if(rootCommandPath===void 0)return null;return extensionDescriptor?.tier??resolvePmCommandVisibilityTier(rootCommandPath)}function resolveJsonHelpCapabilityFamily(rootCommandPath,extensionDescriptor){if(rootCommandPath===void 0)return null;return extensionDescriptor?.family??resolvePmCommandCapabilityFamily(rootCommandPath)}function projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery){if(targetCommand!==rootProgram||!fullDiscovery)return void 0;return PM_COMMAND_ALIAS_CONTRACTS.map(contract=>({alias:contract.alias,canonical:contract.canonical,canonical_argv:[...contract.canonical_argv],available:resolveCommandFromPathTokens(rootProgram,contract.canonical.split(" "))!==null,lifecycle:contract.lifecycle,hidden:contract.hidden,deprecated:contract.lifecycle==="deprecated"}))}function buildPositionalActionHelpProjection(action,targetCommand,resolvedPath,allOptions,extensionDescriptors=new Map,includeAll=false){if(!action){const argumentsList=buildHelpArgumentSummaries(targetCommand);const registeredSubcommands=buildHelpSubcommandSummaries(targetCommand,extensionDescriptors,includeAll);const registeredSubcommandNames=new Set(registeredSubcommands.map(({name})=>name));return{arguments:argumentsList,options:allOptions,subcommands:[...registeredSubcommands,...PM_POSITIONAL_ACTION_CONTRACTS.filter(({parent,action:name})=>parent===resolvedPath&&!registeredSubcommandNames.has(name)).map(({action:name,description})=>({name,aliases:[],description,tier:resolvePmCommandVisibilityTier(resolvedPath.split(" ")[0]),family:resolvePmCommandCapabilityFamily(resolvedPath.split(" ")[0])}))].sort((left,right)=>left.name.localeCompare(right.name)),usage:[resolvedPath,argumentsList.reduce((usage,argument)=>argument.required?usage.replace(`[${argument.name}${argument.variadic?"...":""}]`,`<${argument.name}${argument.variadic?"...":""}>`):usage,targetCommand.usage())].filter(token=>token.length>0).join(" ")}}const acceptedFlags=new Set(action.accepted_flags);return{arguments:action.slots.map(({name,required,variadic,value_kind:valueKind,polymorphic})=>({name,required,variadic,description:polymorphic?`Polymorphic ${valueKind} value; inspect the action contract before mutation.`:`${valueKind.replaceAll("_"," ")} value.`})),options:allOptions.filter(({long,aliases})=>long!==null&&acceptedFlags.has(long)||aliases.some(alias=>acceptedFlags.has(alias))),subcommands:[],usage:[action.command,...action.slots.map(({name,required,variadic})=>{const token=variadic?`${name}...`:name;return required?`<${token}>`:`[${token}]`})].join(" ")}}function buildJsonHelpPayload(rootProgram,targetCommand,argv,requestedPath,extensionDescriptors){const detailMode=resolveHelpDetailMode(argv);const fullDiscovery=isFullHelpDiscovery(argv);const commanderPath=normalizeHelpCommandPath(getCommandPath(targetCommand));const requestedCommandPath=normalizeHelpCommandPath(requestedPath.join(" "));const resolvedPath=requestedCommandPath.length>commanderPath.length?requestedCommandPath:commanderPath;const positionalAction=resolvePmPositionalActionContract(resolvedPath);const projectedPath=positionalAction?.command??commanderPath;const commandPath=projectedPath.length>0?projectedPath:void 0;const rootCommandPath=commandPath;const extensionDescriptor=commandPath?extensionDescriptors.get(resolvePmCommandOperation(commandPath)):void 0;const extensionSurface=commandPath?resolveExtensionCommandSurface(commandPath,extensionDescriptors,getPmCommandHelpVisibilityTier(targetCommand)!==void 0):void 0;const{narrative,intentSource}=resolveJsonHelpNarrative(commandPath,targetCommand.description().trim(),detailMode,extensionDescriptor,positionalAction!==void 0);const allOptionSummaries=compactHelpOptionAliases(mergeHelpOptionSummaries(buildHelpOptionSummaries(targetCommand),buildDynamicExtensionHelpOptionSummaries(extensionDescriptor)));const projection=buildPositionalActionHelpProjection(positionalAction,targetCommand,projectedPath,allOptionSummaries,extensionDescriptors,fullDiscovery);const fullCommandAliases=projectFullCommandAliases(rootProgram,targetCommand,fullDiscovery);return{format:"pm_help_v1",detail_mode:detailMode,root_command:rootProgram.name(),requested_path:requestedPath,resolved_path:projectedPath.length>0?projectedPath:rootProgram.name(),visibility_tier:resolveJsonHelpVisibilityTier(rootCommandPath,extensionSurface),capability_family:resolveJsonHelpCapabilityFamily(rootCommandPath,extensionSurface),description:positionalAction?.description??targetCommand.description(),usage:projection.usage,intent:positionalAction?.description??narrative.intent,intent_source:intentSource,examples:positionalAction?[positionalAction.example]:narrative.examples,tips:positionalAction?[formatPmPositionalActionFlagTip(positionalAction.accepted_flags)]:narrative.tips,arguments:projection.arguments,options:projection.options,subcommands:projection.subcommands,has_subcommands:projection.subcommands.length>0,...fullCommandAliases===void 0?{}:{command_aliases:fullCommandAliases}}}async function maybeRenderBootstrapJsonHelp(rootProgram,argv,extensionDescriptors,requestedArgv=argv){const bootstrapGlobal=parseBootstrapGlobalOptions(argv);if(!bootstrapGlobal.json){return false}const helpRequest=parseBootstrapHelpRequest(argv);if(!helpRequest.requested){return false}const targetCommand=resolveCommandFromPathTokens(rootProgram,helpRequest.commandPathTokens);if(!targetCommand){if(!bootstrapGlobal.quiet){const unknownMessage=`unknown command '${resolvePmCommandOperation(helpRequest.commandPathTokens.join(" "))}'`;const runtimeContext=buildUnknownCommandGuidanceFromRuntime(unknownMessage,rootProgram,extensionDescriptors);const envelope=formatCommanderErrorForJson(unknownMessage,"help",BUILTIN_TYPE_HELP_VALUES,EXIT_CODE.USAGE,{...runtimeContext,attemptedCommand:renderAttemptedCommand(argv),normalizedInvocationArgs:[...argv],providedOptionFlags:extractProvidedOptionFlags(argv)});const output=bootstrapGlobal.tokenAccounting?attachOutputTokenAccounting(envelope,value=>`${JSON.stringify(value,null,2)}
2
2
  `):envelope;writeStderr(`${JSON.stringify(output,null,2)}
3
- `)}process.exitCode=EXIT_CODE.USAGE;return true}if(!bootstrapGlobal.quiet){const payload=buildJsonHelpPayload(rootProgram,targetCommand,argv,helpRequest.commandPathTokens,extensionDescriptors);payload.requested_path=parseBootstrapHelpRequest(requestedArgv).commandPathTokens;writeStdout(`${JSON.stringify(payload,null,2)}
3
+ `)}process.exitCode=EXIT_CODE.USAGE;return true}if(!bootstrapGlobal.quiet){const payload=buildJsonHelpPayload(rootProgram,targetCommand,argv,helpRequest.commandPathTokens,extensionDescriptors);const originalPath=parseBootstrapHelpRequest(requestedArgv).commandPathTokens;payload.requested_path=originalPath;const alias=resolvePmCommandAlias(originalPath.join(" "));if(alias)payload.resolved_path=alias.canonical;if(targetCommand===rootProgram&&!isFullHelpDiscovery(argv)){payload.omission_receipt={has_omissions:true,omitted_field_group_count:1,omitted_field_groups:[{name:"command_aliases",restore_with:"--all"}]}}writeStdout(`${JSON.stringify(payload,null,2)}
4
4
  `)}process.exitCode=EXIT_CODE.SUCCESS;return true}function buildCreateUpdatePolicyIntro(commandName,typeRegistry){const lines=["","Type-aware option policies:"," pass --type <value> with --help to render required/disabled/hidden option policy details for that type.",` active type values: ${typeRegistry.types.join("|")}`];if(commandName==="create"){lines.push(" scheduling shortcut: use --schedule-preset lightweight for Reminder/Meeting/Event minimal create flows.")}return lines.join("\n")}function appendTypeOptionHelpLines(lines,typeDefinition){if(typeDefinition.options.length===0){lines.push(" type options: none");return}lines.push(" type options:");for(const option of typeDefinition.options){const requiredLabel=option.required?" (required)":"";const aliases=option.aliases??[];lines.push(` - ${option.key}${requiredLabel}`);lines.push(` values: ${option.values.length>0?option.values.join("|"):"any non-empty string"}`);lines.push(` aliases: ${aliases.length>0?aliases.join("|"):"none"}`);if(option.description&&option.description.trim().length>0){lines.push(` description: ${option.description.trim()}`)}}}function buildCreatePolicyRequiredSets(commandName,typeDefinition){const progressive=commandName==="create"?new Set(["title","type"]):new Set;const strict=new Set(progressive);if(commandName==="create"){for(const option of[...typeDefinition.required_create_fields,...typeDefinition.required_create_repeatables]){strict.add(option)}}return{progressive,strict}}function appendStrictCreatePolicyHelpLines(lines,typeDefinition,progressiveRequired,strictRequired){const progressive=new Set(progressiveRequired);const strictOnly=strictRequired.filter(option=>!progressive.has(option));const toFlags=options=>options.length>0?options.map(option=>commandOptionFlagLabel("create",option)).join(", "):"none";lines.push(` required in strict mode: ${toFlags(strictOnly)}`);const explicitEmptyFlags=strictOnly.map(resolveCreateExplicitEmptyFlag).filter(flag=>flag!==void 0);lines.push(` explicit empty assertion: ${explicitEmptyFlags.length>0?explicitEmptyFlags.join(", "):"none"}`);if(["Reminder","Meeting","Event"].includes(typeDefinition.name)){lines.push(" schedule preset: --schedule-preset lightweight switches schedule artifacts to progressive required-option policy.");lines.push(" strict parity remains available via --create-mode strict.")}}function buildCreateUpdatePolicyHelpText(commandName,typeRegistry,argv){const selectedTypeRaw=parseBootstrapTypeValue(argv);if(!selectedTypeRaw){return buildCreateUpdatePolicyIntro(commandName,typeRegistry)}const typeDefinition=resolveTypeDefinition(selectedTypeRaw,typeRegistry);if(!typeDefinition){const allowed=typeRegistry.types.join("|");return["",`Type-aware option policies: type "${selectedTypeRaw}" is not in the active registry.`,` active type values: ${allowed}`].join("\n")}const argumentTerminatorIndex=argv.indexOf("--");const optionArgv=argumentTerminatorIndex<0?argv:argv.slice(0,argumentTerminatorIndex);const createModeTokenIndex=optionArgv.findIndex(token=>token==="--create-mode"||token.startsWith("--create-mode="));const createModeToken=createModeTokenIndex<0?void 0:optionArgv[createModeTokenIndex]?.startsWith("--create-mode=")?optionArgv[createModeTokenIndex]?.slice("--create-mode=".length):optionArgv[createModeTokenIndex+1];const strictCreateMode=commandName==="create"&&createModeToken?.toLowerCase()==="strict";const requiredSets=buildCreatePolicyRequiredSets(commandName,typeDefinition);const progressivePolicyState=resolveCommandOptionPolicyState(typeDefinition,commandName,requiredSets.progressive);const policyState=resolveCommandOptionPolicyState(typeDefinition,commandName,strictCreateMode?requiredSets.strict:requiredSets.progressive);const toFlags=options=>options.length>0?options.map(option=>commandOptionFlagLabel(commandName,option)).join(", "):"none";const lines=["",`Type-aware option policies for ${typeDefinition.name}:`,` required: ${toFlags(policyState.required)}`,` disabled: ${toFlags(policyState.disabled)}`,` hidden: ${toFlags(policyState.hidden)}`];if(commandName==="create"){const strictPolicyState=resolveCommandOptionPolicyState(typeDefinition,commandName,requiredSets.strict);appendStrictCreatePolicyHelpLines(lines,typeDefinition,progressivePolicyState.required,strictPolicyState.required)}appendTypeOptionHelpLines(lines,typeDefinition);if(policyState.errors.length>0){lines.push(` config errors: ${policyState.errors.join("; ")}`)}return lines.join("\n")}function attachCreateUpdatePolicyHelpText(rootProgram,typeRegistry,argv){const bootstrapCommand=parseBootstrapCommandName(argv);if(bootstrapCommand!=="create"&&bootstrapCommand!=="update"){return}const command=findDirectChildCommand(rootProgram,bootstrapCommand);if(!command){return}command.addHelpText("after",buildCreateUpdatePolicyHelpText(bootstrapCommand,typeRegistry,argv))}const _testOnly={attachCreateUpdatePolicyHelpText,buildCreateUpdatePolicyHelpText,buildJsonHelpPayload,buildPositionalActionHelpProjection,buildHelpArgumentSummaries,buildHelpOptionSummaries,buildHelpSubcommandSummaries,buildOptionAliasMap,compactHelpOptionAliases,readOptionAttributeName,resolveCommandFromPathTokens,resolveExtensionCommandSurface};export{_testOnly,attachCreateUpdatePolicyHelpText,maybeRenderBootstrapJsonHelp};
5
5
  //# sourceMappingURL=help-json-payload.js.map