@unbrained/pm-cli 2026.11.20 → 2026.11.22
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/pm-developer/SKILL.md +1 -1
- package/.agents/skills/pm-sdk/SKILL.md +1 -1
- package/.agents/skills/pm-test-audit/SKILL.md +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/CONTRIBUTING.md +2 -1
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/register-history-maintenance.js +2 -2
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
- package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +125 -0
- package/dist/cli-bundle/chunks/{chunk-4TZW4NLM.js → chunk-5ZMVLWE3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
- package/dist/cli-bundle/chunks/{chunk-GXGW6KHB.js → chunk-AR4NP5HI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6X2AGUOT.js → chunk-B4PPFOPY.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-XK25TAJZ.js → chunk-B76TFRO2.js} +47 -45
- package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-KDDIHGAO.js → chunk-EIGUKEV6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZAO7VGX3.js → chunk-GTPCAJMZ.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KQSPKWFH.js → chunk-HC2OPETM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5LF5QZT3.js → chunk-HKUV74K3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
- package/dist/cli-bundle/chunks/{chunk-FF4TXJDH.js → chunk-J2LABXBL.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3BOR22MC.js → chunk-J52BEBSS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +3 -0
- package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +3 -0
- package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +31 -0
- package/dist/cli-bundle/chunks/{chunk-DG2EOOFX.js → chunk-TC6XLIYO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MGYAJONE.js → chunk-U7EL3AYA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-ZVEHACE6.js → chunk-X6MIWTTT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-KEBLUTC3.js → chunk-XFHPKXAE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OXG5XPC7.js → chunk-YHVLVSEZ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Y4LXVPA5.js → chunk-YMUSRWV4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQYIKAC6.js → chunk-YR2KEBHP.js} +2 -2
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-ELEMA7IW.js → indexed-receipt-blobs-ITTXIN4K.js} +2 -2
- package/dist/cli-bundle/chunks/{item-revision-GE2CQECR.js → item-revision-4QBMZXKX.js} +2 -2
- package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-actor-5GYX7LP3.js → mutation-actor-FWLYWJ37.js} +2 -2
- package/dist/cli-bundle/chunks/{mutation-admission-72TYKPGU.js → mutation-admission-7ZDCK3G2.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-OQZZEWEB.js → register-list-query-RR5KACJ3.js} +10 -10
- package/dist/cli-bundle/chunks/{register-mutation-YZEUZ6XT.js → register-mutation-57AJQWFV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-JNVCF7EW.js → register-operations-RKWST7CU.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-LDKULZSD.js → register-setup-CMI23PC5.js} +2 -2
- package/dist/cli-bundle/chunks/{settlement-hook-E5LHZ4RD.js → settlement-hook-BXN5LEQD.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-Q2QZ2IBG.js → stage-4KDVXC5Z.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JUYJ7NXL.js → chunk-2ZD7275J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7SB6VKEI.js → chunk-324AHXJO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-IXYBN6D2.js → chunk-3IRCYJI5.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-DH4DHL6V.js → chunk-3V53UBHN.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
- package/dist/cli-bundle/focused-chunks/{chunk-V55XZFOP.js → chunk-4JZITIJB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-BZCLW5V7.js → chunk-BRZV7BFV.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PKMDWIP3.js → chunk-HDEKFSOK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-O25KFLLA.js → chunk-IWOXAUDU.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UATP3RK3.js → chunk-ML3JHCC6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ZKGGGU2K.js → chunk-OPGOOP25.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-PRFEOCNZ.js → chunk-RE7ZWT7D.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KQJNJZKP.js → chunk-URGHTTT3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +13 -0
- package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
- package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PQXTZLK3.js → chunk-WZWXGDYY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-5VSXKA35.js → chunk-YKSLZPLT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-ZTRFCPH7.js → indexed-receipt-blobs-AF4U3F3D.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{item-revision-OXDZHMJ7.js → item-revision-2O6MLPEX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
- package/dist/cli-bundle/focused-chunks/{mutation-actor-6DYIF6NH.js → mutation-actor-TCYDPUGG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-2BYXANVJ.js → mutation-admission-LY73EJWM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{settlement-hook-OUBUN45C.js → settlement-hook-ARYCZQY4.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-FGHSB3QX.js → stage-DQ7RQQ52.js} +2 -2
- package/dist/cli-bundle/main.js +25 -25
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +70 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/core/diagnostics/remediation.js +1 -1
- package/dist/core/extensions/index.d.ts +2 -0
- package/dist/core/extensions/index.js +1 -1
- package/dist/core/fs/atomic-create.js +1 -1
- package/dist/core/fs/file-glob.js +1 -1
- package/dist/core/fs/fs-utils.d.ts +3 -1
- package/dist/core/fs/fs-utils.js +1 -1
- package/dist/core/history/bridge.js +2 -0
- package/dist/core/history/drift-scan.js +1 -1
- package/dist/core/history/history-rewrite.js +1 -1
- package/dist/core/history/history-stream-policy.js +1 -1
- package/dist/core/history/history.d.ts +12 -0
- package/dist/core/history/history.js +2 -2
- package/dist/core/history/projection.js +1 -1
- package/dist/core/history/read.d.ts +20 -1
- package/dist/core/history/read.js +1 -1
- package/dist/core/history/replay.d.ts +46 -5
- package/dist/core/history/replay.js +2 -2
- package/dist/core/history/stream-summary.d.ts +129 -0
- package/dist/core/history/stream-summary.js +3 -0
- package/dist/core/shared/errors.d.ts +8 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/core/shared/url-credentials.js +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
- package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
- package/dist/sdk/completion/fish.js +3 -2
- package/dist/sdk/completion/zsh.js +3 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
- package/dist/sdk/governance/gc.js +1 -1
- package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
- package/dist/sdk/governance/health-merge-evidence.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/governance/validate.js +1 -1
- package/dist/sdk/governance/workspace-position.js +1 -1
- package/dist/sdk/history/append-only-repair.d.ts +30 -0
- package/dist/sdk/history/append-only-repair.js +6 -0
- package/dist/sdk/history/maintenance.d.ts +8 -2
- package/dist/sdk/history/maintenance.js +1 -1
- package/dist/sdk/history/reanchor-refusal.js +2 -0
- package/dist/sdk/history/reseed.d.ts +15 -0
- package/dist/sdk/history/reseed.js +2 -0
- package/dist/sdk/history/salvage.d.ts +19 -8
- package/dist/sdk/history/salvage.js +5 -3
- package/dist/sdk/history-compact.js +1 -1
- package/dist/sdk/history-provenance.js +1 -1
- package/dist/sdk/history-redact.js +1 -1
- package/dist/sdk/history-repair.d.ts +8 -2
- package/dist/sdk/history-repair.js +1 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/item-transaction.d.ts +33 -1
- package/dist/sdk/item-transaction.js +1 -1
- package/dist/sdk/lifecycle/restore.js +1 -1
- package/dist/sdk/merge/index.d.ts +1 -1
- package/dist/sdk/merge/index.js +1 -1
- package/dist/sdk/merge/install.d.ts +20 -6
- package/dist/sdk/merge/install.js +3 -3
- package/dist/sdk/merge/three-way.d.ts +22 -3
- package/dist/sdk/merge/three-way.js +8 -2
- package/dist/sdk/merge/worktree-config.js +2 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.d.ts +67 -5
- package/dist/sdk/query/activity.js +1 -1
- package/dist/sdk/query/context.d.ts +13 -3
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query.d.ts +1 -1
- package/dist/sdk/runtime/actions.js +1 -1
- package/dist/sdk/runtime-input.d.ts +6 -2
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +7 -0
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/structured-mutations.d.ts +5 -5
- package/dist/sdk/structured-mutations.js +1 -1
- package/dist/sdk/transactions/item-finalization.js +2 -0
- package/dist/types.d.ts +20 -0
- package/dist/types.js +1 -1
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
- package/docs/COMMANDS.md +62 -4
- package/docs/HISTORY_RECOVERY.md +229 -5
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/MUTATION_INTEGRITY.md +3 -1
- package/docs/README.md +8 -6
- package/docs/SDK.md +128 -5
- package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
- package/docs/TESTING.md +8 -697
- package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +1 -1
- package/marketplace.json +1 -1
- package/node_modules/tar/package.json +2 -3
- package/package.json +35 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli-bundle/chunks/chunk-2IZGNOGT.js +0 -6
- package/dist/cli-bundle/chunks/chunk-4QQPM3IY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-5OFMWP3Q.js +0 -3
- package/dist/cli-bundle/chunks/chunk-6HRPGEBF.js +0 -2
- package/dist/cli-bundle/chunks/chunk-7ESF676D.js +0 -125
- package/dist/cli-bundle/chunks/chunk-7EZZ4W7O.js +0 -20
- package/dist/cli-bundle/chunks/chunk-FOYRE23V.js +0 -115
- package/dist/cli-bundle/chunks/chunk-HJQ3XPS3.js +0 -31
- package/dist/cli-bundle/chunks/chunk-M5D3CEMY.js +0 -9
- package/dist/cli-bundle/chunks/chunk-VS565KBX.js +0 -2
- package/dist/cli-bundle/chunks/chunk-W4TLA5H3.js +0 -8
- package/dist/cli-bundle/chunks/item-transaction-YSAWJRA2.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-3LRSQXCN.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FOA7XKWP.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FPKVHC3Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-I7XBR2RM.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-MJP3TFVW.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PZSTRYTA.js +0 -102
- package/dist/cli-bundle/focused-chunks/chunk-QNJQPJWO.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-SIPDQBJI.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SJE3PYPI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-TNKI6WKG.js +0 -66
- package/dist/cli-bundle/focused-chunks/chunk-TRCXANRR.js +0 -12
- package/dist/cli-bundle/focused-chunks/item-transaction-54VSTT6L.js +0 -2
- package/dist/sdk/agent/refusal-closure.js +0 -2
- package/dist/sdk/agent/refusal-reachability.js +0 -4
- package/dist/sdk/agent/task-transcript-contracts.js +0 -2
- package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
- package/dist/sdk/authoring.js +0 -2
- package/dist/sdk/compose.js +0 -2
- package/dist/sdk/contracts.js +0 -2
- package/dist/sdk/core-governance.js +0 -2
- package/dist/sdk/core.js +0 -2
- package/dist/sdk/corpus-shape.js +0 -2
- package/dist/sdk/define.js +0 -2
- package/dist/sdk/environment/agent-environment.js +0 -2
- package/dist/sdk/governance/artifact-ledgers.js +0 -2
- package/dist/sdk/governance/coverage-assurance.js +0 -2
- package/dist/sdk/governance/reliability.js +0 -2
- package/dist/sdk/governance.js +0 -2
- package/dist/sdk/graph/adapter.js +0 -2
- package/dist/sdk/graph/conformance.js +0 -2
- package/dist/sdk/graph/index.js +0 -2
- package/dist/sdk/graph.js +0 -2
- package/dist/sdk/index.js +0 -2
- package/dist/sdk/query.js +0 -2
- package/dist/sdk/relationship-migration.js +0 -2
- package/dist/sdk/testing.js +0 -8
- package/dist/sdk/workspace-recipe.js +0 -2
- package/docs/AGENT_PROVENANCE_ADR.md +0 -206
- package/docs/DEFECT_RECURRENCE.md +0 -257
- package/docs/MCP_2026_07_28_CONFORMANCE.md +0 -41
- package/docs/PERFORMANCE.md +0 -189
- package/docs/QUALITY_EVIDENCE.md +0 -130
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +0 -117
- package/docs/performance/cli-transport-overhead.md +0 -51
- package/docs/performance/runner-qualification.md +0 -36
- package/docs/performance/sdk-entrypoint-import-costs.md +0 -32
|
@@ -69,7 +69,7 @@ pm release <ID>
|
|
|
69
69
|
|
|
70
70
|
Before closing a repository defect, inspect its declared `escape_class` and
|
|
71
71
|
`gate_evidence` contract and record the required structured evidence. In pm-cli,
|
|
72
|
-
follow [Defect Evidence](
|
|
72
|
+
follow [Defect Evidence](https://github.com/unbraind/pm-cli/blob/main/docs/DEFECT_RECURRENCE.md#defect-evidence-on-pm-items) (repository-only, excluded from npm)
|
|
73
73
|
and run `pnpm quality:defect-evidence` **after** closure: a gate run while the item
|
|
74
74
|
is active cannot prove terminal-only requirements. Verify runner changes with
|
|
75
75
|
both build-enabled and prebuilt CI environments.
|
|
@@ -104,7 +104,7 @@ so a new public entrypoint cannot ship ungoverned.
|
|
|
104
104
|
The [generated capability routing](../../../docs/generated/AGENT_CAPABILITY_ROUTING.md)
|
|
105
105
|
covers every declared family. Expand only the family needed, then query its
|
|
106
106
|
published SDK symbols and runtime contract. For MCP integrations, start with
|
|
107
|
-
the [current conformance matrix](
|
|
107
|
+
the [current conformance matrix](https://github.com/unbraind/pm-cli/blob/main/docs/MCP_2026_07_28_CONFORMANCE.md) (repository-only, excluded from npm)
|
|
108
108
|
and its SDK-owned request, transport, task, subscription, Skills, and Apps
|
|
109
109
|
contracts; distinguish implementation evidence from exact-release acceptance.
|
|
110
110
|
|
|
@@ -73,7 +73,7 @@ node scripts/run-tests.mjs coverage
|
|
|
73
73
|
being tested. Use real temporary persistence when proving writes or recovery.
|
|
74
74
|
- Run relevant functional, integration, package, performance, and acceptance
|
|
75
75
|
gates according to the changed contract. A focused green run is not a full
|
|
76
|
-
suite result. [Quality evidence](
|
|
76
|
+
suite result. [Quality evidence](https://github.com/unbraind/pm-cli/blob/main/docs/QUALITY_EVIDENCE.md) (repository-only, excluded from npm) defines the
|
|
77
77
|
bounded mutation gate; do not describe it as whole-repository mutation proof.
|
|
78
78
|
- Preserve static quality, docstring, security, release, and public-surface gates.
|
|
79
79
|
This skill does not grant exceptions to repository coding rules.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.
|
|
1
|
+
{"name":"pm","owner":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"description":"Official marketplace for pm CLI — native git-based project management for Claude Code and AI coding agents.","version":"2026.11.22","plugins":[{"name":"pm-claude","source":"./plugins/pm-claude","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.","version":"2026.11.22","author":{"name":"unbrained","url":"https://github.com/unbraind/pm-cli"},"homepage":"https://github.com/unbraind/pm-cli","repository":"https://github.com/unbraind/pm-cli","license":"MIT","keywords":["pm-cli","project-management","mcp","tasks","agents","workflows","git-native","task-tracker","ai"],"category":"productivity"}]}
|
package/CONTRIBUTING.md
CHANGED
|
@@ -166,7 +166,8 @@ Start with the [documentation index](docs/README.md). Focused pages:
|
|
|
166
166
|
- [Agent Guide](docs/AGENT_GUIDE.md) - canonical `pm` workflow for coding agents.
|
|
167
167
|
- [Command Reference](docs/COMMANDS.md) - command families and examples.
|
|
168
168
|
- [Configuration](docs/CONFIGURATION.md) - settings, output, storage, search, and validation.
|
|
169
|
-
- [Testing](docs/TESTING.md) - sandbox-safe
|
|
169
|
+
- [Testing](docs/TESTING.md) - sandbox-safe linked-test workflows.
|
|
170
|
+
- [Repository Testing](https://github.com/unbraind/pm-cli/blob/main/docs/REPOSITORY_TESTING.md) - local checks, CI layout, coverage governance and release gates for this repository (repository-only, excluded from npm).
|
|
170
171
|
- [Architecture](docs/ARCHITECTURE.md) - source tree, storage, mutation contract, history, search, and extension host internals.
|
|
171
172
|
- [Extensions](docs/EXTENSIONS.md) and [SDK](docs/SDK.md) - extension lifecycle and public SDK.
|
|
172
173
|
- [Releasing](https://github.com/unbraind/pm-cli/blob/main/docs/RELEASING.md) (repository-only, excluded from npm) - maintainer release procedure.
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b81f6f48-3465-58b5-b5cf-ada7aaddc901")}catch{}})();import{describeReadCompletenessControls,isReadProjectionRecoveryFlag,resolveReadCompletenessControls,resolveReadOptionRetryArgs,resolveLinkedResourcePositionalRecovery}from"../sdk/agent/command-recovery.js";import{PM_CLI_ERROR_DETAILS_LIMITS,isPmTokenBudgetRecovery,projectPmCliErrorContextDetailsSlot}from"../sdk/errors.js";import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{estimatePmOutputTokens,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,projectPmDiagnosticOutput,projectPmDiagnosticText,resolvePmDiagnosticOutputBudget,withoutGenericRefusalExamples}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";import{redactGuidanceCredentials}from"./runtime/refusal-credential-redaction.js";function projectLeanErrorEnvelope(envelope){const{title:_title,...actionable}=envelope;isGenericRefusalWhy(actionable.why)&&delete actionable.why,isGenericRefusalRequired(actionable.required)&&delete actionable.required;const examples=withoutGenericRefusalExamples(actionable.examples);examples.length>0?actionable.examples=examples:delete actionable.examples;const recovery=projectLeanRecoveryPayload(actionable.recovery);return recovery===void 0?delete actionable.recovery:actionable.recovery=recovery,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){return!message.why||message.recovery?.recovery_mode==="compact"?!1:!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"},CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},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 KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){return entries.length===0?[]:[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values))return;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;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){typeof value=="string"&&value.trim().length>0&&(normalized[key]=value.trim())}function normalizeRecoveryArgs(value){return Array.isArray(value)&&value.length>0&&value.every(entry=>typeof entry=="string")?[...value]:void 0}function assignRecoveryCollection(normalized,key,value){if(key==="normalized_args"||key==="suggested_retry_args"||key==="allowed_values"){const args=normalizeRecoveryArgs(value);args&&(normalized[key]=args);return}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);parsedPositionals.length>0&&(normalized.parsed_positionals=parsedPositionals);return}const values=normalizeStringArray(value);values&&(normalized[key]=values)}function assignRecoveryTokenBudget(target,value){if(!isPmTokenBudgetRecovery(value))return;const{requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}=value;target.token_budget={requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}}const RECOVERY_COUNTER_KEYS=["retry_after_ms","waited_ms","owner_handoffs"];function appendRecoveryCounterLines(lines,normalized){for(const key of RECOVERY_COUNTER_KEYS)typeof normalized[key]=="number"&&lines.push(` ${key}: ${normalized[key]}`)}function assignRecoveryCounters(normalized,payload){for(const key of RECOVERY_COUNTER_KEYS){const value=payload[key];typeof value=="number"&&Number.isSafeInteger(value)&&value>=0&&(normalized[key]=value)}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};assignRecoveryTokenBudget(normalized,payload.token_budget),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),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),payload.candidate_commands_truncated===!0&&(normalized.candidate_commands_truncated=!0),(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),assignRecoveryCounters(normalized,payload);const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);return fallbackCandidates&&(normalized.fallback_candidates=fallbackCandidates),assignRecoveryString(normalized,"next_best_command",payload.next_best_command),Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){value&&lines.push(` ${label}: ${value}`)}function appendRecoveryListLine(lines,label,values,separator){values&&values.length>0&&lines.push(` ${label}: ${values.join(separator)}`)}function appendRecoveryAllowedValues(lines,values,limit){const visible=values?.slice(0,limit).map(value=>/^[\p{L}\p{N}._:/@=-]+$/u.test(value)?value:JSON.stringify(value));appendRecoveryListLine(lines,"allowed_values",visible,", "),values&&values.length>limit&&lines.push(` allowed_values_omitted: ${values.length-limit} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function renderRecoveryBundle(recovery,allowedValuesLimit){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return[];const lines=["Recovery bundle:"];if(normalized.token_budget){const budget=normalized.token_budget;lines.push(` requested_token_budget: ${budget.requested_tokens}`,` feasible_token_budget: ${budget.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${budget.minimum_feasible_tokens??"not established"}`)}if(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," "),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}`)}if(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,", "),appendRecoveryAllowedValues(lines,normalized.allowed_values,allowedValuesLimit),appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", "),typeof normalized.candidate_commands_total=="number"&&lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`),normalized.candidate_commands_truncated===!0&&lines.push(" candidate_commands_truncated: true"),normalized.option_scope!==void 0&&lines.push(` option_scope: ${normalized.option_scope}`),appendRecoveryCounterLines(lines,normalized),appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command),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}const CLAIM_HOLDER_TEXT_MAX_CODE_POINTS=120;function renderClaimHolderLine(message){if(message.claimedBy===void 0)return;const since=message.claimedAt?` since ${message.claimedAt}`:"",holder=Array.from(message.claimedBy),name=holder.length>CLAIM_HOLDER_TEXT_MAX_CODE_POINTS?`${holder.slice(0,CLAIM_HOLDER_TEXT_MAX_CODE_POINTS).join("")}...`:message.claimedBy,activity=message.claimActivity,idle=activity===void 0||activity.idle_hours===null?"":`; idle ${activity.idle_hours}h, ${activity.stale_policy.stale?"stale":"active"} under ${activity.stale_policy.setting}=${activity.stale_policy.threshold_hours}`;return`Held by: ${name} (${message.claimSource??"unknown"}${since})${idle}`}function renderGuidanceLead(message,lean){const lines=[`Error: ${message.title}`];message.code==="close_validation_missing_fields"&&message.recovery?.suggested_retry&&lines.push(`Run: ${message.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!lean||!isGenericRefusalRequired(message.required))&&lines.push("","What is required:",` ${message.required}`),message.nextSteps&&message.nextSteps.length>0&&(lines.push(""),lines.push(...renderList("Next steps:",message.nextSteps))),message.happened!==message.title&&lines.push("","What happened:",` ${message.happened}`);const holderLine=renderClaimHolderLine(message);return holderLine!==void 0&&lines.push("",holderLine),lines}function renderGuidanceExplanation(message,lean){const lines=[];message.why&&!(lean&&isGenericRefusalWhy(message.why))&&lines.push("","Why:",` ${message.why}`);const examples=lean?withoutGenericRefusalExamples(message.examples):message.examples??[];examples.length>0&&lines.push("",...renderList("Examples:",examples));const verificationErrors=message.verificationErrors??[];return verificationErrors.length>0&&lines.push("",...renderList("Verification errors:",verificationErrors)),lines.push(...renderGuidanceDetails(message)),lines}function renderGuidanceDetails(message){if(message.details!==void 0&&Object.keys(message.details).length>0)return["","Details:",...JSON.stringify(message.details,null,2).split(`
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b171d8d7-ee63-55f2-9900-352c9b741710")}catch{}})();import{describeReadCompletenessControls,isReadProjectionRecoveryFlag,resolveReadCompletenessControls,resolveReadOptionRetryArgs,resolveLinkedResourcePositionalRecovery}from"../sdk/agent/command-recovery.js";import{PM_CLI_ERROR_DETAILS_LIMITS,isPmTokenBudgetRecovery,projectPmCliErrorContextDetailsSlot}from"../sdk/errors.js";import{resolveRecoveryCommandName}from"../sdk/agent/command-recovery.js";import{estimatePmOutputTokens,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,projectPmDiagnosticOutput,projectPmDiagnosticText,resolvePmDiagnosticOutputBudget,withoutGenericRefusalExamples}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";import{redactGuidanceCredentials}from"./runtime/refusal-credential-redaction.js";function projectLeanErrorEnvelope(envelope){const{title:_title,...actionable}=envelope;isGenericRefusalWhy(actionable.why)&&delete actionable.why,isGenericRefusalRequired(actionable.required)&&delete actionable.required;const examples=withoutGenericRefusalExamples(actionable.examples);examples.length>0?actionable.examples=examples:delete actionable.examples;const recovery=projectLeanRecoveryPayload(actionable.recovery);return recovery===void 0?delete actionable.recovery:actionable.recovery=recovery,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){return!message.why||message.recovery?.recovery_mode==="compact"?!1:!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"},CALENDAR_HINT={packageName:"@unbrained/pm-calendar",installCommand:"pm install calendar"},SEARCH_ADVANCED_HINT={packageName:"@unbrained/pm-search-advanced",installCommand:"pm install search-advanced"},GOVERNANCE_AUDIT_HINT={packageName:"@unbrained/pm-governance-audit",installCommand:"pm install audit"},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 KNOWN_PACKAGE_COMMAND_HINTS[primary]}function renderList(title,entries){return entries.length===0?[]:[title,...entries.map(entry=>` - ${entry}`)]}function normalizeStringArray(values){if(!Array.isArray(values))return;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;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){typeof value=="string"&&value.trim().length>0&&(normalized[key]=value.trim())}function normalizeRecoveryArgs(value){return Array.isArray(value)&&value.length>0&&value.every(entry=>typeof entry=="string")?[...value]:void 0}function assignRecoveryCollection(normalized,key,value){if(key==="normalized_args"||key==="suggested_retry_args"||key==="allowed_values"){const args=normalizeRecoveryArgs(value);args&&(normalized[key]=args);return}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);parsedPositionals.length>0&&(normalized.parsed_positionals=parsedPositionals);return}const values=normalizeStringArray(value);values&&(normalized[key]=values)}function assignRecoveryTokenBudget(target,value){if(!isPmTokenBudgetRecovery(value))return;const{requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}=value;target.token_budget={requested_tokens,feasible_tokens,minimum_feasible_tokens,minimum_status,basis,reason}}const RECOVERY_COUNTER_KEYS=["retry_after_ms","waited_ms","owner_handoffs"];function appendRecoveryCounterLines(lines,normalized){for(const key of RECOVERY_COUNTER_KEYS)typeof normalized[key]=="number"&&lines.push(` ${key}: ${normalized[key]}`)}function assignRecoveryCounters(normalized,payload){for(const key of RECOVERY_COUNTER_KEYS){const value=payload[key];typeof value=="number"&&Number.isSafeInteger(value)&&value>=0&&(normalized[key]=value)}}function normalizeRecoveryPayload(payload){if(!payload||typeof payload!="object")return;const normalized={};assignRecoveryTokenBudget(normalized,payload.token_budget),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),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),payload.candidate_commands_truncated===!0&&(normalized.candidate_commands_truncated=!0),(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),assignRecoveryCounters(normalized,payload);const fallbackCandidates=normalizeRecoveryCandidates(payload.fallback_candidates);return fallbackCandidates&&(normalized.fallback_candidates=fallbackCandidates),assignRecoveryString(normalized,"next_best_command",payload.next_best_command),Object.keys(normalized).length>0?normalized:void 0}function appendRecoveryTextLine(lines,label,value){value&&lines.push(` ${label}: ${value}`)}function appendRecoveryListLine(lines,label,values,separator){values&&values.length>0&&lines.push(` ${label}: ${values.join(separator)}`)}function appendRecoveryAllowedValues(lines,values,limit){const visible=values?.slice(0,limit).map(value=>/^[\p{L}\p{N}._:/@=-]+$/u.test(value)?value:JSON.stringify(value));appendRecoveryListLine(lines,"allowed_values",visible,", "),values&&values.length>limit&&lines.push(` allowed_values_omitted: ${values.length-limit} (complete domain via SDK error.context.recovery.allowed_values; JSON diagnostics may be budgeted)`)}function renderRecoveryBundle(recovery,allowedValuesLimit){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return[];const lines=["Recovery bundle:"];if(normalized.token_budget){const budget=normalized.token_budget;lines.push(` requested_token_budget: ${budget.requested_tokens}`,` feasible_token_budget: ${budget.feasible_tokens??"unavailable"}`,` minimum_token_budget: ${budget.minimum_feasible_tokens??"not established"}`)}if(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," "),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}`)}if(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,", "),appendRecoveryAllowedValues(lines,normalized.allowed_values,allowedValuesLimit),appendRecoveryListLine(lines,"candidate_commands",normalized.candidate_commands,", "),typeof normalized.candidate_commands_total=="number"&&lines.push(` candidate_commands_total: ${String(normalized.candidate_commands_total)}`),normalized.candidate_commands_truncated===!0&&lines.push(" candidate_commands_truncated: true"),normalized.option_scope!==void 0&&lines.push(` option_scope: ${normalized.option_scope}`),appendRecoveryCounterLines(lines,normalized),appendRecoveryTextLine(lines,"next_best_command",normalized.next_best_command),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}const CLAIM_HOLDER_TEXT_MAX_CODE_POINTS=120;function renderClaimHolderLine(message){if(message.claimedBy===void 0)return;const since=message.claimedAt?` since ${message.claimedAt}`:"",holder=Array.from(message.claimedBy),name=holder.length>CLAIM_HOLDER_TEXT_MAX_CODE_POINTS?`${holder.slice(0,CLAIM_HOLDER_TEXT_MAX_CODE_POINTS).join("")}...`:message.claimedBy,activity=message.claimActivity,idle=activity===void 0||activity.idle_hours===null?"":`; idle ${activity.idle_hours}h, ${activity.stale_policy.stale?"stale":"active"} under ${activity.stale_policy.setting}=${activity.stale_policy.threshold_hours}`;return`Held by: ${name} (${message.claimSource??"unknown"}${since})${idle}`}function renderGuidanceLead(message,lean){const lines=[`Error: ${message.title}`];message.code==="close_validation_missing_fields"&&message.recovery?.suggested_retry&&lines.push(`Run: ${message.recovery.suggested_retry}`,"Template: replace every placeholder with real evidence before running."),(!lean||!isGenericRefusalRequired(message.required))&&lines.push("","What is required:",` ${message.required}`),message.nextSteps&&message.nextSteps.length>0&&(lines.push(""),lines.push(...renderList("Next steps:",message.nextSteps))),message.happened!==message.title&&lines.push("","What happened:",` ${message.happened}`);const holderLine=renderClaimHolderLine(message);return holderLine!==void 0&&lines.push("",holderLine),lines}function renderGuidanceExplanation(message,lean){const lines=[];message.why&&!(lean&&isGenericRefusalWhy(message.why))&&lines.push("","Why:",` ${message.why}`);const examples=lean?withoutGenericRefusalExamples(message.examples):message.examples??[];examples.length>0&&lines.push("",...renderList("Examples:",examples));const verificationErrors=message.verificationErrors??[];return verificationErrors.length>0&&lines.push("",...renderList("Verification errors:",verificationErrors)),lines.push(...renderGuidanceDetails(message)),lines}function renderGuidanceDetails(message){if(message.details!==void 0&&Object.keys(message.details).length>0)return["","Details:",...JSON.stringify(message.details,null,2).split(`
|
|
2
2
|
`).map(line=>` ${line}`)];const omitted=message.detailsOmitted;if(omitted===void 0)return[];const where=omitted.path===void 0?` (over ${omitted.byte_limit} bytes)`:` at ${omitted.path}`;return["",`Details omitted: ${omitted.reason}${where}`]}function renderGuidanceMessage(message,options={}){return renderGuidanceMessageWithRecoveryLimit(message,options,8)}function renderGuidanceMessageWithRecoveryLimit(message,options,allowedValuesLimit){const lean=options.lean===!0,lines=[...renderGuidanceLead(message,lean),...renderGuidanceExplanation(message,lean||message.code==="close_validation_missing_fields")],recovery=message.code==="close_validation_missing_fields"&&message.recovery?{...message.recovery,suggested_retry:void 0}:message.recovery,recoveryLines=renderRecoveryBundle(lean?projectLeanRecoveryPayload(recovery):recovery,allowedValuesLimit);return recoveryLines.length>0&&(lines.push(""),lines.push(...recoveryLines)),lines.join(`
|
|
3
3
|
`)}const TEXT_DIAGNOSTIC_OMISSION_NOTICE="Some guidance was omitted to fit the diagnostic token ceiling; rerun with --json for structured recovery within its own budget.",TEXT_RECOVERY_RETRY_MAX_BYTES=400,TEXT_HAPPENED_MAX_CODE_POINTS=320;function compactTextRecovery(recovery){const normalized=normalizeRecoveryPayload(recovery);if(!normalized)return;const compact={};normalized.suggested_retry&&Buffer.byteLength(normalized.suggested_retry,"utf8")<=TEXT_RECOVERY_RETRY_MAX_BYTES&&(compact.suggested_retry=normalized.suggested_retry);for(const key of["missing","missing_required_fields"]){const values=normalized[key];values&&values.length>0&&(compact[key]=values.slice(0,3))}return normalized.allowed_values&&(compact.allowed_values=normalized.allowed_values),normalized.next_best_command&&(compact.next_best_command=normalized.next_best_command),Object.keys(compact).length>0?compact:void 0}function compactCloseRecoverySteps(message,compact){if(message.code!=="close_validation_missing_fields"||!message.recovery?.suggested_retry||compact.recovery?.suggested_retry)return compact.nextSteps;const nextSteps=compact.recovery?.next_best_command?["Run recovery.next_best_command with real evidence, then repeat the original close."]:[...compact.nextSteps,"Retrieve the complete retry from SDK error.context.recovery.suggested_retry; replace placeholders with real evidence before executing it."];return appendIfMissing(nextSteps,message.partialLegalDomainNotice)}function renderBoundedGuidanceMessage(message,options={}){const full=renderGuidanceMessage(message,options),budget=resolvePmDiagnosticOutputBudget("error").default_max_estimated_tokens_by_format.text,fits=text=>estimatePmOutputTokens(Buffer.byteLength(text,"utf8"))<=budget;if(fits(full))return full;const withoutExplanation={...message,why:void 0},limitedNextSteps=appendIfMissing(message.nextSteps?.slice(0,1)??[],message.partialLegalDomainNotice),limitedCollections={...withoutExplanation,details:void 0,examples:message.examples?.slice(0,1),nextSteps:limitedNextSteps,verificationErrors:message.verificationErrors?.slice(0,3)},compactRecovery={...limitedCollections,recovery:compactTextRecovery(message.recovery)};compactRecovery.nextSteps=compactCloseRecoverySteps(message,compactRecovery);const happenedCodePoints=Array.from(message.happened),boundedHappened={...compactRecovery,examples:void 0,happened:happenedCodePoints.length>TEXT_HAPPENED_MAX_CODE_POINTS?`${happenedCodePoints.slice(0,TEXT_HAPPENED_MAX_CODE_POINTS).join("")}...`:message.happened},essentialDomainGuidance={code:message.code,type:message.type,title:message.title,happened:boundedHappened.happened,required:message.required,nextSteps:appendIfMissing([],message.partialLegalDomainNotice)};essentialDomainGuidance.nextSteps=compactCloseRecoverySteps(message,essentialDomainGuidance);for(const[candidate,limit]of[[withoutExplanation,8],[limitedCollections,8],[compactRecovery,3],[boundedHappened,3],...message.partialLegalDomainNotice?[[essentialDomainGuidance,3],[{...essentialDomainGuidance,happened:message.title},3],[{...essentialDomainGuidance,required:"Correct the producer metadata before relying on a complete legal domain."},3]]:[]]){const text=`${renderGuidanceMessageWithRecoveryLimit(candidate,options,limit)}
|
|
4
4
|
|
|
5
|
-
${TEXT_DIAGNOSTIC_OMISSION_NOTICE}`;if(fits(text))return text}return full}function attachItemDiagnostics(payload,message){message.tombstone!==void 0&&(payload.tombstone=message.tombstone,payload.item_id=message.itemId),message.lease!==void 0&&(payload.lease=message.lease,payload.current_owner=message.currentOwner??null,payload.item_id=message.itemId),message.claimedBy!==void 0&&(payload.claimed_by=message.claimedBy,payload.claimed_at=message.claimedAt??null,payload.claim_source=message.claimSource??"unknown",message.claimActivity!==void 0&&(payload.claim_activity=message.claimActivity),payload.item_id=message.itemId),message.currentRevision!==void 0&&(payload.expected_revision=message.expectedRevision??null,payload.current_revision=message.currentRevision,message.itemId!==void 0&&(payload.item_id=message.itemId))}function attachStructuredGuidanceDetails(payload,message){return message.sideEffects!==void 0&&(payload.side_effects=message.sideEffects),message.previewStorage!==void 0&&(payload.preview_storage=message.previewStorage),message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),attachItemDiagnostics(payload,message),includeWhyInStructuredGuidance(message)&&(payload.why=message.why),message.examples&&message.examples.length>0&&(payload.examples=message.examples),message.nextSteps&&message.nextSteps.length>0&&(payload.next_steps=message.nextSteps),message.verificationErrors&&message.verificationErrors.length>0&&(payload.verification_errors=message.verificationErrors),message.flag!==void 0&&(payload.flag=message.flag),message.value!==void 0&&(payload.value=message.value),message.unmatchedSelectors!==void 0&&(payload.unmatched_selectors=message.unmatchedSelectors),message.availableDependencies!==void 0&&(payload.available_dependencies=message.availableDependencies),message.recovery&&(payload.recovery=message.recovery),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}=`))};return[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(message.flag===void 0&&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 normalizedArgs[candidateIndex+1]}}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??[]),namespaced=findPmNamespacedCommand(invocationArgs),normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs,candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs),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){const envelope=attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode),...message.changed===!1?{changed:!1}:{}},message);return message.details!==void 0&&(envelope.details=message.details),message.detailsOmitted!==void 0&&(envelope.details_omitted=message.detailsOmitted),envelope}function projectJsonErrorGuidance(rawGuidance,exitCode){const guidance=redactGuidanceCredentials(rawGuidance),recovery=guidance.recovery,diagnosticClass=recovery?.suggested_retry||recovery?.suggested_retry_args?.length||recovery?.allowed_values?.length||recovery?.candidate_commands?.length||guidance.nextSteps?.length?"recovery_bundle":"error";return projectPmDiagnosticOutput(withinDiagnosticBudget(guidanceToJsonEnvelope(guidance,exitCode),diagnosticClass),{diagnosticClass})}function withinDiagnosticBudget(envelope,diagnosticClass){if(envelope.details===void 0)return envelope;const budget=resolvePmDiagnosticOutputBudget(diagnosticClass).default_max_estimated_tokens_by_format.json;if(estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(envelope,null,2),"utf8"))<=budget)return envelope;const{details:_dropped,...rest}=envelope;return{...rest,details_omitted:{reason:"diagnostic_budget",byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,...message.changed===!1?{changed:!1}:{}},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;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,result=[];for(const value of values)seen.has(value)||(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);return match?match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry)):[]}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args,fields=recovery?.provided_fields,replacement=allowedValues[0];if(!(!Array.isArray(args)||!Array.isArray(fields)||!replacement))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];return nextArgs[index+1]=replacement,renderPmCommand(nextArgs)}}}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0)return;const codePoints=Array.from(firstLine);return codePoints.length<=120?firstLine:`${codePoints.slice(0,117).join("")}...`}function normalizeContextValue(value,fallback){return typeof value=="string"&&value.trim().length>0?value.trim():fallback}function resolveErrorContextFlag(context,recovery){if(context.flag!==void 0)return context.flag;if(context.field===void 0)return;const flag=context.field.startsWith("--")?context.field:`--${context.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return recovery?.normalized_args?.some(argument=>argument===flag||argument.startsWith(`${flag}=`))?flag:void 0}function resolveTypedRefusalTitle(guidance,code,context,normalizedRawMessage){if(code==="close_validation_missing_fields")return"Close is missing required evidence";const generic=guidance.code==="command_failed"||guidance.code==="invalid_argument_value"&&code!==guidance.code;return(context.code&&generic?buildFallbackTitleFromMessage(normalizedRawMessage):void 0)??guidance.title}function resolveGuidanceDetails(context){const projected=projectPmCliErrorContextDetailsSlot(context);return projected===void 0?{}:"details"in projected?{details:projected.details}:{detailsOmitted:projected.details_omitted}}const PARTIAL_LEGAL_DOMAIN_PREVIEW_MAX_BYTES=400;function previewLegalDomainChoices(values){const shown=[];for(const value of values.slice(0,8)){const rendered=JSON.stringify(value);Buffer.byteLength([...shown,rendered].join(", "),"utf8")<=PARTIAL_LEGAL_DOMAIN_PREVIEW_MAX_BYTES&&shown.push(rendered)}return shown}function partialLegalDomainGuidance(recovery){const domain=recovery?.allowed_values;if(domain===void 0||Array.isArray(domain)&&domain.every(value=>typeof value=="string"))return;const usable=Array.isArray(domain)?domain.filter(value=>typeof value=="string"):[],shown=previewLegalDomainChoices(usable),visible=shown.join(", ")||"none shown",omitted=usable.length>shown.length?` (${usable.length-shown.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${visible}${omitted}. Correct the producer metadata before relying on a complete domain.`}function mergeGuidanceRecovery(guidance,context,incompleteDomain){const normalized=normalizeRecoveryPayload(context),merged=normalized&&guidance?normalizeRecoveryPayload({...guidance,...normalized}):normalized??guidance;if(!incompleteDomain)return merged;const{allowed_values:_untrustedDomain,...retained}=merged??{};return Object.keys(retained).length>0?retained:void 0}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context)return guidance;const normalizedRawMessage=normalizeMessage(rawMessage),code=normalizeContextValue(context.code,guidance.code),type=normalizeContextValue(context.type,errorType(code)),examples=normalizeContextList(context.examples)??guidance.examples,producerNextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps,partialDomain=partialLegalDomainGuidance(context.recovery),nextSteps=partialDomain?[...producerNextSteps?.slice(0,1)??[],partialDomain,...producerNextSteps?.slice(1)??[]]:producerNextSteps,verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors,recovery=mergeGuidanceRecovery(guidance.recovery,context.recovery,partialDomain!==void 0);return{...guidance,code,changed:context.changed,sideEffects:context.side_effects,type,title:resolveTypedRefusalTitle(guidance,code,context,normalizedRawMessage),happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,partialLegalDomainNotice:partialDomain,verificationErrors,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:resolveErrorContextFlag(context,recovery)??guidance.flag,value:context.value??guidance.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,transactionOperation:context.transaction_operation,previewStorage:context.preview_storage,tombstone:context.tombstone,lease:context.lease,currentOwner:context.current_owner,claimedBy:context.claimed_by,claimedAt:context.claimed_at,claimSource:context.claim_source,claimActivity:context.claim_activity,expectedRevision:context.expected_revision,currentRevision:context.current_revision,availableDependencies:context.available_dependencies,recovery,...resolveGuidanceDetails(context)}}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],nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);return applyPmCliErrorContext(makeGuidanceMessage(nearbyRoot?{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}.`]}:{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],isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId),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.`;return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",flag:"id",value:badId,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: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."]}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){return!message.includes("is assigned to")||!message.includes("Use --force to override")?null: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;const args=normalizeRecoveryArgs(context?.recovery?.normalized_args),retry=args?renderPmCommand(args):void 0,guidance=applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:retry?[retry]:["pm gc --scope locks --dry-run"]}),rawMessage,context);return args&&(guidance.recovery={...guidance.recovery,suggested_retry:retry,suggested_retry_args:[...args]}),guidance}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /),missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions)return null;const plural=!!missingRequiredOptions,missingOptionFlag=plural?null:message.replace(/^Missing required option\s+/,"").trim(),missingOptionLabel=missingOptionFlag??"",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){return message.startsWith("No update flags provided")?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):null}function isInvalidArgumentMessage(message,context){if(message.startsWith("Invalid "))return!0;if(!message.includes(" must be ")&&!message.includes(" requires "))return!1;const code=normalizeContextValue(context?.code,void 0);return code===void 0||code==="invalid_argument_value"||context?.allowed!==void 0}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!isInvalidArgumentMessage(message,context))return null;const recovery=normalizeRecoveryPayload(context?.recovery),commandName=inferCommandNameFromRecovery(recovery),helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help",allowedValues=context?.recovery?.allowed_values!==void 0?[]:context?.allowed??inferAllowedValuesFromMessage(message),enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues}),retryExample=buildAllowedValueRetryCommand(recovery,allowedValues),examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"],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);return(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))||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){return commandName==="create"&&optionFlag.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${allowedTypes.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:commandName==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();return normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??normalized}function renderPmCommandFromArgs(argv){if(!(!Array.isArray(argv)||argv.length===0))return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values))return;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),normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0,attemptedCommand=typeof context?.attemptedCommand=="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs),retryCommand=typeof context?.suggestedRetryCommand=="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,suggested_retry_args:context?.suggestedRetryArgs,...overrides})}function appendIfMissing(entries,value){return!value||entries.includes(value)?entries:[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]),LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(Array.isArray(argv))for(const token of argv){if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag))return flag}}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv))return;const commandIndex=argv.indexOf("test");if(commandIndex<0)return;const idToken=argv[commandIndex+1];if(!(typeof idToken!="string"||idToken.startsWith("-")))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;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;const merged=`${key}=${valueTokens.join(" ")}`,rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption)return null;const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]),isType=optionFlag.startsWith("--type"),retryCommand=context?.suggestedRetryCommand,providedFlags=normalizeOptionFlags(context?.providedOptionFlags),missing=[optionFlag],examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes),examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples,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.`],nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase,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),proseRemainder=candidateContext.candidateTotal-proseCommands.length,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,retryCommand?void 0:describeSameCommandCompleteness(optionName,commandName),proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,isDashLeadingValue(optionName)?`"${optionName}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`: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")}const READ_COMPLETENESS_SPELLINGS=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function describeSameCommandCompleteness(optionName,commandName){if(commandName===void 0||!READ_COMPLETENESS_SPELLINGS.includes(optionName.split("=",1)[0]))return;const controls=resolveReadCompletenessControls(commandName);return controls===void 0?void 0:`Completeness controls accepted by pm ${controls.command}: ${describeReadCompletenessControls(controls)}.`}function resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:[...READ_COMPLETENESS_SPELLINGS,"--toon",...commandName==="activity"?["--since"]:[]].includes(optionName.split("=",1)[0])?{}:void 0}function isDashLeadingValue(optionName){return/\s/u.test(optionName)}function resolveDashLeadingValueRetry(args,optionName){const index=args?.indexOf(optionName)??-1;if(args===void 0||index<0||args.includes("--")||args.lastIndexOf(optionName)!==index)return{};if(args.slice(index+1).some(token=>!token.startsWith("-")))return{};const suggestedRetryArgs=[...stripGlobalBootstrapTokens(args.filter((_,position)=>position!==index)),"--",optionName];return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function resolveUnknownOptionRetry(context,optionName,commandName){if(isDashLeadingValue(optionName))return resolveDashLeadingValueRetry(context.normalizedInvocationArgs,optionName);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};const readRetry=resolveReadIntentRetry(context,optionName,commandName);if(readRetry)return readRetry;if(context.suggestedRetryCommand!==void 0)return{retryCommand:context.suggestedRetryCommand};if(isReadProjectionRecoveryFlag(optionName))return{};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("-")!==!0)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??{},optionName=unknownOption[1],suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[],{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName,commandName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc"))return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions);const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext),nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);["--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,commandName?`pm ${resolvePmCommandAlias(commandName)?.canonical??commandName} --help`:"pm --help --all"].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}`,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],runtimeExamples=normalizeContextList(context?.unknownCommandExamples),runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps),packageHint=resolveKnownPackageCommandHint(commandToken),baseExamples=runtimeExamples??["pm --help"],baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."],failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase())),hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))?buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context):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(),token=context?.unknownSubcommandToken?.trim(),allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed)return null;const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,value: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,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 buildLinkedResourcePositionalGuidance(message,commandName,context){if(!/too many arguments/i.test(message))return null;const recovery=resolveLinkedResourcePositionalRecovery(commandName,context?.normalizedInvocationArgs??[]);if(!recovery)return null;const retry=recovery.retryArgs?renderPmCommand(recovery.retryArgs):void 0,template=renderPmCommand(recovery.templateArgs??["test",recovery.itemId,"--add",`command=<actual command>,${recovery.value}`]);return makeGuidanceMessage({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${commandName}.`,required:retry?`Retry the explicit collection mutation: ${retry}`:`Supply the actual command and its metadata together, for example ${template}.`,examples:[retry??template],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:retry,suggested_retry_args:recovery.retryArgs})})}function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??""))return null;const argv=context?.normalizedInvocationArgs??[],commandIndex=argv.findIndex(token=>token===commandName),action=argv[commandIndex+1],parsedItemId=argv[commandIndex+2],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"]),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??[],commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token)),searchIndex=commandIndex===-1?1:commandIndex+1,match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=!1;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=!1;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(!token.startsWith("-")){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);return(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)??buildLinkedResourcePositionalGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context))||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,options={}){const guidance=redactGuidanceCredentials(buildPmCliErrorGuidance(rawMessage,context));return(context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args?[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
5
|
+
${TEXT_DIAGNOSTIC_OMISSION_NOTICE}`;if(fits(text))return text}return full}function attachItemDiagnostics(payload,message){message.tombstone!==void 0&&(payload.tombstone=message.tombstone,payload.item_id=message.itemId),message.lease!==void 0&&(payload.lease=message.lease,payload.current_owner=message.currentOwner??null,payload.item_id=message.itemId),message.claimedBy!==void 0&&(payload.claimed_by=message.claimedBy,payload.claimed_at=message.claimedAt??null,payload.claim_source=message.claimSource??"unknown",message.claimActivity!==void 0&&(payload.claim_activity=message.claimActivity),payload.item_id=message.itemId),message.currentRevision!==void 0&&(payload.expected_revision=message.expectedRevision??null,payload.current_revision=message.currentRevision,message.itemId!==void 0&&(payload.item_id=message.itemId))}function attachStructuredGuidanceDetails(payload,message){return message.sideEffects!==void 0&&(payload.side_effects=message.sideEffects),message.previewStorage!==void 0&&(payload.preview_storage=message.previewStorage),message.transactionOperation!==void 0&&(payload.transaction_operation=message.transactionOperation),attachItemDiagnostics(payload,message),includeWhyInStructuredGuidance(message)&&(payload.why=message.why),message.examples&&message.examples.length>0&&(payload.examples=message.examples),message.nextSteps&&message.nextSteps.length>0&&(payload.next_steps=message.nextSteps),message.verificationErrors&&message.verificationErrors.length>0&&(payload.verification_errors=message.verificationErrors),message.flag!==void 0&&(payload.flag=message.flag),message.value!==void 0&&(payload.value=message.value),message.unmatchedSelectors!==void 0&&(payload.unmatched_selectors=message.unmatchedSelectors),message.availableDependencies!==void 0&&(payload.available_dependencies=message.availableDependencies),message.recovery&&(payload.recovery=message.recovery),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}=`))};return[...`${message.title} ${message.happened}`.matchAll(/--[A-Za-z0-9][A-Za-z0-9_-]*/gu)].map(match=>match[0]).find(flag=>isAdmissibleCandidate(flag))}function resolveRefusalRejectedValue(message,normalizedArgs,candidateFlag){if(message.value!==void 0)return message.value;if(message.flag===void 0&&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 normalizedArgs[candidateIndex+1]}}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??[]),namespaced=findPmNamespacedCommand(invocationArgs),normalizedArgs=namespaced?[namespaced.alias,...invocationArgs.slice(namespaced.canonical_argv.length)]:invocationArgs,candidateFlag=resolveRefusalCandidateFlag(message,normalizedArgs),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){const envelope=attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,exit_code:exitCode,refusal:buildRefusalEnvelope(message,exitCode),...message.changed===!1?{changed:!1}:{}},message);return message.details!==void 0&&(envelope.details=message.details),message.detailsOmitted!==void 0&&(envelope.details_omitted=message.detailsOmitted),envelope}function projectJsonErrorGuidance(rawGuidance,exitCode){const guidance=redactGuidanceCredentials(rawGuidance),recovery=guidance.recovery,diagnosticClass=recovery?.suggested_retry||recovery?.suggested_retry_args?.length||recovery?.allowed_values?.length||recovery?.candidate_commands?.length||guidance.nextSteps?.length?"recovery_bundle":"error";return projectPmDiagnosticOutput(withinDiagnosticBudget(guidanceToJsonEnvelope(guidance,exitCode),diagnosticClass),{diagnosticClass})}function withinDiagnosticBudget(envelope,diagnosticClass){if(envelope.details===void 0)return envelope;const budget=resolvePmDiagnosticOutputBudget(diagnosticClass).default_max_estimated_tokens_by_format.json;if(estimatePmOutputTokens(Buffer.byteLength(JSON.stringify(envelope,null,2),"utf8"))<=budget)return envelope;const{details:_dropped,...rest}=envelope;return{...rest,details_omitted:{reason:"diagnostic_budget",byte_limit:PM_CLI_ERROR_DETAILS_LIMITS.max_bytes}}}function guidanceToClassification(message){return attachStructuredGuidanceDetails({type:message.type,code:message.code,title:message.title,detail:message.happened,required:message.required,...message.changed===!1?{changed:!1}:{}},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;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,result=[];for(const value of values)seen.has(value)||(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);return match?match[1].split(/[|,]/).map(entry=>entry.trim()).filter(entry=>/^[A-Za-z0-9_.-]+$/.test(entry)):[]}function buildAllowedValueRetryCommand(recovery,allowedValues){const args=recovery?.normalized_args,fields=recovery?.provided_fields,replacement=allowedValues[0];if(!(!Array.isArray(args)||!Array.isArray(fields)||!replacement))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];return nextArgs[index+1]=replacement,renderPmCommand(nextArgs)}}}function buildFallbackTitleFromMessage(message){const firstLine=message.split(/\r?\n/)[0].trim();if(firstLine.length===0)return;const codePoints=Array.from(firstLine);return codePoints.length<=120?firstLine:`${codePoints.slice(0,117).join("")}...`}function normalizeContextValue(value,fallback){return typeof value=="string"&&value.trim().length>0?value.trim():fallback}function resolveErrorContextFlag(context,recovery){if(context.flag!==void 0)return context.flag;if(context.field===void 0)return;const flag=context.field.startsWith("--")?context.field:`--${context.field.replaceAll(/([A-Z])([A-Z][a-z])/gu,"$1-$2").replaceAll(/([a-z0-9])([A-Z])/gu,"$1-$2").replaceAll("_","-").toLowerCase()}`;return recovery?.normalized_args?.some(argument=>argument===flag||argument.startsWith(`${flag}=`))?flag:void 0}function resolveTypedRefusalTitle(guidance,code,context,normalizedRawMessage){if(code==="close_validation_missing_fields")return"Close is missing required evidence";const generic=guidance.code==="command_failed"||guidance.code==="invalid_argument_value"&&code!==guidance.code;return(context.code&&generic?buildFallbackTitleFromMessage(normalizedRawMessage):void 0)??guidance.title}function resolveGuidanceDetails(context){const projected=projectPmCliErrorContextDetailsSlot(context);return projected===void 0?{}:"details"in projected?{details:projected.details}:{detailsOmitted:projected.details_omitted}}const PARTIAL_LEGAL_DOMAIN_PREVIEW_MAX_BYTES=400;function previewLegalDomainChoices(values){const shown=[];for(const value of values.slice(0,8)){const rendered=JSON.stringify(value);Buffer.byteLength([...shown,rendered].join(", "),"utf8")<=PARTIAL_LEGAL_DOMAIN_PREVIEW_MAX_BYTES&&shown.push(rendered)}return shown}function partialLegalDomainGuidance(recovery){const domain=recovery?.allowed_values;if(domain===void 0||Array.isArray(domain)&&domain.every(value=>typeof value=="string"))return;const usable=Array.isArray(domain)?domain.filter(value=>typeof value=="string"):[],shown=previewLegalDomainChoices(usable),visible=shown.join(", ")||"none shown",omitted=usable.length>shown.length?` (${usable.length-shown.length} additional valid choices omitted)`:"";return`Incomplete legal domain from malformed producer metadata. Usable choices shown: ${visible}${omitted}. Correct the producer metadata before relying on a complete domain.`}function mergeGuidanceRecovery(guidance,context,incompleteDomain){const normalized=normalizeRecoveryPayload(context),merged=normalized&&guidance?normalizeRecoveryPayload({...guidance,...normalized}):normalized??guidance;if(!incompleteDomain)return merged;const{allowed_values:_untrustedDomain,...retained}=merged??{};return Object.keys(retained).length>0?retained:void 0}function applyPmCliErrorContext(guidance,rawMessage,context){if(!context)return guidance;const normalizedRawMessage=normalizeMessage(rawMessage),code=normalizeContextValue(context.code,guidance.code),type=normalizeContextValue(context.type,errorType(code)),examples=normalizeContextList(context.examples)??guidance.examples,producerNextSteps=normalizeContextList(context.nextSteps)??guidance.nextSteps,partialDomain=partialLegalDomainGuidance(context.recovery),nextSteps=partialDomain?[...producerNextSteps?.slice(0,1)??[],partialDomain,...producerNextSteps?.slice(1)??[]]:producerNextSteps,verificationErrors=normalizeContextList(context.verification_errors)??guidance.verificationErrors,recovery=mergeGuidanceRecovery(guidance.recovery,context.recovery,partialDomain!==void 0);return{...guidance,code,changed:context.changed,sideEffects:context.side_effects,type,title:resolveTypedRefusalTitle(guidance,code,context,normalizedRawMessage),happened:normalizedRawMessage.length>0?normalizedRawMessage:guidance.happened,required:normalizeContextValue(context.required,guidance.required),why:normalizeContextValue(context.why,guidance.why),examples,nextSteps,urlCredentialsRejected:context.url_credentials_rejected??guidance.urlCredentialsRejected,partialLegalDomainNotice:partialDomain,verificationErrors,policyViolations:context.policy_violations,policyViolationCount:context.policy_violation_count,flag:resolveErrorContextFlag(context,recovery)??guidance.flag,value:context.value??guidance.value,unmatchedSelectors:context.unmatched_selectors,itemId:context.item_id,transactionOperation:context.transaction_operation,previewStorage:context.preview_storage,tombstone:context.tombstone,lease:context.lease,currentOwner:context.current_owner,claimedBy:context.claimed_by,claimedAt:context.claimed_at,claimSource:context.claim_source,claimActivity:context.claim_activity,expectedRevision:context.expected_revision,currentRevision:context.current_revision,availableDependencies:context.available_dependencies,recovery,...resolveGuidanceDetails(context)}}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],nearbyRoot=discoverNearbyPmRoot(process.cwd(),attemptedRoot);return applyPmCliErrorContext(makeGuidanceMessage(nearbyRoot?{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}.`]}:{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],isPlaceholder=/^(undefined|null|<.*>|\[.*\]|{.*}|)$/.test(badId),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.`;return applyPmCliErrorContext(makeGuidanceMessage({code:"item_not_found",title:"Item ID not found",flag:"id",value:badId,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: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."]}),rawMessage,context)}function buildOwnershipConflictGuidance(rawMessage,message,context){return!message.includes("is assigned to")||!message.includes("Use --force to override")?null: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;const args=normalizeRecoveryArgs(context?.recovery?.normalized_args),retry=args?renderPmCommand(args):void 0,guidance=applyPmCliErrorContext(makeGuidanceMessage({code:"lock_conflict",title:"Lock conflict",happened:message,required:"Wait for lock release, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget for expected contention.",why:"Locking protects item files from concurrent write races.",examples:retry?[retry]:["pm gc --scope locks --dry-run"]}),rawMessage,context);return args&&(guidance.recovery={...guidance.recovery,suggested_retry:retry,suggested_retry_args:[...args]}),guidance}function buildPmMissingRequiredOptionGuidance(rawMessage,message,context){const missingRequiredOption=message.match(/^Missing required option /),missingRequiredOptions=message.match(/^Missing required options /);if(!missingRequiredOption&&!missingRequiredOptions)return null;const plural=!!missingRequiredOptions,missingOptionFlag=plural?null:message.replace(/^Missing required option\s+/,"").trim(),missingOptionLabel=missingOptionFlag??"",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){return message.startsWith("No update flags provided")?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):null}function isInvalidArgumentMessage(message,context){if(message.startsWith("Invalid "))return!0;if(!message.includes(" must be ")&&!message.includes(" requires "))return!1;const code=normalizeContextValue(context?.code,void 0);return code===void 0||code==="invalid_argument_value"||context?.allowed!==void 0}function buildInvalidArgumentGuidance(rawMessage,message,context){if(!isInvalidArgumentMessage(message,context))return null;const recovery=normalizeRecoveryPayload(context?.recovery),commandName=inferCommandNameFromRecovery(recovery),helpExample=commandName?`pm ${commandName} --help`:"pm <command> --help",allowedValues=context?.recovery?.allowed_values!==void 0?[]:context?.allowed??inferAllowedValuesFromMessage(message),enrichedRecovery=normalizeRecoveryPayload({...recovery,allowed_values:recovery?.allowed_values??allowedValues}),retryExample=buildAllowedValueRetryCommand(recovery,allowedValues),examples=retryExample?[retryExample,helpExample]:[helpExample,"pm contracts --command <command> --flags-only --json"],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);return(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))||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){return commandName==="create"&&optionFlag.startsWith("--type")?[`pm create --title "Example title" --description "Example description" --type ${allowedTypes.split("|")[0]||"Task"} --status open --priority 1 --message "Create item" --create-mode progressive`]:commandName==="update"?['pm update pm-a1b2 --status in_progress --message "Start implementation"']:[`pm ${commandName??"<command>"} --help`]}function normalizeRequiredOptionLabel(rawValue){const normalized=rawValue.trim();return normalized.match(/--[A-Za-z0-9][A-Za-z0-9_-]*/)?.[0]??normalized}function renderPmCommandFromArgs(argv){if(!(!Array.isArray(argv)||argv.length===0))return renderPmCommand(argv)}function normalizeOptionFlags(values){if(!Array.isArray(values))return;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),normalizedArgs=Array.isArray(context?.normalizedInvocationArgs)&&context?.normalizedInvocationArgs.length>0?context.normalizedInvocationArgs:void 0,attemptedCommand=typeof context?.attemptedCommand=="string"?context.attemptedCommand:renderPmCommandFromArgs(normalizedArgs),retryCommand=typeof context?.suggestedRetryCommand=="string"?context.suggestedRetryCommand:void 0;return normalizeRecoveryPayload({attempted_command:attemptedCommand,normalized_args:normalizedArgs,provided_fields:providedFields,suggested_retry:retryCommand,suggested_retry_args:context?.suggestedRetryArgs,...overrides})}function appendIfMissing(entries,value){return!value||entries.includes(value)?entries:[...entries,value]}const LINKED_TEST_MUTATION_FLAGS=new Set(["--add","--add-json","--remove"]),LINKED_TEST_RETRY_KEYS=new Set(["command","cmd","path"]);function findLinkedTestMutationFlag(argv){if(Array.isArray(argv))for(const token of argv){if(!token.startsWith("--"))continue;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(LINKED_TEST_MUTATION_FLAGS.has(flag))return flag}}function buildLinkedTestQuotedRetryCommand(argv){if(!Array.isArray(argv))return;const commandIndex=argv.indexOf("test");if(commandIndex<0)return;const idToken=argv[commandIndex+1];if(!(typeof idToken!="string"||idToken.startsWith("-")))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;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;const merged=`${key}=${valueTokens.join(" ")}`,rewritten=[...argv.slice(0,index+1),merged,...argv.slice(index+2+valueTokens.length)];return renderPmCommand(rewritten)}}function buildMissingRequiredOptionGuidance(message,commandName,allowedTypes,context){const requiredOption=message.match(/required option '([^']+)' not specified/);if(!requiredOption)return null;const optionFlag=normalizeRequiredOptionLabel(requiredOption[1]),isType=optionFlag.startsWith("--type"),retryCommand=context?.suggestedRetryCommand,providedFlags=normalizeOptionFlags(context?.providedOptionFlags),missing=[optionFlag],examples=commandExampleForRequiredOption(commandName,optionFlag,allowedTypes),examplesWithRetry=retryCommand?appendIfMissing(examples,retryCommand):examples,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.`],nextStepsWithRetry=retryCommand?appendIfMissing(nextStepsBase,`Replay with preserved arguments: ${retryCommand}`):nextStepsBase,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),proseRemainder=candidateContext.candidateTotal-proseCommands.length,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,retryCommand?void 0:describeSameCommandCompleteness(optionName,commandName),proseCommands.length?`${optionName} is accepted by ${proseCommands.join(", ")}${proseRemainderText}. Inspect those command contracts only if you intended a different operation.`:void 0,isDashLeadingValue(optionName)?`"${optionName}" contains spaces, so it is a value that starts with --, not an option. Pass it after a -- separator at the end of the command, or through the command's named value flag.`: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")}const READ_COMPLETENESS_SPELLINGS=["--brief","--compact","--standard","--deep","--full","--summary","--depth"];function describeSameCommandCompleteness(optionName,commandName){if(commandName===void 0||!READ_COMPLETENESS_SPELLINGS.includes(optionName.split("=",1)[0]))return;const controls=resolveReadCompletenessControls(commandName);return controls===void 0?void 0:`Completeness controls accepted by pm ${controls.command}: ${describeReadCompletenessControls(controls)}.`}function resolveReadIntentRetry(context,optionName,commandName){const retry=resolveReadOptionRetryArgs(commandName??"",context.normalizedInvocationArgs??[],optionName);return retry?{retryCommand:renderPmCommand(retry),suggestedRetryArgs:retry}:[...READ_COMPLETENESS_SPELLINGS,"--toon",...commandName==="activity"?["--since"]:[]].includes(optionName.split("=",1)[0])?{}:void 0}function isDashLeadingValue(optionName){return/\s/u.test(optionName)}function resolveDashLeadingValueRetry(args,optionName){const index=args?.indexOf(optionName)??-1;if(args===void 0||index<0||args.includes("--")||args.lastIndexOf(optionName)!==index)return{};if(args.slice(index+1).some(token=>!token.startsWith("-")))return{};const suggestedRetryArgs=[...stripGlobalBootstrapTokens(args.filter((_,position)=>position!==index)),"--",optionName];return{retryCommand:renderPmCommand(suggestedRetryArgs),suggestedRetryArgs}}function resolveUnknownOptionRetry(context,optionName,commandName){if(isDashLeadingValue(optionName))return resolveDashLeadingValueRetry(context.normalizedInvocationArgs,optionName);if(["--dry-run","--check","--check-only","--plan","--preview"].includes(optionName.split("=",1)[0]))return{};const readRetry=resolveReadIntentRetry(context,optionName,commandName);if(readRetry)return readRetry;if(context.suggestedRetryCommand!==void 0)return{retryCommand:context.suggestedRetryCommand};if(isReadProjectionRecoveryFlag(optionName))return{};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("-")!==!0)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??{},optionName=unknownOption[1],suggestions=normalizeOptionFlags(guidanceContext.unknownOptionSuggestions)??[],{retryCommand,suggestedRetryArgs}=resolveUnknownOptionRetry(guidanceContext,optionName,commandName);if(commandName==="update"&&(optionName==="--file"||optionName==="--doc"))return buildUnsupportedUpdateOptionGuidance(optionName,context,suggestions);const candidateContext=resolveUnknownOptionCandidateContext(guidanceContext),nextSteps=buildUnknownOptionNextSteps(optionName,commandName,suggestions,candidateContext,retryCommand);["--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,commandName?`pm ${resolvePmCommandAlias(commandName)?.canonical??commandName} --help`:"pm --help --all"].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}`,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],runtimeExamples=normalizeContextList(context?.unknownCommandExamples),runtimeNextSteps=normalizeContextList(context?.unknownCommandNextSteps),packageHint=resolveKnownPackageCommandHint(commandToken),baseExamples=runtimeExamples??["pm --help"],baseNextSteps=runtimeNextSteps??["Verify spelling and active extensions, then rerun."],failedExtensionNames=new Set(context?.failedExtensions?.map(entry=>entry.name.trim().toLowerCase())),hintedExtensionName=packageHint?.packageName.replace(/^@unbrained\/pm-/,"").toLowerCase();return packageHint&&(!hintedExtensionName||!failedExtensionNames.has(hintedExtensionName))?buildKnownPackageCommandGuidance(commandToken,packageHint,baseExamples,baseNextSteps,context):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(),token=context?.unknownSubcommandToken?.trim(),allowed=normalizeContextList(context?.unknownSubcommandAllowedValues);if(!commandPath||!token||!allowed)return null;const retryCommand=context?.suggestedRetryCommand;return makeGuidanceMessage({code:"unknown_subcommand",title:`Unknown ${commandPath} subcommand ${token}`,value: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,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 buildLinkedResourcePositionalGuidance(message,commandName,context){if(!/too many arguments/i.test(message))return null;const recovery=resolveLinkedResourcePositionalRecovery(commandName,context?.normalizedInvocationArgs??[]);if(!recovery)return null;const retry=recovery.retryArgs?renderPmCommand(recovery.retryArgs):void 0,template=renderPmCommand(recovery.templateArgs??["test",recovery.itemId,"--add",`command=<actual command>,${recovery.value}`]);return makeGuidanceMessage({code:"linked_resource_positional_value",title:"Linked-resource values require an explicit --add option",happened:`The value after the item id is not a positional argument of ${commandName}.`,required:retry?`Retry the explicit collection mutation: ${retry}`:`Supply the actual command and its metadata together, for example ${template}.`,examples:[retry??template],recovery:buildCommanderRecoveryPayload(context,{suggested_retry:retry,suggested_retry_args:recovery.retryArgs})})}function buildTransposedCollectionActionGuidance(message,commandName,context){if(!/too many arguments/i.test(message)||!TRANSPOSED_COLLECTION_COMMANDS.has(commandName??""))return null;const argv=context?.normalizedInvocationArgs??[],commandIndex=argv.findIndex(token=>token===commandName),action=argv[commandIndex+1],parsedItemId=argv[commandIndex+2],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"]),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??[],commandIndex=argv.findIndex(token=>CONTEXT_GUIDANCE_COMMAND_NAMES.has(token)),searchIndex=commandIndex===-1?1:commandIndex+1,match=message.match(/got \d+:\s*(\S+)/i);let positional=match?match[1].replace(/\.$/,""):void 0;if(positional===void 0){let skipFlagValue=!1;for(const token of argv.slice(searchIndex)){if(skipFlagValue){skipFlagValue=!1;continue}const flagName=token.split("=")[0];if(CONTEXT_GUIDANCE_VALUE_FLAGS.has(flagName)){skipFlagValue=!token.includes("=");continue}if(!token.startsWith("-")){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);return(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)??buildLinkedResourcePositionalGuidance(message,commandName,context)??buildContextItemArgumentGuidance(message,commandName,context))||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,options={}){const guidance=redactGuidanceCredentials(buildPmCliErrorGuidance(rawMessage,context));return(context?.code==="tracker_root_missing"||context?.code==="tracker_not_initialized")&&guidance.title==="Tracker is not initialized"&&guidance.recovery?.suggested_retry_args?[`Error: ${guidance.title}`,`Run: ${renderPmCommand(guidance.recovery.suggested_retry_args)}`,"Use --json for full recovery details."].join(`
|
|
6
6
|
`):renderBoundedGuidanceText(guidance,options)}function renderBoundedGuidanceText(rawGuidance,options){const guidance=redactGuidanceCredentials(rawGuidance),render=renderOptions=>projectPmDiagnosticText(renderBoundedGuidanceMessage(guidance,renderOptions),guidance.required).output,output=render(options);if(options.lean!==!0)return output;const fallback=render({});return Buffer.byteLength(fallback,"utf8")<Buffer.byteLength(output,"utf8")?fallback: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,options={}){const guidance=buildCommanderErrorGuidance(rawMessage,commandName,allowedTypes,context);return renderBoundedGuidanceText(guidance,options)}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);return isModuleResolutionErrorMessage(message)?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."]}):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};
|
|
7
7
|
//# sourceMappingURL=error-guidance.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
-
`)):printResult(result,global2),"ok"in result&&!result.ok&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function registerHistoryMaintenanceCommands(parent,native){parent.command(native?"attest":"history-attest",{hidden:!native}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(runHistoryAttestAction),parent.command("restore",{hidden:!native}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(runRestoreAction),parent.command(native?"redact":"history-redact",{hidden:!native}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",collect).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",collect).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(id,options,command)=>{const globalOptions=getGlobalOptions(command),startedAt=Date.now(),literal=Array.isArray(options.literal)?options.literal:void 0,regex=Array.isArray(options.regex)?options.regex:void 0,result=await runHistoryRedact(id,{literal,regex,replacement:readOptionString(options,"replacement"),dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force},globalOptions);result.changed&&!result.dry_run&&await invalidateSearchCachesForMutation(globalOptions,result),printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=history-redact took_ms=${Date.now()-startedAt}`)}),parent.command(native?"repair":"history-repair",{hidden:!native}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(id,options,command)=>{const globalOptions=getGlobalOptions(command),startedAt=Date.now(),all=options.all===!0;assertHistoryRepairTarget(id,all);const repairOptions={dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force,normalizeProvenance:options.normalizeProvenance===!0,salvageTail:options.salvageTail===!0};if(all){const result=await runHistoryRepairAll(repairOptions,globalOptions);printResult(result,globalOptions),result.totals.failed>0&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}else{const result=await runHistoryRepair(id,repairOptions,globalOptions);printResult(result,globalOptions)}globalOptions.profile&&printError(`profile:command=history-repair took_ms=${Date.now()-startedAt}`)}),parent.command(native?"compact":"history-compact",{hidden:!native}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(runHistoryCompactAction)}export{registerHistoryMaintenanceCommands};
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54ad8ccf-09e3-502f-bda3-a71491581863")}catch{}})();import{runHistoryAttest}from"../sdk/history/attestation-command.js";import{EXIT_CODE,PmCliError,resolveCliBulkIdsInput,splitCommaList}from"../sdk/runtime-primitives.js";import{assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk}from"./commands/history/history-compact.js";import{runHistoryRedact}from"./commands/history/history-redact.js";import{assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll}from"./commands/history/history-repair.js";import{runRestore}from"./commands/history/restore.js";import{collect,getGlobalOptions,invalidateSearchCachesForMutation,printError,printResult,readOptionString,setActiveCommandResult,writeStdout}from"./registration-helpers.js";function parseNonNegativeIntFlag(raw,flag){if(typeof raw!="string")return;const parsed=Number.parseInt(raw,10);if(!/^\d+$/.test(raw.trim())||!Number.isSafeInteger(parsed))throw new PmCliError(`history-compact ${flag} must be a non-negative integer.`,EXIT_CODE.USAGE);return parsed}async function runHistoryCompactAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),idsValue=await resolveCliBulkIdsInput(readOptionString(options,"ids")),ids=idsValue===void 0?void 0:splitCommaList(idsValue),allOver=parseNonNegativeIntFlag(options.allOver,"--all-over"),minEntries=parseNonNegativeIntFlag(options.minEntries,"--min-entries");if(options.closed===!0&&options.allStreams===!0)throw new PmCliError("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",EXIT_CODE.USAGE);const scope=options.closed===!0?"closed":options.allStreams===!0?"all-streams":void 0;if((ids!==void 0||allOver!==void 0||scope!==void 0)&&typeof options.before=="string")throw new PmCliError("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",EXIT_CODE.USAGE);if(assertHistoryCompactTarget(id,{ids,allOver,scope}),id!==void 0&&minEntries!==void 0)throw new PmCliError("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",EXIT_CODE.USAGE);if(id===void 0){const result=await runHistoryCompactBulk({ids,scope,allOver,minEntries,dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force},globalOptions);printResult(result,globalOptions),result.totals.items_errored>0&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}else{const result=await runHistoryCompact(id,{before:readOptionString(options,"before"),dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force},globalOptions);printResult(result,globalOptions)}globalOptions.profile&&printError(`profile:command=history-compact took_ms=${Date.now()-startedAt}`)}async function runRestoreAction(id,target,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runRestore(id,target,{author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force},globalOptions);await invalidateSearchCachesForMutation(globalOptions,result),printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=restore took_ms=${Date.now()-startedAt}`)}async function runHistoryAttestAction(options,command){const global2=getGlobalOptions(command),result=await runHistoryAttest({verify:readOptionString(options,"verify"),output:readOptionString(options,"output"),hashAlgorithm:readOptionString(options,"hashAlgorithm")},global2);"format"in result?(setActiveCommandResult(result),global2.quiet||writeStdout(`${JSON.stringify(result,null,2)}
|
|
2
|
+
`)):printResult(result,global2),"ok"in result&&!result.ok&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function registerHistoryMaintenanceCommands(parent,native){parent.command(native?"attest":"history-attest",{hidden:!native}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(runHistoryAttestAction),parent.command("restore",{hidden:!native}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(runRestoreAction),parent.command(native?"redact":"history-redact",{hidden:!native}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",collect).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",collect).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(id,options,command)=>{const globalOptions=getGlobalOptions(command),startedAt=Date.now(),literal=Array.isArray(options.literal)?options.literal:void 0,regex=Array.isArray(options.regex)?options.regex:void 0,result=await runHistoryRedact(id,{literal,regex,replacement:readOptionString(options,"replacement"),dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force},globalOptions);result.changed&&!result.dry_run&&await invalidateSearchCachesForMutation(globalOptions,result),printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=history-redact took_ms=${Date.now()-startedAt}`)}),parent.command(native?"repair":"history-repair",{hidden:!native}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--append-only","Bridge breaks; never rewrite entries").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(id,options,command)=>{const globalOptions=getGlobalOptions(command),startedAt=Date.now(),all=options.all===!0;assertHistoryRepairTarget(id,all);const repairOptions={dryRun:options.dryRun===!0,author:readOptionString(options,"author"),message:readOptionString(options,"message"),force:!!options.force,normalizeProvenance:options.normalizeProvenance===!0,salvageTail:options.salvageTail===!0,appendOnly:options.appendOnly===!0};if(all){const result=await runHistoryRepairAll(repairOptions,globalOptions);printResult(result,globalOptions),result.totals.failed>0&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}else{const result=await runHistoryRepair(id,repairOptions,globalOptions);printResult(result,globalOptions)}globalOptions.profile&&printError(`profile:command=history-repair took_ms=${Date.now()-startedAt}`)}),parent.command(native?"compact":"history-compact",{hidden:!native}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(runHistoryCompactAction)}export{registerHistoryMaintenanceCommands};
|
|
3
3
|
//# sourceMappingURL=register-history-maintenance.js.map
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="689cbdf3-974b-5371-8722-91dbd4cca944")}catch{}})();import{EXIT_CODE,PmCliError,readSettings,renderRowsAsCsv,renderRowsAsTable,resolvePmRoot}from"../sdk/runtime-primitives.js";import{renderPmCommandAliasMigrationHint,resolvePmCommandAlias}from"../sdk/cli-contracts.js";import{EVAL_QUERY_SET_SCHEMA_ID}from"../sdk/eval.js";import{applyContextIntentProjection}from"../sdk/context-intent-contracts.js";import{renderPmClosedDomainHelp}from"../sdk/agent/closed-domain-contracts.js";import{serializeNdjsonRows,serializeNdjsonStream}from"../sdk/output.js";import{listMutationEvents,subscribeMutationEventBatches,subscribeMutationEvents}from"../sdk/mutation-events.js";import{registerHistoryActivityCommand}from"./register-history-activity.js";import{registerHistoryMaintenanceCommands}from"./register-history-maintenance.js";import{runAggregate}from"./commands/query/aggregate.js";import{renderContextMarkdown,runContext,resolveContextOutputFormat}from"./commands/query/context.js";import{runEval}from"./commands/query/eval.js";import{runGet}from"./commands/query/get.js";import{runGraph}from"./commands/query/graph.js";import{runHistory}from"./commands/history/history.js";import{runList}from"./commands/query/list.js";import{LIST_COMMAND_DEFAULT_PROJECTIONS}from"../sdk/query/list.js";import{renderNextMarkdown,runNext,resolveNextOutputFormat}from"./commands/query/next.js";import{runSearch}from"./commands/query/search.js";import{addHiddenOption,collect,getGlobalOptions,normalizeAggregateOptions,normalizeContextOptions,normalizeListOptions,normalizeNextOptions,normalizeSearchKeywordsInput,normalizeSearchOptions,printError,printListJsonStream,printResult,setActiveCommandResult,writeStdout}from"./registration-helpers.js";function shouldRegisterListQueryCommand(commandName,commandFilter){return!commandFilter||commandFilter.size===0?!0:commandName==="context"?commandFilter.has("context")||commandFilter.has("ctx"):commandFilter.has(commandName)}function parseListFormat(rawFormat){if(rawFormat===void 0)return;if(typeof rawFormat!="string")throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized==="csv"||normalized==="table"||normalized==="json"||normalized==="ndjson"||normalized==="toon")return normalized;throw new PmCliError("List --format must be one of csv|table|json|ndjson|toon",EXIT_CODE.USAGE)}function resolveReadCommandOutputFormat(commandLabel,rawFormat,globalOptions,allowNdjson=!1){if(rawFormat===void 0)return globalOptions;if(typeof rawFormat!="string")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);const normalized=rawFormat.trim().toLowerCase();if(normalized!=="json"&&(normalized!=="ndjson"||!allowNdjson)&&normalized!=="toon")throw new PmCliError(`${commandLabel} --format must be one of ${allowNdjson?"json|ndjson|toon":"json|toon"}`,EXIT_CODE.USAGE);if(globalOptions.json===!0&&normalized==="toon")throw new PmCliError(`${commandLabel} cannot combine --json with --format toon`,EXIT_CODE.USAGE);return{...globalOptions,json:normalized==="json"||normalized==="ndjson"}}function applyDefaultListProjection(listOptions,commandName){LIST_COMMAND_DEFAULT_PROJECTIONS[commandName]==="brief"&&listOptions.includeBody!==!0&&listOptions.compact!==!0&&listOptions.brief!==!0&&listOptions.full!==!0&&listOptions.fields===void 0&&(listOptions.brief=!0)}function registerContentAndGovernanceFilters(command){command.option("--has-notes","Show only items that have notes").option("--has-learnings","Show only items that have learnings").option("--has-files","Show only items that have linked files").option("--has-docs","Show only items that have linked docs").option("--has-tests","Show only items that have linked tests").option("--has-comments","Show only items that have comments").option("--has-deps","Show only items that have dependencies").option("--has-body","Show only items that have a non-empty body").option("--has-linked-command","Show only items whose linked tests carry a runnable command").option("--no-notes","Show only items that have no notes").option("--no-learnings","Show only items that have no learnings").option("--no-files","Show only items that have no linked files").option("--filter-files-missing","Alias for --no-files").option("--no-docs","Show only items that have no linked docs").option("--filter-docs-missing","Alias for --no-docs").option("--no-tests","Show only items that have no linked tests").option("--no-comments","Show only items that have no comments").option("--no-deps","Show only items that have no dependencies").option("--empty-body","Show only items with an empty body").option("--no-linked-command","Show only items whose linked tests carry no runnable command").option("--filter-reviewer-missing","Show only items missing reviewer").option("--filter-risk-missing","Show only items missing risk").option("--filter-confidence-missing","Show only items missing confidence").option("--filter-sprint-missing","Show only items missing sprint").option("--filter-release-missing","Show only items missing release")}const CANONICAL_LIST_STATUS_VARIANTS={draft:{name:"list-draft",dependencyBlocked:!1},open:{name:"list-open",dependencyBlocked:!1},in_progress:{name:"list-in-progress",dependencyBlocked:!1},blocked:{name:"list-blocked",dependencyBlocked:!0},closed:{name:"list-closed",dependencyBlocked:!1},canceled:{name:"list-canceled",dependencyBlocked:!1}};function resolveRegisteredListOutputContext(options,globalOptions){const streamMode=options.stream===!0,listFormat=parseListFormat(options.format),tabular=listFormat==="csv"||listFormat==="table",effectiveGlobal=listFormat==="json"||listFormat==="ndjson"||listFormat==="toon"?resolveReadCommandOutputFormat("List",options.format,globalOptions,!0):globalOptions;if(streamMode&&!effectiveGlobal.json)throw new PmCliError("--stream requires --json output mode.",EXIT_CODE.USAGE);if((tabular||listFormat==="ndjson")&&streamMode)throw new PmCliError("--format csv|table|ndjson cannot be combined with --stream.",EXIT_CODE.USAGE);return{streamMode,listFormat,effectiveGlobal}}function renderRegisteredListResult(commandName,result,output){if(output.listFormat==="csv"||output.listFormat==="table"){setActiveCommandResult(result);const rows=result.items,rendered=output.listFormat==="csv"?renderRowsAsCsv(rows):renderRowsAsTable(rows);!output.effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
|
|
2
2
|
`)}else if(output.listFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows(result.items);!output.effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
|
|
3
3
|
`)}else output.streamMode?printListJsonStream(commandName,result,output.effectiveGlobal):printResult(result,output.effectiveGlobal)}function projectCliIntentOptions(command,options,globalOptions,positionalArguments=[]){if(globalOptions.outputBudget===void 0)return applyContextIntentProjection(command,options,positionalArguments);const{outputBudget:_outputBudget,...projected}=applyContextIntentProjection(command,{...options,outputBudget:globalOptions.outputBudget},positionalArguments);return projected}async function runRegisteredListCommand(params){const parsedGlobalOptions=getGlobalOptions(params.actionCommand),globalOptions=params.aliasContract?{...parsedGlobalOptions,command:params.aliasContract.canonical}:parsedGlobalOptions,startedAt=Date.now();params.aliasContract?.lifecycle==="deprecated"&&await readSettings(resolvePmRoot(process.cwd(),globalOptions.path)).then(settings=>settings.ux.deprecation_hints)&&printError(renderPmCommandAliasMigrationHint(params.aliasContract));const intentOptions=projectCliIntentOptions("list",params.options,globalOptions),listOptions=normalizeListOptions(intentOptions),selection=resolveRegisteredListSelection(params,listOptions),{effectiveName,effectiveStatus,effectiveDependencyBlocked,effectiveExcludeTerminal}=selection;applyDefaultListProjection(listOptions,params.name),Object.assign(listOptions,{projectionCommand:effectiveName}),effectiveExcludeTerminal&&(listOptions.excludeTerminal=!0),listOptions.dependencyBlocked=effectiveDependencyBlocked;const output=resolveRegisteredListOutputContext(intentOptions,globalOptions),result=await runList(effectiveDependencyBlocked?void 0:effectiveStatus,listOptions,globalOptions);renderRegisteredListResult("list",result,output),globalOptions.profile&&printError(`profile:command=list took_ms=${Date.now()-startedAt}`)}function resolveRegisteredListSelection(params,listOptions){let effectiveName=params.name,effectiveStatus=params.status,effectiveDependencyBlocked=params.dependencyBlocked===!0,effectiveExcludeTerminal=params.excludeTerminal===!0;const requestedStatus=listOptions.status?.trim().toLowerCase(),requestedVariant=params.name==="list"&&requestedStatus!==void 0?CANONICAL_LIST_STATUS_VARIANTS[requestedStatus]:void 0;return params.name==="list"&&(params.options.all===!0||requestedStatus==="all"?(effectiveName="list-all",effectiveExcludeTerminal=!1,listOptions.status=void 0):requestedStatus!==void 0&&requestedVariant!==void 0&&(effectiveName=requestedVariant.name,effectiveStatus=requestedStatus,effectiveDependencyBlocked=requestedVariant.dependencyBlocked,effectiveExcludeTerminal=!1,listOptions.status=void 0)),(effectiveName==="list-open"||effectiveName==="list-in-progress")&&(listOptions.lifecycleBucket=effectiveName==="list-open"?"open":"in_progress",effectiveStatus=void 0),{effectiveName,effectiveStatus,effectiveDependencyBlocked,effectiveExcludeTerminal}}function registerListCommand(program,descriptor){const{name,description,status,excludeTerminal,allowStatusFilter,dependencyBlocked,aliasContract}=descriptor,command=program.command(name,{hidden:aliasContract?.hidden===!0}).description(description);allowStatusFilter&&command.option("--status <value>","Filter by status (repeatable or comma-separated; matches any; all selects every status)",collect),name==="list"&&command.option("--all","Include every lifecycle status"),command.option("--for <intent>",`Apply a declared context intent projection. ${renderPmClosedDomainHelp("list","--for")}`).option("--token-budget <n>","Override the selected intent's maximum estimated output tokens").option("--type <value>","Filter by item type (repeatable or comma-separated; matches any)",collect).option("--tag <value>","Filter by tag (repeatable or comma-separated; matches any)",collect).option("--priority <value>","Filter by priority (repeatable or comma-separated; matches any)",collect).option("--deadline-before <value>","Filter by deadline upper bound (ISO/date string or relative)").option("--deadline-after <value>","Filter by deadline lower bound (ISO/date string or relative)").option("--today","Filter to items updated since local midnight today").option("--recent","Filter to items updated in the last 7 days").option("--updated-after <value>","Updated since ISO timestamp or signed relative (-2h/-7d for past); use last-window ISO").option("--updated-before <value>","Filter by updated_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-after <value>","Filter by created_at lower bound: ISO timestamp or signed relative (-2h/+1d)").option("--created-before <value>","Filter by created_at upper bound: ISO timestamp or signed relative (-2h/+1d)").option("--ids <value>","Filter by explicit item IDs (comma-separated or repeatable)").option("--assignee <value>","Filter by assignee",collect).option("--assignee-filter <value>","Filter assignee presence: assigned|unassigned").option("--parent <value>","Filter by parent item ID").option("--sprint <value>","Filter by sprint",collect).option("--release <value>","Filter by release",collect).option("--filter-ac-missing","Show only items missing acceptance_criteria").option("--filter-estimates-missing","Show only items missing estimated_minutes").option("--filter-resolution-missing","Show only terminal items missing resolution").option("--filter-metadata-missing","Show only items missing any tracked metadata (AC, estimate, or resolution)").option("--limit <n>","Alias for --output-limit; --output-budget may cap rows").option("--offset <n>","Skip the first n matching rows before limit is applied").option("--after <cursor>","Query next_cursor; output_cursor uses --output-cursor").option("--no-truncate","Disable default token cap; explicit --limit and --output-budget apply").option("--include-body","Include item body in each returned list row").option("--strict-read","Fail closed if any item document or item directory cannot be read").option("--compact","Render compact list projection fields (mutually exclusive with --brief/--full/--fields)").option("--brief","Brief rows: id, status, type, title and leading sort field (priority by default; excludes --compact/--full/--fields)").option("--full","Render full list projection fields (mutually exclusive with --compact/--brief/--fields)").option("--fields <value>",`Render custom comma-separated list fields (mutually exclusive with --compact/--brief/--full). ${renderPmClosedDomainHelp(name,"--fields")}`).option("--sort <value>","Sort field: priority|deadline|updated_at|created_at|title|parent (aliases: updated, created)").option("--order <value>","Sort order: asc|desc (requires --sort)").option("--tree","Render rows in parent/child tree order").option("--tree-depth <n>","Maximum recursion depth with --tree (0 keeps root rows only)").option("--format <value>","Output render mode: csv|table (human export) or json|ndjson|toon (machine output override)").option("--stream","Emit line-delimited JSON rows (requires --json)"),registerContentAndGovernanceFilters(command),command.action(async(options,actionCommand)=>{await runRegisteredListCommand({name,status,excludeTerminal,dependencyBlocked,options,actionCommand,aliasContract})}),addHiddenOption(command,"--tags <value>","Alias for --tag"),addHiddenOption(command,"--assignee_filter <value>","Alias for --assignee-filter"),addHiddenOption(command,"--tree_depth <n>","Alias for --tree-depth"),addHiddenOption(command,"--token_budget <n>","Alias for --token-budget"),addHiddenOption(command,"--filter-estimate-missing","Alias for --filter-estimates-missing")}async function runAggregateAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runAggregate(normalizeAggregateOptions(options),globalOptions);printResult(result,globalOptions),globalOptions.profile&&printError(`profile:command=aggregate took_ms=${Date.now()-startedAt}`)}async function runContextAction(options,actionCommand){const globalOptions=getGlobalOptions(actionCommand),startedAt=Date.now(),normalized=normalizeContextOptions(projectCliIntentOptions("context",options,globalOptions)),result=await runContext(normalized,globalOptions),outputFormat=resolveContextOutputFormat(normalized,globalOptions);if(outputFormat==="markdown")globalOptions.quiet||writeStdout(`${renderContextMarkdown(result)}
|
|
4
4
|
`);else if(outputFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows([...result.high_level,...result.low_level,...result.blocked_fallback]);!globalOptions.quiet&&rendered.length>0&&writeStdout(`${rendered}
|
|
5
|
-
`)}else printResult(result,{...globalOptions,json:outputFormat==="json"});globalOptions.profile&&printError(`profile:command=context took_ms=${Date.now()-startedAt}`)}async function runNextAction(options,actionCommand){const globalOptions=getGlobalOptions(actionCommand),startedAt=Date.now(),nextOptions=normalizeNextOptions(projectCliIntentOptions("next",options,globalOptions)),result=await runNext(nextOptions,globalOptions),outputFormat=resolveNextOutputFormat(nextOptions,globalOptions);outputFormat==="markdown"?globalOptions.quiet||writeStdout(`${renderNextMarkdown(result)}
|
|
5
|
+
`);const historyRead=result.activity_history_read;historyRead!==void 0&&printError(`[pm] warning: activity_history_read reason=${historyRead.reason} streams_read=${historyRead.streams_read}/${historyRead.streams_total}`)}else printResult(result,{...globalOptions,json:outputFormat==="json"});globalOptions.profile&&printError(`profile:command=context took_ms=${Date.now()-startedAt}`)}async function runNextAction(options,actionCommand){const globalOptions=getGlobalOptions(actionCommand),startedAt=Date.now(),nextOptions=normalizeNextOptions(projectCliIntentOptions("next",options,globalOptions)),result=await runNext(nextOptions,globalOptions),outputFormat=resolveNextOutputFormat(nextOptions,globalOptions);outputFormat==="markdown"?globalOptions.quiet||writeStdout(`${renderNextMarkdown(result)}
|
|
6
6
|
`):printResult(result,{...globalOptions,json:outputFormat==="json"}),globalOptions.profile&&printError(`profile:command=next took_ms=${Date.now()-startedAt}`)}async function runSearchAction(keywords,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),query=normalizeSearchKeywordsInput(keywords),intentOptions=projectCliIntentOptions("search",options,globalOptions,[query]),searchOptions=normalizeSearchOptions(intentOptions),result=await runSearch(query,searchOptions,globalOptions),outputFormat=typeof intentOptions.format=="string"?intentOptions.format.trim().toLowerCase():void 0,effectiveGlobal=resolveReadCommandOutputFormat("Search",intentOptions.format,globalOptions,!0);if(outputFormat==="ndjson"){setActiveCommandResult(result);const rendered=serializeNdjsonRows(result.items);!effectiveGlobal.quiet&&rendered.length>0&&writeStdout(`${rendered}
|
|
7
7
|
`)}else printResult(result,effectiveGlobal);globalOptions.profile&&printError(`profile:command=search took_ms=${Date.now()-startedAt}`)}async function runEvalAction(options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),result=await runEval({mode:typeof options.mode=="string"?options.mode:void 0,k:typeof options.k=="string"?options.k:void 0,failUnder:typeof options.failUnder=="string"?options.failUnder:void 0,queries:typeof options.queries=="string"?options.queries:void 0,format:typeof options.format=="string"?options.format:void 0},globalOptions);if(printResult(result,resolveReadCommandOutputFormat("Eval",options.format,globalOptions)),globalOptions.profile&&printError(`profile:command=eval took_ms=${Date.now()-startedAt}`),!result.passed)throw new PmCliError("Eval gate failed: one or more aggregate or per-query thresholds were not met; inspect the metric report",EXIT_CODE.GENERIC_FAILURE)}async function runGetAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now(),intentOptions=projectCliIntentOptions("get",options,globalOptions,[id]),result=await runGet(id,globalOptions,{depth:typeof intentOptions.depth=="string"?intentOptions.depth:void 0,fields:typeof intentOptions.fields=="string"?intentOptions.fields:void 0,full:!!intentOptions.full,tree:intentOptions.tree===!0,treeDepth:typeof intentOptions.treeDepth=="string"?intentOptions.treeDepth:typeof intentOptions.tree_depth=="string"?intentOptions.tree_depth:void 0,at:typeof intentOptions.at=="string"?intentOptions.at:void 0});printResult(result,resolveReadCommandOutputFormat("Get",intentOptions.format,globalOptions)),globalOptions.profile&&printError(`profile:command=get took_ms=${Date.now()-startedAt}`)}async function runHistoryAction(id,options,command){const globalOptions=getGlobalOptions(command),startedAt=Date.now();if([options.compact,options.raw,options.full,options.provenance].filter(value=>value===!0).length>1)throw new PmCliError("History projection options are mutually exclusive. Use --compact, --provenance, or --full.",EXIT_CODE.USAGE);const field=typeof options.field=="string"?options.field:void 0,strictExit=!!options.strictExit||!!options.failOnWarn;if(strictExit&&!options.verify)throw new PmCliError("--strict-exit requires --verify (it gates on the verification result).",EXIT_CODE.USAGE);const result=await runHistory(id,{limit:typeof options.limit=="string"?options.limit:void 0,order:options.order,compact:!(options.full===!0||options.provenance===!0),provenance:options.provenance===!0,provenanceSummary:options.provenanceSummary===!0,harness:readRepeatableStringOption(options,"harness"),agentInstance:readRepeatableStringOption(options,"agentInstance"),provenanceFilter:readRepeatableStringOption(options,"provenanceFilter"),diff:!!options.diff||field!==void 0,field,verify:!!options.verify},globalOptions);printResult(result,resolveReadCommandOutputFormat("History",options.format,globalOptions)),strictExit&&result.verification&&!result.verification.ok&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE),globalOptions.profile&&printError(`profile:command=history took_ms=${Date.now()-startedAt}`)}function readRepeatableStringOption(options,key){const value=options[key];return Array.isArray(value)?value:void 0}function buildMutationEventOptions(options,pmRoot){const harness=readRepeatableStringOption(options,"harness"),agentInstance=readRepeatableStringOption(options,"agentInstance"),provenanceFilter=readRepeatableStringOption(options,"provenanceFilter"),rawCursorMode=typeof options.cursorMode=="string"?options.cursorMode:void 0;if(rawCursorMode!==void 0&&rawCursorMode!=="batch"&&rawCursorMode!=="row")throw new PmCliError("Events --cursor-mode must be batch or row.",EXIT_CODE.USAGE,{code:"invalid_event_cursor_mode"});const cursorMode=rawCursorMode;return{pmRoot,since:typeof options.since=="string"?options.since:void 0,type:readRepeatableStringOption(options,"type"),author:readRepeatableStringOption(options,"author"),item:readRepeatableStringOption(options,"item"),limit:typeof options.limit=="string"?Number(options.limit):void 0,full:options.full===!0,...options.verify===!0?{verify:!0}:{},...options.provenance===!0?{provenance:!0}:{},...options.provenanceSummary===!0?{provenanceSummary:!0}:{},...harness===void 0?{}:{harness},...agentInstance===void 0?{}:{agentInstance},...provenanceFilter===void 0?{}:{provenanceFilter},cursorMode}}async function followMutationEvents(eventOptions,options,quiet){if(options.provenanceSummary===!0)throw new PmCliError("Events --provenance-summary is bounded to one page and cannot be combined with --follow.",EXIT_CODE.USAGE);const intervalMs=typeof options.intervalMs=="string"?Number(options.intervalMs):void 0;if(eventOptions.cursorMode==="row"){for await(const event of subscribeMutationEvents({...eventOptions,intervalMs}))quiet||writeStdout(`${JSON.stringify(event)}
|
|
8
8
|
`);return}for await(const page of subscribeMutationEventBatches({...eventOptions,intervalMs}))quiet||writeStdout(`${serializeNdjsonStream(page.events,{count:page.count,has_more:page.has_more,next_cursor:page.next_cursor??null,source:page.source,integrity:page.integrity,...page.verified_streams===void 0?{}:{verified_streams:page.verified_streams},heartbeat:page.count===0})}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e772af0a-0c47-5507-b353-8a68808b0751")}catch{}})();import{URL_CREDENTIAL_PLACEHOLDER,invocationCarriesUrlCredentials,redactUrlCredentialsInText,redactUrlCredentialsInToken}from"../../sdk/command-line.js";const ARGV_TOKEN_FIELDS=new Set(["normalized_args","suggested_retry_args","provided_fields","parsed_positionals","normalizedInvocationArgs","providedOptionFlags","suggestedRetryArgs"]),FIXED_CONTRACT_FIELDS=new Set(["code","original_code","type","recovery_mode","option_scope","diagnostic_class"]),RESTORE_CREDENTIALS_STEP=`URL credentials in this invocation were replaced with ${URL_CREDENTIAL_PLACEHOLDER}; restore them before replaying any command shown here.`;function rejectedCredentialsStep(source){return`URL credentials in this invocation were replaced with ${URL_CREDENTIAL_PLACEHOLDER}. Those in ${source} caused this refusal, so do not restore them: give ${source} a value without URL credentials, and restore any other redacted credentials before replaying.`}function redactRefusalArgv(argv){return argv.map(redactUrlCredentialsInToken)}function childPosition(position,key){return position==="producer"||key==="details"?"producer":position==="schema"&&key==="recovery"?"schema":"typed"}function redactKey(key,copy,pass){const safe=redactUrlCredentialsInText(key);safe!==key&&(pass.changed=!0);let candidate=safe;for(let suffix=2;Object.hasOwn(copy,candidate);suffix+=1)candidate=`${safe} (${suffix})`;return candidate}function redactString(value,pass,tokenField){const redacted=redactUrlCredentialsInText(tokenField?redactUrlCredentialsInToken(value):value);return redacted!==value&&(pass.changed=!0),redacted}function isVerbatimSchemaEntry(position,key,entry){return position!=="schema"?!1:key==="urlCredentialsRejected"||FIXED_CONTRACT_FIELDS.has(key)&&typeof entry=="string"}function redactValue(value,pass,tokenField,position){if(typeof value=="string"&&pass.ownSteps.has(value))return value;if(typeof value=="string")return redactString(value,pass,tokenField);if(typeof value!="object"||value===null)return value;const existing=pass.copies.get(value);if(existing!==void 0)return existing;if(Array.isArray(value)){const copy2=[];pass.copies.set(value,copy2);for(const entry of value)copy2.push(redactValue(entry,pass,tokenField,position));return copy2}const copy={};pass.copies.set(value,copy);for(const[key,entry]of Object.entries(value)){if(isVerbatimSchemaEntry(position,key,entry)){copy[key]=entry;continue}const safeKey=position==="producer"?redactKey(key,copy,pass):key;copy[safeKey]=redactValue(entry,pass,tokenField||ARGV_TOKEN_FIELDS.has(key),childPosition(position,key))}return copy}function redactGuidanceCredentials(guidance){const rejected=guidance.urlCredentialsRejected,leadingStep=rejected===void 0?RESTORE_CREDENTIALS_STEP:rejectedCredentialsStep(rejected.source),ownSteps=new Set([RESTORE_CREDENTIALS_STEP,leadingStep]),pass={copies:new Map,changed:!1,ownSteps},safe=redactValue(guidance,pass,!1,"schema");if(!pass.changed&&!invocationCarriesUrlCredentials())return guidance;safe.recovery&&(safe.recovery={...safe.recovery,suggested_retry:void 0,suggested_retry_args:void 0});const steps=(safe.nextSteps??[]).filter(step=>!ownSteps.has(step));return safe.nextSteps=[leadingStep,...steps],safe}export{RESTORE_CREDENTIALS_STEP,redactGuidanceCredentials,redactRefusalArgv,rejectedCredentialsStep};
|
|
2
2
|
//# sourceMappingURL=refusal-credential-redaction.js.map
|