@unbrained/pm-cli 2026.9.25 → 2026.9.27

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 (161) hide show
  1. package/.agents/skills/README.md +1 -0
  2. package/.agents/skills/pm-developer/SKILL.md +3 -0
  3. package/.agents/skills/pm-test-audit/LICENSE.txt +21 -0
  4. package/.agents/skills/pm-test-audit/SKILL.md +103 -0
  5. package/.agents/skills/pm-test-audit/references/AUDIT.md +54 -0
  6. package/.agents/skills/pm-test-audit/references/CAMPAIGN.md +47 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +28 -1
  9. package/dist/cli/commander-usage.js +2 -2
  10. package/dist/cli/error-guidance.js +1 -1
  11. package/dist/cli/main.js +2 -2
  12. package/dist/cli/register-list-query.js +2 -2
  13. package/dist/cli/register-setup.js +1 -1
  14. package/dist/cli/runtime/selection.d.ts +3 -1
  15. package/dist/cli/runtime/selection.js +1 -1
  16. package/dist/cli/schema/registration.js +2 -2
  17. package/dist/cli-bundle/bundle-manifest.json +155 -147
  18. package/dist/cli-bundle/chunks/chunk-3BTJ66CB.js +238 -0
  19. package/dist/cli-bundle/chunks/{chunk-5AP67ZXH.js → chunk-4SLLCDFL.js} +39 -39
  20. package/dist/cli-bundle/chunks/{chunk-GAU55CWI.js → chunk-4UPZLUT2.js} +7 -7
  21. package/dist/cli-bundle/chunks/{chunk-25KTCTBL.js → chunk-6OJVQ7SW.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-445ARBKY.js → chunk-7TAGYNFP.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-GOWZEBTH.js → chunk-AUS6USO4.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-YDIGMRLZ.js → chunk-IEP3VAT5.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-3IB4THWX.js → chunk-JX6WCCHL.js} +6 -6
  26. package/dist/cli-bundle/chunks/chunk-LC6WEA5U.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-CZ3VJJEA.js → chunk-LKGQUZ5M.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-P7ZSJOWH.js → chunk-OKVDVERQ.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-COFQCKF4.js → chunk-TSF2LPIH.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-YABJDOOX.js → chunk-V5UGBYHN.js} +3 -3
  31. package/dist/cli-bundle/chunks/{register-list-query-IZ7ZVTDE.js → register-list-query-6PAJ4PBU.js} +4 -4
  32. package/dist/cli-bundle/chunks/{register-mutation-IPAZTFDZ.js → register-mutation-RZCXZXYS.js} +4 -4
  33. package/dist/cli-bundle/chunks/{register-operations-APN33LNI.js → register-operations-GK6VU2H2.js} +2 -2
  34. package/dist/cli-bundle/chunks/register-setup-ASEMNMBF.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-KRIHJH5U.js → chunk-6J2YCGSN.js} +5 -5
  36. package/dist/cli-bundle/focused-chunks/{chunk-XKH2FC5D.js → chunk-6UNKK3UH.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-NRHTXBTI.js → chunk-DQ3MB7BO.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-PMPFLA6X.js → chunk-E7LYK7V5.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-GZD4ZYIB.js +20 -0
  40. package/dist/cli-bundle/focused-chunks/chunk-KMPKKSA6.js +2 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-TLF6N56J.js → chunk-LBDWUHQD.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-UIFVIE5F.js → chunk-MILJCOFJ.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-MK5AKKHK.js → chunk-NETVXIH5.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-Q355NPLH.js → chunk-NWRVNHAD.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-IXNNMP2R.js → chunk-NZAG7OKB.js} +12 -12
  46. package/dist/cli-bundle/focused-chunks/{chunk-OY3VHCTX.js → chunk-OJKJFDIG.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-OJRX6G22.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-NVVB2HJC.js → chunk-PDVL7QYU.js} +16 -16
  49. package/dist/cli-bundle/focused-chunks/{chunk-O7MIBEMK.js → chunk-QO4MTAEA.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-ABA3KRPY.js → chunk-SMADBUPL.js} +2 -2
  51. package/dist/cli-bundle/main.js +21 -21
  52. package/dist/cli-bundle/sdk-authoring.js +1 -1
  53. package/dist/cli-bundle/sdk-contracts.js +1 -1
  54. package/dist/cli-bundle/sdk-core.js +20 -20
  55. package/dist/cli-bundle/sdk-governance.js +1 -1
  56. package/dist/cli-bundle/sdk-graph.js +1 -1
  57. package/dist/cli-bundle/sdk-merge.js +46 -46
  58. package/dist/cli-bundle/sdk-query.js +1 -1
  59. package/dist/cli-bundle/sdk-runtime.js +1 -1
  60. package/dist/cli-bundle/sdk-testing.js +1 -1
  61. package/dist/cli-bundle/sdk.js +8 -8
  62. package/dist/core/search/embedding-batches.d.ts +47 -15
  63. package/dist/core/search/embedding-batches.js +1 -1
  64. package/dist/core/search/eval-thresholds.d.ts +14 -0
  65. package/dist/core/search/eval-thresholds.js +2 -0
  66. package/dist/core/search/eval.d.ts +4 -1
  67. package/dist/core/search/eval.js +1 -1
  68. package/dist/core/search/http-client.d.ts +7 -0
  69. package/dist/core/search/http-client.js +1 -1
  70. package/dist/sdk/agent-capability-contracts.js +1 -1
  71. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  72. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  73. package/dist/sdk/completion/shared.d.ts +1 -1
  74. package/dist/sdk/completion/shared.js +1 -1
  75. package/dist/sdk/eval.d.ts +19 -17
  76. package/dist/sdk/eval.js +1 -1
  77. package/dist/sdk/extension/static-inventory.d.ts +54 -0
  78. package/dist/sdk/extension/static-inventory.js +2 -0
  79. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  80. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  81. package/dist/sdk/governance/reindex.d.ts +4 -1
  82. package/dist/sdk/governance/reindex.js +2 -2
  83. package/dist/sdk/guide-topics.js +1 -1
  84. package/dist/sdk/index.d.ts +1 -0
  85. package/dist/sdk/index.js +1 -1
  86. package/dist/sdk/public-surface.json +1 -1
  87. package/dist/sdk/query/complete-list.js +1 -1
  88. package/dist/sdk/query.d.ts +3 -0
  89. package/dist/sdk/query.js +1 -1
  90. package/dist/sdk/read-output/provenance.d.ts +20 -0
  91. package/dist/sdk/read-output/provenance.js +2 -0
  92. package/dist/sdk/read-output-contracts.js +1 -1
  93. package/dist/sdk/runtime/schema-preview.d.ts +2 -0
  94. package/dist/sdk/runtime/schema-preview.js +2 -0
  95. package/dist/sdk/runtime/schema.js +1 -1
  96. package/dist/sdk/runtime-input.js +1 -1
  97. package/dist/sdk/runtime-primitives.d.ts +2 -1
  98. package/dist/sdk/runtime-primitives.js +1 -1
  99. package/docs/CLI_GRAMMAR.md +31 -0
  100. package/docs/CODEX_PLUGIN.md +8 -0
  101. package/docs/EXTENSION_LIFECYCLE.md +18 -0
  102. package/docs/README.md +1 -0
  103. package/docs/RELEASING.md +51 -2
  104. package/docs/SEARCH_QUALITY.md +116 -0
  105. package/docs/agent-task-token-baseline.json +4 -4
  106. package/docs/generated/AGENT_CAPABILITY_ROUTING.md +1 -1
  107. package/docs/generated/AGENT_COMMAND_SURFACE.md +5 -1
  108. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -0
  109. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +14 -7
  110. package/marketplace.json +2 -2
  111. package/package.json +2 -2
  112. package/packages/pm-beads/package.json +1 -1
  113. package/packages/pm-calendar/package.json +1 -1
  114. package/packages/pm-command-kit/package.json +1 -1
  115. package/packages/pm-digital-twin/package.json +1 -1
  116. package/packages/pm-governance-audit/package.json +1 -1
  117. package/packages/pm-guide-shell/package.json +1 -1
  118. package/packages/pm-kanban/package.json +1 -1
  119. package/packages/pm-lifecycle-hooks/package.json +1 -1
  120. package/packages/pm-linked-test-adapters/package.json +1 -1
  121. package/packages/pm-search-advanced/package.json +1 -1
  122. package/packages/pm-templates/package.json +1 -1
  123. package/packages/pm-todos/package.json +1 -1
  124. package/packages/pm-vcs/package.json +1 -1
  125. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  126. package/plugins/pm-claude/README.md +5 -1
  127. package/plugins/pm-claude/package.json +2 -2
  128. package/plugins/pm-claude/skills/pm-audit/SKILL.md +14 -103
  129. package/plugins/pm-claude/skills/pm-audit/agents/openai.yaml +4 -0
  130. package/plugins/pm-claude/skills/pm-developer/SKILL.md +20 -143
  131. package/plugins/pm-claude/skills/pm-developer/agents/openai.yaml +4 -0
  132. package/plugins/pm-claude/skills/pm-planner/SKILL.md +16 -167
  133. package/plugins/pm-claude/skills/pm-planner/agents/openai.yaml +4 -0
  134. package/plugins/pm-claude/skills/pm-release/SKILL.md +18 -102
  135. package/plugins/pm-claude/skills/pm-release/agents/openai.yaml +4 -0
  136. package/plugins/pm-claude/skills/pm-workflow/SKILL.md +25 -156
  137. package/plugins/pm-claude/skills/pm-workflow/agents/openai.yaml +4 -0
  138. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  139. package/plugins/pm-codex/README.md +10 -2
  140. package/plugins/pm-codex/mcp.json +11 -0
  141. package/plugins/pm-codex/package.json +2 -2
  142. package/plugins/pm-codex/plugin.json +45 -0
  143. package/plugins/pm-codex/skills/pm-audit/SKILL.md +21 -0
  144. package/plugins/pm-codex/skills/pm-audit/agents/openai.yaml +4 -0
  145. package/plugins/pm-codex/skills/pm-auditor/SKILL.md +5 -40
  146. package/plugins/pm-codex/skills/pm-auditor/agents/openai.yaml +3 -5
  147. package/plugins/pm-codex/skills/pm-developer/SKILL.md +26 -0
  148. package/plugins/pm-codex/skills/pm-developer/agents/openai.yaml +4 -0
  149. package/plugins/pm-codex/skills/pm-native/SKILL.md +7 -87
  150. package/plugins/pm-codex/skills/pm-native/agents/openai.yaml +3 -5
  151. package/plugins/pm-codex/skills/pm-planner/SKILL.md +22 -0
  152. package/plugins/pm-codex/skills/pm-planner/agents/openai.yaml +4 -0
  153. package/plugins/pm-codex/skills/pm-release/SKILL.md +17 -38
  154. package/plugins/pm-codex/skills/pm-release/agents/openai.yaml +2 -4
  155. package/plugins/pm-codex/skills/pm-workflow/SKILL.md +39 -0
  156. package/plugins/pm-codex/skills/pm-workflow/agents/openai.yaml +4 -0
  157. package/dist/cli-bundle/chunks/chunk-JDHWZYZU.js +0 -238
  158. package/dist/cli-bundle/chunks/register-setup-HPHIKG5U.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-HQPTDJLF.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-V2X37U6J.js +0 -2
  161. package/dist/cli-bundle/focused-chunks/chunk-Y2M4QLAA.js +0 -20
