@unbrained/pm-cli 2026.9.7 → 2026.9.8
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 +12 -4
- package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
- package/.agents/skills/pm-extensions/SKILL.md +6 -0
- package/.agents/skills/pm-sdk/SKILL.md +11 -2
- package/.agents/skills/pm-user/SKILL.md +5 -0
- package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +211 -181
- package/dist/cli/after-command-context-usage.js +1 -48
- package/dist/cli/argv-utils.js +1 -40
- package/dist/cli/bootstrap-args.js +1 -9
- package/dist/cli/bundle-integrity.js +2 -110
- package/dist/cli/commander-usage.js +11 -771
- package/dist/cli/commands/activity.js +1 -9
- package/dist/cli/commands/aggregate.js +1 -5
- package/dist/cli/commands/append.js +1 -5
- package/dist/cli/commands/claim.js +1 -5
- package/dist/cli/commands/close-many.js +1 -5
- package/dist/cli/commands/close.js +1 -9
- package/dist/cli/commands/comments.js +1 -5
- package/dist/cli/commands/config.js +1 -9
- package/dist/cli/commands/context.js +1 -9
- package/dist/cli/commands/contracts.js +1 -5
- package/dist/cli/commands/copy.js +1 -9
- package/dist/cli/commands/create.js +1 -9
- package/dist/cli/commands/delete.js +1 -9
- package/dist/cli/commands/deps.js +1 -9
- package/dist/cli/commands/docs.js +1 -9
- package/dist/cli/commands/duplicates.js +1 -9
- package/dist/cli/commands/eval.js +1 -9
- package/dist/cli/commands/extension/describe.js +1 -5
- package/dist/cli/commands/extension/scaffold.js +1 -5
- package/dist/cli/commands/extension/shared.js +1 -5
- package/dist/cli/commands/extension.js +1 -9
- package/dist/cli/commands/files.js +1 -9
- package/dist/cli/commands/focus.js +1 -9
- package/dist/cli/commands/gc.js +1 -9
- package/dist/cli/commands/get.js +1 -9
- package/dist/cli/commands/graph.js +1 -10
- package/dist/cli/commands/health.js +1 -9
- package/dist/cli/commands/history-compact.js +1 -10
- package/dist/cli/commands/history-redact.js +1 -11
- package/dist/cli/commands/history-repair.js +1 -10
- package/dist/cli/commands/history.js +1 -5
- package/dist/cli/commands/index.js +1 -58
- package/dist/cli/commands/init-agent-guidance.js +1 -9
- package/dist/cli/commands/init.js +1 -9
- package/dist/cli/commands/learnings.js +1 -5
- package/dist/cli/commands/lifecycle-transitions.js +1 -5
- package/dist/cli/commands/list.js +1 -9
- package/dist/cli/commands/merge.js +1 -11
- package/dist/cli/commands/next.js +1 -9
- package/dist/cli/commands/notes.js +1 -5
- package/dist/cli/commands/plan.js +1 -9
- package/dist/cli/commands/profile.js +1 -9
- package/dist/cli/commands/restore.js +1 -9
- package/dist/cli/commands/scheduling-shortcuts.js +1 -9
- package/dist/cli/commands/schema.js +1 -10
- package/dist/cli/commands/search.js +1 -9
- package/dist/cli/commands/stats.js +1 -9
- package/dist/cli/commands/telemetry.js +1 -9
- package/dist/cli/commands/test-all.js +1 -9
- package/dist/cli/commands/test-runs.js +1 -9
- package/dist/cli/commands/test.js +1 -9
- package/dist/cli/commands/update-many.js +1 -5
- package/dist/cli/commands/update.js +1 -9
- package/dist/cli/commands/upgrade.js +1 -5
- package/dist/cli/commands/validate.js +1 -15
- package/dist/cli/context-intent-invocation.js +1 -20
- package/dist/cli/description-stdin.js +1 -17
- package/dist/cli/error-guidance.js +1 -1353
- package/dist/cli/extension-command-help.js +5 -636
- package/dist/cli/extension-command-options.js +1 -427
- package/dist/cli/extension-recovery.js +1 -126
- package/dist/cli/help-content.js +2 -1001
- package/dist/cli/help-json-payload.js +4 -570
- package/dist/cli/main.d.ts +4 -0
- package/dist/cli/main.js +5 -2573
- package/dist/cli/migration-gates.js +1 -289
- package/dist/cli/public.js +1 -20
- package/dist/cli/register-annotations.js +1 -270
- package/dist/cli/register-assurance.js +1 -62
- package/dist/cli/register-files-lookup.js +1 -56
- package/dist/cli/register-history-activity.d.ts +8 -0
- package/dist/cli/register-history-activity.js +2 -0
- package/dist/cli/register-history-author.js +1 -38
- package/dist/cli/register-history-maintenance.d.ts +9 -0
- package/dist/cli/register-history-maintenance.js +2 -0
- package/dist/cli/register-list-query.js +10 -943
- package/dist/cli/register-mutation-options.js +1 -9
- package/dist/cli/register-mutation.js +19 -1893
- package/dist/cli/register-operations.js +1 -920
- package/dist/cli/register-setup.js +1 -716
- package/dist/cli/register-structured-mutation.js +1 -196
- package/dist/cli/registration-helpers.js +1 -5
- package/dist/cli/runtime-compatibility-boundary.js +4 -42
- package/dist/cli/schema-registration-helpers.js +1 -73
- package/dist/cli/search-refresh.js +1 -13
- package/dist/cli/stats-analytics-json.js +1 -68
- package/dist/cli/telemetry-flush.js +1 -10
- package/dist/cli-bundle/bundle-manifest.json +164 -156
- package/dist/cli-bundle/chunks/chunk-3BZZA6A3.js +5 -0
- package/dist/cli-bundle/chunks/chunk-AMRDVX36.js +235 -0
- package/dist/cli-bundle/chunks/chunk-DAM4CBBR.js +2202 -0
- package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-FLDWYEND.js +77 -0
- package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-G5ADGQ2D.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-JAAEYHUA.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-JX4DH4WC.js → chunk-KR3RP4FH.js} +3 -3
- package/dist/cli-bundle/chunks/chunk-LEZOUXG6.js +2 -0
- package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
- package/dist/cli-bundle/chunks/chunk-QOEKOECV.js +29 -0
- package/dist/cli-bundle/chunks/chunk-RHSFOMHU.js +2 -0
- package/dist/cli-bundle/chunks/chunk-XOD2PCB6.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-YVEQ2AMO.js} +4 -4
- package/dist/cli-bundle/chunks/register-list-query-KSK3R63M.js +11 -0
- package/dist/cli-bundle/chunks/register-mutation-IQ5C7U6O.js +20 -0
- package/dist/cli-bundle/chunks/{register-operations-I5W3KMGB.js → register-operations-DWVHR2NC.js} +2 -2
- package/dist/cli-bundle/chunks/register-setup-BQ5SVD4B.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-3WRPWLA7.js +3 -0
- package/dist/cli-bundle/focused-chunks/chunk-7MBUII7U.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-COPBO5HW.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-DUN4IXYN.js +20 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-EE5QSM4Z.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-HJVARYM3.js +6 -0
- package/dist/cli-bundle/focused-chunks/chunk-IAUOUGVR.js +177 -0
- package/dist/cli-bundle/focused-chunks/chunk-KOOMJ54F.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-MZDXX7JY.js +56 -0
- package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-OPFHFGDD.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QHNETP77.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-RMWES4M6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-RXT4P5QH.js +10 -0
- package/dist/cli-bundle/focused-chunks/chunk-SDOL6FM2.js +12 -0
- package/dist/cli-bundle/focused-chunks/chunk-SQV4AAUC.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-PEFABF7E.js → chunk-WE3IUNIW.js} +3 -3
- package/dist/cli-bundle/focused-chunks/chunk-YALOUBWJ.js +2 -0
- package/dist/cli-bundle/main.js +20 -20
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +2 -2
- package/dist/cli-bundle/sdk-core.js +29 -29
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +42 -42
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +11 -11
- package/dist/cli.js +1 -104
- package/dist/core/checkpoint/checkpoint-gc.js +1 -169
- package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
- package/dist/core/config/nested-settings.js +1 -534
- package/dist/core/config/positional-value.js +1 -109
- package/dist/core/diagnostics/remediation.js +1 -506
- package/dist/core/extensions/activation-summary-markdown.js +2 -145
- package/dist/core/extensions/activation-summary.js +1 -92
- package/dist/core/extensions/activation-transaction.js +1 -46
- package/dist/core/extensions/capability-usage.js +1 -173
- package/dist/core/extensions/command-hook-context.js +1 -13
- package/dist/core/extensions/command-metadata-contract.js +1 -22
- package/dist/core/extensions/command-visibility-tier.js +1 -29
- package/dist/core/extensions/contribution-inventory.js +1 -173
- package/dist/core/extensions/exporter-output-contract.js +1 -66
- package/dist/core/extensions/extension-candidate.js +1 -18
- package/dist/core/extensions/extension-capability-aliases.js +1 -158
- package/dist/core/extensions/extension-hook-runtime.js +1 -699
- package/dist/core/extensions/extension-policy.js +1 -599
- package/dist/core/extensions/extension-registries.js +1 -62
- package/dist/core/extensions/extension-runtime-helpers.js +1 -33
- package/dist/core/extensions/extension-types.js +1 -102
- package/dist/core/extensions/flag-definition-validation.js +1 -52
- package/dist/core/extensions/flag-value-types.js +1 -64
- package/dist/core/extensions/index.js +1 -526
- package/dist/core/extensions/item-field-types.js +1 -39
- package/dist/core/extensions/item-fields.js +1 -261
- package/dist/core/extensions/loader.js +1 -2223
- package/dist/core/extensions/manifest-schema.js +1 -69
- package/dist/core/extensions/module-graph-snapshot.js +1 -33
- package/dist/core/extensions/preflight-ownership.js +1 -41
- package/dist/core/extensions/registration-validation.js +1 -82
- package/dist/core/extensions/registration-values.js +1 -209
- package/dist/core/extensions/reserved-host-flags.js +1 -36
- package/dist/core/extensions/runtime-registrations.js +1 -67
- package/dist/core/extensions/service-ownership.js +1 -19
- package/dist/core/extensions/version-compat.js +1 -216
- package/dist/core/fs/fs-utils.js +2 -158
- package/dist/core/fs/host-environment-errors.js +1 -141
- package/dist/core/fs/index.js +1 -9
- package/dist/core/fs/path-utils.js +1 -17
- package/dist/core/governance/content-fields.js +1 -160
- package/dist/core/governance/issue-codes.js +1 -151
- package/dist/core/governance/metadata-coverage.js +1 -358
- package/dist/core/history/drift-cache.js +3 -72
- package/dist/core/history/drift-scan.js +1 -342
- package/dist/core/history/event-classification.js +1 -109
- package/dist/core/history/event-index.js +8 -784
- package/dist/core/history/history-compact-bulk.js +1 -104
- package/dist/core/history/history-diff.js +1 -158
- package/dist/core/history/history-rewrite.d.ts +6 -1
- package/dist/core/history/history-rewrite.js +1 -107
- package/dist/core/history/history-storage-stats.js +1 -102
- package/dist/core/history/history-stream-policy.js +1 -62
- package/dist/core/history/history.js +2 -617
- package/dist/core/history/identity.js +1 -30
- package/dist/core/history/index.js +1 -9
- package/dist/core/history/projection.js +1 -196
- package/dist/core/history/read.d.ts +9 -0
- package/dist/core/history/read.js +1 -57
- package/dist/core/history/replay.js +2 -439
- package/dist/core/history/version-address.js +1 -32
- package/dist/core/history/workspace-history.js +2 -433
- package/dist/core/io/body-file.js +1 -62
- package/dist/core/io/bulk-ids-input.js +1 -112
- package/dist/core/item/actionability.js +1 -327
- package/dist/core/item/dependency-reference.js +1 -20
- package/dist/core/item/id.js +1 -112
- package/dist/core/item/index.js +1 -12
- package/dist/core/item/item-format-version.js +1 -78
- package/dist/core/item/item-format.js +5 -1473
- package/dist/core/item/item-record.js +1 -23
- package/dist/core/item/item-type-definition.js +1 -133
- package/dist/core/item/parent-reference-policy.js +1 -57
- package/dist/core/item/parse.js +2 -603
- package/dist/core/item/plan-lifecycle.js +1 -19
- package/dist/core/item/priority.js +1 -61
- package/dist/core/item/sprint-release-format.js +1 -38
- package/dist/core/item/status-filter.js +1 -115
- package/dist/core/item/status.js +1 -43
- package/dist/core/item/toon-decode.js +1 -29
- package/dist/core/item/type-registry.js +1 -715
- package/dist/core/item/type-synonyms.js +1 -38
- package/dist/core/lock/index.js +1 -9
- package/dist/core/lock/lock-gc.js +1 -240
- package/dist/core/lock/lock.js +3 -590
- package/dist/core/output/mutation-projection.js +1 -217
- package/dist/core/output/output-control.js +1 -25
- package/dist/core/output/output.js +11 -494
- package/dist/core/output/query-summary.js +1 -58
- package/dist/core/output/tabular.js +1 -77
- package/dist/core/packages/manifest.js +1 -244
- package/dist/core/packages/root.js +1 -84
- package/dist/core/profile/profile-describe.js +1 -83
- package/dist/core/profile/profile-lint.js +1 -415
- package/dist/core/profile/profile-plan.js +0 -0
- package/dist/core/profile/profile-presets.js +1 -370
- package/dist/core/reproducibility/context.js +1 -82
- package/dist/core/schema/fields-file.js +2 -288
- package/dist/core/schema/item-types-file.js +2 -296
- package/dist/core/schema/runtime-field-filters.js +1 -49
- package/dist/core/schema/runtime-field-values.js +1 -313
- package/dist/core/schema/runtime-schema.js +2 -826
- package/dist/core/schema/status-defs-file.js +2 -227
- package/dist/core/schema/status-token.js +1 -31
- package/dist/core/schema/type-inference.js +1 -95
- package/dist/core/schema/type-presets.js +1 -87
- package/dist/core/schema/type-workflows.js +1 -104
- package/dist/core/search/background-refresh.js +2 -286
- package/dist/core/search/bm25.js +1 -146
- package/dist/core/search/cache.js +2 -534
- package/dist/core/search/corpus.js +1 -311
- package/dist/core/search/embedding-batches.js +1 -163
- package/dist/core/search/eval.js +1 -225
- package/dist/core/search/http-client.js +1 -75
- package/dist/core/search/providers.js +1 -242
- package/dist/core/search/relevance.js +1 -244
- package/dist/core/search/semantic-defaults.js +1 -199
- package/dist/core/search/staleness.js +1 -30
- package/dist/core/search/vector-stores.js +2 -664
- package/dist/core/search/vectorization-metadata.js +1 -81
- package/dist/core/sentry/helpers.js +1 -272
- package/dist/core/sentry/instrument.js +1 -387
- package/dist/core/session/session-state.js +1 -260
- package/dist/core/shared/agent-session-context.js +1 -133
- package/dist/core/shared/author.js +1 -1172
- package/dist/core/shared/command-types.js +1 -4
- package/dist/core/shared/conflict-markers.js +1 -31
- package/dist/core/shared/constants.js +1 -405
- package/dist/core/shared/errors.js +1 -20
- package/dist/core/shared/html-entity-decode.js +1 -131
- package/dist/core/shared/index.js +1 -12
- package/dist/core/shared/item-metadata-contract.js +1 -89
- package/dist/core/shared/lazy-module.js +1 -16
- package/dist/core/shared/levenshtein.js +1 -61
- package/dist/core/shared/memo.js +1 -19
- package/dist/core/shared/numeric-parsers.js +1 -20
- package/dist/core/shared/option-alias-visibility.js +1 -67
- package/dist/core/shared/primitives.js +1 -127
- package/dist/core/shared/serial-queue.js +1 -79
- package/dist/core/shared/serialization.js +1 -210
- package/dist/core/shared/split-comma-list.js +1 -30
- package/dist/core/shared/text-normalization.js +1 -38
- package/dist/core/shared/time.js +1 -306
- package/dist/core/store/index.js +1 -12
- package/dist/core/store/item-format-migration.js +1 -125
- package/dist/core/store/item-metadata-cache.js +1 -1116
- package/dist/core/store/item-metadata-query-index.js +9 -394
- package/dist/core/store/item-metadata-read-work.js +1 -43
- package/dist/core/store/item-store.js +1 -693
- package/dist/core/store/paths.d.ts +1 -1
- package/dist/core/store/paths.js +1 -214
- package/dist/core/store/settings-read-cache.js +1 -85
- package/dist/core/store/settings-validator.js +1 -421
- package/dist/core/store/settings.js +3 -1309
- package/dist/core/store/tracker-preflight.js +1 -141
- package/dist/core/telemetry/consent.js +5 -108
- package/dist/core/telemetry/observability.js +1 -246
- package/dist/core/telemetry/runtime.js +4 -1988
- package/dist/core/test/background-runs.js +4 -945
- package/dist/core/test/item-test-run-tracking.js +1 -63
- package/dist/core/test/run-selectors.js +1 -120
- package/dist/core/validate/estimate-defaults.js +1 -89
- package/dist/core/validate/fix-planning.js +1 -189
- package/dist/core/validate/linked-artifact-reference.js +1 -36
- package/dist/core/validate/missing-by-type.js +1 -34
- package/dist/core/validate/missing-link-owners.js +1 -95
- package/dist/core/validate/stale-file-classification.js +1 -82
- package/dist/mcp/http-server.js +5 -448
- package/dist/mcp/legacy-adapter.js +1 -77
- package/dist/mcp/runtime-capabilities.js +1 -200
- package/dist/mcp/server.js +4 -1233
- package/dist/mcp/tool-definitions.js +1 -804
- package/dist/sdk/actionability.js +1 -13
- package/dist/sdk/agent/closed-domain-contracts.js +1 -161
- package/dist/sdk/agent/command-recovery.js +1 -59
- package/dist/sdk/agent/command-suggestions.js +1 -66
- package/dist/sdk/agent/create-option-policy.js +1 -31
- package/dist/sdk/agent/identity-config.js +1 -106
- package/dist/sdk/agent/item-addressing.js +1 -207
- package/dist/sdk/agent/refusal-closure-census.js +1 -151
- package/dist/sdk/agent/refusal-closure.js +1 -133
- package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
- package/dist/sdk/agent/refusal-reachability.js +1 -593
- package/dist/sdk/agent/subcommand-recovery.js +1 -83
- package/dist/sdk/agent/task-transcript-contracts.js +1 -197
- package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
- package/dist/sdk/agent-capability-contracts.js +1 -428
- package/dist/sdk/agent-session-context.js +1 -9
- package/dist/sdk/annotations.js +1 -448
- package/dist/sdk/author-attribution.js +1 -468
- package/dist/sdk/authoring.js +1 -20
- package/dist/sdk/cli-bootstrap.js +1 -838
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
- package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
- package/dist/sdk/cli-contracts/command-aliases.js +1 -107
- package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
- package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
- package/dist/sdk/cli-contracts/commander-types.js +1 -159
- package/dist/sdk/cli-contracts/completeness.js +1 -393
- package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
- package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
- package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
- package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
- package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
- package/dist/sdk/cli-contracts/string-lists.js +1 -16
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
- package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
- package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
- package/dist/sdk/cli-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts.js +1 -17
- package/dist/sdk/cli-program.js +1 -49
- package/dist/sdk/command-line.d.ts +2 -5
- package/dist/sdk/command-line.js +1 -78
- package/dist/sdk/comments.js +1 -133
- package/dist/sdk/compile-cache.js +1 -73
- package/dist/sdk/completion.js +157 -837
- package/dist/sdk/compose.js +1 -1090
- package/dist/sdk/config.js +1 -1204
- package/dist/sdk/context/recency.js +1 -33
- package/dist/sdk/context/semantic-session-attribution.js +1 -82
- package/dist/sdk/context/usage-egress.js +1 -29
- package/dist/sdk/context/usage-ledger.js +3 -185
- package/dist/sdk/context-intent-contracts.js +1 -709
- package/dist/sdk/context-intent-runtime.js +1 -115
- package/dist/sdk/context-packing.js +1 -218
- package/dist/sdk/context-relevance.js +1 -503
- package/dist/sdk/context-signal-store.js +2 -426
- package/dist/sdk/context-usage.js +1 -367
- package/dist/sdk/contracts.js +1 -23
- package/dist/sdk/core-governance.js +1 -14
- package/dist/sdk/core.js +1 -14
- package/dist/sdk/corpus-shape.js +1 -401
- package/dist/sdk/define.js +1 -220
- package/dist/sdk/dependencies.js +1 -718
- package/dist/sdk/dependency-flag-validation.js +1 -156
- package/dist/sdk/dependency-provenance.js +1 -135
- package/dist/sdk/docs.js +1 -14
- package/dist/sdk/duplicates.js +1 -40
- package/dist/sdk/environment/agent-environment.js +1 -466
- package/dist/sdk/environment/host-environment-errors.js +1 -8
- package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
- package/dist/sdk/environment/source-context.js +1 -28
- package/dist/sdk/environment/tracker-preflight.js +1 -9
- package/dist/sdk/error-code-catalog.js +1 -153
- package/dist/sdk/error-runtime.js +1 -58
- package/dist/sdk/errors.js +1 -58
- package/dist/sdk/eval.js +1 -190
- package/dist/sdk/extension/author-manifest.js +1 -92
- package/dist/sdk/extension/bundled-catalog.js +1 -332
- package/dist/sdk/extension/concurrency.js +1 -25
- package/dist/sdk/extension/copy-scope.d.ts +2 -0
- package/dist/sdk/extension/copy-scope.js +2 -0
- package/dist/sdk/extension/custom-field-collisions.js +1 -30
- package/dist/sdk/extension/describe.js +3 -189
- package/dist/sdk/extension/doctor.js +1 -606
- package/dist/sdk/extension/install-plan.d.ts +69 -0
- package/dist/sdk/extension/install-plan.js +2 -0
- package/dist/sdk/extension/install-receipts.d.ts +7 -0
- package/dist/sdk/extension/install-receipts.js +2 -0
- package/dist/sdk/extension/install-runtime.js +3 -313
- package/dist/sdk/extension/install-snapshot.js +1 -66
- package/dist/sdk/extension/install-sources.js +5 -1057
- package/dist/sdk/extension/managed-state.js +2 -252
- package/dist/sdk/extension/migrations.js +2 -174
- package/dist/sdk/extension/output-ownership.js +1 -25
- package/dist/sdk/extension/runtime-summary.js +1 -18
- package/dist/sdk/extension/scaffold.js +4 -2308
- package/dist/sdk/extension/shared.js +1 -147
- package/dist/sdk/extension/source-resolution.js +1 -65
- package/dist/sdk/extension/update-check.js +1 -67
- package/dist/sdk/extension-command-context.js +1 -44
- package/dist/sdk/extension-contracts.js +1 -73
- package/dist/sdk/extension.d.ts +7 -2
- package/dist/sdk/extension.js +1 -2196
- package/dist/sdk/files.js +1 -535
- package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
- package/dist/sdk/flag-invocation-contracts.js +1 -344
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
- package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
- package/dist/sdk/generated-error-code-catalog.js +1 -16
- package/dist/sdk/governance/assurance-action-contracts.js +1 -4
- package/dist/sdk/governance/assurance-action.js +1 -411
- package/dist/sdk/governance/assurance-limits.js +1 -10
- package/dist/sdk/governance/assurance-mutation-error.js +1 -81
- package/dist/sdk/governance/assurance-presets.js +1 -135
- package/dist/sdk/governance/assurance-runtime.js +1 -238
- package/dist/sdk/governance/assurance.js +4 -1182
- package/dist/sdk/governance/boundary-fixtures.js +1 -200
- package/dist/sdk/governance/coverage-assurance.js +1 -60
- package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
- package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
- package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
- package/dist/sdk/governance/defect-recurrence.js +1 -623
- package/dist/sdk/governance/extension-host-version.js +1 -115
- package/dist/sdk/governance/gc.js +1 -368
- package/dist/sdk/governance/health.js +1 -2367
- package/dist/sdk/governance/hierarchy-validation.js +1 -108
- package/dist/sdk/governance/linked-file-report.js +1 -71
- package/dist/sdk/governance/merge-receipt-history.js +1 -206
- package/dist/sdk/governance/provenance-health.js +1 -282
- package/dist/sdk/governance/reindex.js +4 -761
- package/dist/sdk/governance/stale-work.js +1 -82
- package/dist/sdk/governance/status-role-diagnostics.js +1 -35
- package/dist/sdk/governance/storage-integrity.js +1 -280
- package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
- package/dist/sdk/governance/upgrade.js +2 -327
- package/dist/sdk/governance/validate-history-drift.js +1 -81
- package/dist/sdk/governance/validate-item-reader.js +1 -17
- package/dist/sdk/governance/validate-normalization.js +1 -36
- package/dist/sdk/governance/validate.js +1 -2261
- package/dist/sdk/governance/workspace-position.js +1 -163
- package/dist/sdk/governance.d.ts +1 -0
- package/dist/sdk/governance.js +1 -31
- package/dist/sdk/graph/adapter.js +1 -181
- package/dist/sdk/graph/analytics.js +1 -474
- package/dist/sdk/graph/assembly.js +1 -377
- package/dist/sdk/graph/cache.js +1 -160
- package/dist/sdk/graph/centrality.js +1 -258
- package/dist/sdk/graph/conformance.js +1 -130
- package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
- package/dist/sdk/graph/deadline-scheduling.js +2 -0
- package/dist/sdk/graph/durable-cache.d.ts +1 -1
- package/dist/sdk/graph/durable-cache.js +1 -361
- package/dist/sdk/graph/governance-contracts.js +1 -34
- package/dist/sdk/graph/governance.d.ts +13 -1
- package/dist/sdk/graph/governance.js +1 -735
- package/dist/sdk/graph/hierarchy-integrity.js +1 -310
- package/dist/sdk/graph/index.d.ts +3 -2
- package/dist/sdk/graph/index.js +1 -26
- package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
- package/dist/sdk/graph/lifecycle-coverage.js +2 -0
- package/dist/sdk/graph/mutation-advisory.js +1 -176
- package/dist/sdk/graph/remediation.js +1 -197
- package/dist/sdk/graph/run.d.ts +15 -1
- package/dist/sdk/graph/run.js +1 -768
- package/dist/sdk/graph/scheduling.js +1 -124
- package/dist/sdk/graph/traversal.js +1 -284
- package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
- package/dist/sdk/graph.js +1 -15
- package/dist/sdk/guide-topics.js +1 -707
- package/dist/sdk/guide.js +1 -279
- package/dist/sdk/history/maintenance.d.ts +71 -0
- package/dist/sdk/history/maintenance.js +2 -0
- package/dist/sdk/history/salvage.js +2 -247
- package/dist/sdk/history/subject.d.ts +19 -0
- package/dist/sdk/history/subject.js +2 -0
- package/dist/sdk/history-analytics.js +1 -282
- package/dist/sdk/history-compact.js +1 -527
- package/dist/sdk/history-mcp.js +1 -68
- package/dist/sdk/history-provenance.js +1 -182
- package/dist/sdk/history-read.js +1 -96
- package/dist/sdk/history-redact.d.ts +1 -14
- package/dist/sdk/history-redact.js +1 -643
- package/dist/sdk/history-repair.d.ts +5 -0
- package/dist/sdk/history-repair.js +1 -657
- package/dist/sdk/improvement-ledger-validation.js +1 -62
- package/dist/sdk/improvement-ledger.js +2 -257
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.js +1 -183
- package/dist/sdk/init-agent-guidance.js +2 -496
- package/dist/sdk/init.js +2 -820
- package/dist/sdk/invocation-author.js +1 -39
- package/dist/sdk/item-children.js +1 -90
- package/dist/sdk/item-metadata-index.js +1 -15
- package/dist/sdk/item-schedule.js +1 -27
- package/dist/sdk/item-transaction.js +1 -396
- package/dist/sdk/learnings.js +1 -29
- package/dist/sdk/lifecycle/append.js +2 -53
- package/dist/sdk/lifecycle/claim.d.ts +2 -0
- package/dist/sdk/lifecycle/claim.js +1 -242
- package/dist/sdk/lifecycle/close-many.js +1 -438
- package/dist/sdk/lifecycle/close.js +1 -468
- package/dist/sdk/lifecycle/copy.js +1 -212
- package/dist/sdk/lifecycle/create.js +1 -1949
- package/dist/sdk/lifecycle/delete.js +1 -45
- package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
- package/dist/sdk/lifecycle/focus.js +1 -91
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
- package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
- package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
- package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
- package/dist/sdk/lifecycle/mcp-actions.js +1 -51
- package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
- package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
- package/dist/sdk/lifecycle/plan.js +1 -1606
- package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
- package/dist/sdk/lifecycle/reopen.js +1 -68
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
- package/dist/sdk/lifecycle/restore.d.ts +1 -0
- package/dist/sdk/lifecycle/restore.js +1 -330
- package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
- package/dist/sdk/lifecycle/update-many.js +1 -861
- package/dist/sdk/lifecycle/update.js +1 -2136
- package/dist/sdk/lifecycle-completion.js +1 -92
- package/dist/sdk/lifecycle-policy.js +1 -120
- package/dist/sdk/linked-artifacts.js +1 -530
- package/dist/sdk/mcp/apps.js +4 -133
- package/dist/sdk/mcp/authorization.js +1 -404
- package/dist/sdk/mcp/discovery.js +1 -494
- package/dist/sdk/mcp/interactions.js +1 -336
- package/dist/sdk/mcp/protocol.d.ts +7 -0
- package/dist/sdk/mcp/protocol.js +1 -184
- package/dist/sdk/mcp/skills.js +1 -389
- package/dist/sdk/mcp/subscriptions.js +1 -211
- package/dist/sdk/mcp/tasks.js +2 -430
- package/dist/sdk/mcp/transport.js +1 -260
- package/dist/sdk/merge/abandoned-receipts.js +1 -46
- package/dist/sdk/merge/driver.js +1 -212
- package/dist/sdk/merge/index.js +1 -16
- package/dist/sdk/merge/install.js +3 -561
- package/dist/sdk/merge/receipt-file-boundary.js +1 -46
- package/dist/sdk/merge/receipt-operation.js +1 -96
- package/dist/sdk/merge/receipt-schema.js +1 -397
- package/dist/sdk/merge/receipts.js +4 -525
- package/dist/sdk/merge/reconcile.js +1 -352
- package/dist/sdk/merge/three-way.js +3 -775
- package/dist/sdk/merge.js +1 -10
- package/dist/sdk/mutation-events.js +1 -292
- package/dist/sdk/mutation-guard.js +1 -216
- package/dist/sdk/notes.js +1 -139
- package/dist/sdk/output-contracts.js +1 -172
- package/dist/sdk/output-projection.js +1 -430
- package/dist/sdk/output-token-accounting.js +1 -140
- package/dist/sdk/output.js +1 -64
- package/dist/sdk/ownership-source.js +1 -21
- package/dist/sdk/package-import-adapters.js +1 -442
- package/dist/sdk/package-migrations.js +1 -20
- package/dist/sdk/package-runtime-options.js +1 -80
- package/dist/sdk/pagination.js +1 -162
- package/dist/sdk/profile.js +1 -454
- package/dist/sdk/provenance.js +1 -258
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/activity.js +1 -401
- package/dist/sdk/query/aggregate.d.ts +16 -0
- package/dist/sdk/query/aggregate.js +1 -390
- package/dist/sdk/query/calendar.js +1 -964
- package/dist/sdk/query/complete-list.js +1 -215
- package/dist/sdk/query/context.js +1 -1702
- package/dist/sdk/query/duplicate-candidates.js +1 -70
- package/dist/sdk/query/get.js +1 -450
- package/dist/sdk/query/history.js +1 -186
- package/dist/sdk/query/item-filter-options.js +1 -9
- package/dist/sdk/query/light-metadata.js +1 -18
- package/dist/sdk/query/list-filter-shared.js +1 -81
- package/dist/sdk/query/list.js +1 -1304
- package/dist/sdk/query/multi-value-filters.js +1 -78
- package/dist/sdk/query/next.js +1 -513
- package/dist/sdk/query/parsers.js +1 -44
- package/dist/sdk/query/projection-contracts.js +1 -184
- package/dist/sdk/query/search-contracts.js +1 -230
- package/dist/sdk/query/search-pagination.js +1 -35
- package/dist/sdk/query/search-rendering.js +1 -105
- package/dist/sdk/query/search.js +2 -1987
- package/dist/sdk/query.js +1 -35
- package/dist/sdk/read-output/continuation.js +1 -194
- package/dist/sdk/read-output-budget.js +1 -135
- package/dist/sdk/read-output-contracts.js +1 -1225
- package/dist/sdk/read-output-rows.js +1 -186
- package/dist/sdk/read-output-session.js +1 -208
- package/dist/sdk/relationship-analytics.js +1 -410
- package/dist/sdk/relationship-context.js +1 -284
- package/dist/sdk/relationship-history.js +4 -519
- package/dist/sdk/relationship-kinds/contract.js +1 -22
- package/dist/sdk/relationship-migration.js +1 -77
- package/dist/sdk/relationships.js +1 -579
- package/dist/sdk/reproducibility/process.js +1 -87
- package/dist/sdk/runtime-action-aliases.js +1 -59
- package/dist/sdk/runtime-extended-actions.js +1 -177
- package/dist/sdk/runtime-input.js +1 -614
- package/dist/sdk/runtime-primitives.js +1 -84
- package/dist/sdk/runtime-public-contracts.js +1 -4
- package/dist/sdk/runtime-stats-options.js +1 -38
- package/dist/sdk/runtime.js +1 -1928
- package/dist/sdk/scheduling-shortcuts.js +1 -63
- package/dist/sdk/schema-migration.js +3 -856
- package/dist/sdk/schema.js +1 -1376
- package/dist/sdk/search-refresh-worker.js +1 -18
- package/dist/sdk/similarity-scoring.js +1 -53
- package/dist/sdk/similarity.js +1 -326
- package/dist/sdk/start-task-status.js +1 -14
- package/dist/sdk/stats.js +1 -270
- package/dist/sdk/structured-mutations.js +1 -580
- package/dist/sdk/telemetry-flush.js +1 -13
- package/dist/sdk/telemetry.js +1 -405
- package/dist/sdk/templates.js +2 -292
- package/dist/sdk/test/batch.js +2 -509
- package/dist/sdk/test/entry.js +1 -70
- package/dist/sdk/test/execution.js +6 -2211
- package/dist/sdk/test/linked-command-detection.js +1 -546
- package/dist/sdk/test/measurements.js +1 -91
- package/dist/sdk/test/parsers.js +1 -545
- package/dist/sdk/test/runs.js +1 -193
- package/dist/sdk/test/trust.js +2 -206
- package/dist/sdk/testing.js +4 -1391
- package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
- package/dist/sdk/traceability/source-traceability.js +1 -292
- package/dist/sdk/tracker-root-discovery.js +1 -9
- package/dist/sdk/workspace-contracts-cache.js +1 -28
- package/dist/sdk/workspace-contracts.js +1 -33
- package/dist/sdk/workspace-memory.js +2 -318
- package/dist/sdk/workspace-recipe.js +1 -71
- package/dist/sdk/workspace-snapshot.js +4 -613
- package/dist/sdk/workspace-transaction-gc.js +1 -149
- package/dist/sdk/workspace-transaction.js +2 -363
- package/dist/sdk/workspace.js +3 -127
- package/dist/types/index.js +1 -9
- package/dist/types.js +1 -245
- package/docs/AGENT_GUIDE.md +1 -1
- package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
- package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
- package/docs/EXTENSIONS.md +1 -0
- package/docs/HISTORY_MAINTENANCE.md +125 -0
- package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
- package/docs/PACKAGE_EVIDENCE.md +92 -0
- package/docs/PLANNING_MEASUREMENTS.md +183 -0
- package/docs/README.md +3 -0
- package/docs/SCRIPTING.md +21 -0
- package/docs/TESTING.md +23 -0
- package/docs/generated/FLAG_LEXICON_BUDGETS.md +5 -5
- package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +2 -2
- package/marketplace.json +2 -2
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/finalize-build.mjs +45 -3
- package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
- package/dist/cli-bundle/chunks/chunk-BAX2BYUW.js +0 -2111
- package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
- package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
- package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
- package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
- package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
- package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
- package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
- package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
- package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
- package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
- package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
- package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
- package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
|
@@ -1,1607 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module sdk/lifecycle/plan
|
|
3
|
-
*
|
|
4
|
-
* Implements the pm plan command surface and its agent-facing runtime behavior.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f7e870b6-fd80-5742-bc81-826d8f102d30")}catch(e){}}();
|
|
8
|
-
import { assertInitializedTracker } from "../environment/tracker-preflight.js";
|
|
9
|
-
import { getActiveExtensionRegistrations, isTerminalStatus, resolveItemTypeRegistry, resolveRuntimeStatusRegistry, resolveTypeName, EXIT_CODE, PmCliError, splitCommaList, nowIso, locateItem, mutateItem, readLocatedItem, resolvePmRoot, readSettings, resolveAuthor, isTerminalPlanMode, preserveMutationStdinTokenFields, transferMutationStdinTokenPolicy, } from "../runtime-primitives.js";
|
|
10
|
-
import { PLAN_HARNESS_VALUES, PLAN_MODE_VALUES, PLAN_STEP_LINK_KIND_VALUES, PLAN_STEP_STATUS_VALUES, } from "../../types/index.js";
|
|
11
|
-
import { runCreate, } from "./create.js";
|
|
12
|
-
import { createUnknownSubcommandError } from "../agent/subcommand-recovery.js";
|
|
13
|
-
/** Public contract for plan subcommands, shared by SDK and presentation-layer consumers. */
|
|
14
|
-
export const PLAN_SUBCOMMANDS = [
|
|
15
|
-
"create",
|
|
16
|
-
"show",
|
|
17
|
-
"add-step",
|
|
18
|
-
"update-step",
|
|
19
|
-
"complete-step",
|
|
20
|
-
"block-step",
|
|
21
|
-
"reorder-step",
|
|
22
|
-
"remove-step",
|
|
23
|
-
"link",
|
|
24
|
-
"unlink",
|
|
25
|
-
"decision",
|
|
26
|
-
"discovery",
|
|
27
|
-
"validation",
|
|
28
|
-
"resume",
|
|
29
|
-
"approve",
|
|
30
|
-
"materialize",
|
|
31
|
-
];
|
|
32
|
-
/** Supported values accepted by the plan show depth contract. */
|
|
33
|
-
export const PLAN_SHOW_DEPTH_VALUES = ["brief", "standard", "deep"];
|
|
34
|
-
const STEP_ID_PREFIX = "plan-step-";
|
|
35
|
-
const DEFAULT_PLAN_MODE = "draft";
|
|
36
|
-
/** Public contract for plan template names, shared by SDK and presentation-layer consumers. */
|
|
37
|
-
export const PLAN_TEMPLATE_NAMES = [
|
|
38
|
-
"bug-investigation",
|
|
39
|
-
"feature-implementation",
|
|
40
|
-
"refactoring-sprint",
|
|
41
|
-
];
|
|
42
|
-
// Built-in step scaffolds for the most common agent workflows. Each seeds an
|
|
43
|
-
// ordered list of pending steps so `pm plan create --template <name>` produces a
|
|
44
|
-
// ready-to-execute plan instead of an empty shell (GH-158 #2).
|
|
45
|
-
const PLAN_TEMPLATES = {
|
|
46
|
-
"bug-investigation": [
|
|
47
|
-
{
|
|
48
|
-
title: "Reproduce the bug",
|
|
49
|
-
body: "Capture exact steps, inputs, and the observed vs expected behavior.",
|
|
50
|
-
},
|
|
51
|
-
{
|
|
52
|
-
title: "Locate the root cause",
|
|
53
|
-
body: "Trace the failure to the responsible code path with evidence.",
|
|
54
|
-
},
|
|
55
|
-
{
|
|
56
|
-
title: "Write a failing test",
|
|
57
|
-
body: "Add a regression test that fails for the current bug.",
|
|
58
|
-
},
|
|
59
|
-
{
|
|
60
|
-
title: "Implement the fix",
|
|
61
|
-
body: "Apply the minimal change that makes the failing test pass.",
|
|
62
|
-
},
|
|
63
|
-
{
|
|
64
|
-
title: "Verify and document",
|
|
65
|
-
body: "Run the full suite and record the resolution and verification.",
|
|
66
|
-
},
|
|
67
|
-
],
|
|
68
|
-
"feature-implementation": [
|
|
69
|
-
{
|
|
70
|
-
title: "Clarify requirements & acceptance criteria",
|
|
71
|
-
body: "Confirm scope, edge cases, and done-conditions.",
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
title: "Design the approach",
|
|
75
|
-
body: "Decide the data model, interfaces, and integration points.",
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
title: "Implement the change",
|
|
79
|
-
body: "Build the feature behind the agreed design.",
|
|
80
|
-
},
|
|
81
|
-
{ title: "Add tests", body: "Cover the new behavior and its edge cases." },
|
|
82
|
-
{
|
|
83
|
-
title: "Update docs & changelog",
|
|
84
|
-
body: "Document the feature and surface it to users.",
|
|
85
|
-
},
|
|
86
|
-
],
|
|
87
|
-
"refactoring-sprint": [
|
|
88
|
-
{
|
|
89
|
-
title: "Map the current structure & risks",
|
|
90
|
-
body: "Inventory the code to change and its blast radius.",
|
|
91
|
-
},
|
|
92
|
-
{
|
|
93
|
-
title: "Add characterization tests",
|
|
94
|
-
body: "Lock in current behavior before refactoring.",
|
|
95
|
-
},
|
|
96
|
-
{
|
|
97
|
-
title: "Refactor incrementally",
|
|
98
|
-
body: "Apply small, reversible steps keeping tests green.",
|
|
99
|
-
},
|
|
100
|
-
{
|
|
101
|
-
title: "Verify behavior is unchanged",
|
|
102
|
-
body: "Run the full suite and compare against the baseline.",
|
|
103
|
-
},
|
|
104
|
-
{
|
|
105
|
-
title: "Clean up & document",
|
|
106
|
-
body: "Remove dead code and record the new structure.",
|
|
107
|
-
},
|
|
108
|
-
],
|
|
109
|
-
};
|
|
110
|
-
/** Resolves the ordered step seeds for a built-in plan template, rejecting unknown names with the allowed set so agents can self-correct. */
|
|
111
|
-
export function resolvePlanTemplateSteps(raw) {
|
|
112
|
-
const normalized = raw.trim().toLowerCase();
|
|
113
|
-
const template = Object.prototype.hasOwnProperty.call(PLAN_TEMPLATES, normalized)
|
|
114
|
-
? PLAN_TEMPLATES[normalized]
|
|
115
|
-
: undefined;
|
|
116
|
-
if (!template) {
|
|
117
|
-
throw new PmCliError(`Unknown plan template "${raw}". Allowed: ${PLAN_TEMPLATE_NAMES.join(", ")}`, EXIT_CODE.USAGE, {
|
|
118
|
-
code: "unknown_plan_template",
|
|
119
|
-
examples: [
|
|
120
|
-
`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`,
|
|
121
|
-
],
|
|
122
|
-
});
|
|
123
|
-
}
|
|
124
|
-
return template.map((step) => ({ ...step }));
|
|
125
|
-
}
|
|
126
|
-
/** Computes whole-percent step completion (`round(completed / total * 100)`), returning 0 for an empty plan so the field is always a stable number. */
|
|
127
|
-
function planCompletionPct(completed, total) {
|
|
128
|
-
return total > 0 ? Math.round((completed / total) * 100) : 0;
|
|
129
|
-
}
|
|
130
|
-
/* c8 ignore start -- detailed plan helper branches are validated through broader plan workflow integration tests. */
|
|
131
|
-
/** pm-6mit: ordered step titles from repeated --step values. Unlike toArray this NEVER comma-splits — each --step value is one full step title, so titles containing commas survive intact (also why --step must not be list:true in contracts: the bootstrap coalescer would comma-join values). */
|
|
132
|
-
function toOrderedStepTitles(value) {
|
|
133
|
-
const values = Array.isArray(value)
|
|
134
|
-
? value
|
|
135
|
-
: value === undefined || value === null
|
|
136
|
-
? []
|
|
137
|
-
: [value];
|
|
138
|
-
return values
|
|
139
|
-
.filter((entry) => entry !== undefined && entry !== null)
|
|
140
|
-
.map((entry) => (typeof entry === "string" ? entry : String(entry)).trim())
|
|
141
|
-
.filter((entry) => entry.length > 0);
|
|
142
|
-
}
|
|
143
|
-
function toArray(value) {
|
|
144
|
-
if (Array.isArray(value))
|
|
145
|
-
return value.flatMap((entry) => splitCommaList(entry, { unique: false }));
|
|
146
|
-
if (typeof value === "string" && value.trim().length > 0) {
|
|
147
|
-
return splitCommaList(value, { unique: false });
|
|
148
|
-
}
|
|
149
|
-
return [];
|
|
150
|
-
}
|
|
151
|
-
function toSpecArray(value) {
|
|
152
|
-
if (Array.isArray(value))
|
|
153
|
-
return value.map((entry) => entry.trim()).filter(Boolean);
|
|
154
|
-
if (typeof value === "string" && value.trim().length > 0)
|
|
155
|
-
return [value.trim()];
|
|
156
|
-
return [];
|
|
157
|
-
}
|
|
158
|
-
function asPlanMode(value, fallback = DEFAULT_PLAN_MODE) {
|
|
159
|
-
if (value === undefined)
|
|
160
|
-
return fallback;
|
|
161
|
-
const normalized = value.trim().toLowerCase();
|
|
162
|
-
const found = PLAN_MODE_VALUES.find((entry) => entry === normalized);
|
|
163
|
-
if (!found) {
|
|
164
|
-
throw new PmCliError(`Invalid plan mode "${value}". Allowed: ${PLAN_MODE_VALUES.join(", ")}`, EXIT_CODE.USAGE);
|
|
165
|
-
}
|
|
166
|
-
return found;
|
|
167
|
-
}
|
|
168
|
-
function asStepStatus(value, fallback = "pending") {
|
|
169
|
-
if (value === undefined)
|
|
170
|
-
return fallback;
|
|
171
|
-
const normalized = value.trim().toLowerCase();
|
|
172
|
-
const found = PLAN_STEP_STATUS_VALUES.find((entry) => entry === normalized);
|
|
173
|
-
if (!found) {
|
|
174
|
-
throw new PmCliError(`Invalid step status "${value}". Allowed: ${PLAN_STEP_STATUS_VALUES.join(", ")}`, EXIT_CODE.USAGE);
|
|
175
|
-
}
|
|
176
|
-
return found;
|
|
177
|
-
}
|
|
178
|
-
function asLinkKind(value, fallback = "related") {
|
|
179
|
-
if (value === undefined)
|
|
180
|
-
return fallback;
|
|
181
|
-
const normalized = value.trim().toLowerCase();
|
|
182
|
-
const found = PLAN_STEP_LINK_KIND_VALUES.find((entry) => entry === normalized);
|
|
183
|
-
if (!found) {
|
|
184
|
-
throw new PmCliError(`Invalid step link kind "${value}". Allowed: ${PLAN_STEP_LINK_KIND_VALUES.join(", ")}`, EXIT_CODE.USAGE);
|
|
185
|
-
}
|
|
186
|
-
return found;
|
|
187
|
-
}
|
|
188
|
-
function asHarness(value) {
|
|
189
|
-
if (value === undefined)
|
|
190
|
-
return undefined;
|
|
191
|
-
const normalized = value.trim().toLowerCase();
|
|
192
|
-
if (normalized.length === 0)
|
|
193
|
-
return undefined;
|
|
194
|
-
const found = PLAN_HARNESS_VALUES.find((entry) => entry === normalized);
|
|
195
|
-
if (!found) {
|
|
196
|
-
throw new PmCliError(`Invalid plan harness "${value}". Allowed: ${PLAN_HARNESS_VALUES.join(", ")}`, EXIT_CODE.USAGE);
|
|
197
|
-
}
|
|
198
|
-
return found;
|
|
199
|
-
}
|
|
200
|
-
function asDepth(value) {
|
|
201
|
-
if (value === undefined)
|
|
202
|
-
return "brief";
|
|
203
|
-
const normalized = value.trim().toLowerCase();
|
|
204
|
-
const found = PLAN_SHOW_DEPTH_VALUES.find((entry) => entry === normalized);
|
|
205
|
-
if (!found) {
|
|
206
|
-
throw new PmCliError(`Invalid --depth "${value}". Allowed: ${PLAN_SHOW_DEPTH_VALUES.join(", ")}`, EXIT_CODE.USAGE);
|
|
207
|
-
}
|
|
208
|
-
return found;
|
|
209
|
-
}
|
|
210
|
-
function parsePlanFields(raw) {
|
|
211
|
-
if (raw === undefined) {
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
const fields = raw
|
|
215
|
-
.split(",")
|
|
216
|
-
.map((entry) => entry.trim())
|
|
217
|
-
.filter((entry) => entry.length > 0);
|
|
218
|
-
if (fields.length === 0) {
|
|
219
|
-
throw new PmCliError("Plan --fields requires a comma-separated list of plan field names", EXIT_CODE.USAGE);
|
|
220
|
-
}
|
|
221
|
-
return fields;
|
|
222
|
-
}
|
|
223
|
-
const PLAN_FIELD_KEYS = new Set([
|
|
224
|
-
"id",
|
|
225
|
-
"title",
|
|
226
|
-
"status",
|
|
227
|
-
"mode",
|
|
228
|
-
"scope",
|
|
229
|
-
"harness",
|
|
230
|
-
"parent",
|
|
231
|
-
"resume_context",
|
|
232
|
-
"steps_summary",
|
|
233
|
-
"current_step",
|
|
234
|
-
"blocked_steps",
|
|
235
|
-
"steps",
|
|
236
|
-
"decisions",
|
|
237
|
-
"discoveries",
|
|
238
|
-
"validation",
|
|
239
|
-
"linked_items",
|
|
240
|
-
]);
|
|
241
|
-
function projectPlanForFields(plan, fields) {
|
|
242
|
-
const source = plan;
|
|
243
|
-
const projected = {};
|
|
244
|
-
const unknownFields = [];
|
|
245
|
-
for (const field of fields) {
|
|
246
|
-
const normalized = field.startsWith("plan.")
|
|
247
|
-
? field.slice("plan.".length)
|
|
248
|
-
: field;
|
|
249
|
-
if (normalized.length === 0) {
|
|
250
|
-
continue;
|
|
251
|
-
}
|
|
252
|
-
if (!PLAN_FIELD_KEYS.has(normalized)) {
|
|
253
|
-
unknownFields.push(field);
|
|
254
|
-
continue;
|
|
255
|
-
}
|
|
256
|
-
if (Object.prototype.hasOwnProperty.call(source, normalized)) {
|
|
257
|
-
projected[normalized] = source[normalized];
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
if (unknownFields.length > 0) {
|
|
261
|
-
throw new PmCliError(`Unknown Plan --fields value(s): ${unknownFields.join(", ")}`, EXIT_CODE.USAGE, {
|
|
262
|
-
nextSteps: [
|
|
263
|
-
`Use --fields ${[...PLAN_FIELD_KEYS].join(",")}`,
|
|
264
|
-
"Run pm plan show <id> --depth brief for compact default fields.",
|
|
265
|
-
],
|
|
266
|
-
recovery: {
|
|
267
|
-
provided_fields: unknownFields,
|
|
268
|
-
suggested_retry: `pm plan show <id> --fields ${[...PLAN_FIELD_KEYS].join(",")}`,
|
|
269
|
-
},
|
|
270
|
-
});
|
|
271
|
-
}
|
|
272
|
-
return projected;
|
|
273
|
-
}
|
|
274
|
-
function parsePairList(raw, label) {
|
|
275
|
-
const out = {};
|
|
276
|
-
for (const entry of raw.split(",")) {
|
|
277
|
-
const trimmed = entry.trim();
|
|
278
|
-
if (trimmed.length === 0)
|
|
279
|
-
continue;
|
|
280
|
-
const equalsIndex = trimmed.indexOf("=");
|
|
281
|
-
if (equalsIndex <= 0) {
|
|
282
|
-
throw new PmCliError(`Invalid ${label} entry "${trimmed}"; expected key=value`, EXIT_CODE.USAGE, {
|
|
283
|
-
code: "malformed_plan_step_evidence",
|
|
284
|
-
required: `${label} entries must use comma-separated key=value fields.`,
|
|
285
|
-
why: "Structured Plan evidence must be validated before it is persisted.",
|
|
286
|
-
examples: [
|
|
287
|
-
'--file "path=src/index.ts,scope=project,note=implementation"',
|
|
288
|
-
'--test "command=pnpm test,note=regression"',
|
|
289
|
-
'--doc "path=docs/PLAN.md,scope=project"',
|
|
290
|
-
],
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
out[trimmed.slice(0, equalsIndex).trim().toLowerCase()] = trimmed
|
|
294
|
-
.slice(equalsIndex + 1)
|
|
295
|
-
.trim();
|
|
296
|
-
}
|
|
297
|
-
return out;
|
|
298
|
-
}
|
|
299
|
-
function parseStepFile(spec) {
|
|
300
|
-
const fields = parsePairList(spec, "--file");
|
|
301
|
-
if (!fields.path) {
|
|
302
|
-
throw new PmCliError("--file requires path=<value>", EXIT_CODE.USAGE, {
|
|
303
|
-
code: "malformed_plan_step_evidence",
|
|
304
|
-
required: "--file requires a non-empty path field.",
|
|
305
|
-
why: "Plan file evidence needs a stable path for later verification.",
|
|
306
|
-
});
|
|
307
|
-
}
|
|
308
|
-
const file = { path: fields.path };
|
|
309
|
-
if (fields.scope === "global" || fields.scope === "project")
|
|
310
|
-
file.scope = fields.scope;
|
|
311
|
-
if (fields.note)
|
|
312
|
-
file.note = fields.note;
|
|
313
|
-
return file;
|
|
314
|
-
}
|
|
315
|
-
function parseStepTest(spec) {
|
|
316
|
-
const fields = parsePairList(spec, "--test");
|
|
317
|
-
if (!fields.command && !fields.path) {
|
|
318
|
-
throw new PmCliError("--test requires at least command=<value> or path=<value>", EXIT_CODE.USAGE, {
|
|
319
|
-
code: "malformed_plan_step_evidence",
|
|
320
|
-
required: "--test requires a command or path field.",
|
|
321
|
-
why: "Plan test evidence must identify something runnable or inspectable.",
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
const test = {};
|
|
325
|
-
if (fields.command)
|
|
326
|
-
test.command = fields.command;
|
|
327
|
-
if (fields.path)
|
|
328
|
-
test.path = fields.path;
|
|
329
|
-
if (fields.note)
|
|
330
|
-
test.note = fields.note;
|
|
331
|
-
return test;
|
|
332
|
-
}
|
|
333
|
-
function parseStepDoc(spec) {
|
|
334
|
-
const fields = parsePairList(spec, "--doc");
|
|
335
|
-
if (!fields.path) {
|
|
336
|
-
throw new PmCliError("--doc requires path=<value>", EXIT_CODE.USAGE, {
|
|
337
|
-
code: "malformed_plan_step_evidence",
|
|
338
|
-
required: "--doc requires a non-empty path field.",
|
|
339
|
-
why: "Plan documentation evidence needs a stable path for later verification.",
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
const doc = { path: fields.path };
|
|
343
|
-
if (fields.scope === "global" || fields.scope === "project")
|
|
344
|
-
doc.scope = fields.scope;
|
|
345
|
-
if (fields.note)
|
|
346
|
-
doc.note = fields.note;
|
|
347
|
-
return doc;
|
|
348
|
-
}
|
|
349
|
-
function summarizeSteps(steps) {
|
|
350
|
-
const summary = {
|
|
351
|
-
total: steps.length,
|
|
352
|
-
pending: 0,
|
|
353
|
-
in_progress: 0,
|
|
354
|
-
blocked: 0,
|
|
355
|
-
completed: 0,
|
|
356
|
-
skipped: 0,
|
|
357
|
-
superseded: 0,
|
|
358
|
-
completion_pct: 0,
|
|
359
|
-
};
|
|
360
|
-
for (const step of steps) {
|
|
361
|
-
summary[step.status] += 1;
|
|
362
|
-
}
|
|
363
|
-
summary.completion_pct = planCompletionPct(summary.completed, summary.total);
|
|
364
|
-
return summary;
|
|
365
|
-
}
|
|
366
|
-
function newStepId(existing) {
|
|
367
|
-
const used = new Set(existing.map((step) => step.id));
|
|
368
|
-
for (let cursor = existing.length + 1; cursor < existing.length + 1024; cursor += 1) {
|
|
369
|
-
const candidate = `${STEP_ID_PREFIX}${String(cursor).padStart(3, "0")}`;
|
|
370
|
-
if (!used.has(candidate))
|
|
371
|
-
return candidate;
|
|
372
|
-
}
|
|
373
|
-
/* c8 ignore next -- step id allocation only fails if 1024 consecutive ids are taken. */
|
|
374
|
-
throw new PmCliError("Could not allocate step id (limit reached)", EXIT_CODE.GENERIC_FAILURE);
|
|
375
|
-
}
|
|
376
|
-
function resolveStepRef(steps, ref) {
|
|
377
|
-
const trimmed = ref.trim();
|
|
378
|
-
if (trimmed.length === 0) {
|
|
379
|
-
throw new PmCliError("Step reference cannot be empty", EXIT_CODE.USAGE);
|
|
380
|
-
}
|
|
381
|
-
const direct = steps.find((step) => step.id === trimmed);
|
|
382
|
-
if (direct)
|
|
383
|
-
return direct;
|
|
384
|
-
if (/^\d+$/.test(trimmed)) {
|
|
385
|
-
const order = Number.parseInt(trimmed, 10);
|
|
386
|
-
const byOrder = steps.find((step) => step.order === order);
|
|
387
|
-
if (byOrder)
|
|
388
|
-
return byOrder;
|
|
389
|
-
}
|
|
390
|
-
throw new PmCliError(`Step "${ref}" not found in plan`, EXIT_CODE.NOT_FOUND);
|
|
391
|
-
}
|
|
392
|
-
// pm-fl0c #10 (2026-05-28): skip steps whose status is "completed" and steps
|
|
393
|
-
// that already have an `implements` link from a prior materialize run, so
|
|
394
|
-
// `pm plan materialize --steps all` is idempotent and never re-creates fresh
|
|
395
|
-
// Tasks for work already tracked. Explicit step refs are still allowed
|
|
396
|
-
// through (the user asked by ID) but the skip-reason is recorded.
|
|
397
|
-
function classifyMaterializeSkip(step) {
|
|
398
|
-
if (step.status === "completed") {
|
|
399
|
-
return { reason: "already_completed" };
|
|
400
|
-
}
|
|
401
|
-
const existingImplements = (step.linked_items ?? []).find((link) => link.kind === "implements");
|
|
402
|
-
if (existingImplements) {
|
|
403
|
-
return {
|
|
404
|
-
reason: "already_materialized",
|
|
405
|
-
existing_id: existingImplements.id,
|
|
406
|
-
};
|
|
407
|
-
}
|
|
408
|
-
return undefined;
|
|
409
|
-
}
|
|
410
|
-
function resolveMaterializeTargets(steps, refs) {
|
|
411
|
-
const allRefs = refs.filter((ref) => ref.trim().toLowerCase() === "all");
|
|
412
|
-
const targets = [];
|
|
413
|
-
const skipped = [];
|
|
414
|
-
if (allRefs.length > 0) {
|
|
415
|
-
if (refs.length > allRefs.length) {
|
|
416
|
-
throw new PmCliError("pm plan materialize --steps all cannot be combined with other step refs", EXIT_CODE.USAGE);
|
|
417
|
-
}
|
|
418
|
-
for (const step of steps
|
|
419
|
-
.slice()
|
|
420
|
-
.sort((left, right) => left.order - right.order)) {
|
|
421
|
-
const skip = classifyMaterializeSkip(step);
|
|
422
|
-
if (skip) {
|
|
423
|
-
skipped.push({ from_step: step.id, ...skip });
|
|
424
|
-
continue;
|
|
425
|
-
}
|
|
426
|
-
targets.push(step);
|
|
427
|
-
}
|
|
428
|
-
return { targets, skipped };
|
|
429
|
-
}
|
|
430
|
-
const seen = new Set();
|
|
431
|
-
for (const ref of refs) {
|
|
432
|
-
const step = resolveStepRef(steps, ref);
|
|
433
|
-
if (seen.has(step.id))
|
|
434
|
-
continue;
|
|
435
|
-
seen.add(step.id);
|
|
436
|
-
const skip = classifyMaterializeSkip(step);
|
|
437
|
-
if (skip) {
|
|
438
|
-
skipped.push({ from_step: step.id, ...skip });
|
|
439
|
-
continue;
|
|
440
|
-
}
|
|
441
|
-
targets.push(step);
|
|
442
|
-
}
|
|
443
|
-
return { targets, skipped };
|
|
444
|
-
}
|
|
445
|
-
function resolvePlanLogText(kind, options) {
|
|
446
|
-
const canonical = kind === "decision"
|
|
447
|
-
? options.decisionText
|
|
448
|
-
: kind === "discovery"
|
|
449
|
-
? options.discoveryText
|
|
450
|
-
: options.validationText;
|
|
451
|
-
const shorthand = kind === "decision"
|
|
452
|
-
? options.decision
|
|
453
|
-
: kind === "discovery"
|
|
454
|
-
? options.discovery
|
|
455
|
-
: options.validation;
|
|
456
|
-
return canonical?.trim() || shorthand?.trim() || undefined;
|
|
457
|
-
}
|
|
458
|
-
function findCurrentStep(steps) {
|
|
459
|
-
return (steps.find((step) => step.status === "in_progress") ??
|
|
460
|
-
steps.find((step) => step.status === "pending"));
|
|
461
|
-
}
|
|
462
|
-
function blockedSteps(steps) {
|
|
463
|
-
return steps
|
|
464
|
-
.filter((step) => step.status === "blocked")
|
|
465
|
-
.map((step) => ({
|
|
466
|
-
id: step.id,
|
|
467
|
-
order: step.order,
|
|
468
|
-
title: step.title,
|
|
469
|
-
blocked_reason: step.blocked_reason,
|
|
470
|
-
}));
|
|
471
|
-
}
|
|
472
|
-
function projectPlan(item, depth = "brief") {
|
|
473
|
-
const steps = (item.plan_steps ?? [])
|
|
474
|
-
.slice()
|
|
475
|
-
.sort((left, right) => left.order - right.order);
|
|
476
|
-
const summary = summarizeSteps(steps);
|
|
477
|
-
const current = findCurrentStep(steps);
|
|
478
|
-
const projection = {
|
|
479
|
-
id: item.id,
|
|
480
|
-
title: item.title,
|
|
481
|
-
status: item.status,
|
|
482
|
-
mode: (item.plan_mode ?? DEFAULT_PLAN_MODE),
|
|
483
|
-
scope: item.plan_scope,
|
|
484
|
-
harness: item.plan_harness,
|
|
485
|
-
parent: item.parent,
|
|
486
|
-
resume_context: item.plan_resume_context,
|
|
487
|
-
steps_summary: summary,
|
|
488
|
-
current_step: current
|
|
489
|
-
? {
|
|
490
|
-
id: current.id,
|
|
491
|
-
order: current.order,
|
|
492
|
-
title: current.title,
|
|
493
|
-
status: current.status,
|
|
494
|
-
}
|
|
495
|
-
: undefined,
|
|
496
|
-
blocked_steps: blockedSteps(steps),
|
|
497
|
-
linked_items: (item.dependencies ?? []).map((dep) => ({
|
|
498
|
-
id: dep.id,
|
|
499
|
-
kind: dep.kind,
|
|
500
|
-
})),
|
|
501
|
-
};
|
|
502
|
-
if (depth === "standard" || depth === "deep") {
|
|
503
|
-
projection.steps = steps;
|
|
504
|
-
}
|
|
505
|
-
if (depth === "deep") {
|
|
506
|
-
projection.decisions = item.plan_decisions ?? [];
|
|
507
|
-
projection.discoveries = item.plan_discoveries ?? [];
|
|
508
|
-
projection.validation = item.plan_validation ?? [];
|
|
509
|
-
}
|
|
510
|
-
return projection;
|
|
511
|
-
}
|
|
512
|
-
function nextActionsFor(planId, plan) {
|
|
513
|
-
const tips = [];
|
|
514
|
-
if (plan.steps_summary.total === 0) {
|
|
515
|
-
tips.push(`pm plan add-step ${planId} --step-title "First step"`);
|
|
516
|
-
}
|
|
517
|
-
if (plan.current_step) {
|
|
518
|
-
tips.push(`pm plan update-step ${planId} ${plan.current_step.id} --step-status in_progress`, `pm plan complete-step ${planId} ${plan.current_step.id} --step-evidence "..."`);
|
|
519
|
-
}
|
|
520
|
-
if (plan.steps_summary.blocked > 0) {
|
|
521
|
-
tips.push(`pm plan show ${planId} --depth standard`);
|
|
522
|
-
}
|
|
523
|
-
if (plan.mode === "draft" || plan.mode === "research") {
|
|
524
|
-
tips.push(`pm plan approve ${planId} --message "ready to execute"`);
|
|
525
|
-
}
|
|
526
|
-
if (plan.steps_summary.completed === plan.steps_summary.total &&
|
|
527
|
-
plan.steps_summary.total > 0 &&
|
|
528
|
-
!isTerminalPlanMode(plan.mode) &&
|
|
529
|
-
plan.status !== "closed" &&
|
|
530
|
-
plan.status !== "canceled") {
|
|
531
|
-
tips.push(`pm close ${planId} "plan complete"`);
|
|
532
|
-
}
|
|
533
|
-
return tips;
|
|
534
|
-
}
|
|
535
|
-
function ensurePlanItem(item) {
|
|
536
|
-
const normalizedType = (item.type ?? "").trim().toLowerCase();
|
|
537
|
-
if (normalizedType !== "plan") {
|
|
538
|
-
throw new PmCliError(`Item ${item.id} is type ${item.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`, EXIT_CODE.USAGE, {
|
|
539
|
-
code: "wrong_item_type",
|
|
540
|
-
required: "Use pm plan commands only with items whose type is Plan.",
|
|
541
|
-
why: "Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",
|
|
542
|
-
examples: [
|
|
543
|
-
`pm get ${item.id} --depth brief`,
|
|
544
|
-
'pm plan create --title "Execution plan" --scope "<goal>"',
|
|
545
|
-
],
|
|
546
|
-
});
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
async function loadContext(global) {
|
|
550
|
-
const pmRoot = resolvePmRoot(process.cwd(), global.path);
|
|
551
|
-
await assertInitializedTracker(pmRoot);
|
|
552
|
-
const settings = await readSettings(pmRoot);
|
|
553
|
-
return { pmRoot, settings };
|
|
554
|
-
}
|
|
555
|
-
async function readPlanItem(ctx, id) {
|
|
556
|
-
const typeRegistry = resolveItemTypeRegistry(ctx.settings, getActiveExtensionRegistrations());
|
|
557
|
-
const located = await locateItem(ctx.pmRoot, id, ctx.settings.id_prefix, ctx.settings.item_format, typeRegistry.type_to_folder);
|
|
558
|
-
if (!located) {
|
|
559
|
-
throw new PmCliError(`Plan ${id} not found`, EXIT_CODE.NOT_FOUND);
|
|
560
|
-
}
|
|
561
|
-
const loaded = await readLocatedItem(located, {
|
|
562
|
-
schema: ctx.settings.schema,
|
|
563
|
-
});
|
|
564
|
-
ensurePlanItem(loaded.document.metadata);
|
|
565
|
-
return { document: loaded.document, itemId: located.id };
|
|
566
|
-
}
|
|
567
|
-
function buildPlanCreateDependencies(options) {
|
|
568
|
-
const deps = [];
|
|
569
|
-
if (options.parent) {
|
|
570
|
-
deps.push(`id=${options.parent.trim()},kind=parent`);
|
|
571
|
-
}
|
|
572
|
-
for (const ref of toArray(options.related))
|
|
573
|
-
deps.push(`id=${ref},kind=related`);
|
|
574
|
-
for (const ref of toArray(options.blocks))
|
|
575
|
-
deps.push(`id=${ref},kind=blocks`);
|
|
576
|
-
for (const ref of toArray(options.blockedBy))
|
|
577
|
-
deps.push(`id=${ref},kind=blocked_by`);
|
|
578
|
-
return deps.length > 0 ? deps : undefined;
|
|
579
|
-
}
|
|
580
|
-
function buildInitialValidation(options) {
|
|
581
|
-
const text = options.validationText?.trim();
|
|
582
|
-
const command = options.validationCommand?.trim();
|
|
583
|
-
const expected = options.validationExpected?.trim();
|
|
584
|
-
if (!text && !command && !expected) {
|
|
585
|
-
return undefined;
|
|
586
|
-
}
|
|
587
|
-
return {
|
|
588
|
-
text: text || command || "Validation check",
|
|
589
|
-
command: command || undefined,
|
|
590
|
-
expected: expected || undefined,
|
|
591
|
-
};
|
|
592
|
-
}
|
|
593
|
-
function hasPlanStepDetailOptions(options) {
|
|
594
|
-
return (Boolean(options.stepBody?.trim()) ||
|
|
595
|
-
Boolean(options.stepOwner?.trim()) ||
|
|
596
|
-
Boolean(options.stepStatus?.trim()) ||
|
|
597
|
-
Boolean(options.stepEvidence?.trim()) ||
|
|
598
|
-
Boolean(options.stepBlockedReason?.trim()) ||
|
|
599
|
-
Boolean(options.stepReplacement?.trim()) ||
|
|
600
|
-
toArray(options.dependsOn).length > 0 ||
|
|
601
|
-
toArray(options.link).length > 0);
|
|
602
|
-
}
|
|
603
|
-
function resolveInitialStepSeed(options) {
|
|
604
|
-
const stepTitleFlag = options.stepTitle?.trim() || undefined;
|
|
605
|
-
const repeatedStepTitles = toOrderedStepTitles(options.step);
|
|
606
|
-
const templateSteps = options.template?.trim()
|
|
607
|
-
? resolvePlanTemplateSteps(options.template)
|
|
608
|
-
: [];
|
|
609
|
-
return {
|
|
610
|
-
repeatedStepTitles,
|
|
611
|
-
stepTitleFlag,
|
|
612
|
-
stepTitles: [
|
|
613
|
-
...(stepTitleFlag ? [stepTitleFlag] : []),
|
|
614
|
-
...repeatedStepTitles,
|
|
615
|
-
...templateSteps.map((step) => step.title),
|
|
616
|
-
],
|
|
617
|
-
templateSteps,
|
|
618
|
-
};
|
|
619
|
-
}
|
|
620
|
-
function assertInitialStepSeedAllowed(seed, hasPerStepDetailOptions) {
|
|
621
|
-
if ((seed.stepTitleFlag || seed.repeatedStepTitles.length > 0) &&
|
|
622
|
-
seed.templateSteps.length > 0) {
|
|
623
|
-
throw new PmCliError("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source", EXIT_CODE.USAGE, {
|
|
624
|
-
code: "ambiguous_option_combination",
|
|
625
|
-
examples: [
|
|
626
|
-
`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`,
|
|
627
|
-
'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"',
|
|
628
|
-
],
|
|
629
|
-
});
|
|
630
|
-
}
|
|
631
|
-
if (seed.stepTitles.length > 1 && hasPerStepDetailOptions) {
|
|
632
|
-
throw new PmCliError("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually", EXIT_CODE.USAGE, {
|
|
633
|
-
code: "ambiguous_option_combination",
|
|
634
|
-
examples: [
|
|
635
|
-
'pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"',
|
|
636
|
-
'pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"',
|
|
637
|
-
],
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
}
|
|
641
|
-
function buildSingleInitialStep(options, title) {
|
|
642
|
-
const status = asStepStatus(options.stepStatus, "pending");
|
|
643
|
-
const linkedItems = buildLinkInputs(options, "depends_on");
|
|
644
|
-
const files = toSpecArray(options.file).map(parseStepFile);
|
|
645
|
-
const tests = toSpecArray(options.test).map(parseStepTest);
|
|
646
|
-
const docs = toSpecArray(options.doc).map(parseStepDoc);
|
|
647
|
-
const now = nowIso();
|
|
648
|
-
return {
|
|
649
|
-
id: "plan-step-001",
|
|
650
|
-
order: 1,
|
|
651
|
-
title,
|
|
652
|
-
body: options.stepBody?.trim() || undefined,
|
|
653
|
-
status,
|
|
654
|
-
owner: options.stepOwner?.trim() || undefined,
|
|
655
|
-
evidence: options.stepEvidence?.trim() || undefined,
|
|
656
|
-
blocked_reason: status === "blocked"
|
|
657
|
-
? options.stepBlockedReason?.trim() || ""
|
|
658
|
-
: undefined,
|
|
659
|
-
linked_items: linkedItems.length > 0 ? linkedItems : undefined,
|
|
660
|
-
files: files.length > 0 ? files : undefined,
|
|
661
|
-
tests: tests.length > 0 ? tests : undefined,
|
|
662
|
-
docs: docs.length > 0 ? docs : undefined,
|
|
663
|
-
created_at: now,
|
|
664
|
-
updated_at: now,
|
|
665
|
-
completed_at: status === "completed" ? now : undefined,
|
|
666
|
-
};
|
|
667
|
-
}
|
|
668
|
-
function buildInitialSteps(options) {
|
|
669
|
-
const seed = resolveInitialStepSeed(options);
|
|
670
|
-
const hasDetailOptions = hasPlanStepDetailOptions(options);
|
|
671
|
-
assertInitialStepSeedAllowed(seed, hasDetailOptions);
|
|
672
|
-
if (seed.stepTitles.length === 0) {
|
|
673
|
-
return { steps: [], hasPerStepDetailOptions: hasDetailOptions };
|
|
674
|
-
}
|
|
675
|
-
if (seed.stepTitles.length === 1) {
|
|
676
|
-
return {
|
|
677
|
-
steps: [buildSingleInitialStep(options, seed.stepTitles[0])],
|
|
678
|
-
hasPerStepDetailOptions: hasDetailOptions,
|
|
679
|
-
};
|
|
680
|
-
}
|
|
681
|
-
const now = nowIso();
|
|
682
|
-
return {
|
|
683
|
-
steps: seed.stepTitles.map((stepTitle, index) => ({
|
|
684
|
-
id: `${STEP_ID_PREFIX}${String(index + 1).padStart(3, "0")}`,
|
|
685
|
-
order: index + 1,
|
|
686
|
-
title: stepTitle,
|
|
687
|
-
body: seed.templateSteps[index]?.body,
|
|
688
|
-
status: "pending",
|
|
689
|
-
created_at: now,
|
|
690
|
-
updated_at: now,
|
|
691
|
-
})),
|
|
692
|
-
hasPerStepDetailOptions: hasDetailOptions,
|
|
693
|
-
};
|
|
694
|
-
}
|
|
695
|
-
function preservePlanCreateStdinPolicy(source, createOptions, derivedLiteralFields = []) {
|
|
696
|
-
transferMutationStdinTokenPolicy(source, createOptions);
|
|
697
|
-
if (derivedLiteralFields.length > 0) {
|
|
698
|
-
preserveMutationStdinTokenFields(createOptions, derivedLiteralFields);
|
|
699
|
-
}
|
|
700
|
-
}
|
|
701
|
-
async function planCreate(options, global, ctx) {
|
|
702
|
-
const title = options.title?.trim();
|
|
703
|
-
if (!title) {
|
|
704
|
-
throw new PmCliError("pm plan create requires --title", EXIT_CODE.USAGE, {
|
|
705
|
-
code: "missing_required_option",
|
|
706
|
-
examples: [
|
|
707
|
-
'pm plan create --title "Refactor lock retry" --scope pm-a1b2',
|
|
708
|
-
],
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
const mode = asPlanMode(options.mode, DEFAULT_PLAN_MODE);
|
|
712
|
-
const harness = asHarness(options.harness);
|
|
713
|
-
const fromSearch = options.fromSearch?.trim();
|
|
714
|
-
const initialValidation = buildInitialValidation(options);
|
|
715
|
-
const { steps: initialSteps, hasPerStepDetailOptions } = buildInitialSteps(options);
|
|
716
|
-
if (initialSteps.length === 0 && hasPerStepDetailOptions) {
|
|
717
|
-
throw new PmCliError("pm plan create step options require --step-title (or a single --step)", EXIT_CODE.USAGE, {
|
|
718
|
-
code: "missing_required_option",
|
|
719
|
-
examples: [
|
|
720
|
-
'pm plan create --title "Execution plan" --step-title "Read the code"',
|
|
721
|
-
],
|
|
722
|
-
});
|
|
723
|
-
}
|
|
724
|
-
const description = options.description?.trim() ?? options.scope?.trim() ?? title;
|
|
725
|
-
const requestedAssignee = options.claim
|
|
726
|
-
? resolveAuthor(options.author, ctx.settings.author_default)
|
|
727
|
-
: options.assignee?.trim() || undefined;
|
|
728
|
-
const createOptions = {
|
|
729
|
-
...options,
|
|
730
|
-
title,
|
|
731
|
-
description,
|
|
732
|
-
type: "Plan",
|
|
733
|
-
template: undefined,
|
|
734
|
-
file: toSpecArray(options.file),
|
|
735
|
-
test: toSpecArray(options.test),
|
|
736
|
-
doc: toSpecArray(options.doc),
|
|
737
|
-
field: toSpecArray(options.field),
|
|
738
|
-
// Ownership is assigned by the atomic Plan metadata mutation below. The
|
|
739
|
-
// base create must remain author-owned so strict ownership governance does
|
|
740
|
-
// not reject the metadata seed as a cross-owner follow-up mutation.
|
|
741
|
-
assignee: resolveAuthor(options.author, ctx.settings.author_default),
|
|
742
|
-
blockedBy: undefined,
|
|
743
|
-
dep: buildPlanCreateDependencies(options),
|
|
744
|
-
message: options.message ??
|
|
745
|
-
(fromSearch ? `plan create (search: ${fromSearch})` : `plan create`),
|
|
746
|
-
};
|
|
747
|
-
preservePlanCreateStdinPolicy(options, createOptions);
|
|
748
|
-
const createResult = await runCreate(createOptions, global);
|
|
749
|
-
// Seed every Plan-specific field before assigning the requested owner so
|
|
750
|
-
// cross-owner creation cannot reject a follow-up enrichment and leave a
|
|
751
|
-
// partially initialized Plan.
|
|
752
|
-
const seedResult = await mutateItem({
|
|
753
|
-
pmRoot: ctx.pmRoot,
|
|
754
|
-
settings: ctx.settings,
|
|
755
|
-
id: createResult.item.id,
|
|
756
|
-
op: "plan_create_metadata",
|
|
757
|
-
author: resolveAuthor(options.author, ctx.settings.author_default),
|
|
758
|
-
message: "seed plan metadata",
|
|
759
|
-
mutate(doc) {
|
|
760
|
-
const changedFields = ["plan_mode"];
|
|
761
|
-
doc.metadata.plan_mode = mode;
|
|
762
|
-
if (harness) {
|
|
763
|
-
doc.metadata.plan_harness = harness;
|
|
764
|
-
changedFields.push("plan_harness");
|
|
765
|
-
}
|
|
766
|
-
const scope = options.scope?.trim();
|
|
767
|
-
if (scope) {
|
|
768
|
-
doc.metadata.plan_scope = scope;
|
|
769
|
-
changedFields.push("plan_scope");
|
|
770
|
-
}
|
|
771
|
-
const resumeContext = options.resumeContext?.trim();
|
|
772
|
-
if (resumeContext) {
|
|
773
|
-
doc.metadata.plan_resume_context = resumeContext;
|
|
774
|
-
changedFields.push("plan_resume_context");
|
|
775
|
-
}
|
|
776
|
-
doc.metadata.plan_steps = initialSteps;
|
|
777
|
-
changedFields.push("plan_steps");
|
|
778
|
-
if (initialValidation) {
|
|
779
|
-
doc.metadata.plan_validation = [
|
|
780
|
-
...(doc.metadata.plan_validation ?? []),
|
|
781
|
-
initialValidation,
|
|
782
|
-
];
|
|
783
|
-
changedFields.push("plan_validation");
|
|
784
|
-
}
|
|
785
|
-
if (requestedAssignee) {
|
|
786
|
-
doc.metadata.assignee = requestedAssignee;
|
|
787
|
-
changedFields.push("assignee");
|
|
788
|
-
}
|
|
789
|
-
return { changedFields };
|
|
790
|
-
},
|
|
791
|
-
});
|
|
792
|
-
const plan = projectPlan(seedResult.item, "brief");
|
|
793
|
-
return {
|
|
794
|
-
action: "create",
|
|
795
|
-
plan,
|
|
796
|
-
step: initialSteps[0],
|
|
797
|
-
next_actions: nextActionsFor(createResult.item.id, plan),
|
|
798
|
-
warnings: [...createResult.warnings],
|
|
799
|
-
generated_at: nowIso(),
|
|
800
|
-
};
|
|
801
|
-
}
|
|
802
|
-
async function planShow(id, options, ctx) {
|
|
803
|
-
const depth = asDepth(options.depth);
|
|
804
|
-
const fields = parsePlanFields(options.fields);
|
|
805
|
-
const { document, itemId } = await readPlanItem(ctx, id);
|
|
806
|
-
const fullPlan = projectPlan(document.metadata, fields === null ? depth : "deep");
|
|
807
|
-
const plan = fields === null ? fullPlan : projectPlanForFields(fullPlan, fields);
|
|
808
|
-
return {
|
|
809
|
-
action: "show",
|
|
810
|
-
plan,
|
|
811
|
-
next_actions: nextActionsFor(itemId, fullPlan),
|
|
812
|
-
warnings: [],
|
|
813
|
-
generated_at: nowIso(),
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
/** Compare the union of persisted Plan metadata keys so additions, updates, and removals are all audited. */
|
|
817
|
-
function changedPlanMetadataFields(beforePlanFields, metadata) {
|
|
818
|
-
const afterPlanFields = new Map(Object.entries(metadata)
|
|
819
|
-
.filter(([key]) => key.startsWith("plan_"))
|
|
820
|
-
.map(([key, value]) => [key, JSON.stringify(value)]));
|
|
821
|
-
return [
|
|
822
|
-
...new Set([...beforePlanFields.keys(), ...afterPlanFields.keys()]),
|
|
823
|
-
].filter((key) => beforePlanFields.get(key) !== afterPlanFields.get(key));
|
|
824
|
-
}
|
|
825
|
-
async function mutatePlanSteps(args) {
|
|
826
|
-
const author = resolveAuthor(args.options.author, args.ctx.settings.author_default);
|
|
827
|
-
let resultStep;
|
|
828
|
-
const result = await mutateItem({
|
|
829
|
-
pmRoot: args.ctx.pmRoot,
|
|
830
|
-
settings: args.ctx.settings,
|
|
831
|
-
id: args.id,
|
|
832
|
-
op: args.op,
|
|
833
|
-
author,
|
|
834
|
-
message: args.options.message ?? args.message,
|
|
835
|
-
force: args.options.force,
|
|
836
|
-
mutate(doc) {
|
|
837
|
-
ensurePlanItem(doc.metadata);
|
|
838
|
-
const statusRegistry = resolveRuntimeStatusRegistry(args.ctx.settings.schema);
|
|
839
|
-
if (isTerminalStatus(doc.metadata.status, statusRegistry) ||
|
|
840
|
-
isTerminalPlanMode(doc.metadata.plan_mode)) {
|
|
841
|
-
throw new PmCliError(`Plan ${doc.metadata.id} is terminal (status=${doc.metadata.status}, plan_mode=${doc.metadata.plan_mode ?? "unset"}) and cannot be mutated.`, EXIT_CODE.CONFLICT, {
|
|
842
|
-
code: "terminal_plan_mutation",
|
|
843
|
-
required: "Create or reopen a non-terminal Plan before changing its execution context or steps.",
|
|
844
|
-
why: "Terminal Plan history is immutable execution evidence.",
|
|
845
|
-
});
|
|
846
|
-
}
|
|
847
|
-
const steps = (doc.metadata.plan_steps ?? []).slice();
|
|
848
|
-
const beforePlanFields = new Map(Object.entries(doc.metadata)
|
|
849
|
-
.filter(([key]) => key.startsWith("plan_"))
|
|
850
|
-
.map(([key, value]) => [key, JSON.stringify(value)]));
|
|
851
|
-
const outcome = args.mutator(steps, doc);
|
|
852
|
-
resultStep = outcome.resultStep;
|
|
853
|
-
const sorted = steps
|
|
854
|
-
.slice()
|
|
855
|
-
.sort((left, right) => left.order - right.order)
|
|
856
|
-
.map((step, index) => ({ ...step, order: index + 1 }));
|
|
857
|
-
doc.metadata.plan_steps = sorted;
|
|
858
|
-
const changedFields = changedPlanMetadataFields(beforePlanFields, doc.metadata);
|
|
859
|
-
if (changedFields.length === 0 && outcome.changedSteps.length === 0) {
|
|
860
|
-
return { changedFields: [] };
|
|
861
|
-
}
|
|
862
|
-
return {
|
|
863
|
-
changedFields: changedFields.length > 0 ? changedFields : ["plan_steps"],
|
|
864
|
-
};
|
|
865
|
-
},
|
|
866
|
-
});
|
|
867
|
-
return {
|
|
868
|
-
document: { metadata: result.item, body: result.body },
|
|
869
|
-
resultStep,
|
|
870
|
-
itemId: result.item.id,
|
|
871
|
-
};
|
|
872
|
-
}
|
|
873
|
-
async function planAddStep(id, options, ctx) {
|
|
874
|
-
const title = options.stepTitle?.trim();
|
|
875
|
-
if (!title) {
|
|
876
|
-
throw new PmCliError("pm plan add-step requires --step-title", EXIT_CODE.USAGE);
|
|
877
|
-
}
|
|
878
|
-
const status = asStepStatus(options.stepStatus, "pending");
|
|
879
|
-
const allowMultipleActive = options.allowMultipleActive === true;
|
|
880
|
-
const { document, resultStep, itemId } = await mutatePlanSteps({
|
|
881
|
-
id,
|
|
882
|
-
options,
|
|
883
|
-
ctx,
|
|
884
|
-
op: "plan_add_step",
|
|
885
|
-
message: `plan add-step "${title}"`,
|
|
886
|
-
mutator(steps) {
|
|
887
|
-
const order = steps.length + 1;
|
|
888
|
-
assertInProgressStepAllowed(steps, undefined, status, allowMultipleActive);
|
|
889
|
-
const step = buildAddedPlanStep(steps, options, { order, title, status });
|
|
890
|
-
steps.push(step);
|
|
891
|
-
return { changedSteps: [step.id], resultStep: step };
|
|
892
|
-
},
|
|
893
|
-
});
|
|
894
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
895
|
-
return {
|
|
896
|
-
action: "add-step",
|
|
897
|
-
plan,
|
|
898
|
-
step: resultStep,
|
|
899
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
900
|
-
warnings: [],
|
|
901
|
-
generated_at: nowIso(),
|
|
902
|
-
};
|
|
903
|
-
}
|
|
904
|
-
function assertInProgressStepAllowed(steps, currentStepId, desiredStatus, allowMultipleActive) {
|
|
905
|
-
if (desiredStatus !== "in_progress" || allowMultipleActive) {
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
const activeStep = steps.find((step) => step.id !== currentStepId && step.status === "in_progress");
|
|
909
|
-
if (!activeStep) {
|
|
910
|
-
return;
|
|
911
|
-
}
|
|
912
|
-
throw new PmCliError(`Plan already has step ${activeStep.id} in_progress. Pass --allow-multiple-active or update that step first.`, EXIT_CODE.CONFLICT);
|
|
913
|
-
}
|
|
914
|
-
function buildAddedPlanStep(existingSteps, options, seed) {
|
|
915
|
-
const linkedItems = buildLinkInputs(options, "depends_on");
|
|
916
|
-
const files = toSpecArray(options.file).map(parseStepFile);
|
|
917
|
-
const tests = toSpecArray(options.test).map(parseStepTest);
|
|
918
|
-
const docs = toSpecArray(options.doc).map(parseStepDoc);
|
|
919
|
-
const now = nowIso();
|
|
920
|
-
return {
|
|
921
|
-
id: newStepId(existingSteps),
|
|
922
|
-
order: seed.order,
|
|
923
|
-
title: seed.title,
|
|
924
|
-
body: options.stepBody?.trim() || undefined,
|
|
925
|
-
status: seed.status,
|
|
926
|
-
owner: options.stepOwner?.trim() || undefined,
|
|
927
|
-
evidence: options.stepEvidence?.trim() || undefined,
|
|
928
|
-
blocked_reason: seed.status === "blocked"
|
|
929
|
-
? options.stepBlockedReason?.trim() || ""
|
|
930
|
-
: undefined,
|
|
931
|
-
linked_items: linkedItems.length > 0 ? linkedItems : undefined,
|
|
932
|
-
files: files.length > 0 ? files : undefined,
|
|
933
|
-
tests: tests.length > 0 ? tests : undefined,
|
|
934
|
-
docs: docs.length > 0 ? docs : undefined,
|
|
935
|
-
created_at: now,
|
|
936
|
-
updated_at: now,
|
|
937
|
-
completed_at: seed.status === "completed" ? now : undefined,
|
|
938
|
-
};
|
|
939
|
-
}
|
|
940
|
-
function buildLinkInputs(options, fallbackKind) {
|
|
941
|
-
const dependsOn = toArray(options.dependsOn).map((id) => ({ id, kind: fallbackKind }));
|
|
942
|
-
const related = toArray(options.related).map((id) => ({ id, kind: "related" }));
|
|
943
|
-
const blocks = toArray(options.blocks).map((id) => ({ id, kind: "blocks" }));
|
|
944
|
-
const blockedBy = toArray(options.blockedBy).map((id) => ({ id, kind: "blocked_by" }));
|
|
945
|
-
const explicit = toArray(options.link);
|
|
946
|
-
const explicitKind = asLinkKind(options.linkKind, fallbackKind);
|
|
947
|
-
const note = options.linkNote?.trim();
|
|
948
|
-
const explicitLinks = explicit.map((id) => {
|
|
949
|
-
const link = { id, kind: explicitKind };
|
|
950
|
-
if (note)
|
|
951
|
-
link.note = note;
|
|
952
|
-
return link;
|
|
953
|
-
});
|
|
954
|
-
return [...dependsOn, ...related, ...blocks, ...blockedBy, ...explicitLinks];
|
|
955
|
-
}
|
|
956
|
-
async function planUpdateStep(id, options, ctx, args) {
|
|
957
|
-
const { document, resultStep, itemId } = await mutatePlanSteps({
|
|
958
|
-
id,
|
|
959
|
-
options,
|
|
960
|
-
ctx,
|
|
961
|
-
op: args.op,
|
|
962
|
-
message: options.message ?? `${args.op} ${args.stepRef}`,
|
|
963
|
-
mutator(steps, doc) {
|
|
964
|
-
const step = resolveStepRef(steps, args.stepRef);
|
|
965
|
-
const now = nowIso();
|
|
966
|
-
const desiredStatus = args.finalStatus ?? asStepStatus(options.stepStatus, step.status);
|
|
967
|
-
const allowMultipleActive = options.allowMultipleActive === true ||
|
|
968
|
-
args.allowMultipleActive === true;
|
|
969
|
-
assertInProgressStepAllowed(steps, step.status === "in_progress" ? step.id : undefined, desiredStatus, allowMultipleActive);
|
|
970
|
-
applyStepUpdates(step, options, desiredStatus, now);
|
|
971
|
-
doc.metadata.updated_at = now;
|
|
972
|
-
return { changedSteps: [step.id], resultStep: step };
|
|
973
|
-
},
|
|
974
|
-
});
|
|
975
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
976
|
-
return {
|
|
977
|
-
action: args.op === "plan_complete_step"
|
|
978
|
-
? "complete-step"
|
|
979
|
-
: args.op === "plan_block_step"
|
|
980
|
-
? "block-step"
|
|
981
|
-
: "update-step",
|
|
982
|
-
plan,
|
|
983
|
-
step: resultStep,
|
|
984
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
985
|
-
warnings: [],
|
|
986
|
-
generated_at: nowIso(),
|
|
987
|
-
};
|
|
988
|
-
}
|
|
989
|
-
function applyStepUpdates(step, options, desiredStatus, now) {
|
|
990
|
-
assertBlockedStepReason(step, options, desiredStatus);
|
|
991
|
-
applyStepFieldUpdates(step, options);
|
|
992
|
-
step.status = desiredStatus;
|
|
993
|
-
step.updated_at = now;
|
|
994
|
-
applyStepCompletionTimestamp(step, desiredStatus, now);
|
|
995
|
-
}
|
|
996
|
-
function assertBlockedStepReason(step, options, desiredStatus) {
|
|
997
|
-
if (desiredStatus !== "blocked" ||
|
|
998
|
-
options.stepBlockedReason?.trim() ||
|
|
999
|
-
step.blocked_reason) {
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
throw new PmCliError("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.", EXIT_CODE.USAGE);
|
|
1003
|
-
}
|
|
1004
|
-
function applyStepFieldUpdates(step, options) {
|
|
1005
|
-
const title = options.stepTitle?.trim();
|
|
1006
|
-
if (title) {
|
|
1007
|
-
step.title = title;
|
|
1008
|
-
}
|
|
1009
|
-
if (options.stepBody !== undefined) {
|
|
1010
|
-
step.body = options.stepBody.trim() || undefined;
|
|
1011
|
-
}
|
|
1012
|
-
if (options.stepOwner !== undefined) {
|
|
1013
|
-
step.owner = options.stepOwner.trim() || undefined;
|
|
1014
|
-
}
|
|
1015
|
-
if (options.stepEvidence !== undefined) {
|
|
1016
|
-
step.evidence = options.stepEvidence.trim() || undefined;
|
|
1017
|
-
}
|
|
1018
|
-
if (options.stepBlockedReason !== undefined) {
|
|
1019
|
-
step.blocked_reason = options.stepBlockedReason.trim() || undefined;
|
|
1020
|
-
}
|
|
1021
|
-
if (options.stepReplacement !== undefined) {
|
|
1022
|
-
step.superseded_by = options.stepReplacement.trim() || undefined;
|
|
1023
|
-
}
|
|
1024
|
-
const files = toSpecArray(options.file).map(parseStepFile);
|
|
1025
|
-
const tests = toSpecArray(options.test).map(parseStepTest);
|
|
1026
|
-
const docs = toSpecArray(options.doc).map(parseStepDoc);
|
|
1027
|
-
if (files.length > 0) {
|
|
1028
|
-
step.files = mergePlanStepEvidence(step.files, files);
|
|
1029
|
-
}
|
|
1030
|
-
if (tests.length > 0) {
|
|
1031
|
-
step.tests = mergePlanStepEvidence(step.tests, tests);
|
|
1032
|
-
}
|
|
1033
|
-
if (docs.length > 0) {
|
|
1034
|
-
step.docs = mergePlanStepEvidence(step.docs, docs);
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
/** Append structured Plan evidence while preserving first-seen order and rejecting duplicate payloads. */
|
|
1038
|
-
function mergePlanStepEvidence(existing, added) {
|
|
1039
|
-
const merged = [...(existing ?? [])];
|
|
1040
|
-
const seen = new Set(merged.map((entry) => JSON.stringify(entry)));
|
|
1041
|
-
for (const entry of added) {
|
|
1042
|
-
const key = JSON.stringify(entry);
|
|
1043
|
-
if (seen.has(key))
|
|
1044
|
-
continue;
|
|
1045
|
-
seen.add(key);
|
|
1046
|
-
merged.push(entry);
|
|
1047
|
-
}
|
|
1048
|
-
return merged;
|
|
1049
|
-
}
|
|
1050
|
-
function applyStepCompletionTimestamp(step, desiredStatus, now) {
|
|
1051
|
-
if (desiredStatus === "completed" && !step.completed_at) {
|
|
1052
|
-
step.completed_at = now;
|
|
1053
|
-
return;
|
|
1054
|
-
}
|
|
1055
|
-
if (desiredStatus !== "completed") {
|
|
1056
|
-
step.completed_at = undefined;
|
|
1057
|
-
}
|
|
1058
|
-
}
|
|
1059
|
-
async function planReorderStep(id, options, ctx, stepRef, newOrder) {
|
|
1060
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1061
|
-
id,
|
|
1062
|
-
options,
|
|
1063
|
-
ctx,
|
|
1064
|
-
op: "plan_reorder_step",
|
|
1065
|
-
message: options.message ?? `plan reorder-step ${stepRef} -> ${newOrder}`,
|
|
1066
|
-
mutator(steps) {
|
|
1067
|
-
const step = resolveStepRef(steps, stepRef);
|
|
1068
|
-
const filtered = steps.filter((entry) => entry.id !== step.id);
|
|
1069
|
-
const clamped = Math.max(1, Math.min(newOrder, filtered.length + 1));
|
|
1070
|
-
filtered.splice(clamped - 1, 0, step);
|
|
1071
|
-
filtered.forEach((entry, index) => {
|
|
1072
|
-
entry.order = index + 1;
|
|
1073
|
-
entry.updated_at = nowIso();
|
|
1074
|
-
});
|
|
1075
|
-
steps.length = 0;
|
|
1076
|
-
steps.push(...filtered);
|
|
1077
|
-
return { changedSteps: [step.id], resultStep: step };
|
|
1078
|
-
},
|
|
1079
|
-
});
|
|
1080
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
1081
|
-
return {
|
|
1082
|
-
action: "reorder-step",
|
|
1083
|
-
plan,
|
|
1084
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1085
|
-
warnings: [],
|
|
1086
|
-
generated_at: nowIso(),
|
|
1087
|
-
};
|
|
1088
|
-
}
|
|
1089
|
-
async function planRemoveStep(id, options, ctx, stepRef) {
|
|
1090
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1091
|
-
id,
|
|
1092
|
-
options,
|
|
1093
|
-
ctx,
|
|
1094
|
-
op: "plan_remove_step",
|
|
1095
|
-
message: options.message ?? `plan remove-step ${stepRef}`,
|
|
1096
|
-
mutator(steps) {
|
|
1097
|
-
const step = resolveStepRef(steps, stepRef);
|
|
1098
|
-
const remaining = steps.filter((entry) => entry.id !== step.id);
|
|
1099
|
-
remaining.forEach((entry, index) => {
|
|
1100
|
-
entry.order = index + 1;
|
|
1101
|
-
});
|
|
1102
|
-
steps.length = 0;
|
|
1103
|
-
steps.push(...remaining);
|
|
1104
|
-
return { changedSteps: [step.id] };
|
|
1105
|
-
},
|
|
1106
|
-
});
|
|
1107
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
1108
|
-
return {
|
|
1109
|
-
action: "remove-step",
|
|
1110
|
-
plan,
|
|
1111
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1112
|
-
warnings: [],
|
|
1113
|
-
generated_at: nowIso(),
|
|
1114
|
-
};
|
|
1115
|
-
}
|
|
1116
|
-
async function planLink(id, options, ctx, stepRef) {
|
|
1117
|
-
const newLinks = buildLinkInputs(options, asLinkKind(options.linkKind, "related"));
|
|
1118
|
-
if (newLinks.length === 0) {
|
|
1119
|
-
throw new PmCliError("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id", EXIT_CODE.USAGE);
|
|
1120
|
-
}
|
|
1121
|
-
const promoteToItemDep = options.promoteToItemDep === true;
|
|
1122
|
-
const { document, itemId, resultStep } = await mutatePlanSteps({
|
|
1123
|
-
id,
|
|
1124
|
-
options,
|
|
1125
|
-
ctx,
|
|
1126
|
-
op: "plan_link_step",
|
|
1127
|
-
message: options.message ?? `plan link ${stepRef}`,
|
|
1128
|
-
mutator(steps, doc) {
|
|
1129
|
-
const step = resolveStepRef(steps, stepRef);
|
|
1130
|
-
const existing = step.linked_items ?? [];
|
|
1131
|
-
const dedupKey = (link) => `${link.kind}:${link.id}`;
|
|
1132
|
-
const seen = new Set(existing.map(dedupKey));
|
|
1133
|
-
for (const link of newLinks) {
|
|
1134
|
-
const key = dedupKey(link);
|
|
1135
|
-
if (seen.has(key))
|
|
1136
|
-
continue;
|
|
1137
|
-
existing.push(link);
|
|
1138
|
-
seen.add(key);
|
|
1139
|
-
}
|
|
1140
|
-
step.linked_items = existing;
|
|
1141
|
-
step.updated_at = nowIso();
|
|
1142
|
-
if (promoteToItemDep) {
|
|
1143
|
-
const deps = doc.metadata.dependencies ?? [];
|
|
1144
|
-
const depKey = (dep) => `${dep.kind}:${dep.id}`;
|
|
1145
|
-
const seenDeps = new Set(deps.map(depKey));
|
|
1146
|
-
for (const link of newLinks) {
|
|
1147
|
-
const promotedKind = link.kind === "depends_on" ? "blocked_by" : link.kind;
|
|
1148
|
-
const candidate = {
|
|
1149
|
-
id: link.id,
|
|
1150
|
-
kind: promotedKind,
|
|
1151
|
-
created_at: nowIso(),
|
|
1152
|
-
author: resolveAuthor(options.author, ctx.settings.author_default),
|
|
1153
|
-
};
|
|
1154
|
-
if (seenDeps.has(depKey(candidate)))
|
|
1155
|
-
continue;
|
|
1156
|
-
deps.push(candidate);
|
|
1157
|
-
seenDeps.add(depKey(candidate));
|
|
1158
|
-
}
|
|
1159
|
-
doc.metadata.dependencies = deps;
|
|
1160
|
-
}
|
|
1161
|
-
return { changedSteps: [step.id], resultStep: step };
|
|
1162
|
-
},
|
|
1163
|
-
});
|
|
1164
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
1165
|
-
return {
|
|
1166
|
-
action: "link",
|
|
1167
|
-
plan,
|
|
1168
|
-
step: resultStep,
|
|
1169
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1170
|
-
warnings: [],
|
|
1171
|
-
generated_at: nowIso(),
|
|
1172
|
-
};
|
|
1173
|
-
}
|
|
1174
|
-
async function planUnlink(id, options, ctx, stepRef) {
|
|
1175
|
-
const removeIds = toArray(options.link);
|
|
1176
|
-
if (removeIds.length === 0) {
|
|
1177
|
-
throw new PmCliError("pm plan unlink requires --link <id> to remove", EXIT_CODE.USAGE);
|
|
1178
|
-
}
|
|
1179
|
-
const { document, itemId, resultStep } = await mutatePlanSteps({
|
|
1180
|
-
id,
|
|
1181
|
-
options,
|
|
1182
|
-
ctx,
|
|
1183
|
-
op: "plan_unlink_step",
|
|
1184
|
-
message: options.message ?? `plan unlink ${stepRef}`,
|
|
1185
|
-
mutator(steps) {
|
|
1186
|
-
const step = resolveStepRef(steps, stepRef);
|
|
1187
|
-
const filtered = (step.linked_items ?? []).filter((link) => !removeIds.includes(link.id));
|
|
1188
|
-
step.linked_items = filtered.length > 0 ? filtered : undefined;
|
|
1189
|
-
step.updated_at = nowIso();
|
|
1190
|
-
return { changedSteps: [step.id], resultStep: step };
|
|
1191
|
-
},
|
|
1192
|
-
});
|
|
1193
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
1194
|
-
return {
|
|
1195
|
-
action: "unlink",
|
|
1196
|
-
plan,
|
|
1197
|
-
step: resultStep,
|
|
1198
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1199
|
-
warnings: [],
|
|
1200
|
-
generated_at: nowIso(),
|
|
1201
|
-
};
|
|
1202
|
-
}
|
|
1203
|
-
async function planAppendLog(id, options, ctx, kind) {
|
|
1204
|
-
const logText = resolvePlanLogText(kind, options);
|
|
1205
|
-
if (!logText) {
|
|
1206
|
-
const canonical = `--${kind}-text`;
|
|
1207
|
-
const shorthand = `--${kind}`;
|
|
1208
|
-
throw new PmCliError(`pm plan ${kind} requires ${canonical}`, EXIT_CODE.USAGE, {
|
|
1209
|
-
code: "missing_required_option",
|
|
1210
|
-
examples: [
|
|
1211
|
-
`pm plan ${kind} <plan-id> ${canonical} "..."`,
|
|
1212
|
-
`pm plan ${kind} <plan-id> ${shorthand} "..."`,
|
|
1213
|
-
],
|
|
1214
|
-
recovery: {
|
|
1215
|
-
suggested_retry: `pm plan ${kind} <plan-id> ${canonical} <value>`,
|
|
1216
|
-
},
|
|
1217
|
-
});
|
|
1218
|
-
}
|
|
1219
|
-
const author = resolveAuthor(options.author, ctx.settings.author_default);
|
|
1220
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1221
|
-
id,
|
|
1222
|
-
options,
|
|
1223
|
-
ctx,
|
|
1224
|
-
op: `plan_append_${kind}`,
|
|
1225
|
-
message: options.message ?? `plan ${kind} append`,
|
|
1226
|
-
mutator(_steps, doc) {
|
|
1227
|
-
const now = nowIso();
|
|
1228
|
-
if (kind === "decision") {
|
|
1229
|
-
const list = doc.metadata.plan_decisions ?? [];
|
|
1230
|
-
list.push({
|
|
1231
|
-
ts: now,
|
|
1232
|
-
author,
|
|
1233
|
-
decision: logText,
|
|
1234
|
-
rationale: options.decisionRationale?.trim() || undefined,
|
|
1235
|
-
evidence: options.decisionEvidence?.trim() || undefined,
|
|
1236
|
-
});
|
|
1237
|
-
doc.metadata.plan_decisions = list;
|
|
1238
|
-
return { changedSteps: [] };
|
|
1239
|
-
}
|
|
1240
|
-
if (kind === "discovery") {
|
|
1241
|
-
const list = doc.metadata.plan_discoveries ?? [];
|
|
1242
|
-
list.push({ ts: now, author, text: logText });
|
|
1243
|
-
doc.metadata.plan_discoveries = list;
|
|
1244
|
-
return { changedSteps: [] };
|
|
1245
|
-
}
|
|
1246
|
-
const list = doc.metadata.plan_validation ?? [];
|
|
1247
|
-
list.push({
|
|
1248
|
-
text: logText,
|
|
1249
|
-
command: options.validationCommand?.trim() || undefined,
|
|
1250
|
-
expected: options.validationExpected?.trim() || undefined,
|
|
1251
|
-
});
|
|
1252
|
-
doc.metadata.plan_validation = list;
|
|
1253
|
-
return { changedSteps: [] };
|
|
1254
|
-
},
|
|
1255
|
-
});
|
|
1256
|
-
const plan = projectPlan(document.metadata, "deep");
|
|
1257
|
-
return {
|
|
1258
|
-
action: kind,
|
|
1259
|
-
plan,
|
|
1260
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1261
|
-
warnings: [],
|
|
1262
|
-
generated_at: nowIso(),
|
|
1263
|
-
};
|
|
1264
|
-
}
|
|
1265
|
-
async function planResume(id, options, ctx) {
|
|
1266
|
-
const text = options.resumeContext?.trim();
|
|
1267
|
-
if (!text) {
|
|
1268
|
-
throw new PmCliError("pm plan resume requires --resume-context <text>", EXIT_CODE.USAGE);
|
|
1269
|
-
}
|
|
1270
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1271
|
-
id,
|
|
1272
|
-
options,
|
|
1273
|
-
ctx,
|
|
1274
|
-
op: "plan_resume",
|
|
1275
|
-
message: options.message ?? "plan resume context update",
|
|
1276
|
-
mutator(_steps, doc) {
|
|
1277
|
-
doc.metadata.plan_resume_context = text;
|
|
1278
|
-
const scope = options.scope?.trim();
|
|
1279
|
-
if (scope)
|
|
1280
|
-
doc.metadata.plan_scope = scope;
|
|
1281
|
-
return { changedSteps: [] };
|
|
1282
|
-
},
|
|
1283
|
-
});
|
|
1284
|
-
const plan = projectPlan(document.metadata, "brief");
|
|
1285
|
-
return {
|
|
1286
|
-
action: "resume",
|
|
1287
|
-
plan,
|
|
1288
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1289
|
-
warnings: [],
|
|
1290
|
-
generated_at: nowIso(),
|
|
1291
|
-
};
|
|
1292
|
-
}
|
|
1293
|
-
async function planApprove(id, options, ctx) {
|
|
1294
|
-
const mode = asPlanMode(options.mode ?? "approved", "approved");
|
|
1295
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1296
|
-
id,
|
|
1297
|
-
options,
|
|
1298
|
-
ctx,
|
|
1299
|
-
op: "plan_approve",
|
|
1300
|
-
message: options.message ?? `plan approve mode=${mode}`,
|
|
1301
|
-
mutator(_steps, doc) {
|
|
1302
|
-
doc.metadata.plan_mode = mode;
|
|
1303
|
-
const scope = options.scope?.trim();
|
|
1304
|
-
if (scope)
|
|
1305
|
-
doc.metadata.plan_scope = scope;
|
|
1306
|
-
return { changedSteps: [] };
|
|
1307
|
-
},
|
|
1308
|
-
});
|
|
1309
|
-
const plan = projectPlan(document.metadata, "brief");
|
|
1310
|
-
return {
|
|
1311
|
-
action: "approve",
|
|
1312
|
-
plan,
|
|
1313
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1314
|
-
warnings: [],
|
|
1315
|
-
generated_at: nowIso(),
|
|
1316
|
-
};
|
|
1317
|
-
}
|
|
1318
|
-
function buildMaterializeSkippedWarnings(materializeSkipped) {
|
|
1319
|
-
return materializeSkipped.map((entry) => `plan_materialize_skipped:${entry.from_step}:${entry.reason}${entry.existing_id ? `:${entry.existing_id}` : ""}`);
|
|
1320
|
-
}
|
|
1321
|
-
function buildMaterializeNoopResult(planRead, materializeSkipped) {
|
|
1322
|
-
const plan = projectPlan(planRead.document.metadata, "standard");
|
|
1323
|
-
return {
|
|
1324
|
-
action: "materialize",
|
|
1325
|
-
plan,
|
|
1326
|
-
materialized: [],
|
|
1327
|
-
materialize_skipped: materializeSkipped,
|
|
1328
|
-
next_actions: nextActionsFor(planRead.itemId, plan),
|
|
1329
|
-
warnings: buildMaterializeSkippedWarnings(materializeSkipped),
|
|
1330
|
-
generated_at: nowIso(),
|
|
1331
|
-
};
|
|
1332
|
-
}
|
|
1333
|
-
function buildMaterializeDependencies(parent, planItemId, step) {
|
|
1334
|
-
const deps = [
|
|
1335
|
-
`id=${parent},kind=parent`,
|
|
1336
|
-
`id=${planItemId},kind=discovered_from`,
|
|
1337
|
-
];
|
|
1338
|
-
for (const link of step.linked_items ?? []) {
|
|
1339
|
-
const realKind = link.kind === "blocked_by" ||
|
|
1340
|
-
link.kind === "blocks" ||
|
|
1341
|
-
link.kind === "related" ||
|
|
1342
|
-
link.kind === "discovered_from"
|
|
1343
|
-
? link.kind
|
|
1344
|
-
: "related";
|
|
1345
|
-
deps.push(`id=${link.id},kind=${realKind}`);
|
|
1346
|
-
}
|
|
1347
|
-
return deps;
|
|
1348
|
-
}
|
|
1349
|
-
async function createMaterializedStepItems(params) {
|
|
1350
|
-
const materialized = [];
|
|
1351
|
-
const materializeFields = {};
|
|
1352
|
-
const reservedMaterializeKeys = new Set([
|
|
1353
|
-
"title",
|
|
1354
|
-
"description",
|
|
1355
|
-
"type",
|
|
1356
|
-
"parent",
|
|
1357
|
-
"tags",
|
|
1358
|
-
"author",
|
|
1359
|
-
"message",
|
|
1360
|
-
"dep",
|
|
1361
|
-
]);
|
|
1362
|
-
for (const specification of toSpecArray(params.options.field)) {
|
|
1363
|
-
const separator = specification.indexOf("=");
|
|
1364
|
-
if (separator <= 0) {
|
|
1365
|
-
throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`, EXIT_CODE.USAGE);
|
|
1366
|
-
}
|
|
1367
|
-
const name = specification.slice(0, separator).trim();
|
|
1368
|
-
const value = specification.slice(separator + 1).trim();
|
|
1369
|
-
if (name.length === 0) {
|
|
1370
|
-
throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`, EXIT_CODE.USAGE);
|
|
1371
|
-
}
|
|
1372
|
-
const segments = name
|
|
1373
|
-
.trim()
|
|
1374
|
-
.replaceAll(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
1375
|
-
.replaceAll(/[^A-Za-z0-9]+/g, " ")
|
|
1376
|
-
.split(/\s+/)
|
|
1377
|
-
.filter(Boolean)
|
|
1378
|
-
.map((segment) => segment.toLowerCase());
|
|
1379
|
-
if (segments.length === 0) {
|
|
1380
|
-
throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`, EXIT_CODE.USAGE);
|
|
1381
|
-
}
|
|
1382
|
-
const [first, ...rest] = segments;
|
|
1383
|
-
const fieldKey = `${first}${rest.map((segment) => `${segment.slice(0, 1).toUpperCase()}${segment.slice(1)}`).join("")}`;
|
|
1384
|
-
if (reservedMaterializeKeys.has(fieldKey)) {
|
|
1385
|
-
throw new PmCliError(`Invalid --field entry "${specification}"; "${fieldKey}" is reserved by materialize and cannot be overridden`, EXIT_CODE.USAGE);
|
|
1386
|
-
}
|
|
1387
|
-
materializeFields[fieldKey] = value;
|
|
1388
|
-
}
|
|
1389
|
-
for (const step of params.targets) {
|
|
1390
|
-
const createOptions = {
|
|
1391
|
-
...materializeFields,
|
|
1392
|
-
title: step.title,
|
|
1393
|
-
description: step.body?.trim() || step.title,
|
|
1394
|
-
type: params.resolvedTypeName,
|
|
1395
|
-
parent: params.parent,
|
|
1396
|
-
tags: params.tags,
|
|
1397
|
-
author: params.options.author,
|
|
1398
|
-
message: params.options.message ??
|
|
1399
|
-
`materialized from plan ${params.planItemId} step ${step.id}`,
|
|
1400
|
-
dep: buildMaterializeDependencies(params.parent, params.planItemId, step),
|
|
1401
|
-
};
|
|
1402
|
-
preservePlanCreateStdinPolicy(params.options, createOptions, [
|
|
1403
|
-
"description",
|
|
1404
|
-
...Object.keys(materializeFields),
|
|
1405
|
-
]);
|
|
1406
|
-
const created = await runCreate(createOptions, {
|
|
1407
|
-
...{},
|
|
1408
|
-
path: params.pmRoot,
|
|
1409
|
-
});
|
|
1410
|
-
materialized.push({
|
|
1411
|
-
id: created.item.id,
|
|
1412
|
-
title: created.item.title,
|
|
1413
|
-
type: params.resolvedTypeName,
|
|
1414
|
-
parent: created.item.parent,
|
|
1415
|
-
tags: created.item.tags ?? [],
|
|
1416
|
-
from_step: step.id,
|
|
1417
|
-
});
|
|
1418
|
-
}
|
|
1419
|
-
return materialized;
|
|
1420
|
-
}
|
|
1421
|
-
function linkMaterializedStepItems(currentSteps, targets, materialized) {
|
|
1422
|
-
for (const target of targets) {
|
|
1423
|
-
const matched = materialized.find((entry) => entry.from_step === target.id);
|
|
1424
|
-
if (!matched) {
|
|
1425
|
-
continue;
|
|
1426
|
-
}
|
|
1427
|
-
const step = currentSteps.find((entry) => entry.id === target.id);
|
|
1428
|
-
if (!step) {
|
|
1429
|
-
continue;
|
|
1430
|
-
}
|
|
1431
|
-
const links = step.linked_items ?? [];
|
|
1432
|
-
links.push({
|
|
1433
|
-
id: matched.id,
|
|
1434
|
-
kind: "implements",
|
|
1435
|
-
note: `materialized as ${matched.type}`,
|
|
1436
|
-
});
|
|
1437
|
-
step.linked_items = links;
|
|
1438
|
-
step.updated_at = nowIso();
|
|
1439
|
-
}
|
|
1440
|
-
}
|
|
1441
|
-
async function planMaterialize(id, options, ctx) {
|
|
1442
|
-
const stepRefs = toArray(options.steps);
|
|
1443
|
-
if (stepRefs.length === 0) {
|
|
1444
|
-
throw new PmCliError("pm plan materialize requires --steps <ids|orders|all>", EXIT_CODE.USAGE);
|
|
1445
|
-
}
|
|
1446
|
-
const targetType = options.materializeType?.trim() || "Task";
|
|
1447
|
-
const typeRegistry = resolveItemTypeRegistry(ctx.settings, getActiveExtensionRegistrations());
|
|
1448
|
-
const resolvedTypeName = resolveTypeName(targetType, typeRegistry);
|
|
1449
|
-
if (!resolvedTypeName) {
|
|
1450
|
-
throw new PmCliError(`Invalid --materialize-type "${targetType}"`, EXIT_CODE.USAGE);
|
|
1451
|
-
}
|
|
1452
|
-
const parent = options.materializeParent?.trim() || id;
|
|
1453
|
-
const tags = options.materializeTags;
|
|
1454
|
-
const planRead = await readPlanItem(ctx, id);
|
|
1455
|
-
const steps = (planRead.document.metadata.plan_steps ?? []).slice();
|
|
1456
|
-
const { targets, skipped: materializeSkipped } = resolveMaterializeTargets(steps, stepRefs);
|
|
1457
|
-
if (targets.length === 0) {
|
|
1458
|
-
if (materializeSkipped.length > 0) {
|
|
1459
|
-
return buildMaterializeNoopResult(planRead, materializeSkipped);
|
|
1460
|
-
}
|
|
1461
|
-
throw new PmCliError("No matching plan steps found for --steps", EXIT_CODE.NOT_FOUND);
|
|
1462
|
-
}
|
|
1463
|
-
const materialized = await createMaterializedStepItems({
|
|
1464
|
-
targets,
|
|
1465
|
-
parent,
|
|
1466
|
-
planItemId: planRead.itemId,
|
|
1467
|
-
resolvedTypeName,
|
|
1468
|
-
tags,
|
|
1469
|
-
options,
|
|
1470
|
-
pmRoot: ctx.pmRoot,
|
|
1471
|
-
});
|
|
1472
|
-
const { document, itemId } = await mutatePlanSteps({
|
|
1473
|
-
id,
|
|
1474
|
-
options,
|
|
1475
|
-
ctx,
|
|
1476
|
-
op: "plan_materialize",
|
|
1477
|
-
message: options.message ?? `plan materialize ${stepRefs.join(",")}`,
|
|
1478
|
-
mutator(currentSteps) {
|
|
1479
|
-
linkMaterializedStepItems(currentSteps, targets, materialized);
|
|
1480
|
-
return { changedSteps: targets.map((entry) => entry.id) };
|
|
1481
|
-
},
|
|
1482
|
-
});
|
|
1483
|
-
const plan = projectPlan(document.metadata, "standard");
|
|
1484
|
-
return {
|
|
1485
|
-
action: "materialize",
|
|
1486
|
-
plan,
|
|
1487
|
-
materialized,
|
|
1488
|
-
...(materializeSkipped.length > 0
|
|
1489
|
-
? { materialize_skipped: materializeSkipped }
|
|
1490
|
-
: {}),
|
|
1491
|
-
next_actions: nextActionsFor(itemId, plan),
|
|
1492
|
-
warnings: buildMaterializeSkippedWarnings(materializeSkipped),
|
|
1493
|
-
generated_at: nowIso(),
|
|
1494
|
-
};
|
|
1495
|
-
}
|
|
1496
|
-
function normalizePlanStepAliasInput(input) {
|
|
1497
|
-
if (input.subcommand === "create") {
|
|
1498
|
-
return input;
|
|
1499
|
-
}
|
|
1500
|
-
const stepValues = toOrderedStepTitles(input.options.step);
|
|
1501
|
-
if (stepValues.length > 1) {
|
|
1502
|
-
throw new PmCliError(`pm plan ${input.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`, EXIT_CODE.USAGE);
|
|
1503
|
-
}
|
|
1504
|
-
if (stepValues.length === 1 && !input.options.stepTitle?.trim()) {
|
|
1505
|
-
return {
|
|
1506
|
-
...input,
|
|
1507
|
-
options: transferMutationStdinTokenPolicy(input.options, {
|
|
1508
|
-
...input.options,
|
|
1509
|
-
stepTitle: stepValues[0],
|
|
1510
|
-
}),
|
|
1511
|
-
};
|
|
1512
|
-
}
|
|
1513
|
-
return input;
|
|
1514
|
-
}
|
|
1515
|
-
function requirePlanId(input, label) {
|
|
1516
|
-
if (!input.id) {
|
|
1517
|
-
throw new PmCliError(`pm plan ${label} requires a plan id`, EXIT_CODE.USAGE);
|
|
1518
|
-
}
|
|
1519
|
-
return input.id;
|
|
1520
|
-
}
|
|
1521
|
-
function requirePlanStepRef(input, label) {
|
|
1522
|
-
const id = requirePlanId(input, label);
|
|
1523
|
-
if (!input.stepRef) {
|
|
1524
|
-
throw new PmCliError(`pm plan ${label} requires <plan-id> <step>`, EXIT_CODE.USAGE);
|
|
1525
|
-
}
|
|
1526
|
-
return { id, stepRef: input.stepRef };
|
|
1527
|
-
}
|
|
1528
|
-
function requireReorderTarget(input) {
|
|
1529
|
-
const target = requirePlanStepRef(input, "reorder-step");
|
|
1530
|
-
if (input.reorderTo === undefined) {
|
|
1531
|
-
throw new PmCliError("pm plan reorder-step requires <plan-id> <step> <new-order>", EXIT_CODE.USAGE);
|
|
1532
|
-
}
|
|
1533
|
-
return { ...target, reorderTo: input.reorderTo };
|
|
1534
|
-
}
|
|
1535
|
-
const PLAN_DISPATCHERS = {
|
|
1536
|
-
create: (input, ctx) => planCreate(input.options, input.global, ctx),
|
|
1537
|
-
show: (input, ctx) => planShow(requirePlanId(input, "show"), input.options, ctx),
|
|
1538
|
-
"add-step": (input, ctx) => planAddStep(requirePlanId(input, "add-step"), input.options, ctx),
|
|
1539
|
-
"update-step": (input, ctx) => {
|
|
1540
|
-
const target = requirePlanStepRef(input, "update-step");
|
|
1541
|
-
return planUpdateStep(target.id, input.options, ctx, {
|
|
1542
|
-
stepRef: target.stepRef,
|
|
1543
|
-
op: "plan_update_step",
|
|
1544
|
-
});
|
|
1545
|
-
},
|
|
1546
|
-
"complete-step": (input, ctx) => {
|
|
1547
|
-
const target = requirePlanStepRef(input, "complete-step");
|
|
1548
|
-
return planUpdateStep(target.id, input.options, ctx, {
|
|
1549
|
-
stepRef: target.stepRef,
|
|
1550
|
-
finalStatus: "completed",
|
|
1551
|
-
op: "plan_complete_step",
|
|
1552
|
-
});
|
|
1553
|
-
},
|
|
1554
|
-
"block-step": (input, ctx) => {
|
|
1555
|
-
const target = requirePlanStepRef(input, "block-step");
|
|
1556
|
-
return planUpdateStep(target.id, input.options, ctx, {
|
|
1557
|
-
stepRef: target.stepRef,
|
|
1558
|
-
finalStatus: "blocked",
|
|
1559
|
-
op: "plan_block_step",
|
|
1560
|
-
});
|
|
1561
|
-
},
|
|
1562
|
-
"reorder-step": (input, ctx) => {
|
|
1563
|
-
const target = requireReorderTarget(input);
|
|
1564
|
-
return planReorderStep(target.id, input.options, ctx, target.stepRef, target.reorderTo);
|
|
1565
|
-
},
|
|
1566
|
-
"remove-step": (input, ctx) => {
|
|
1567
|
-
const target = requirePlanStepRef(input, "remove-step");
|
|
1568
|
-
return planRemoveStep(target.id, input.options, ctx, target.stepRef);
|
|
1569
|
-
},
|
|
1570
|
-
link: (input, ctx) => {
|
|
1571
|
-
const target = requirePlanStepRef(input, "link");
|
|
1572
|
-
return planLink(target.id, input.options, ctx, target.stepRef);
|
|
1573
|
-
},
|
|
1574
|
-
unlink: (input, ctx) => {
|
|
1575
|
-
const target = requirePlanStepRef(input, "unlink");
|
|
1576
|
-
return planUnlink(target.id, input.options, ctx, target.stepRef);
|
|
1577
|
-
},
|
|
1578
|
-
decision: (input, ctx) => planAppendLog(requirePlanId(input, "decision"), input.options, ctx, "decision"),
|
|
1579
|
-
discovery: (input, ctx) => planAppendLog(requirePlanId(input, "discovery"), input.options, ctx, "discovery"),
|
|
1580
|
-
validation: (input, ctx) => planAppendLog(requirePlanId(input, "validation"), input.options, ctx, "validation"),
|
|
1581
|
-
resume: (input, ctx) => planResume(requirePlanId(input, "resume"), input.options, ctx),
|
|
1582
|
-
approve: (input, ctx) => planApprove(requirePlanId(input, "approve"), input.options, ctx),
|
|
1583
|
-
materialize: (input, ctx) => planMaterialize(requirePlanId(input, "materialize"), input.options, ctx),
|
|
1584
|
-
};
|
|
1585
|
-
function resolvePlanDispatcher(subcommand) {
|
|
1586
|
-
const dispatcher = PLAN_DISPATCHERS[subcommand];
|
|
1587
|
-
if (!dispatcher) {
|
|
1588
|
-
throw createUnknownSubcommandError({
|
|
1589
|
-
command_path: "plan",
|
|
1590
|
-
token: subcommand,
|
|
1591
|
-
allowed: PLAN_SUBCOMMANDS,
|
|
1592
|
-
});
|
|
1593
|
-
}
|
|
1594
|
-
return dispatcher;
|
|
1595
|
-
}
|
|
1596
|
-
/** Implements run plan for the public runtime surface of this module. */
|
|
1597
|
-
export async function runPlan(input) {
|
|
1598
|
-
const ctx = await loadContext(input.global);
|
|
1599
|
-
const normalizedInput = normalizePlanStepAliasInput(input);
|
|
1600
|
-
return resolvePlanDispatcher(normalizedInput.subcommand)(normalizedInput, ctx);
|
|
1601
|
-
}
|
|
1602
|
-
/** Internal Plan mutation helpers exposed only for branch-complete regression coverage. */
|
|
1603
|
-
export const _testOnlyPlanCommand = {
|
|
1604
|
-
changedPlanMetadataFields,
|
|
1605
|
-
};
|
|
1
|
+
!(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="374c7cb8-9fd0-5a2d-8aaf-9d09b63abaf0")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,resolveTypeName,EXIT_CODE,PmCliError,splitCommaList,nowIso,locateItem,mutateItem,readLocatedItem,resolvePmRoot,readSettings,resolveAuthor,isTerminalPlanMode,preserveMutationStdinTokenFields,transferMutationStdinTokenPolicy}from"../runtime-primitives.js";import{PLAN_HARNESS_VALUES,PLAN_MODE_VALUES,PLAN_STEP_LINK_KIND_VALUES,PLAN_STEP_STATUS_VALUES}from"../../types/index.js";import{runCreate}from"./create.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";const PLAN_SUBCOMMANDS=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"];const PLAN_SHOW_DEPTH_VALUES=["brief","standard","deep"];const STEP_ID_PREFIX="plan-step-";const DEFAULT_PLAN_MODE="draft";const PLAN_TEMPLATE_NAMES=["bug-investigation","feature-implementation","refactoring-sprint"];const PLAN_TEMPLATES={"bug-investigation":[{title:"Reproduce the bug",body:"Capture exact steps, inputs, and the observed vs expected behavior."},{title:"Locate the root cause",body:"Trace the failure to the responsible code path with evidence."},{title:"Write a failing test",body:"Add a regression test that fails for the current bug."},{title:"Implement the fix",body:"Apply the minimal change that makes the failing test pass."},{title:"Verify and document",body:"Run the full suite and record the resolution and verification."}],"feature-implementation":[{title:"Clarify requirements & acceptance criteria",body:"Confirm scope, edge cases, and done-conditions."},{title:"Design the approach",body:"Decide the data model, interfaces, and integration points."},{title:"Implement the change",body:"Build the feature behind the agreed design."},{title:"Add tests",body:"Cover the new behavior and its edge cases."},{title:"Update docs & changelog",body:"Document the feature and surface it to users."}],"refactoring-sprint":[{title:"Map the current structure & risks",body:"Inventory the code to change and its blast radius."},{title:"Add characterization tests",body:"Lock in current behavior before refactoring."},{title:"Refactor incrementally",body:"Apply small, reversible steps keeping tests green."},{title:"Verify behavior is unchanged",body:"Run the full suite and compare against the baseline."},{title:"Clean up & document",body:"Remove dead code and record the new structure."}]};function resolvePlanTemplateSteps(raw){const normalized=raw.trim().toLowerCase();const template=Object.prototype.hasOwnProperty.call(PLAN_TEMPLATES,normalized)?PLAN_TEMPLATES[normalized]:void 0;if(!template){throw new PmCliError(`Unknown plan template "${raw}". Allowed: ${PLAN_TEMPLATE_NAMES.join(", ")}`,EXIT_CODE.USAGE,{code:"unknown_plan_template",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`]})}return template.map(step=>({...step}))}function planCompletionPct(completed,total){return total>0?Math.round(completed/total*100):0}function toOrderedStepTitles(value){const values=Array.isArray(value)?value:value===void 0||value===null?[]:[value];return values.filter(entry=>entry!==void 0&&entry!==null).map(entry=>(typeof entry==="string"?entry:String(entry)).trim()).filter(entry=>entry.length>0)}function toArray(value){if(Array.isArray(value))return value.flatMap(entry=>splitCommaList(entry,{unique:false}));if(typeof value==="string"&&value.trim().length>0){return splitCommaList(value,{unique:false})}return[]}function toSpecArray(value){if(Array.isArray(value))return value.map(entry=>entry.trim()).filter(Boolean);if(typeof value==="string"&&value.trim().length>0)return[value.trim()];return[]}function asPlanMode(value,fallback=DEFAULT_PLAN_MODE){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_MODE_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan mode "${value}". Allowed: ${PLAN_MODE_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asStepStatus(value,fallback="pending"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_STATUS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step status "${value}". Allowed: ${PLAN_STEP_STATUS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asLinkKind(value,fallback="related"){if(value===void 0)return fallback;const normalized=value.trim().toLowerCase();const found=PLAN_STEP_LINK_KIND_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid step link kind "${value}". Allowed: ${PLAN_STEP_LINK_KIND_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asHarness(value){if(value===void 0)return void 0;const normalized=value.trim().toLowerCase();if(normalized.length===0)return void 0;const found=PLAN_HARNESS_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid plan harness "${value}". Allowed: ${PLAN_HARNESS_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function asDepth(value){if(value===void 0)return"brief";const normalized=value.trim().toLowerCase();const found=PLAN_SHOW_DEPTH_VALUES.find(entry=>entry===normalized);if(!found){throw new PmCliError(`Invalid --depth "${value}". Allowed: ${PLAN_SHOW_DEPTH_VALUES.join(", ")}`,EXIT_CODE.USAGE)}return found}function parsePlanFields(raw){if(raw===void 0){return null}const fields=raw.split(",").map(entry=>entry.trim()).filter(entry=>entry.length>0);if(fields.length===0){throw new PmCliError("Plan --fields requires a comma-separated list of plan field names",EXIT_CODE.USAGE)}return fields}const PLAN_FIELD_KEYS=new Set(["id","title","status","mode","scope","harness","parent","resume_context","steps_summary","current_step","blocked_steps","steps","decisions","discoveries","validation","linked_items"]);function projectPlanForFields(plan,fields){const source=plan;const projected={};const unknownFields=[];for(const field of fields){const normalized=field.startsWith("plan.")?field.slice("plan.".length):field;if(normalized.length===0){continue}if(!PLAN_FIELD_KEYS.has(normalized)){unknownFields.push(field);continue}if(Object.prototype.hasOwnProperty.call(source,normalized)){projected[normalized]=source[normalized]}}if(unknownFields.length>0){throw new PmCliError(`Unknown Plan --fields value(s): ${unknownFields.join(", ")}`,EXIT_CODE.USAGE,{nextSteps:[`Use --fields ${[...PLAN_FIELD_KEYS].join(",")}`,"Run pm plan show <id> --depth brief for compact default fields."],recovery:{provided_fields:unknownFields,suggested_retry:`pm plan show <id> --fields ${[...PLAN_FIELD_KEYS].join(",")}`}})}return projected}function parsePairList(raw,label){const out={};for(const entry of raw.split(",")){const trimmed=entry.trim();if(trimmed.length===0)continue;const equalsIndex=trimmed.indexOf("=");if(equalsIndex<=0){throw new PmCliError(`Invalid ${label} entry "${trimmed}"; expected key=value`,EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:`${label} entries must use comma-separated key=value fields.`,why:"Structured Plan evidence must be validated before it is persisted.",examples:['--file "path=src/index.ts,scope=project,note=implementation"','--test "command=pnpm test,note=regression"','--doc "path=docs/PLAN.md,scope=project"']})}out[trimmed.slice(0,equalsIndex).trim().toLowerCase()]=trimmed.slice(equalsIndex+1).trim()}return out}function parseStepFile(spec){const fields=parsePairList(spec,"--file");if(!fields.path){throw new PmCliError("--file requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--file requires a non-empty path field.",why:"Plan file evidence needs a stable path for later verification."})}const file={path:fields.path};if(fields.scope==="global"||fields.scope==="project")file.scope=fields.scope;if(fields.note)file.note=fields.note;return file}function parseStepTest(spec){const fields=parsePairList(spec,"--test");if(!fields.command&&!fields.path){throw new PmCliError("--test requires at least command=<value> or path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--test requires a command or path field.",why:"Plan test evidence must identify something runnable or inspectable."})}const test={};if(fields.command)test.command=fields.command;if(fields.path)test.path=fields.path;if(fields.note)test.note=fields.note;return test}function parseStepDoc(spec){const fields=parsePairList(spec,"--doc");if(!fields.path){throw new PmCliError("--doc requires path=<value>",EXIT_CODE.USAGE,{code:"malformed_plan_step_evidence",required:"--doc requires a non-empty path field.",why:"Plan documentation evidence needs a stable path for later verification."})}const doc={path:fields.path};if(fields.scope==="global"||fields.scope==="project")doc.scope=fields.scope;if(fields.note)doc.note=fields.note;return doc}function summarizeSteps(steps){const summary={total:steps.length,pending:0,in_progress:0,blocked:0,completed:0,skipped:0,superseded:0,completion_pct:0};for(const step of steps){summary[step.status]+=1}summary.completion_pct=planCompletionPct(summary.completed,summary.total);return summary}function newStepId(existing){const used=new Set(existing.map(step=>step.id));for(let cursor=existing.length+1;cursor<existing.length+1024;cursor+=1){const candidate=`${STEP_ID_PREFIX}${String(cursor).padStart(3,"0")}`;if(!used.has(candidate))return candidate}throw new PmCliError("Could not allocate step id (limit reached)",EXIT_CODE.GENERIC_FAILURE)}function resolveStepRef(steps,ref){const trimmed=ref.trim();if(trimmed.length===0){throw new PmCliError("Step reference cannot be empty",EXIT_CODE.USAGE)}const direct=steps.find(step=>step.id===trimmed);if(direct)return direct;if(/^\d+$/.test(trimmed)){const order=Number.parseInt(trimmed,10);const byOrder=steps.find(step=>step.order===order);if(byOrder)return byOrder}throw new PmCliError(`Step "${ref}" not found in plan`,EXIT_CODE.NOT_FOUND)}function classifyMaterializeSkip(step){if(step.status==="completed"){return{reason:"already_completed"}}const existingImplements=(step.linked_items??[]).find(link=>link.kind==="implements");if(existingImplements){return{reason:"already_materialized",existing_id:existingImplements.id}}return void 0}function resolveMaterializeTargets(steps,refs){const allRefs=refs.filter(ref=>ref.trim().toLowerCase()==="all");const targets=[];const skipped=[];if(allRefs.length>0){if(refs.length>allRefs.length){throw new PmCliError("pm plan materialize --steps all cannot be combined with other step refs",EXIT_CODE.USAGE)}for(const step of steps.slice().sort((left,right)=>left.order-right.order)){const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}const seen=new Set;for(const ref of refs){const step=resolveStepRef(steps,ref);if(seen.has(step.id))continue;seen.add(step.id);const skip=classifyMaterializeSkip(step);if(skip){skipped.push({from_step:step.id,...skip});continue}targets.push(step)}return{targets,skipped}}function resolvePlanLogText(kind,options){const canonical=kind==="decision"?options.decisionText:kind==="discovery"?options.discoveryText:options.validationText;const shorthand=kind==="decision"?options.decision:kind==="discovery"?options.discovery:options.validation;return canonical?.trim()||shorthand?.trim()||void 0}function findCurrentStep(steps){return steps.find(step=>step.status==="in_progress")??steps.find(step=>step.status==="pending")}function blockedSteps(steps){return steps.filter(step=>step.status==="blocked").map(step=>({id:step.id,order:step.order,title:step.title,blocked_reason:step.blocked_reason}))}function projectPlan(item,depth="brief"){const steps=(item.plan_steps??[]).slice().sort((left,right)=>left.order-right.order);const summary=summarizeSteps(steps);const current=findCurrentStep(steps);const projection={id:item.id,title:item.title,status:item.status,mode:item.plan_mode??DEFAULT_PLAN_MODE,scope:item.plan_scope,harness:item.plan_harness,parent:item.parent,resume_context:item.plan_resume_context,steps_summary:summary,current_step:current?{id:current.id,order:current.order,title:current.title,status:current.status}:void 0,blocked_steps:blockedSteps(steps),linked_items:(item.dependencies??[]).map(dep=>({id:dep.id,kind:dep.kind}))};if(depth==="standard"||depth==="deep"){projection.steps=steps}if(depth==="deep"){projection.decisions=item.plan_decisions??[];projection.discoveries=item.plan_discoveries??[];projection.validation=item.plan_validation??[]}return projection}function nextActionsFor(planId,plan){const tips=[];if(plan.steps_summary.total===0){tips.push(`pm plan add-step ${planId} --step-title "First step"`)}if(plan.current_step){tips.push(`pm plan update-step ${planId} ${plan.current_step.id} --step-status in_progress`,`pm plan complete-step ${planId} ${plan.current_step.id} --step-evidence "..."`)}if(plan.steps_summary.blocked>0){tips.push(`pm plan show ${planId} --depth standard`)}if(plan.mode==="draft"||plan.mode==="research"){tips.push(`pm plan approve ${planId} --message "ready to execute"`)}if(plan.steps_summary.completed===plan.steps_summary.total&&plan.steps_summary.total>0&&!isTerminalPlanMode(plan.mode)&&plan.status!=="closed"&&plan.status!=="canceled"){tips.push(`pm close ${planId} "plan complete"`)}return tips}function ensurePlanItem(item){const normalizedType=(item.type??"").trim().toLowerCase();if(normalizedType!=="plan"){throw new PmCliError(`Item ${item.id} is type ${item.type}; pm plan commands require type=Plan. Use pm plan create or pm create --type Plan first.`,EXIT_CODE.USAGE,{code:"wrong_item_type",required:"Use pm plan commands only with items whose type is Plan.",why:"Plan commands read and mutate Plan-specific step, decision, discovery, and validation fields.",examples:[`pm get ${item.id} --depth brief`,'pm plan create --title "Execution plan" --scope "<goal>"']})}}async function loadContext(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);return{pmRoot,settings}}async function readPlanItem(ctx,id){const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const located=await locateItem(ctx.pmRoot,id,ctx.settings.id_prefix,ctx.settings.item_format,typeRegistry.type_to_folder);if(!located){throw new PmCliError(`Plan ${id} not found`,EXIT_CODE.NOT_FOUND)}const loaded=await readLocatedItem(located,{schema:ctx.settings.schema});ensurePlanItem(loaded.document.metadata);return{document:loaded.document,itemId:located.id}}function buildPlanCreateDependencies(options){const deps=[];if(options.parent){deps.push(`id=${options.parent.trim()},kind=parent`)}for(const ref of toArray(options.related))deps.push(`id=${ref},kind=related`);for(const ref of toArray(options.blocks))deps.push(`id=${ref},kind=blocks`);for(const ref of toArray(options.blockedBy))deps.push(`id=${ref},kind=blocked_by`);return deps.length>0?deps:void 0}function buildInitialValidation(options){const text=options.validationText?.trim();const command=options.validationCommand?.trim();const expected=options.validationExpected?.trim();if(!text&&!command&&!expected){return void 0}return{text:text||command||"Validation check",command:command||void 0,expected:expected||void 0}}function hasPlanStepDetailOptions(options){return Boolean(options.stepBody?.trim())||Boolean(options.stepOwner?.trim())||Boolean(options.stepStatus?.trim())||Boolean(options.stepEvidence?.trim())||Boolean(options.stepBlockedReason?.trim())||Boolean(options.stepReplacement?.trim())||toArray(options.dependsOn).length>0||toArray(options.link).length>0}function resolveInitialStepSeed(options){const stepTitleFlag=options.stepTitle?.trim()||void 0;const repeatedStepTitles=toOrderedStepTitles(options.step);const templateSteps=options.template?.trim()?resolvePlanTemplateSteps(options.template):[];return{repeatedStepTitles,stepTitleFlag,stepTitles:[...stepTitleFlag?[stepTitleFlag]:[],...repeatedStepTitles,...templateSteps.map(step=>step.title)],templateSteps}}function assertInitialStepSeedAllowed(seed,hasPerStepDetailOptions){if((seed.stepTitleFlag||seed.repeatedStepTitles.length>0)&&seed.templateSteps.length>0){throw new PmCliError("pm plan create --template cannot be combined with --step-title or --step; choose one step seeding source",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:[`pm plan create --title "Fix login crash" --template ${PLAN_TEMPLATE_NAMES[0]}`,'pm plan create --title "Custom plan" --step "Read the code" --step "Write the fix"']})}if(seed.stepTitles.length>1&&hasPerStepDetailOptions){throw new PmCliError("pm plan create per-step options apply to a single initial step; with multiple --step values create the plan first, then refine steps individually",EXIT_CODE.USAGE,{code:"ambiguous_option_combination",examples:['pm plan create --title "Execution plan" --step "Read the code" --step "Write the fix"','pm plan update-step <plan-id> plan-step-001 --step-body "Inspect retry path"']})}}function buildSingleInitialStep(options,title){const status=asStepStatus(options.stepStatus,"pending");const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:"plan-step-001",order:1,title,body:options.stepBody?.trim()||void 0,status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:status==="completed"?now:void 0}}function buildInitialSteps(options){const seed=resolveInitialStepSeed(options);const hasDetailOptions=hasPlanStepDetailOptions(options);assertInitialStepSeedAllowed(seed,hasDetailOptions);if(seed.stepTitles.length===0){return{steps:[],hasPerStepDetailOptions:hasDetailOptions}}if(seed.stepTitles.length===1){return{steps:[buildSingleInitialStep(options,seed.stepTitles[0])],hasPerStepDetailOptions:hasDetailOptions}}const now=nowIso();return{steps:seed.stepTitles.map((stepTitle,index)=>({id:`${STEP_ID_PREFIX}${String(index+1).padStart(3,"0")}`,order:index+1,title:stepTitle,body:seed.templateSteps[index]?.body,status:"pending",created_at:now,updated_at:now})),hasPerStepDetailOptions:hasDetailOptions}}function preservePlanCreateStdinPolicy(source,createOptions,derivedLiteralFields=[]){transferMutationStdinTokenPolicy(source,createOptions);if(derivedLiteralFields.length>0){preserveMutationStdinTokenFields(createOptions,derivedLiteralFields)}}async function planCreate(options,global2,ctx){const title=options.title?.trim();if(!title){throw new PmCliError("pm plan create requires --title",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Refactor lock retry" --scope pm-a1b2']})}const mode=asPlanMode(options.mode,DEFAULT_PLAN_MODE);const harness=asHarness(options.harness);const fromSearch=options.fromSearch?.trim();const initialValidation=buildInitialValidation(options);const{steps:initialSteps,hasPerStepDetailOptions}=buildInitialSteps(options);if(initialSteps.length===0&&hasPerStepDetailOptions){throw new PmCliError("pm plan create step options require --step-title (or a single --step)",EXIT_CODE.USAGE,{code:"missing_required_option",examples:['pm plan create --title "Execution plan" --step-title "Read the code"']})}const description=options.description?.trim()??options.scope?.trim()??title;const requestedAssignee=options.claim?resolveAuthor(options.author,ctx.settings.author_default):options.assignee?.trim()||void 0;const createOptions={...options,title,description,type:"Plan",template:void 0,file:toSpecArray(options.file),test:toSpecArray(options.test),doc:toSpecArray(options.doc),field:toSpecArray(options.field),assignee:resolveAuthor(options.author,ctx.settings.author_default),blockedBy:void 0,dep:buildPlanCreateDependencies(options),message:options.message??(fromSearch?`plan create (search: ${fromSearch})`:`plan create`)};preservePlanCreateStdinPolicy(options,createOptions);const createResult=await runCreate(createOptions,global2);const seedResult=await mutateItem({pmRoot:ctx.pmRoot,settings:ctx.settings,id:createResult.item.id,op:"plan_create_metadata",author:resolveAuthor(options.author,ctx.settings.author_default),message:"seed plan metadata",mutate(doc){const changedFields=["plan_mode"];doc.metadata.plan_mode=mode;if(harness){doc.metadata.plan_harness=harness;changedFields.push("plan_harness")}const scope=options.scope?.trim();if(scope){doc.metadata.plan_scope=scope;changedFields.push("plan_scope")}const resumeContext=options.resumeContext?.trim();if(resumeContext){doc.metadata.plan_resume_context=resumeContext;changedFields.push("plan_resume_context")}doc.metadata.plan_steps=initialSteps;changedFields.push("plan_steps");if(initialValidation){doc.metadata.plan_validation=[...doc.metadata.plan_validation??[],initialValidation];changedFields.push("plan_validation")}if(requestedAssignee){doc.metadata.assignee=requestedAssignee;changedFields.push("assignee")}return{changedFields}}});const plan=projectPlan(seedResult.item,"brief");return{action:"create",plan,step:initialSteps[0],next_actions:nextActionsFor(createResult.item.id,plan),warnings:[...createResult.warnings],generated_at:nowIso()}}async function planShow(id,options,ctx){const depth=asDepth(options.depth);const fields=parsePlanFields(options.fields);const{document,itemId}=await readPlanItem(ctx,id);const fullPlan=projectPlan(document.metadata,fields===null?depth:"deep");const plan=fields===null?fullPlan:projectPlanForFields(fullPlan,fields);return{action:"show",plan,next_actions:nextActionsFor(itemId,fullPlan),warnings:[],generated_at:nowIso()}}function changedPlanMetadataFields(beforePlanFields,metadata){const afterPlanFields=new Map(Object.entries(metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));return[...new Set([...beforePlanFields.keys(),...afterPlanFields.keys()])].filter(key=>beforePlanFields.get(key)!==afterPlanFields.get(key))}async function mutatePlanSteps(args){const author=resolveAuthor(args.options.author,args.ctx.settings.author_default);let resultStep;const result=await mutateItem({pmRoot:args.ctx.pmRoot,settings:args.ctx.settings,id:args.id,op:args.op,author,message:args.options.message??args.message,force:args.options.force,mutate(doc){ensurePlanItem(doc.metadata);const statusRegistry=resolveRuntimeStatusRegistry(args.ctx.settings.schema);if(isTerminalStatus(doc.metadata.status,statusRegistry)||isTerminalPlanMode(doc.metadata.plan_mode)){throw new PmCliError(`Plan ${doc.metadata.id} is terminal (status=${doc.metadata.status}, plan_mode=${doc.metadata.plan_mode??"unset"}) and cannot be mutated.`,EXIT_CODE.CONFLICT,{code:"terminal_plan_mutation",required:"Create or reopen a non-terminal Plan before changing its execution context or steps.",why:"Terminal Plan history is immutable execution evidence."})}const steps=(doc.metadata.plan_steps??[]).slice();const beforePlanFields=new Map(Object.entries(doc.metadata).filter(([key])=>key.startsWith("plan_")).map(([key,value])=>[key,JSON.stringify(value)]));const outcome=args.mutator(steps,doc);resultStep=outcome.resultStep;const sorted=steps.slice().sort((left,right)=>left.order-right.order).map((step,index)=>({...step,order:index+1}));doc.metadata.plan_steps=sorted;const changedFields=changedPlanMetadataFields(beforePlanFields,doc.metadata);if(changedFields.length===0&&outcome.changedSteps.length===0){return{changedFields:[]}}return{changedFields:changedFields.length>0?changedFields:["plan_steps"]}}});return{document:{metadata:result.item,body:result.body},resultStep,itemId:result.item.id}}async function planAddStep(id,options,ctx){const title=options.stepTitle?.trim();if(!title){throw new PmCliError("pm plan add-step requires --step-title",EXIT_CODE.USAGE)}const status=asStepStatus(options.stepStatus,"pending");const allowMultipleActive=options.allowMultipleActive===true;const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_add_step",message:`plan add-step "${title}"`,mutator(steps){const order=steps.length+1;assertInProgressStepAllowed(steps,void 0,status,allowMultipleActive);const step=buildAddedPlanStep(steps,options,{order,title,status});steps.push(step);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"add-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function assertInProgressStepAllowed(steps,currentStepId,desiredStatus,allowMultipleActive){if(desiredStatus!=="in_progress"||allowMultipleActive){return}const activeStep=steps.find(step=>step.id!==currentStepId&&step.status==="in_progress");if(!activeStep){return}throw new PmCliError(`Plan already has step ${activeStep.id} in_progress. Pass --allow-multiple-active or update that step first.`,EXIT_CODE.CONFLICT)}function buildAddedPlanStep(existingSteps,options,seed){const linkedItems=buildLinkInputs(options,"depends_on");const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);const now=nowIso();return{id:newStepId(existingSteps),order:seed.order,title:seed.title,body:options.stepBody?.trim()||void 0,status:seed.status,owner:options.stepOwner?.trim()||void 0,evidence:options.stepEvidence?.trim()||void 0,blocked_reason:seed.status==="blocked"?options.stepBlockedReason?.trim()||"":void 0,linked_items:linkedItems.length>0?linkedItems:void 0,files:files.length>0?files:void 0,tests:tests.length>0?tests:void 0,docs:docs.length>0?docs:void 0,created_at:now,updated_at:now,completed_at:seed.status==="completed"?now:void 0}}function buildLinkInputs(options,fallbackKind){const dependsOn=toArray(options.dependsOn).map(id=>({id,kind:fallbackKind}));const related=toArray(options.related).map(id=>({id,kind:"related"}));const blocks=toArray(options.blocks).map(id=>({id,kind:"blocks"}));const blockedBy=toArray(options.blockedBy).map(id=>({id,kind:"blocked_by"}));const explicit=toArray(options.link);const explicitKind=asLinkKind(options.linkKind,fallbackKind);const note=options.linkNote?.trim();const explicitLinks=explicit.map(id=>{const link={id,kind:explicitKind};if(note)link.note=note;return link});return[...dependsOn,...related,...blocks,...blockedBy,...explicitLinks]}async function planUpdateStep(id,options,ctx,args){const{document,resultStep,itemId}=await mutatePlanSteps({id,options,ctx,op:args.op,message:options.message??`${args.op} ${args.stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,args.stepRef);const now=nowIso();const desiredStatus=args.finalStatus??asStepStatus(options.stepStatus,step.status);const allowMultipleActive=options.allowMultipleActive===true||args.allowMultipleActive===true;assertInProgressStepAllowed(steps,step.status==="in_progress"?step.id:void 0,desiredStatus,allowMultipleActive);applyStepUpdates(step,options,desiredStatus,now);doc.metadata.updated_at=now;return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:args.op==="plan_complete_step"?"complete-step":args.op==="plan_block_step"?"block-step":"update-step",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function applyStepUpdates(step,options,desiredStatus,now){assertBlockedStepReason(step,options,desiredStatus);applyStepFieldUpdates(step,options);step.status=desiredStatus;step.updated_at=now;applyStepCompletionTimestamp(step,desiredStatus,now)}function assertBlockedStepReason(step,options,desiredStatus){if(desiredStatus!=="blocked"||options.stepBlockedReason?.trim()||step.blocked_reason){return}throw new PmCliError("Blocking a step requires --step-blocked-reason or an already-recorded blocked_reason.",EXIT_CODE.USAGE)}function applyStepFieldUpdates(step,options){const title=options.stepTitle?.trim();if(title){step.title=title}if(options.stepBody!==void 0){step.body=options.stepBody.trim()||void 0}if(options.stepOwner!==void 0){step.owner=options.stepOwner.trim()||void 0}if(options.stepEvidence!==void 0){step.evidence=options.stepEvidence.trim()||void 0}if(options.stepBlockedReason!==void 0){step.blocked_reason=options.stepBlockedReason.trim()||void 0}if(options.stepReplacement!==void 0){step.superseded_by=options.stepReplacement.trim()||void 0}const files=toSpecArray(options.file).map(parseStepFile);const tests=toSpecArray(options.test).map(parseStepTest);const docs=toSpecArray(options.doc).map(parseStepDoc);if(files.length>0){step.files=mergePlanStepEvidence(step.files,files)}if(tests.length>0){step.tests=mergePlanStepEvidence(step.tests,tests)}if(docs.length>0){step.docs=mergePlanStepEvidence(step.docs,docs)}}function mergePlanStepEvidence(existing,added){const merged=[...existing??[]];const seen=new Set(merged.map(entry=>JSON.stringify(entry)));for(const entry of added){const key=JSON.stringify(entry);if(seen.has(key))continue;seen.add(key);merged.push(entry)}return merged}function applyStepCompletionTimestamp(step,desiredStatus,now){if(desiredStatus==="completed"&&!step.completed_at){step.completed_at=now;return}if(desiredStatus!=="completed"){step.completed_at=void 0}}async function planReorderStep(id,options,ctx,stepRef,newOrder){const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_reorder_step",message:options.message??`plan reorder-step ${stepRef} -> ${newOrder}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=steps.filter(entry=>entry.id!==step.id);const clamped=Math.max(1,Math.min(newOrder,filtered.length+1));filtered.splice(clamped-1,0,step);filtered.forEach((entry,index)=>{entry.order=index+1;entry.updated_at=nowIso()});steps.length=0;steps.push(...filtered);return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"reorder-step",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planRemoveStep(id,options,ctx,stepRef){const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_remove_step",message:options.message??`plan remove-step ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const remaining=steps.filter(entry=>entry.id!==step.id);remaining.forEach((entry,index)=>{entry.order=index+1});steps.length=0;steps.push(...remaining);return{changedSteps:[step.id]}}});const plan=projectPlan(document.metadata,"standard");return{action:"remove-step",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planLink(id,options,ctx,stepRef){const newLinks=buildLinkInputs(options,asLinkKind(options.linkKind,"related"));if(newLinks.length===0){throw new PmCliError("pm plan link requires at least one --link/--related/--blocks/--blocked-by/--depends-on id",EXIT_CODE.USAGE)}const promoteToItemDep=options.promoteToItemDep===true;const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_link_step",message:options.message??`plan link ${stepRef}`,mutator(steps,doc){const step=resolveStepRef(steps,stepRef);const existing=step.linked_items??[];const dedupKey=link=>`${link.kind}:${link.id}`;const seen=new Set(existing.map(dedupKey));for(const link of newLinks){const key=dedupKey(link);if(seen.has(key))continue;existing.push(link);seen.add(key)}step.linked_items=existing;step.updated_at=nowIso();if(promoteToItemDep){const deps=doc.metadata.dependencies??[];const depKey=dep=>`${dep.kind}:${dep.id}`;const seenDeps=new Set(deps.map(depKey));for(const link of newLinks){const promotedKind=link.kind==="depends_on"?"blocked_by":link.kind;const candidate={id:link.id,kind:promotedKind,created_at:nowIso(),author:resolveAuthor(options.author,ctx.settings.author_default)};if(seenDeps.has(depKey(candidate)))continue;deps.push(candidate);seenDeps.add(depKey(candidate))}doc.metadata.dependencies=deps}return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"link",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planUnlink(id,options,ctx,stepRef){const removeIds=toArray(options.link);if(removeIds.length===0){throw new PmCliError("pm plan unlink requires --link <id> to remove",EXIT_CODE.USAGE)}const{document,itemId,resultStep}=await mutatePlanSteps({id,options,ctx,op:"plan_unlink_step",message:options.message??`plan unlink ${stepRef}`,mutator(steps){const step=resolveStepRef(steps,stepRef);const filtered=(step.linked_items??[]).filter(link=>!removeIds.includes(link.id));step.linked_items=filtered.length>0?filtered:void 0;step.updated_at=nowIso();return{changedSteps:[step.id],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"unlink",plan,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planAppendLog(id,options,ctx,kind){const logText=resolvePlanLogText(kind,options);if(!logText){const canonical=`--${kind}-text`;const shorthand=`--${kind}`;throw new PmCliError(`pm plan ${kind} requires ${canonical}`,EXIT_CODE.USAGE,{code:"missing_required_option",examples:[`pm plan ${kind} <plan-id> ${canonical} "..."`,`pm plan ${kind} <plan-id> ${shorthand} "..."`],recovery:{suggested_retry:`pm plan ${kind} <plan-id> ${canonical} <value>`}})}const author=resolveAuthor(options.author,ctx.settings.author_default);const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:`plan_append_${kind}`,message:options.message??`plan ${kind} append`,mutator(_steps,doc){const now=nowIso();if(kind==="decision"){const list2=doc.metadata.plan_decisions??[];list2.push({ts:now,author,decision:logText,rationale:options.decisionRationale?.trim()||void 0,evidence:options.decisionEvidence?.trim()||void 0});doc.metadata.plan_decisions=list2;return{changedSteps:[]}}if(kind==="discovery"){const list2=doc.metadata.plan_discoveries??[];list2.push({ts:now,author,text:logText});doc.metadata.plan_discoveries=list2;return{changedSteps:[]}}const list=doc.metadata.plan_validation??[];list.push({text:logText,command:options.validationCommand?.trim()||void 0,expected:options.validationExpected?.trim()||void 0});doc.metadata.plan_validation=list;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"deep");return{action:kind,plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planResume(id,options,ctx){const text=options.resumeContext?.trim();if(!text){throw new PmCliError("pm plan resume requires --resume-context <text>",EXIT_CODE.USAGE)}const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_resume",message:options.message??"plan resume context update",mutator(_steps,doc){doc.metadata.plan_resume_context=text;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"resume",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planApprove(id,options,ctx){const mode=asPlanMode(options.mode??"approved","approved");const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_approve",message:options.message??`plan approve mode=${mode}`,mutator(_steps,doc){doc.metadata.plan_mode=mode;const scope=options.scope?.trim();if(scope)doc.metadata.plan_scope=scope;return{changedSteps:[]}}});const plan=projectPlan(document.metadata,"brief");return{action:"approve",plan,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}function buildMaterializeSkippedWarnings(materializeSkipped){return materializeSkipped.map(entry=>`plan_materialize_skipped:${entry.from_step}:${entry.reason}${entry.existing_id?`:${entry.existing_id}`:""}`)}function buildMaterializeNoopResult(planRead,materializeSkipped){const plan=projectPlan(planRead.document.metadata,"standard");return{action:"materialize",plan,materialized:[],materialize_skipped:materializeSkipped,next_actions:nextActionsFor(planRead.itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function buildMaterializeDependencies(parent,planItemId,step){const deps=[`id=${parent},kind=parent`,`id=${planItemId},kind=discovered_from`];for(const link of step.linked_items??[]){const realKind=link.kind==="blocked_by"||link.kind==="blocks"||link.kind==="related"||link.kind==="discovered_from"?link.kind:"related";deps.push(`id=${link.id},kind=${realKind}`)}return deps}async function createMaterializedStepItems(params){const materialized=[];const materializeFields={};const reservedMaterializeKeys=new Set(["title","description","type","parent","tags","author","message","dep"]);for(const specification of toSpecArray(params.options.field)){const separator=specification.indexOf("=");if(separator<=0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const name=specification.slice(0,separator).trim();const value=specification.slice(separator+1).trim();if(name.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const segments=name.trim().replaceAll(/([a-z0-9])([A-Z])/g,"$1 $2").replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(Boolean).map(segment=>segment.toLowerCase());if(segments.length===0){throw new PmCliError(`Invalid --field entry "${specification}"; expected name=value`,EXIT_CODE.USAGE)}const[first,...rest]=segments;const fieldKey=`${first}${rest.map(segment=>`${segment.slice(0,1).toUpperCase()}${segment.slice(1)}`).join("")}`;if(reservedMaterializeKeys.has(fieldKey)){throw new PmCliError(`Invalid --field entry "${specification}"; "${fieldKey}" is reserved by materialize and cannot be overridden`,EXIT_CODE.USAGE)}materializeFields[fieldKey]=value}for(const step of params.targets){const createOptions={...materializeFields,title:step.title,description:step.body?.trim()||step.title,type:params.resolvedTypeName,parent:params.parent,tags:params.tags,author:params.options.author,message:params.options.message??`materialized from plan ${params.planItemId} step ${step.id}`,dep:buildMaterializeDependencies(params.parent,params.planItemId,step)};preservePlanCreateStdinPolicy(params.options,createOptions,["description",...Object.keys(materializeFields)]);const created=await runCreate(createOptions,{...{},path:params.pmRoot});materialized.push({id:created.item.id,title:created.item.title,type:params.resolvedTypeName,parent:created.item.parent,tags:created.item.tags??[],from_step:step.id})}return materialized}function linkMaterializedStepItems(currentSteps,targets,materialized){for(const target of targets){const matched=materialized.find(entry=>entry.from_step===target.id);if(!matched){continue}const step=currentSteps.find(entry=>entry.id===target.id);if(!step){continue}const links=step.linked_items??[];links.push({id:matched.id,kind:"implements",note:`materialized as ${matched.type}`});step.linked_items=links;step.updated_at=nowIso()}}async function planMaterialize(id,options,ctx){const stepRefs=toArray(options.steps);if(stepRefs.length===0){throw new PmCliError("pm plan materialize requires --steps <ids|orders|all>",EXIT_CODE.USAGE)}const targetType=options.materializeType?.trim()||"Task";const typeRegistry=resolveItemTypeRegistry(ctx.settings,getActiveExtensionRegistrations());const resolvedTypeName=resolveTypeName(targetType,typeRegistry);if(!resolvedTypeName){throw new PmCliError(`Invalid --materialize-type "${targetType}"`,EXIT_CODE.USAGE)}const parent=options.materializeParent?.trim()||id;const tags=options.materializeTags;const planRead=await readPlanItem(ctx,id);const steps=(planRead.document.metadata.plan_steps??[]).slice();const{targets,skipped:materializeSkipped}=resolveMaterializeTargets(steps,stepRefs);if(targets.length===0){if(materializeSkipped.length>0){return buildMaterializeNoopResult(planRead,materializeSkipped)}throw new PmCliError("No matching plan steps found for --steps",EXIT_CODE.NOT_FOUND)}const materialized=await createMaterializedStepItems({targets,parent,planItemId:planRead.itemId,resolvedTypeName,tags,options,pmRoot:ctx.pmRoot});const{document,itemId}=await mutatePlanSteps({id,options,ctx,op:"plan_materialize",message:options.message??`plan materialize ${stepRefs.join(",")}`,mutator(currentSteps){linkMaterializedStepItems(currentSteps,targets,materialized);return{changedSteps:targets.map(entry=>entry.id)}}});const plan=projectPlan(document.metadata,"standard");return{action:"materialize",plan,materialized,...materializeSkipped.length>0?{materialize_skipped:materializeSkipped}:{},next_actions:nextActionsFor(itemId,plan),warnings:buildMaterializeSkippedWarnings(materializeSkipped),generated_at:nowIso()}}function normalizePlanStepAliasInput(input){if(input.subcommand==="create"){return input}const stepValues=toOrderedStepTitles(input.options.step);if(stepValues.length>1){throw new PmCliError(`pm plan ${input.subcommand} accepts a single --step/--step-title value (repeated --step seeds ordered steps only on pm plan create)`,EXIT_CODE.USAGE)}if(stepValues.length===1&&!input.options.stepTitle?.trim()){return{...input,options:transferMutationStdinTokenPolicy(input.options,{...input.options,stepTitle:stepValues[0]})}}return input}function requirePlanId(input,label){if(!input.id){throw new PmCliError(`pm plan ${label} requires a plan id`,EXIT_CODE.USAGE)}return input.id}function requirePlanStepRef(input,label){const id=requirePlanId(input,label);if(!input.stepRef){throw new PmCliError(`pm plan ${label} requires <plan-id> <step>`,EXIT_CODE.USAGE)}return{id,stepRef:input.stepRef}}function requireReorderTarget(input){const target=requirePlanStepRef(input,"reorder-step");if(input.reorderTo===void 0){throw new PmCliError("pm plan reorder-step requires <plan-id> <step> <new-order>",EXIT_CODE.USAGE)}return{...target,reorderTo:input.reorderTo}}const PLAN_DISPATCHERS={create:(input,ctx)=>planCreate(input.options,input.global,ctx),show:(input,ctx)=>planShow(requirePlanId(input,"show"),input.options,ctx),"add-step":(input,ctx)=>planAddStep(requirePlanId(input,"add-step"),input.options,ctx),"update-step":(input,ctx)=>{const target=requirePlanStepRef(input,"update-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,op:"plan_update_step"})},"complete-step":(input,ctx)=>{const target=requirePlanStepRef(input,"complete-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"completed",op:"plan_complete_step"})},"block-step":(input,ctx)=>{const target=requirePlanStepRef(input,"block-step");return planUpdateStep(target.id,input.options,ctx,{stepRef:target.stepRef,finalStatus:"blocked",op:"plan_block_step"})},"reorder-step":(input,ctx)=>{const target=requireReorderTarget(input);return planReorderStep(target.id,input.options,ctx,target.stepRef,target.reorderTo)},"remove-step":(input,ctx)=>{const target=requirePlanStepRef(input,"remove-step");return planRemoveStep(target.id,input.options,ctx,target.stepRef)},link:(input,ctx)=>{const target=requirePlanStepRef(input,"link");return planLink(target.id,input.options,ctx,target.stepRef)},unlink:(input,ctx)=>{const target=requirePlanStepRef(input,"unlink");return planUnlink(target.id,input.options,ctx,target.stepRef)},decision:(input,ctx)=>planAppendLog(requirePlanId(input,"decision"),input.options,ctx,"decision"),discovery:(input,ctx)=>planAppendLog(requirePlanId(input,"discovery"),input.options,ctx,"discovery"),validation:(input,ctx)=>planAppendLog(requirePlanId(input,"validation"),input.options,ctx,"validation"),resume:(input,ctx)=>planResume(requirePlanId(input,"resume"),input.options,ctx),approve:(input,ctx)=>planApprove(requirePlanId(input,"approve"),input.options,ctx),materialize:(input,ctx)=>planMaterialize(requirePlanId(input,"materialize"),input.options,ctx)};function resolvePlanDispatcher(subcommand){const dispatcher=PLAN_DISPATCHERS[subcommand];if(!dispatcher){throw createUnknownSubcommandError({command_path:"plan",token:subcommand,allowed:PLAN_SUBCOMMANDS})}return dispatcher}async function runPlan(input){const ctx=await loadContext(input.global);const normalizedInput=normalizePlanStepAliasInput(input);return resolvePlanDispatcher(normalizedInput.subcommand)(normalizedInput,ctx)}const _testOnlyPlanCommand={changedPlanMetadataFields};export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,_testOnlyPlanCommand,resolvePlanTemplateSteps,runPlan};
|
|
1606
2
|
//# sourceMappingURL=plan.js.map
|
|
1607
|
-
//# debugId=f7e870b6-fd80-5742-bc81-826d8f102d30
|