@@ -24,6 +24,7 @@ it. `docs/COMMANDS.md` is ~29k tokens and `docs/SDK.md` is ~45k.
24
24
  | Skill | Use when |
25
25
  | --------------------------------- | ------------------------------------------------------ |
26
26
  | [`pm-developer`](pm-developer/SKILL.md) | Changing code, docs, tests, or release gates |
27
+ | [`pm-test-audit`](pm-test-audit/SKILL.md) | Writing, reviewing, or auditing tests and their regression value |
27
28
  | [`pm-user`](pm-user/SKILL.md) | Intake, triage, prioritization, planning, reporting |
28
29
  | [`pm-extensions`](pm-extensions/SKILL.md) | Package and extension lifecycle and authoring |
29
30
  | [`pm-sdk`](pm-sdk/SKILL.md) | Integrations, embedding, and domain packs on the SDK |
@@ -106,6 +106,9 @@ Always read the `omission_receipt` before treating a result as complete. See
106
106
 
107
107
  ## Verification Defaults
108
108
 
109
+ For test authoring, review, or cleanup, apply [pm-test-audit](../pm-test-audit/SKILL.md)
110
+ to preserve independent contracts while removing low-value duplication.
111
+
109
112
  ```bash
110
113
  pnpm build
111
114
  node scripts/run-tests.mjs test -- <targets>
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 OpenClaw Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,103 @@
1
+ ---
2
+ name: pm-test-audit
3
+ description: Use when writing, changing, reviewing, or auditing pm-cli tests. Checks regression value, duplicate coverage, implementation coupling, and test-only production seams while preserving SDK contracts, sandbox isolation, and exact coverage gates.
4
+ license: MIT
5
+ compatibility: Repository development with Node.js, pnpm, and the checkout-built pm CLI.
6
+ metadata:
7
+ owner: unbrained
8
+ domain: pm-cli
9
+ scope: test-quality
10
+ ---
11
+
12
+ # pm Test Audit
13
+
14
+ Tracker: [pm-xvibt6](../../pm/tasks/pm-xvibt6.toon).
15
+ Adapted from OpenClaw's [test-audit skill](https://github.com/openclaw/openclaw/blob/e0d80000067d224e93af6107ed093a21e046879f/.agents/skills/test-audit/SKILL.md);
16
+ upstream copyright and terms are in [LICENSE.txt](LICENSE.txt).
17
+
18
+ Use alongside [pm-developer](../pm-developer/SKILL.md). Project management is
19
+ context management: retain why a test exists, its contract owner, and the
20
+ regression evidence so the next audit need not rediscover them.
21
+
22
+ ## Choose the Scope
23
+
24
+ - **Authoring:** apply the four questions below before adding or changing tests.
25
+ - **Audit:** read [audit evidence](references/AUDIT.md) before proposing removals.
26
+ - **Campaign:** also read [campaign procedure](references/CAMPAIGN.md) for a broad sweep.
27
+
28
+ Do not expand a focused request into a repository-wide deletion campaign.
29
+
30
+ ## Four Questions Before Editing
31
+
32
+ 1. What observable behavior, invariant, or independent contract does this prove?
33
+ 2. What credible regression makes it fail? For a bug fix, demonstrate the intended
34
+ failure before the fix and success afterward with the same test and harness.
35
+ 3. Why does existing coverage not catch it? Choose one primary owner at the
36
+ strongest useful boundary. An additional layer needs a distinct risk, such as
37
+ CLI parsing, MCP transport, persistence, or package installation. Extend a
38
+ table or shared fixture when the behavior and setup are already covered.
39
+ 4. Does it demand a production export, flag, wrapper, or injection hook solely
40
+ to observe private details? Prefer exercising the real boundary. Published
41
+ `@unbrained/pm-cli/sdk/testing` helpers are public contracts, not automatically
42
+ disposable test-only seams.
43
+
44
+ Domain semantics belong in the SDK; thin CLI/MCP adapters need their own transport
45
+ proof, not copies of every SDK case. Read complete tests and production owners
46
+ before editing, plus relevant callers, neighboring tests, history, and scoped
47
+ `AGENTS.md`. Inspect actual dependency types in `node_modules`; do not guess APIs.
48
+
49
+ ## Verification and Safety
50
+
51
+ Follow [Testing](../../../docs/TESTING.md) for the affected surface. Use the
52
+ repository runner, which isolates tracker roots and builds the checkout:
53
+
54
+ ```bash
55
+ node scripts/run-tests.mjs test -- <target>
56
+ node scripts/run-tests.mjs coverage
57
+ ```
58
+
59
+ - Never run tests against the real `.agents/pm`. Manual dogfood uses a temporary
60
+ workspace outside this checkout and its ancestor workspaces, with both
61
+ `PM_PATH` and `PM_GLOBAL_PATH` isolated. Clean up only directories you created.
62
+ - Do not edit source while a runner or build owns it. Negative controls and
63
+ pre-fix comparisons belong in an isolated copy/worktree with temporary
64
+ `PM_PATH` and `PM_GLOBAL_PATH` set for every direct stateful CLI command,
65
+ including linked-test metadata commands. A nested worktree alone does not
66
+ isolate tracker discovery. Keep these test roots separate from intentional
67
+ repository tracking below. Change the intended condition; unrelated setup
68
+ failures do not establish regression sensitivity.
69
+ - Keep canonical full-source coverage at **100/100/100/100**. Do not shrink the
70
+ denominator, add ignore directives, lower gates, or duplicate assertions to
71
+ recover a number. Restore meaningful behavioral proof when coverage drops.
72
+ - Mocks may isolate external boundaries; they must not implement the behavior
73
+ being tested. Use real temporary persistence when proving writes or recovery.
74
+ - Run relevant functional, integration, package, performance, and acceptance
75
+ gates according to the changed contract. A focused green run is not a full
76
+ suite result. [Quality evidence](../../../docs/QUALITY_EVIDENCE.md) defines the
77
+ bounded mutation gate; do not describe it as whole-repository mutation proof.
78
+ - Preserve static quality, docstring, security, release, and public-surface gates.
79
+ This skill does not grant exceptions to repository coding rules.
80
+
81
+ ## PM Evidence and Handoff
82
+
83
+ Bootstrap and orient using root `AGENTS.md`; search all statuses before creating
84
+ work. Read the selected item's full metadata and history, follow omission
85
+ receipts, then claim/start only items actually being edited. Keep investigation
86
+ read-only until there is a justified change. Use typed relationships for real
87
+ ownership, dependencies, or verification; never manufacture graph depth.
88
+
89
+ Link files, docs, and sandbox-safe test commands through `pm`. Record retained
90
+ contracts, removed duplication, pre-fix failure and post-fix proof, commands and
91
+ results, and limitations. Reuse canonical follow-up items for product defects;
92
+ never delete a failing regression merely to make the suite green. Close with
93
+ structured evidence and release the claim, or return paused work to an appropriate
94
+ non-active state. Delivery and review follow the user's authorized scope and
95
+ [review loop](../../../docs/PR_REVIEW_LOOP.md).
96
+
97
+ For current command flags use command-specific help/contracts. Optional deeper
98
+ workflow guidance is available after installing guide-shell:
99
+
100
+ ```bash
101
+ pm package install guide-shell --project
102
+ pm guide workflows --depth brief
103
+ ```
@@ -0,0 +1,54 @@
1
+ # Evidence Before Removing a Test
2
+
3
+ Start with read-only discovery. Test count, runtime, coverage percentage, or a
4
+ suspicious name is a lead, not proof that a test is low-value.
5
+
6
+ ## Candidates to Investigate
7
+
8
+ - Assertion-free probes, self-comparisons, or expected values calculated by the
9
+ same implementation under test.
10
+ - Copied export/manifest inventories or source-text checks without an independent
11
+ compatibility, packaging, security, or architecture contract.
12
+ - Private predicate, mock-call-shape, and wiring assertions that repeat stronger
13
+ observable behavior coverage.
14
+ - Identical scenarios across SDK, CLI, MCP, and packages without distinct
15
+ boundary failure modes; prefer a named keeper over another copy.
16
+ - Fixtures that pre-seed the receipt, ordering, admission, or callback result the
17
+ production owner should produce; persistence tests that never write anything.
18
+ - Tests that assert a flag was forwarded but never prove its promised behavior.
19
+ - Test-only production exports, globals, wrappers, dead branches, or injected
20
+ switches with no supported consumer contract.
21
+ - Negative controls that fail at an unrelated guard, and names claiming behavior
22
+ that their assertions never observe.
23
+
24
+ Read the complete test and production owner, trace non-test callers and relevant
25
+ callees, and inspect overlapping tests, CI routing, history, and configuration.
26
+ Do not assume no in-repo caller means a published SDK export is unused.
27
+
28
+ ## Reasons to Retain
29
+
30
+ Keep independent public SDK, protocol, configuration, migration, storage,
31
+ security, platform, default, package/release, and generated cross-language
32
+ contracts. Observable ordering can be a contract. Static inspection can be the
33
+ cheapest independent architectural guard; ask whether it survives harmless
34
+ identifier refactoring. Slowness and use of mocks are not deletion criteria on
35
+ their own. A previously failing retained test may expose a product defect.
36
+
37
+ ## Candidate Ledger
38
+
39
+ For each candidate, record:
40
+
41
+ | Evidence | Required detail |
42
+ | --- | --- |
43
+ | Identity | Exact path and test/table row; production owner and callers |
44
+ | Failure | Credible regression the assertion can detect |
45
+ | Contract | Independent external obligation, or why none exists |
46
+ | Overlap | Named keeper and distinct behavior it still proves |
47
+ | Seam | Production change deletion would permit, or none |
48
+ | Decision | Retain, repair, consolidate, or delete, with rationale |
49
+ | Verification | Exact command, negative control where appropriate, and result |
50
+
51
+ Establish the keeper before removing duplicates. Remove private obsolete seams
52
+ only after caller and public-contract checks. Prefer simpler production code,
53
+ but do not use net lines deleted as a success quota. Avoid trivial one-use
54
+ wrappers or test helpers that merely mirror the implementation.
@@ -0,0 +1,47 @@
1
+ # Broad Test Audit Campaign
2
+
3
+ Use only for an authorized broad sweep. Adapted from the upstream
4
+ [campaign procedure](https://github.com/openclaw/openclaw/blob/e0d80000067d224e93af6107ed093a21e046879f/.agents/skills/test-audit/CAMPAIGN.md).
5
+
6
+ 1. **Pin a baseline.** Record the commit, test inventory, full-suite outcomes,
7
+ coverage, and existing failures in the canonical pm item. Baseline failures
8
+ are investigations, not permission to discard tests. Check all-status lineage
9
+ before creating follow-ups.
10
+ 2. **Partition by owner.** Include SDK domains, CLI/MCP adapters, packages,
11
+ release scripts, plugins, and shared harnesses within the requested scope.
12
+ Assign each test one lane. If delegation is authorized, use read-only
13
+ discovery lanes first and a single integration owner for shared harnesses.
14
+ 3. **Build the ledger.** Apply [audit evidence](AUDIT.md) to every declaration in
15
+ scope; distinguish table rows with different contracts. Mark retain, repair,
16
+ consolidate, or delete. Record uncovered/unread inventory explicitly instead
17
+ of claiming a complete sweep.
18
+ 4. **Consolidate with proof.** Name and strengthen the keeper first. Preserve
19
+ real SDK behavior and distinct CLI/MCP serialization, error, lifecycle,
20
+ persistence, package, and release guarantees. A fake external service can be
21
+ useful; a mock implementing the production algorithm proves nothing.
22
+ 5. **Integrate coherently.** Serialize shared build/harness edits, remove only
23
+ obsolete private seams, and update routing/inventory when required. Preserve
24
+ the canonical coverage denominator and every mandatory gate. Do not weaken
25
+ caps, thresholds, documentation requirements, or lint rules to pass.
26
+ 6. **Check preservation independently.** Revisit each removed contract against
27
+ the keeper and current production boundary. Use targeted mutations or pre-fix
28
+ controls in an isolated copy with temporary `PM_PATH` and `PM_GLOBAL_PATH`
29
+ for every direct stateful CLI command to establish meaningful failure. Record exact
30
+ changed bytes, failure reason, restoration, and passing rerun. Never mutate
31
+ the working tree under a running test command.
32
+ 7. **Handle product defects explicitly.** Track a real defect separately within
33
+ the coherent delivery, with failing-before/passing-after proof and the
34
+ repository's structured defect evidence. Reuse existing lineage; do not hide
35
+ unrelated repairs inside mass test deletion.
36
+ 8. **Reconcile and verify.** Incorporate upstream changes without force-pushing
37
+ shared history. Reassess newly introduced contracts rather than blindly
38
+ preserving deletions. Run focused tests, full suite/coverage, static quality,
39
+ and affected acceptance/package/performance gates on the integrated tree.
40
+ 9. **Hand off honestly.** Report baseline and final counts, covered lanes, named
41
+ keepers, production seams removed, regressions demonstrated, full commands,
42
+ results, and remaining risks. A review inventory is not a correctness
43
+ certificate. Follow the authorized PR workflow; unavailable reviewers are
44
+ unavailable evidence, not approval.
45
+
46
+ Update pm files/docs/tests/comments and durable learnings as evidence accrues.
47
+ Close only implemented work with structured results and release ownership.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.",
9
- "version": "2026.9.25"
9
+ "version": "2026.9.27"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "pm-claude",
14
14
  "source": "./plugins/pm-claude",
15
15
  "description": "Native pm CLI integration for Claude Code — 28 MCP tools, 5 workflow skills, 14 slash commands, 4 subagents, hybrid TUI task tracking, session context injection, and coordination subagents for git-based project management without leaving Claude Code.",
16
- "version": "2026.9.25",
16
+ "version": "2026.9.27",
17
17
  "author": {
18
18
  "name": "unbrained",
19
19
  "url": "https://github.com/unbraind/pm-cli"
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 2026.9.27 - 2026-09-27
4
+
5
+ ### Fixed
6
+
7
+ - SDK complete-list receipt falsely reports legacy aliases for canonical helper ([pm-vf9iaf](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-vf9iaf.toon))
8
+
9
+ ### Security
10
+
11
+ - Expose static extension inventory for hosted and agent reads ([pm-lhhnx9](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-lhhnx9.toon))
12
+
13
+ ### Other
14
+
15
+ - Consolidate workspace customization discovery and commands under workspace with permanent compatibility aliases ([pm-npr3](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-npr3.toon))
16
+ - Declare workspace, templates and guide ownership with bounded agent orientation ([pm-uk9dwh](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-uk9dwh.toon))
17
+ - Dispatch daily releases at 04:45 Europe/Vienna with the hosted schedule as fallback ([pm-9url9h](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-9url9h.toon))
18
+
19
+ ## 2026.9.26 - 2026-09-26
20
+
21
+ ### Fixed
22
+
23
+ - Refuse unsupported schema dry-run flags before mutation ([pm-s74dca](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-s74dca.toon))
24
+ - Releases from the default branch are supported with analyzer evidence ([pm-u1baah](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-u1baah.toon))
25
+
26
+ ### Other
27
+
28
+ - Adapt OpenClaw test-audit skill to pm SDK and repository test governance ([pm-xvibt6](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/tasks/pm-xvibt6.toon))
29
+ - Bound embedding requests, enforce retrieval floors, and protect schema previews ([pm-g0b88h](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/changesets/pm-g0b88h.toon))
30
+
3
31
  ## 2026.9.25 - 2026-09-25
4
32
 
5
33
  ### Fixed
@@ -350,7 +378,6 @@
350
378
  - Metadata index rebuilds and mutations repeatedly scan an unindexed FTS identity column ([pm-gtw5zh](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gtw5zh.toon))
351
379
  - Read sessions emit invalid continuation identities from workspace activity rows ([pm-s8ybl9](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-s8ybl9.toon))
352
380
  - Scale fixtures silently omit unregistered Story items from metadata reads ([pm-fx80w2](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-fx80w2.toon))
353
- - Releases from the default branch are supported with analyzer evidence ([pm-u1baah](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-u1baah.toon))
354
381
 
355
382
  ### Other
356
383
 
@@ -1,4 +1,4 @@
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]="d5db626f-7623-552b-8458-bfe83a065dfb")}catch(e2){}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths}from"../sdk/agent/command-suggestions.js";import{renderMissingOptionRetry}from"../sdk/agent/command-recovery.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|");const OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"};const SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}};const SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions){return[]}const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions)){if(normalizeLongFlag(flag)===normalizedUnknown){return suggestions}}return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0){return renderedUsage}if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===true);const{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage);const enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,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]="667ad638-d21d-5a49-a00e-1335cb3f10be")}catch(e2){}})();import{pathExists,resolveItemTypeRegistry,EXIT_CODE,getSettingsPath,resolvePmRoot,readSettings,getActiveExtensionRegistrations,locateItem,runActiveServiceOverride,levenshteinDistanceWithinLimit}from"../sdk/runtime-primitives.js";import{BUILTIN_ITEM_TYPE_VALUES}from"../types/index.js";import{PM_CORE_COMMAND_NAMES,resolveSubcommandFlagContractsForCommand}from"../sdk/cli-contracts.js";import{formatCommanderErrorForDisplay,formatCommanderErrorForJson,projectLeanErrorEnvelope}from"./error-guidance.js";import{normalizeHelpCommandPath}from"./help-content.js";import{getCommandPath}from"./registration-helpers.js";import{EXECUTABLE_COMMAND_ALIASES,findBootstrapCommandTokenIndex,normalizeBootstrapInvocation,parseBootstrapHelpRequest,parseBootstrapGlobalOptions,parseBootstrapCommandName}from"./bootstrap-args.js";import{extractProvidedOptionFlags,normalizeLongFlag,renderPmCommand}from"./argv-utils.js";import{normalizeExtensionNameForMatch}from"./commands/extension/shared.js";import{canonicalizeCommandSuggestions,rankCommandPaths}from"../sdk/agent/command-suggestions.js";import{renderMissingOptionRetry}from"../sdk/agent/command-recovery.js";import{attachOutputTokenAccounting}from"../sdk/output-token-accounting.js";import{findPmNamespacedCommand,resolvePmCommandAlias}from"../sdk/cli-contracts/command-aliases.js";const BUILTIN_TYPE_HELP_VALUES=BUILTIN_ITEM_TYPE_VALUES.join("|");const OPTIONAL_PACKAGE_INSTALL_HINTS={calendar:"calendar",cal:"calendar",reindex:"search-advanced","search-advanced":"search-advanced",guide:"guide-shell",completion:"guide-shell",templates:"templates","test-runs":"linked-test-adapters",beads:"beads",todos:"todos"};const SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS={comments:{"--body":["--add"],"--text":["--add"],"--comment":["--add"]},notes:{"--body":["--add"],"--text":["--add"],"--note":["--add"]},learnings:{"--body":["--add"],"--text":["--add"],"--learning":["--add"]},update:{"--add-tag":["--add-tags"],"--remove-tag":["--remove-tags"],"--tag":["--tags"]},create:{"--add-tag":["--add-tags"],"--tag":["--tags"]}};const SCHEMA_SUBCOMMAND_VALUES=["add-field","add-status","add-type","apply-preset","list","list-fields","remap-status","remove-field","remove-status","remove-type","rename-field","rename-type","show","show-field","show-status"];function getSemanticUnknownOptionSuggestions(commandName,unknownOption){const commandSuggestions=SEMANTIC_UNKNOWN_OPTION_SUGGESTIONS[commandName];if(!commandSuggestions){return[]}const normalizedUnknown=normalizeLongFlag(unknownOption);for(const[flag,suggestions]of Object.entries(commandSuggestions)){if(normalizeLongFlag(flag)===normalizedUnknown){return suggestions}}return[]}function appendCommanderExtensionFailures(renderedUsage,json,failures){if(failures.length===0){return renderedUsage}if(json){const primaryFailure2=failures.find(entry=>entry.declared_command_match===true);const{token_accounting:priorAccounting,...usage}=JSON.parse(renderedUsage);const enriched={...usage,...primaryFailure2?{extension_command_failure:{code:"extension_command_activation_failed",extension:primaryFailure2.name,layer:primaryFailure2.layer,error:primaryFailure2.error,recovery_commands:primaryFailure2.recovery_commands??[]}}:{},failed_extensions:failures};return JSON.stringify(priorAccounting===void 0?enriched:attachOutputTokenAccounting(enriched,value=>`${JSON.stringify(value,null,2)}
2
2
  `),null,2)}const details=failures.map(entry=>`- ${entry.layer}:${entry.name}: ${entry.error}`).join("\n");const primaryFailure=failures.find(entry=>entry.declared_command_match===true);if(!primaryFailure){return`${renderedUsage}
3
3
  Extension activation failures:
4
4
  ${details}`}const recovery=(primaryFailure.recovery_commands??[]).map(command=>`- ${command}`).join("\n");return`Extension command unavailable: ${primaryFailure.layer}:${primaryFailure.name}
@@ -8,6 +8,6 @@ ${recovery}`:""}
8
8
 
9
9
  ${renderedUsage}
10
10
  Extension activation failures:
11
- ${details}`}function resolveUnknownCommanderToken(invocationArgv){const helpRequest=parseBootstrapHelpRequest(invocationArgv);return helpRequest.commandPathTokens[0]??parseBootstrapCommandName(invocationArgv)??"<command>"}function collectRuntimeCommandPaths(root,extensionDescriptors){const commandPaths=new Set;const queue=[...root.commands];while(queue.length>0){const current=queue.shift();if(!current){continue}const normalizedPath=normalizeHelpCommandPath(getCommandPath(current));const hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));if(normalizedPath.length>0&&!hasInternalSegment){commandPaths.add(normalizedPath)}queue.push(...current.commands)}for(const descriptorPath of extensionDescriptors.keys()){const normalizedPath=normalizeHelpCommandPath(descriptorPath);const hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));if(normalizedPath.length>0&&!hasInternalSegment){commandPaths.add(normalizedPath)}}return[...commandPaths].sort((left,right)=>left.localeCompare(right))}function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase();const normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0){return Number.POSITIVE_INFINITY}const pathSegments=normalizedPath.split(" ");if(normalizedPath===normalizedToken){return 0}if(pathSegments.includes(normalizedToken)){return 1}if(pathSegments.some(segment=>segment.startsWith(normalizedToken))){return 2}if(normalizedPath.includes(normalizedToken)){return 3}const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of pathSegments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);if(distance!==null){bestDistance=Math.min(bestDistance,distance)}}if(Number.isFinite(bestDistance)){return 4+bestDistance}return Number.POSITIVE_INFINITY}function toComparableFlag(flag){return normalizeLongFlag(flag).slice(2).replace(/-/g,"")}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function resolveOptionalPackageInstallHint(commandPath){const canonicalPath=resolvePmCommandAlias(commandPath)?.canonical??EXECUTABLE_COMMAND_ALIASES[commandPath]??commandPath;const topLevel=canonicalPath.split(" ")[0]?.trim().toLowerCase();if(!topLevel){return null}const packageAlias=OPTIONAL_PACKAGE_INSTALL_HINTS[topLevel];if(!packageAlias){return null}return{packageAlias,canonicalPath,installCommand:`pm package install ${packageAlias} --project`}}function normalizePackageCommandAliasToken(value){let normalized=normalizeExtensionNameForMatch(value);for(const prefix of["@unbrained/","builtin-","pm-"]){if(normalized.startsWith(prefix)){normalized=normalized.slice(prefix.length)}}return normalized}function collectInstalledPackageCommandPathHints(unknownToken,extensionDescriptors){const normalizedUnknown=normalizePackageCommandAliasToken(unknownToken);if(normalizedUnknown.length===0){return[]}const hints=[];for(const descriptor of extensionDescriptors.values()){const identifiers=new Set;const source=descriptor.source;if(source){for(const identifier of[source.name,source.package]){const normalizedIdentifier=normalizePackageCommandAliasToken(identifier??"");if(normalizedIdentifier.length>0){identifiers.add(normalizedIdentifier)}}}if(identifiers.size===0){continue}const matches=[...identifiers].some(identifier=>identifier===normalizedUnknown||identifier.includes(normalizedUnknown)||normalizedUnknown.includes(identifier));if(matches){hints.push(descriptor.command)}}return[...new Set(hints)].sort((left,right)=>left.localeCompare(right))}function collectKnownLongFlags(commandName,contractsOverride){const flags=new Set;const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);for(const contract of contracts){if(contract.flag.startsWith("--")){flags.add(normalizeLongFlag(contract.flag))}for(const alias of contract.aliases??[]){if(alias.startsWith("--")){flags.add(normalizeLongFlag(alias))}}}return[...flags].sort((left,right)=>left.localeCompare(right))}function suggestNearestLongFlags(unknownOption,knownFlags){if(!unknownOption.startsWith("--")){return[]}const unknownComparable=toComparableFlag(unknownOption);if(unknownComparable.length===0){return[]}const maxDistance=unknownComparable.length>=8?2:1;const candidates=[];for(const flag of knownFlags){const flagComparable=toComparableFlag(flag);if(flagComparable===unknownComparable){continue}if(unknownComparable.length>=3&&flagComparable.startsWith(unknownComparable)){candidates.push({flag,rank:0,distance:flagComparable.length-unknownComparable.length});continue}const distance=levenshteinDistanceWithinLimit(unknownComparable,flagComparable,maxDistance);if(distance===null||distance<=0){continue}candidates.push({flag,rank:1,distance})}return candidates.sort((left,right)=>{if(left.rank!==right.rank){return left.rank-right.rank}if(left.distance!==right.distance){return left.distance-right.distance}return left.flag.localeCompare(right.flag)}).map(entry=>entry.flag).slice(0,3)}let crossCommandFlagIndexCache;const CROSS_COMMAND_FLAG_EXCLUSIONS=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function getCrossCommandFlagIndex(){if(crossCommandFlagIndexCache){return crossCommandFlagIndexCache}const index=new Map;for(const command of PM_CORE_COMMAND_NAMES){if(CROSS_COMMAND_FLAG_EXCLUSIONS.has(command)){continue}for(const flag of collectKnownLongFlags(command)){const commands=index.get(flag)??[];commands.push(command);index.set(flag,commands)}}crossCommandFlagIndexCache=index;return crossCommandFlagIndexCache}function findOtherCommandsForFlag(unknownOption,currentCommand){if(!unknownOption.startsWith("--")){return[]}const commands=getCrossCommandFlagIndex().get(normalizeLongFlag(unknownOption));if(!commands){return[]}const normalizedCurrent=currentCommand?.trim().toLowerCase();const currentFlags=new Set(collectKnownLongFlags(normalizedCurrent));return[...new Set(commands.filter(command=>command!==normalizedCurrent).map(command=>({command,sharedFlagCount:collectKnownLongFlags(command).filter(flag=>currentFlags.has(flag)).length})).sort((left,right)=>left.sharedFlagCount!==right.sharedFlagCount?right.sharedFlagCount-left.sharedFlagCount:left.command.localeCompare(right.command)).map(({command})=>resolvePmCommandAlias(command)?.canonical??command))]}function rewriteUnknownOptionArgv(argv,unknownOption,replacementFlag){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const key=equalsIndex>=0?token.slice(0,equalsIndex):token;if(normalizeLongFlag(key)!==normalizeLongFlag(unknownOption)){continue}const next=[...argv];next[index]=equalsIndex>=0?`${replacementFlag}${token.slice(equalsIndex)}`:replacementFlag;return next}return void 0}function scoreRuntimeCommandCandidates(params){const commandPathSet=new Set(params.commandPaths);const scoreAgainstUnknown=candidatePath=>Math.min(scoreCommandPathMatch(candidatePath,params.normalizedUnknown),params.primaryToken!==params.normalizedUnknown?scoreCommandPathMatch(candidatePath,params.primaryToken):Number.POSITIVE_INFINITY);const scoresByCommandPath=new Map;const recordCandidateScore=(commandPath,score)=>{if(!Number.isFinite(score)||!commandPathSet.has(commandPath)){return}const existing=scoresByCommandPath.get(commandPath);if(existing===void 0||score<existing){scoresByCommandPath.set(commandPath,score)}};for(const commandPath of params.commandPaths){recordCandidateScore(commandPath,scoreAgainstUnknown(commandPath))}for(const[aliasToken,canonicalPath]of Object.entries(EXECUTABLE_COMMAND_ALIASES)){if(aliasToken==="read"){continue}recordCandidateScore(canonicalPath,scoreAgainstUnknown(aliasToken))}return[...scoresByCommandPath.entries()].sort(([leftPath,leftScore],[rightPath,rightScore])=>leftScore!==rightScore?leftScore-rightScore:leftPath.localeCompare(rightPath)).map(([commandPath])=>commandPath)}function resolveUnknownCommandCandidates(params){const exactAlias=resolvePmCommandAlias(params.normalizedUnknown);const semanticCandidates=rankCommandPaths(params.commandPaths,params.primaryToken);const rankedCandidates=scoreRuntimeCommandCandidates(params);const installedPackageCandidates=collectInstalledPackageCommandPathHints(params.primaryToken,params.extensionDescriptors).filter(commandPath=>params.commandPaths.includes(commandPath));return canonicalizeCommandSuggestions([...exactAlias&&params.commandPaths.includes(exactAlias.canonical)?[exactAlias.canonical_argv.join(" ")]:[],...semanticCandidates,...rankedCandidates,...installedPackageCandidates],params.commandPaths,params.primaryToken).filter(path=>!params.normalizedUnknown.includes(" ")||path!==params.normalizedUnknown)}function resolveUnknownCommandFallbacks(commandPaths){const topLevel=[...new Set(commandPaths.map(commandPath=>commandPath.split(" ")[0]).filter(segment=>segment.length>0))];return topLevel.sort((left,right)=>left.localeCompare(right))}function buildUnknownCommandExamples(suggestedPaths,hasConcreteCandidates){const suggestedExamples=suggestedPaths.map(path=>`pm ${path} --help`);if(hasConcreteCandidates){return[...new Set([...suggestedExamples,"pm --help --all"])]}return[...new Set(["pm --help --all",...suggestedExamples])]}function buildUnknownCommandGuidanceFromRuntime(rawMessage,root,extensionDescriptors){const unknownCommandMatch=rawMessage.match(/unknown command '([^']+)'/i);if(!unknownCommandMatch||typeof unknownCommandMatch[1]!=="string"){return void 0}const normalizedUnknown=normalizeHelpCommandPath(unknownCommandMatch[1]);if(normalizedUnknown.length===0){return void 0}const commandPaths=collectRuntimeCommandPaths(root,extensionDescriptors);if(commandPaths.length===0){return void 0}const optionalPackageHint=resolveOptionalPackageInstallHint(normalizedUnknown);if(optionalPackageHint&&!commandPaths.includes(optionalPackageHint.canonicalPath.split(" ")[0])){return{unknownCommandExamples:[optionalPackageHint.installCommand,`pm ${optionalPackageHint.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${normalizedUnknown}" is provided by the "${optionalPackageHint.packageAlias}" package. Install it with: ${optionalPackageHint.installCommand}. Command after installation: pm ${optionalPackageHint.canonicalPath}.`],suggestedRetryCommand:optionalPackageHint.installCommand}}const primaryToken=normalizedUnknown.split(" ")[0];const combinedCandidates=resolveUnknownCommandCandidates({commandPaths,normalizedUnknown,primaryToken,extensionDescriptors});const fallbackTopLevel=resolveUnknownCommandFallbacks(commandPaths);const suggestedPaths=(combinedCandidates.length>0?combinedCandidates:canonicalizeCommandSuggestions(fallbackTopLevel,commandPaths)).slice(0,3);const examples=buildUnknownCommandExamples(suggestedPaths,combinedCandidates.length>0);const didYouMean=combinedCandidates.length>0?`Did you mean: ${suggestedPaths.join(", ")}?`:null;return{unknownCommandExamples:examples,unknownCommandNextSteps:[...didYouMean?[didYouMean]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...didYouMean?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function dedupeStrings(values){return Array.from(new Set(values))}function firstWhitespaceSeparatedToken(input){let token="";for(const character of input){if(character===" "||character===" "||character==="\n"||character==="\r"||character==="\f"||character==="\v"){break}token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;while(end>0){const character=token[end-1];if(character!==","&&character!==":"&&character!==";"){break}end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>{if(candidate.name().trim().toLowerCase()===normalizedToken){return true}const aliases=typeof candidate.aliases==="function"?candidate.aliases():[];return aliases.some(alias=>alias.trim().toLowerCase()===normalizedToken)})}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0){return true}let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===true)&&(declaredArguments.at(-1)?.variadic===true||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return true}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot))){return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}const settings=await readSettings(pmRoot);const extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations();const typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName);const candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-")){try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i);const suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]):void 0;const otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[];const declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0){return void 0}const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i);const requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--")){return void 0}const commandName=parseBootstrapCommandName(invocationArgv);if(!commandName){return void 0}return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message)){return void 0}if(parseBootstrapCommandName(invocationArgv)!=="schema"){return void 0}const schemaIndex=findBootstrapCommandTokenIndex(invocationArgv);const verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase();const noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun){return void 0}const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined)){return void 0}const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const rawMessage=typeof error==="object"&&error!==null?error.message:void 0;const message=rawMessage??"Invalid command usage";const invocationArgv=normalizeBootstrapInvocation(process.argv.slice(2)).argv;const bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv);const commandIndex=findBootstrapCommandTokenIndex(invocationArgv);const commandName=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);const attemptedCommand=renderAttemptedCommand(invocationArgv);const providedOptionFlags=extractProvidedOptionFlags(invocationArgv);const workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName);const allowedTypes=workspaceUsage.allowedTypes;const unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors);const unknownOption=resolveUnknownOptionSuggestions(message,commandName);const splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv);const suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides);const{message,commandName,allowedTypes,unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions}=usageContext;const formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,{unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions});const serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});if(serviceOverride.handled&&typeof serviceOverride.result==="string"){return serviceOverride.result}return formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=false,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides);const envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,unknownOptionOtherCommands:usageContext.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:usageContext.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:usageContext.unknownOptionOtherCommandsTruncated,unknownOptionScope:usageContext.unknownOptionScope,unknownSubcommandPath:usageContext.unknownSubcommandPath,unknownSubcommandToken:usageContext.unknownSubcommandToken,unknownSubcommandAllowedValues:usageContext.unknownSubcommandAllowedValues,suggestedRetryCommand:usageContext.suggestedRetryCommand,verifiedCollectionItemId:usageContext.verifiedCollectionItemId,failedExtensions:usageContext.failedExtensions});const projected=lean?projectLeanErrorEnvelope(envelope):envelope;const accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===true;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
11
+ ${details}`}function resolveUnknownCommanderToken(invocationArgv){const helpRequest=parseBootstrapHelpRequest(invocationArgv);return helpRequest.commandPathTokens[0]??parseBootstrapCommandName(invocationArgv)??"<command>"}function collectRuntimeCommandPaths(root,extensionDescriptors){const commandPaths=new Set;const queue=[...root.commands];while(queue.length>0){const current=queue.shift();if(!current){continue}const normalizedPath=normalizeHelpCommandPath(getCommandPath(current));const hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));if(normalizedPath.length>0&&!hasInternalSegment){commandPaths.add(normalizedPath)}queue.push(...current.commands)}for(const descriptorPath of extensionDescriptors.keys()){const normalizedPath=normalizeHelpCommandPath(descriptorPath);const hasInternalSegment=normalizedPath.split(" ").some(segment=>segment.startsWith("_"));if(normalizedPath.length>0&&!hasInternalSegment){commandPaths.add(normalizedPath)}}return[...commandPaths].sort((left,right)=>left.localeCompare(right))}function scoreCommandPathMatch(commandPath,queryToken){const normalizedPath=commandPath.trim().toLowerCase();const normalizedToken=queryToken.trim().toLowerCase();if(normalizedToken.length===0){return Number.POSITIVE_INFINITY}const pathSegments=normalizedPath.split(" ");if(normalizedPath===normalizedToken){return 0}if(pathSegments.includes(normalizedToken)){return 1}if(pathSegments.some(segment=>segment.startsWith(normalizedToken))){return 2}if(normalizedPath.includes(normalizedToken)){return 3}const maxDistance=normalizedToken.length>=5?2:1;let bestDistance=Number.POSITIVE_INFINITY;for(const segment of pathSegments){const distance=levenshteinDistanceWithinLimit(segment,normalizedToken,maxDistance);if(distance!==null){bestDistance=Math.min(bestDistance,distance)}}if(Number.isFinite(bestDistance)){return 4+bestDistance}return Number.POSITIVE_INFINITY}function toComparableFlag(flag){return normalizeLongFlag(flag).slice(2).replace(/-/g,"")}function renderAttemptedCommand(argv){return renderPmCommand(argv)}function resolveOptionalPackageInstallHint(commandPath){const canonicalPath=resolvePmCommandAlias(commandPath)?.canonical??EXECUTABLE_COMMAND_ALIASES[commandPath]??commandPath;const topLevel=canonicalPath.split(" ")[0]?.trim().toLowerCase();if(!topLevel){return null}const packageAlias=OPTIONAL_PACKAGE_INSTALL_HINTS[topLevel];if(!packageAlias){return null}return{packageAlias,canonicalPath,installCommand:`pm package install ${packageAlias} --project`}}function normalizePackageCommandAliasToken(value){let normalized=normalizeExtensionNameForMatch(value);for(const prefix of["@unbrained/","builtin-","pm-"]){if(normalized.startsWith(prefix)){normalized=normalized.slice(prefix.length)}}return normalized}function collectInstalledPackageCommandPathHints(unknownToken,extensionDescriptors){const normalizedUnknown=normalizePackageCommandAliasToken(unknownToken);if(normalizedUnknown.length===0){return[]}const hints=[];for(const descriptor of extensionDescriptors.values()){const identifiers=new Set;const source=descriptor.source;if(source){for(const identifier of[source.name,source.package]){const normalizedIdentifier=normalizePackageCommandAliasToken(identifier??"");if(normalizedIdentifier.length>0){identifiers.add(normalizedIdentifier)}}}if(identifiers.size===0){continue}const matches=[...identifiers].some(identifier=>identifier===normalizedUnknown||identifier.includes(normalizedUnknown)||normalizedUnknown.includes(identifier));if(matches){hints.push(descriptor.command)}}return[...new Set(hints)].sort((left,right)=>left.localeCompare(right))}function collectKnownLongFlags(commandName,contractsOverride){const flags=new Set;const contracts=contractsOverride??resolveSubcommandFlagContractsForCommand(commandName);for(const contract of contracts){if(contract.flag.startsWith("--")){flags.add(normalizeLongFlag(contract.flag))}for(const alias of contract.aliases??[]){if(alias.startsWith("--")){flags.add(normalizeLongFlag(alias))}}}return[...flags].sort((left,right)=>left.localeCompare(right))}function suggestNearestLongFlags(unknownOption,knownFlags){if(!unknownOption.startsWith("--")){return[]}const unknownComparable=toComparableFlag(unknownOption);if(unknownComparable.length===0){return[]}const maxDistance=unknownComparable.length>=8?2:1;const candidates=[];for(const flag of knownFlags){const flagComparable=toComparableFlag(flag);if(flagComparable===unknownComparable){continue}if(unknownComparable.length>=3&&flagComparable.startsWith(unknownComparable)){candidates.push({flag,rank:0,distance:flagComparable.length-unknownComparable.length});continue}const distance=levenshteinDistanceWithinLimit(unknownComparable,flagComparable,maxDistance);if(distance===null||distance<=0){continue}candidates.push({flag,rank:1,distance})}return candidates.sort((left,right)=>{if(left.rank!==right.rank){return left.rank-right.rank}if(left.distance!==right.distance){return left.distance-right.distance}return left.flag.localeCompare(right.flag)}).map(entry=>entry.flag).slice(0,3)}let crossCommandFlagIndexCache;const CROSS_COMMAND_FLAG_EXCLUSIONS=new Set(["ctx","packages","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","start-task","pause-task","close-task","help"]);function getCrossCommandFlagIndex(){if(crossCommandFlagIndexCache){return crossCommandFlagIndexCache}const index=new Map;for(const command of PM_CORE_COMMAND_NAMES){if(CROSS_COMMAND_FLAG_EXCLUSIONS.has(command)){continue}for(const flag of collectKnownLongFlags(command)){const commands=index.get(flag)??[];commands.push(command);index.set(flag,commands)}}crossCommandFlagIndexCache=index;return crossCommandFlagIndexCache}function findOtherCommandsForFlag(unknownOption,currentCommand){if(!unknownOption.startsWith("--")){return[]}const commands=getCrossCommandFlagIndex().get(normalizeLongFlag(unknownOption));if(!commands){return[]}const normalizedCurrent=currentCommand?.trim().toLowerCase();const currentFlags=new Set(collectKnownLongFlags(normalizedCurrent));return[...new Set(commands.filter(command=>command!==normalizedCurrent).map(command=>({command,sharedFlagCount:collectKnownLongFlags(command).filter(flag=>currentFlags.has(flag)).length})).sort((left,right)=>left.sharedFlagCount!==right.sharedFlagCount?right.sharedFlagCount-left.sharedFlagCount:left.command.localeCompare(right.command)).map(({command})=>resolvePmCommandAlias(command)?.canonical??command))]}function rewriteUnknownOptionArgv(argv,unknownOption,replacementFlag){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(!token.startsWith("--")){continue}const equalsIndex=token.indexOf("=");const key=equalsIndex>=0?token.slice(0,equalsIndex):token;if(normalizeLongFlag(key)!==normalizeLongFlag(unknownOption)){continue}const next=[...argv];next[index]=equalsIndex>=0?`${replacementFlag}${token.slice(equalsIndex)}`:replacementFlag;return next}return void 0}function scoreRuntimeCommandCandidates(params){const commandPathSet=new Set(params.commandPaths);const scoreAgainstUnknown=candidatePath=>Math.min(scoreCommandPathMatch(candidatePath,params.normalizedUnknown),params.primaryToken!==params.normalizedUnknown?scoreCommandPathMatch(candidatePath,params.primaryToken):Number.POSITIVE_INFINITY);const scoresByCommandPath=new Map;const recordCandidateScore=(commandPath,score)=>{if(!Number.isFinite(score)||!commandPathSet.has(commandPath)){return}const existing=scoresByCommandPath.get(commandPath);if(existing===void 0||score<existing){scoresByCommandPath.set(commandPath,score)}};for(const commandPath of params.commandPaths){recordCandidateScore(commandPath,scoreAgainstUnknown(commandPath))}for(const[aliasToken,canonicalPath]of Object.entries(EXECUTABLE_COMMAND_ALIASES)){if(aliasToken==="read"){continue}recordCandidateScore(canonicalPath,scoreAgainstUnknown(aliasToken))}return[...scoresByCommandPath.entries()].sort(([leftPath,leftScore],[rightPath,rightScore])=>leftScore!==rightScore?leftScore-rightScore:leftPath.localeCompare(rightPath)).map(([commandPath])=>commandPath)}function resolveUnknownCommandCandidates(params){const exactAlias=resolvePmCommandAlias(params.normalizedUnknown);const semanticCandidates=rankCommandPaths(params.commandPaths,params.primaryToken);const rankedCandidates=scoreRuntimeCommandCandidates(params);const installedPackageCandidates=collectInstalledPackageCommandPathHints(params.primaryToken,params.extensionDescriptors).filter(commandPath=>params.commandPaths.includes(commandPath));return canonicalizeCommandSuggestions([...exactAlias&&params.commandPaths.includes(exactAlias.canonical)?[exactAlias.canonical_argv.join(" ")]:[],...semanticCandidates,...rankedCandidates,...installedPackageCandidates],params.commandPaths,params.primaryToken).filter(path=>!params.normalizedUnknown.includes(" ")||path!==params.normalizedUnknown)}function resolveUnknownCommandFallbacks(commandPaths){const topLevel=[...new Set(commandPaths.map(commandPath=>commandPath.split(" ")[0]).filter(segment=>segment.length>0))];return topLevel.sort((left,right)=>left.localeCompare(right))}function buildUnknownCommandExamples(suggestedPaths,hasConcreteCandidates){const suggestedExamples=suggestedPaths.map(path=>`pm ${path} --help`);if(hasConcreteCandidates){return[...new Set([...suggestedExamples,"pm --help --all"])]}return[...new Set(["pm --help --all",...suggestedExamples])]}function buildUnknownCommandGuidanceFromRuntime(rawMessage,root,extensionDescriptors){const unknownCommandMatch=rawMessage.match(/unknown command '([^']+)'/i);if(!unknownCommandMatch||typeof unknownCommandMatch[1]!=="string"){return void 0}const normalizedUnknown=normalizeHelpCommandPath(unknownCommandMatch[1]);if(normalizedUnknown.length===0){return void 0}const commandPaths=collectRuntimeCommandPaths(root,extensionDescriptors);if(commandPaths.length===0){return void 0}const optionalPackageHint=resolveOptionalPackageInstallHint(normalizedUnknown);if(optionalPackageHint&&!commandPaths.includes(optionalPackageHint.canonicalPath.split(" ")[0])){return{unknownCommandExamples:[optionalPackageHint.installCommand,`pm ${optionalPackageHint.canonicalPath} --help`,"pm --help --all"],unknownCommandNextSteps:[`"${normalizedUnknown}" is provided by the "${optionalPackageHint.packageAlias}" package. Install it with: ${optionalPackageHint.installCommand}. Command after installation: pm ${optionalPackageHint.canonicalPath}.`],suggestedRetryCommand:optionalPackageHint.installCommand}}const primaryToken=normalizedUnknown.split(" ")[0];const combinedCandidates=resolveUnknownCommandCandidates({commandPaths,normalizedUnknown,primaryToken,extensionDescriptors});const fallbackTopLevel=resolveUnknownCommandFallbacks(commandPaths);const suggestedPaths=(combinedCandidates.length>0?combinedCandidates:canonicalizeCommandSuggestions(fallbackTopLevel,commandPaths)).slice(0,3);const examples=buildUnknownCommandExamples(suggestedPaths,combinedCandidates.length>0);const didYouMean=combinedCandidates.length>0?`Did you mean: ${suggestedPaths.join(", ")}?`:null;return{unknownCommandExamples:examples,unknownCommandNextSteps:[...didYouMean?[didYouMean]:[],'Run "pm --help --all" to list every command available in this runtime, including active extensions.',...didYouMean?["Use one of the suggested command paths above with --help to inspect valid flags and usage."]:[]]}}function dedupeStrings(values){return Array.from(new Set(values))}function firstWhitespaceSeparatedToken(input){let token="";for(const character of input){if(character===" "||character===" "||character==="\n"||character==="\r"||character==="\f"||character==="\v"){break}token+=character}return token}function trimTrailingPunctuationToken(token){let end=token.length;while(end>0){const character=token[end-1];if(character!==","&&character!==":"&&character!==";"){break}end-=1}return token.slice(0,end)}function resolveChildCommandByToken(parent,token){const normalizedToken=token.trim().toLowerCase();return parent.commands.find(candidate=>{if(candidate.name().trim().toLowerCase()===normalizedToken){return true}const aliases=typeof candidate.aliases==="function"?candidate.aliases():[];return aliases.some(alias=>alias.trim().toLowerCase()===normalizedToken)})}function isKnownHelpCommandPath(root,commandPathTokens){if(commandPathTokens.length===0){return true}let current=root;for(const[tokenIndex,token]of commandPathTokens.entries()){const next=resolveChildCommandByToken(current,token);if(!next){const declaredArguments=current.registeredArguments;return declaredArguments.length>0&&(current.commands.length===0||declaredArguments[0]?.required===true)&&(declaredArguments.at(-1)?.variadic===true||commandPathTokens.length-tokenIndex<=declaredArguments.length)}current=next}return true}async function resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName){try{const pmRoot=resolvePmRoot(process.cwd(),bootstrapGlobal.path);if(!await pathExists(getSettingsPath(pmRoot))){return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}const settings=await readSettings(pmRoot);const extensionRegistrations=bootstrapGlobal.noExtensions?void 0:getActiveExtensionRegistrations();const typeRegistry=resolveItemTypeRegistry(settings,extensionRegistrations);let verifiedCollectionItemId;if(/too many arguments/i.test(message)&&["comments","docs","files","learnings","notes","test"].includes(commandName??"")){const commandIndex=invocationArgv.findIndex(token=>token===commandName);const candidate=invocationArgv[commandIndex+2];if(invocationArgv[commandIndex+1]?.toLowerCase()==="add"&&candidate!==void 0&&!candidate.startsWith("-")){try{verifiedCollectionItemId=(await locateItem(pmRoot,candidate,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder))?.id}catch{}}}return{allowedTypes:typeRegistry.types.length>0?typeRegistry.types.join("|"):BUILTIN_TYPE_HELP_VALUES,pmRoot,settings,typeToFolder:typeRegistry.type_to_folder,verifiedCollectionItemId}}catch{return{allowedTypes:BUILTIN_TYPE_HELP_VALUES}}}function resolveUnknownOptionSuggestions(message,commandName){const match=message.match(/unknown option '([^']+)'/i);const suggestions=match&&commandName?dedupeStrings([...getSemanticUnknownOptionSuggestions(commandName,match[1]),...suggestNearestLongFlags(match[1],collectKnownLongFlags(commandName))]):void 0;const otherCommands=match?findOtherCommandsForFlag(match[1],commandName):[];const declaredOnPath=match!==null&&collectKnownLongFlags(commandName).includes(normalizeLongFlag(match[1]));return{match,suggestions,otherCommands,scope:declaredOnPath?"declared_on_path":otherCommands.length>0?"declared_elsewhere":"declared_nowhere"}}function resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOptionMatch,unknownOptionSuggestions){if(!unknownOptionMatch||!unknownOptionSuggestions||unknownOptionSuggestions.length===0){return void 0}const rewritten=rewriteUnknownOptionArgv(invocationArgv,unknownOptionMatch[1],unknownOptionSuggestions[0]);return rewritten?renderAttemptedCommand(rewritten):void 0}function resolveSuggestedRetryForMissingOption(message,invocationArgv){const missingRequiredOption=message.match(/required option '([^']+)' not specified/i);const requiredOptionToken=missingRequiredOption?.[1]?trimTrailingPunctuationToken(firstWhitespaceSeparatedToken(missingRequiredOption[1].trim())):void 0;if(!requiredOptionToken?.startsWith("--")){return void 0}const commandName=parseBootstrapCommandName(invocationArgv);if(!commandName){return void 0}return renderMissingOptionRetry(invocationArgv,commandName,[requiredOptionToken])}function resolveSplitSchemaSubcommand(message,invocationArgv){if(!/too many arguments/i.test(message)){return void 0}const commandIndex=findBootstrapCommandTokenIndex(invocationArgv);const namespaced=findPmNamespacedCommand(invocationArgv.slice(commandIndex));if(namespaced?.alias!=="schema"){return void 0}const schemaIndex=commandIndex+namespaced.canonical_argv.length-1;const verb=invocationArgv[schemaIndex+1]?.trim().toLowerCase();const noun=invocationArgv[schemaIndex+2]?.trim().toLowerCase();if(!verb||!noun){return void 0}const joined=`${verb}-${noun}`;if(!SCHEMA_SUBCOMMAND_VALUES.includes(joined)){return void 0}const rewritten=[...invocationArgv.slice(0,schemaIndex+1),joined,...invocationArgv.slice(schemaIndex+3)];return{unknownSubcommandPath:"schema",unknownSubcommandToken:`${verb} ${noun}`,unknownSubcommandAllowedValues:[...SCHEMA_SUBCOMMAND_VALUES],suggestedRetryCommand:renderAttemptedCommand(rewritten)}}async function resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const rawMessage=typeof error==="object"&&error!==null?error.message:void 0;const message=rawMessage??"Invalid command usage";const invocationArgv=normalizeBootstrapInvocation(process.argv.slice(2)).argv;const bootstrapGlobal=parseBootstrapGlobalOptions(invocationArgv);const commandIndex=findBootstrapCommandTokenIndex(invocationArgv);const commandName=findPmNamespacedCommand(invocationArgv.slice(commandIndex))?.alias??parseBootstrapCommandName(invocationArgv);const attemptedCommand=renderAttemptedCommand(invocationArgv);const providedOptionFlags=extractProvidedOptionFlags(invocationArgv);const workspaceUsage=await resolveWorkspaceUsageContext(bootstrapGlobal,message,invocationArgv,commandName);const allowedTypes=workspaceUsage.allowedTypes;const unknownCommandGuidance=buildUnknownCommandGuidanceFromRuntime(message,rootProgram,extensionDescriptors);const unknownOption=resolveUnknownOptionSuggestions(message,commandName);const splitSchemaSubcommand=resolveSplitSchemaSubcommand(message,invocationArgv);const suggestedRetryCommand=splitSchemaSubcommand?.suggestedRetryCommand??resolveSuggestedRetryForUnknownOption(invocationArgv,unknownOption.match,unknownOption.suggestions)??resolveSuggestedRetryForMissingOption(message,invocationArgv);return{message,commandName,allowedTypes,attemptedCommand,normalizedInvocationArgs:[...invocationArgv],providedOptionFlags,unknownOptionSuggestions:unknownOption.suggestions,unknownOptionOtherCommands:unknownOption.otherCommands.length>0?unknownOption.otherCommands.slice(0,12):void 0,unknownOptionOtherCommandsTotal:unknownOption.otherCommands.length>0?unknownOption.otherCommands.length:void 0,unknownOptionOtherCommandsTruncated:unknownOption.otherCommands.length>12||void 0,unknownOptionScope:unknownOption.scope,suggestedRetryCommand,verifiedCollectionItemId:workspaceUsage.verifiedCollectionItemId,...splitSchemaSubcommand,...unknownCommandGuidance,...guidanceOverrides}}async function formatCommanderUsageMessage(error,rootProgram,extensionDescriptors,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides);const{message,commandName,allowedTypes,unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions}=usageContext;const formatted=formatCommanderErrorForDisplay(message,commandName,allowedTypes,{unknownCommandExamples,unknownCommandNextSteps,attemptedCommand,normalizedInvocationArgs,providedOptionFlags,unknownOptionSuggestions,unknownOptionOtherCommands,unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated,unknownOptionScope,unknownSubcommandPath,unknownSubcommandToken,unknownSubcommandAllowedValues,suggestedRetryCommand,verifiedCollectionItemId,failedExtensions});const serviceOverride=await runActiveServiceOverride("help_format",{message:formatted,command:commandName,allowed_types:allowedTypes});if(serviceOverride.handled&&typeof serviceOverride.result==="string"){return serviceOverride.result}return formatted}async function formatCommanderUsageJson(error,rootProgram,extensionDescriptors,lean=false,guidanceOverrides={}){const usageContext=await resolveCommanderUsageContext(error,rootProgram,extensionDescriptors,guidanceOverrides);const envelope=formatCommanderErrorForJson(usageContext.message,usageContext.commandName,usageContext.allowedTypes,EXIT_CODE.USAGE,{unknownCommandExamples:usageContext.unknownCommandExamples,unknownCommandNextSteps:usageContext.unknownCommandNextSteps,attemptedCommand:usageContext.attemptedCommand,normalizedInvocationArgs:usageContext.normalizedInvocationArgs,providedOptionFlags:usageContext.providedOptionFlags,unknownOptionSuggestions:usageContext.unknownOptionSuggestions,unknownOptionOtherCommands:usageContext.unknownOptionOtherCommands,unknownOptionOtherCommandsTotal:usageContext.unknownOptionOtherCommandsTotal,unknownOptionOtherCommandsTruncated:usageContext.unknownOptionOtherCommandsTruncated,unknownOptionScope:usageContext.unknownOptionScope,unknownSubcommandPath:usageContext.unknownSubcommandPath,unknownSubcommandToken:usageContext.unknownSubcommandToken,unknownSubcommandAllowedValues:usageContext.unknownSubcommandAllowedValues,suggestedRetryCommand:usageContext.suggestedRetryCommand,verifiedCollectionItemId:usageContext.verifiedCollectionItemId,failedExtensions:usageContext.failedExtensions});const projected=lean?projectLeanErrorEnvelope(envelope):envelope;const accountingRequested=parseBootstrapGlobalOptions(usageContext.normalizedInvocationArgs).tokenAccounting===true;return JSON.stringify(accountingRequested?attachOutputTokenAccounting(projected,value=>`${JSON.stringify(value,null,2)}
12
12
  `):projected,null,2)}const _testOnly={collectKnownLongFlags,collectInstalledPackageCommandPathHints,resolveOptionalPackageInstallHint,resolveSuggestedRetryForMissingOption,suggestNearestLongFlags};export{BUILTIN_TYPE_HELP_VALUES,_testOnly,appendCommanderExtensionFailures,buildUnknownCommandGuidanceFromRuntime,collectRuntimeCommandPaths,formatCommanderUsageJson,formatCommanderUsageMessage,isKnownHelpCommandPath,resolveChildCommandByToken,resolveCommanderUsageContext,resolveUnknownCommanderToken,scoreCommandPathMatch};
13
13
  //# sourceMappingURL=commander-usage.js.map