@unbrained/pm-cli 2026.9.28 → 2026.9.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/.agents/skills/pm-developer/references/GRAPH_AND_RELATIONSHIPS.md +7 -6
  2. package/.agents/skills/pm-user/references/BACKLOG_SHAPING.md +1 -1
  3. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +26 -3
  4. package/.claude-plugin/marketplace.json +2 -2
  5. package/CHANGELOG.md +26 -0
  6. package/dist/cli/error-guidance.js +1 -1
  7. package/dist/cli/help-json-payload.js +2 -2
  8. package/dist/cli/main.js +2 -2
  9. package/dist/cli/runtime/invocation-options.d.ts +3 -1
  10. package/dist/cli/runtime/invocation-options.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +152 -152
  12. package/dist/cli-bundle/chunks/{chunk-UT7GRGHY.js → chunk-6XTJLOKW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-VMJLM7P2.js → chunk-6YEET7XI.js} +22 -22
  14. package/dist/cli-bundle/chunks/{chunk-NEUIVBFO.js → chunk-A6NDNRCK.js} +3 -3
  15. package/dist/cli-bundle/chunks/{chunk-GLH2LNRH.js → chunk-BNAT4EYR.js} +9 -9
  16. package/dist/cli-bundle/chunks/{chunk-CPOWTIIS.js → chunk-BTCE36JS.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-35DME35A.js → chunk-BX4LEJX4.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-A2G5OG6W.js → chunk-EGAIIWI3.js} +2 -2
  19. package/dist/cli-bundle/chunks/chunk-FYTXVVZG.js +2 -0
  20. package/dist/cli-bundle/chunks/{chunk-ZFHJP7YD.js → chunk-O23CQ5T4.js} +31 -29
  21. package/dist/cli-bundle/chunks/{chunk-NBDB3SRC.js → chunk-UIAH7UFK.js} +67 -67
  22. package/dist/cli-bundle/chunks/{chunk-OYCCWPBM.js → chunk-USTAFHIM.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-PR4UAMI5.js → chunk-XRN3JYNN.js} +85 -85
  24. package/dist/cli-bundle/chunks/{chunk-PLNNUAFZ.js → chunk-YM342ELM.js} +2 -2
  25. package/dist/cli-bundle/chunks/{register-list-query-N6RP6PSP.js → register-list-query-SYNBVMNG.js} +2 -2
  26. package/dist/cli-bundle/chunks/{register-mutation-CY7JGQE6.js → register-mutation-4GSUK23D.js} +2 -2
  27. package/dist/cli-bundle/chunks/{register-operations-53HAD3QP.js → register-operations-7FCJUC4Z.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-setup-NVX6374E.js → register-setup-YTWW2KL5.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-BRLXKRI2.js → chunk-3CAZ7Z4R.js} +4 -4
  30. package/dist/cli-bundle/focused-chunks/{chunk-K7GSZ7YZ.js → chunk-4AORVUT4.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-AZA4AEOR.js → chunk-AKB3JN57.js} +33 -33
  32. package/dist/cli-bundle/focused-chunks/{chunk-OVVCXTIE.js → chunk-EFD4ATS7.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-IJXZQE3D.js → chunk-EVMH4SKN.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-IWLMQLBO.js → chunk-IDB6E3ZV.js} +28 -28
  35. package/dist/cli-bundle/focused-chunks/{chunk-YZB7IPR6.js → chunk-IQBFYQF2.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-BGWF6CMP.js → chunk-KZULQIAG.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-ZMQTIS3L.js → chunk-MOUCTR72.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-6IVQPNYN.js → chunk-OMBDUJWZ.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-DTLRXY77.js → chunk-RIJQQOEZ.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-A5O3VYWV.js → chunk-T4PZJQG4.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-V7OPZRL6.js → chunk-UPOMLSW7.js} +14 -14
  42. package/dist/cli-bundle/focused-chunks/{chunk-5KJXX2TZ.js → chunk-XB5Q2P7Z.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-ONDNR3VU.js → chunk-XUCXRZZZ.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-Y5Z3XNGY.js → chunk-ZJ3CLTV4.js} +2 -2
  45. package/dist/cli-bundle/main.js +22 -22
  46. package/dist/cli-bundle/sdk-authoring.js +1 -1
  47. package/dist/cli-bundle/sdk-contracts.js +1 -1
  48. package/dist/cli-bundle/sdk-core.js +22 -21
  49. package/dist/cli-bundle/sdk-governance.js +1 -1
  50. package/dist/cli-bundle/sdk-graph.js +1 -1
  51. package/dist/cli-bundle/sdk-merge.js +38 -38
  52. package/dist/cli-bundle/sdk-query.js +1 -1
  53. package/dist/cli-bundle/sdk-runtime.js +1 -1
  54. package/dist/cli-bundle/sdk-testing.js +1 -1
  55. package/dist/cli-bundle/sdk.js +2 -2
  56. package/dist/core/extensions/extension-types.d.ts +13 -0
  57. package/dist/core/extensions/extension-types.js +1 -1
  58. package/dist/core/history/replay.js +1 -1
  59. package/dist/core/history/workspace-history.d.ts +17 -0
  60. package/dist/core/history/workspace-history.js +1 -1
  61. package/dist/core/output/mutation-projection.js +1 -1
  62. package/dist/core/telemetry/runtime.js +2 -2
  63. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  64. package/dist/sdk/extension-command-context.d.ts +1 -7
  65. package/dist/sdk/extension-command-context.js +1 -1
  66. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  67. package/dist/sdk/index.d.ts +1 -0
  68. package/dist/sdk/index.js +1 -1
  69. package/dist/sdk/lifecycle/plan-mutation-receipt.d.ts +53 -0
  70. package/dist/sdk/lifecycle/plan-mutation-receipt.js +2 -0
  71. package/dist/sdk/lifecycle/plan.d.ts +3 -0
  72. package/dist/sdk/lifecycle/plan.js +1 -1
  73. package/dist/sdk/lifecycle/update.d.ts +2 -0
  74. package/dist/sdk/lifecycle/update.js +1 -1
  75. package/dist/sdk/linked-artifacts.js +1 -1
  76. package/dist/sdk/merge/install.js +1 -1
  77. package/dist/sdk/public-surface.json +1 -1
  78. package/dist/sdk/runtime/actions.js +1 -1
  79. package/dist/sdk/runtime-input.d.ts +2 -0
  80. package/dist/sdk/runtime-input.js +1 -1
  81. package/dist/sdk/runtime.js +1 -1
  82. package/dist/sdk/similarity-scoring.js +1 -1
  83. package/dist/sdk/structured-mutations.js +1 -1
  84. package/dist/sdk/telemetry.d.ts +2 -0
  85. package/dist/sdk/telemetry.js +3 -1
  86. package/dist/sdk/testing.js +1 -1
  87. package/docs/CLI_GRAMMAR.md +18 -1
  88. package/docs/ECOSYSTEM_PLANNING_REVIEW.md +270 -0
  89. package/docs/MERGE_SAFETY.md +11 -6
  90. package/docs/README.md +2 -0
  91. package/docs/RELEASE_RELIABILITY.md +26 -4
  92. package/docs/SDK_AUDITED_MUTATIONS.md +52 -0
  93. package/docs/SDK_EVIDENCE_TRACEABILITY.md +34 -0
  94. package/docs/agent-task-token-baseline.json +28 -2
  95. package/docs/agent-task-transcripts.json +137 -14
  96. package/docs/ecosystem-review-2026-09-28.json +3159 -0
  97. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  98. package/marketplace.json +2 -2
  99. package/package.json +1 -1
  100. package/packages/pm-beads/package.json +1 -1
  101. package/packages/pm-calendar/package.json +1 -1
  102. package/packages/pm-command-kit/package.json +1 -1
  103. package/packages/pm-digital-twin/package.json +1 -1
  104. package/packages/pm-governance-audit/package.json +1 -1
  105. package/packages/pm-guide-shell/package.json +1 -1
  106. package/packages/pm-kanban/package.json +1 -1
  107. package/packages/pm-lifecycle-hooks/package.json +1 -1
  108. package/packages/pm-linked-test-adapters/package.json +1 -1
  109. package/packages/pm-search-advanced/package.json +1 -1
  110. package/packages/pm-templates/package.json +1 -1
  111. package/packages/pm-todos/package.json +1 -1
  112. package/packages/pm-vcs/package.json +1 -1
  113. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  114. package/plugins/pm-claude/package.json +2 -2
  115. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  116. package/plugins/pm-codex/package.json +2 -2
  117. package/plugins/pm-codex/plugin.json +1 -1
  118. package/dist/cli-bundle/chunks/chunk-YERBAGQD.js +0 -2
package/dist/sdk/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e15c7545-0658-5d93-b488-92667c781a2c")}catch(e2){}})();import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"./agent-capability-contracts.js";export*from"./mcp/protocol.js";export*from"./mcp/interactions.js";export*from"./mcp/tasks.js";export*from"./mcp/subscriptions.js";export*from"./mcp/transport.js";export*from"./mcp/authorization.js";export*from"./mcp/apps.js";export*from"./mcp/skills.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./agent-session-context.js";export*from"./environment/agent-environment.js";import{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict}from"./annotations.js";import{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution}from"./author-attribution.js";import{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape}from"./corpus-shape.js";export*from"./core-governance.js";import{createPmCliProgram}from"./cli-program.js";import{runSearchRefreshWorkerEntrypoint}from"./search-refresh-worker.js";import{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment}from"./reproducibility/process.js";import{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe}from"./workspace-recipe.js";import{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{flushTelemetryQueue}from"./telemetry-flush.js";import{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from"./cli-contracts.js";import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens}from"./cli-bootstrap.js";import{quoteCommandArg,quoteWindowsCommandArg,renderPmCommand}from"./command-line.js";export*from"./agent/command-recovery.js";export*from"./agent/command-suggestions.js";export*from"./agent/item-addressing.js";export*from"./agent/create-option-policy.js";import{runGc}from"./governance/gc.js";import{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits}from"./governance/coverage-assurance.js";import{_testOnlyHealthCommand,runHealth}from"./governance/health.js";import{_testOnlyValidateCommand,projectValidateCounts,runValidate}from"./governance/validate.js";import{runExtension}from"./extension.js";import{inspectStaticExtensionInventory}from"./extension/static-inventory.js";import{buildExtensionInstallPlan,planExtensionDirectoryCopy}from"./extension/install-plan.js";import{resolveExtensionInstallSourceIdentity}from"./extension/source-resolution.js";import{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations}from"./extension/migrations.js";import{findInstalledNpmPackageCandidate}from"./extension/install-sources.js";import{buildExtensionDescribeResult,renderExtensionDescribeMarkdown}from"./extension/describe.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{isRuntimeRecord}from"./runtime-input.js";import{resolveStartTaskInProgressStatus}from"./start-task-status.js";import{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall}from"./merge/install.js";import{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration}from"./schema-migration.js";import{runWithActiveExtensions}from"./runtime.js";import{applyInvocationAuthorOverride}from"./invocation-author.js";import{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets}from"./mutation-guard.js";import{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText}from"./similarity.js";import{inspectStaleInProgressItems,scanStaleInProgressItems}from"./governance/stale-work.js";import{describeItemOwnershipConflict}from"./ownership-source.js";import{discoverNearbyPmRoot}from"./tracker-root-discovery.js";import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"./environment/tracker-preflight.js";import{_testOnly}from"./templates.js";import{runConfig,_testOnlyConfigCommand}from"./config.js";export*from"./agent/identity-config.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnly2}from"./init-agent-guidance.js";import{runInit,summarizeInitResult,_testOnly as _testOnly3}from"./init.js";import{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"./profile.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata}from"./cli-contracts.js";export*from"./compose.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-runtime.js";export*from"./governance/assurance-presets.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/merge-receipt-history.js";export*from"./compile-cache.js";export*from"./environment/project-runtime-compatibility.js";export*from"./environment/source-context.js";export*from"./environment/host-environment-errors.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-relevance.js";export*from"./context/recency.js";export*from"./context-intent-contracts.js";export*from"./context-intent-runtime.js";export*from"./context-signal-store.js";export*from"./workspace-memory.js";export*from"./lifecycle-completion.js";export*from"./lifecycle-policy.js";export*from"./output-projection.js";export*from"./read-output-contracts.js";export*from"./read-output-rows.js";export*from"./read-output-session.js";export*from"./output-token-accounting.js";export*from"./context-packing.js";export*from"./context-usage.js";import{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS}from"../core/history/event-classification.js";export*from"./dependency-provenance.js";export*from"./duplicates.js";export*from"./lifecycle/reopen.js";export*from"./history-compact.js";export*from"./history-read.js";export*from"../core/history/operation-contract.js";export*from"./history/maintenance.js";import{readHistorySnapshot}from"../core/history/read.js";export*from"./history-provenance.js";export*from"./mutation-events.js";export*from"./history-redact.js";import{_testOnly as _testOnly4}from"./history-redact.js";export*from"./history-repair.js";export*from"./item-children.js";export*from"./item-schedule.js";export*from"./merge/index.js";import{runDeps}from"./dependencies.js";export*from"./graph/index.js";import{runDocs}from"./docs.js";import{runFiles,runFilesDiscover,runFilesLookup}from"./files.js";import{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths}from"./linked-artifacts.js";export*from"./pagination.js";export*from"./query/item-filter-options.js";export*from"./query/parsers.js";export*from"./output.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";export*from"./workspace-transaction.js";export*from"./workspace-transaction-gc.js";export*from"./item-transaction.js";export*from"./item-metadata-index.js";export*from"./structured-mutations.js";export*from"./runtime-primitives.js";export*from"./error-runtime.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./agent/refusal-reachability.js";export*from"./agent/refusal-closure-census.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/refusal-corpus-contracts.js";import{MERGE_SUBCOMMAND_VALUES}from"./cli-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export*from"./agent/subcommand-recovery.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./relationships.js";export*from"./actionability.js";import{runCreate}from"./lifecycle/create.js";import{runPlan}from"./lifecycle/plan.js";import{runAppend}from"./lifecycle/append.js";import{isAlreadyClaimedError,runClaim,runClaimNext,runRelease}from"./lifecycle/claim.js";import{runStartTask,runPauseTask,runCloseTask}from"./lifecycle/task-composition.js";import{runCloseMany}from"./lifecycle/close-many.js";import{runUpdateMany}from"./lifecycle/update-many.js";import{runComments}from"./comments.js";import{runNotes}from"./notes.js";import{runLearnings}from"./learnings.js";import{runUpgrade}from"./governance/upgrade.js";import{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES}from"./lifecycle/plan.js";export*from"./define.js";import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate}from"./runtime.js";import{extensionMigrate,packageMigrate}from"./package-migrations.js";import{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate}from"./runtime.js";import{runStats}from"./stats.js";import{readImprovementLedger,recordImprovementObservation}from"./improvement-ledger.js";import{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics}from"./history-analytics.js";import{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval}from"./eval.js";import{runTelemetry,TELEMETRY_SUBCOMMANDS}from"./telemetry.js";import{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight}from"./test/execution.js";import{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./test/measurements.js";import{runTestAll}from"./test/batch.js";import{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./test/parsers.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch}from"./test/trust.js";import{runStartBackgroundRun,runTestRunsWorker}from"./test/runs.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";export*from"./authoring.js";export*from"./governance.js";export*from"./mcp/discovery.js";export*from"./query.js";export*from"./testing.js";export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,BASELINE_ITEM_FORMAT_VERSION,BUILTIN_CORPUS_SHAPES,BUILTIN_ITEM_TYPE_VALUES,BUILTIN_PROFILES,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIDENCE_TEXT_VALUES,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTEXT_OUTPUT_VALUES,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_EVAL_QUERIES_RELATIVE_PATH,DELETE_FLAG_CONTRACTS,DEPENDENCY_KIND_VALUES,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,EVENTS_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EXECUTABLE_COMMAND_ALIASES,EXIT_CODE,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_EVENT_CLASSIFICATION_VERSION,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,INIT_AGENT_GUIDANCE_MODE_VALUES,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ISSUE_SEVERITY_VALUES,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,ITEM_TYPE_VALUES,LEARNINGS_FLAG_CONTRACTS,LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MAINTENANCE_HISTORY_OPERATIONS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,MERGE_SUBCOMMAND_VALUES,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NEXT_OUTPUT_VALUES,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_CLI_EXPECTED_ERROR_NAME,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_COMMAND_ALIAS_CONTRACTS,PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES,PM_CORPUS_SHAPE_SCHEMA,PM_DEPRECATED_TOOL_ACTIONS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXACT_COVERAGE_METRICS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_GITIGNORE_END,PM_GITIGNORE_START,PM_HISTORY_COMMAND_ALIASES,PM_ITEM_ACTION_SUBCOMMANDS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,PM_MUTATION_ACTION_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_PACKAGE_RESOURCE_KINDS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_RELOCATED_COMMAND_ALIASES,PM_REPRODUCIBLE_PROCESS_ENV,PM_TOOL_ACTIONS,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,PM_WORKSPACE_RECIPE_SCHEMA,PROFILE_FLAG_CONTRACTS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,PROFILE_SUBCOMMANDS,PmCliError,PmClient,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESERVED_ITEM_FIELD_NAMES,RESTORE_FLAG_CONTRACTS,RISK_VALUES,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,SNAPSHOT_SCHEMA,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,STATUS_VALUES,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,SUBSTANTIVE_HISTORY_OPERATIONS,TELEMETRY_FLAG_CONTRACTS,TELEMETRY_SUBCOMMANDS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TEST_RUN_MEASUREMENT_LIMIT,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,WORKSPACE_SNAPSHOT_ACTIONS,_testOnly4 as _testOnly,_testOnlyConfigCommand,_testOnlyHealthCommand,_testOnly3 as _testOnlyInit,_testOnly2 as _testOnlyInitAgentGuidance,_testOnly as _testOnlyTemplates,_testOnlyValidateCommand,acknowledgeLinkedTests,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,acquireLock,aggregate,analyzePmToolActionParity,analyzeSdkActionCoverage,analyzeSdkCliParameterCompleteness,append,appendHistoryEntry,applyBootstrapPagerPolicy,applyInvocationAuthorOverride,applyPathMigrations,applyStandaloneNote,applyStoredExtensionMigrationState,artifactKey,assertInitializedTracker,assertLinkedArtifactMutationIsUnambiguous,assertReadableTrackerRoot,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,auditMergeAttributeFence,buildCorpusShapeItemPlan,buildExtensionDescribeResult,buildExtensionInstallPlan,buildMergeAttributePatterns,buildPmActionToolInputSchema,buildTrackerInitializationRecovery,canonicalDocument,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,clearWorkspaceContractsCache,close,closeItem,closeTask,coalesceRepeatedListFlags,collectPackageExtensionDirectories,comments,commitImportedItem,compactFlagAliasContracts,config,context,copy,countFailureCategories,create,createCorpusShapeMeasurement,createExtensionCommandSdk,createHistoryEntry,createPmCliExpectedError,createPmCliProgram,createPmCommandOutputBudget,createReproducibleProcessRunner,createWorkspaceSnapshot,dedupeLinkedArtifacts,defineCorpusShape,definePmCommandOutputBudget,defineWorkspaceRecipe,deleteItem,deleteWorkspaceSnapshot,deps,deriveSchemaEvolutionMigrationId,describeItemOwnershipConflict,describeProfileComposition,describeProjectProfile,diffTestRunMeasurements,discoverNearbyPmRoot,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureScope,ensureTrackerInitialized,estimatePmOutputTokens,evaluateMutationGuard,evaluateProvenanceCoverage,evaluateSimilarityGovernance,executeWorkspaceRecipe,expandAddGlobEntries,extension,extensionActivate,extensionDeactivate,extensionList,extensionMigrate,extractReferencedPmItemIdsFromCommand,files,filesDiscover,filesLookup,findCoverageDeficits,findDuplicateClusters,findGitWorkspaceRoot,findInstalledNpmPackageCandidate,findPmNamespacedCommand,findSimilarItems,flushTelemetryQueue,focus,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,formatSchemaEvolutionMigrationHuman,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getMutationActionContract,getPmGitignoreBlock,getSettingsPath,getWorkspaceContracts,graph,hasSubcommandFlagContractsForCommand,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,inferPmOutputBudgetClass,init,inspectHistoryAuthorStream,inspectStaleInProgressItems,inspectStaticExtensionInventory,inspectWorkspaceSnapshot,installMergeFence,isAlreadyClaimedError,isErrnoError,isMutationAction,isPmCliExpectedError,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,isRuntimeRecord,isTimestampLiteral,jaccardSimilarity,learnings,limitAnnotationEntries,linkedTestTrustFingerprint,lintProjectProfile,list,listAliasPluralKeys,listAllComplete,listAllItemMetadata,listBuiltinCorpusShapes,listMutationActions,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,listProfiles,listWorkspaceSnapshots,loadCreateTemplateOptions,locateItem,measureCorpusShapePlan,mergeLinkedTestTwoTokenEntries,next,normalizeAnnotationTransportOptions,normalizeBootstrapInvocation,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeLegacyExtensionActionSyntax,normalizeLinkedPath,normalizeProfileName,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageMigrate,packageReload,packageUninstall,parseAddEntries,parseAddGlobEntries,parseAnnotationTextInput,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,parseEvalQuerySet,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,parseMigrateEntries,parseRemoveEntries,parseTags,parseTestRunMeasurements,parseUnknownAuthorHistoryEventCoordinates,pathExists,pauseTask,planExtensionDirectoryCopy,planProfileApplication,planSchemaEvolutionMigration,planUnknownAuthorHistoryAcknowledgment,planWorkspaceSnapshotRestore,prepareSimilarityText,profile,profileApply,profileLint,profileList,profileShow,projectFleetAttributionAnalytics,projectPmDiagnosticOutput,projectPmDiagnosticText,projectProvenanceCoverageAnalytics,projectValidateCounts,queryTestRunMeasurementsBelow,quoteCommandArg,quoteWindowsCommandArg,readAnnotationEntries,readBooleanOption,readCsvListOption,readExtensionMigrationState,readFileIfExists,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readHistoryAnalyticsWindow,readHistorySnapshot,readImprovementLedger,readLocatedItem,readPmPackageManifest,readRequiredString,readSettings,readStringArrayFromCommanderOptions,readStringOption,recordImprovementObservation,refreshMergeAttributeFenceIfInstalled,release,removeFileIfExists,renameArtifactsResultKey,renderCalendarMarkdown,renderCalendarToon,renderExtensionDescribeMarkdown,renderGuideMarkdown,renderPmCommand,renderPmCommandAliasMigrationHint,renderPmCommandVisibilityMarkdown,reopen,resolveAnnotationIndex,resolveAnnotationInput,resolveBuiltinCorpusShape,resolveCalendarOutputFormat,resolveExtensionInstallSourceIdentity,resolveExtensionMigrationStatePath,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolveLinkedTestFailureExitCode,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,resolveMergeInstallContext,resolvePmCommandAlias,resolvePmCommandCapabilityFamily,resolvePmCommandOperation,resolvePmCommandOutputBudget,resolvePmCommandVisibilityTier,resolvePmDiagnosticOutputBudget,resolvePmHistoryOperation,resolvePmPositionalActionFlagContracts,resolvePmRoot,resolvePmToolCustomFieldCollision,resolveProfile,resolveProjectMergeTypeFolders,resolveReproducibleProcessEnvironment,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveStartTaskInProgressStatus,resolveSubcommandFlagContractsForCommand,resolveUnknownAuthorAcknowledgmentSelector,restore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runAnnotationCommand,runAppend,runCalendar,runClaim,runClaimNext,runClose,runCloseMany,runCloseTask,runComments,runCompletion,runConfig,runContext,runCopy,runCreate,runDelete,runDeps,runDocs,runEval,runEvent,runExtension,runExtensionMigrateAction,runExtensionMigrations,runFiles,runFilesDiscover,runFilesLookup,runFleetAttributionAnalytics,runFocus,runGc,runGet,runGuide,runHealth,runInit,runInitAgentGuidance,runLearnings,runLinkedArtifacts,runLinkedTests,runList,runMeet,runMergeInstall,runNext,runNotes,runPauseTask,runPlan,runProfileApply,runProfileLint,runProfileList,runProfileShow,runProvenanceCoverageAnalytics,runReindex,runRelease,runRemind,runRestore,runSchemaEvolutionMigration,runSearch,runSearchRefreshWorkerEntrypoint,runStartBackgroundRun,runStartTask,runStats,runTelemetry,runTemplatesList,runTemplatesSave,runTemplatesShow,runTest,runTestAll,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker,runUpdate,runUpdateMany,runUpgrade,runValidate,runWithActiveExtensions,runWithReproducibleProcessEnvironment,runWithWorkspaceRecipe,scanHistoryAuthorAttribution,scanItemFormatVersions,scanMutationSecrets,scanStaleInProgressItems,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,scorePreparedItemSimilarity,search,selectImportAuthor,serializeItemDocument,similarityAdvisoryWarnings,sortLinkedArtifacts,splitFrontMatter,startTask,stats,stripGlobalBootstrapTokens,summarizeContextPreflight,summarizeInitResult,toCompletionFlagString,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,validateLinkedPaths,verifyToolOptionCliParity,withFlagAliasMetadata,wrapOwnershipConflict,writeFileAtomic};
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]="e9d5c73b-d4fe-56ca-a2ad-229b04baad63")}catch(e2){}})();import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"./agent-capability-contracts.js";export*from"./mcp/protocol.js";export*from"./mcp/interactions.js";export*from"./mcp/tasks.js";export*from"./mcp/subscriptions.js";export*from"./mcp/transport.js";export*from"./mcp/authorization.js";export*from"./mcp/apps.js";export*from"./mcp/skills.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./agent-session-context.js";export*from"./environment/agent-environment.js";import{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict}from"./annotations.js";import{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution}from"./author-attribution.js";import{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape}from"./corpus-shape.js";export*from"./core-governance.js";import{createPmCliProgram}from"./cli-program.js";import{runSearchRefreshWorkerEntrypoint}from"./search-refresh-worker.js";import{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment}from"./reproducibility/process.js";import{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe}from"./workspace-recipe.js";import{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{flushTelemetryQueue}from"./telemetry-flush.js";import{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from"./cli-contracts.js";import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens}from"./cli-bootstrap.js";import{quoteCommandArg,quoteWindowsCommandArg,renderPmCommand}from"./command-line.js";export*from"./agent/command-recovery.js";export*from"./agent/command-suggestions.js";export*from"./agent/item-addressing.js";export*from"./agent/create-option-policy.js";import{runGc}from"./governance/gc.js";import{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits}from"./governance/coverage-assurance.js";import{_testOnlyHealthCommand,runHealth}from"./governance/health.js";import{_testOnlyValidateCommand,projectValidateCounts,runValidate}from"./governance/validate.js";import{runExtension}from"./extension.js";import{inspectStaticExtensionInventory}from"./extension/static-inventory.js";import{buildExtensionInstallPlan,planExtensionDirectoryCopy}from"./extension/install-plan.js";import{resolveExtensionInstallSourceIdentity}from"./extension/source-resolution.js";import{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations}from"./extension/migrations.js";import{findInstalledNpmPackageCandidate}from"./extension/install-sources.js";import{buildExtensionDescribeResult,renderExtensionDescribeMarkdown}from"./extension/describe.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{isRuntimeRecord}from"./runtime-input.js";import{resolveStartTaskInProgressStatus}from"./start-task-status.js";import{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall}from"./merge/install.js";import{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration}from"./schema-migration.js";import{runWithActiveExtensions}from"./runtime.js";import{applyInvocationAuthorOverride}from"./invocation-author.js";import{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets}from"./mutation-guard.js";import{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText}from"./similarity.js";import{inspectStaleInProgressItems,scanStaleInProgressItems}from"./governance/stale-work.js";import{describeItemOwnershipConflict}from"./ownership-source.js";import{discoverNearbyPmRoot}from"./tracker-root-discovery.js";import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"./environment/tracker-preflight.js";import{_testOnly}from"./templates.js";import{runConfig,_testOnlyConfigCommand}from"./config.js";export*from"./agent/identity-config.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnly2}from"./init-agent-guidance.js";import{runInit,summarizeInitResult,_testOnly as _testOnly3}from"./init.js";import{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"./profile.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata}from"./cli-contracts.js";export*from"./compose.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-runtime.js";export*from"./governance/assurance-presets.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/merge-receipt-history.js";export*from"./compile-cache.js";export*from"./environment/project-runtime-compatibility.js";export*from"./environment/source-context.js";export*from"./environment/host-environment-errors.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-relevance.js";export*from"./context/recency.js";export*from"./context-intent-contracts.js";export*from"./context-intent-runtime.js";export*from"./context-signal-store.js";export*from"./workspace-memory.js";export*from"./lifecycle-completion.js";export*from"./lifecycle-policy.js";export*from"./output-projection.js";export*from"./read-output-contracts.js";export*from"./read-output-rows.js";export*from"./read-output-session.js";export*from"./output-token-accounting.js";export*from"./context-packing.js";export*from"./context-usage.js";import{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS}from"../core/history/event-classification.js";export*from"./dependency-provenance.js";export*from"./duplicates.js";export*from"./lifecycle/reopen.js";export*from"./history-compact.js";export*from"./history-read.js";export*from"../core/history/operation-contract.js";export*from"./history/maintenance.js";import{readHistorySnapshot}from"../core/history/read.js";export*from"./history-provenance.js";export*from"./mutation-events.js";export*from"./history-redact.js";import{_testOnly as _testOnly4}from"./history-redact.js";export*from"./history-repair.js";export*from"./item-children.js";export*from"./item-schedule.js";export*from"./merge/index.js";import{runDeps}from"./dependencies.js";export*from"./graph/index.js";import{runDocs}from"./docs.js";import{runFiles,runFilesDiscover,runFilesLookup}from"./files.js";import{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths}from"./linked-artifacts.js";export*from"./pagination.js";export*from"./query/item-filter-options.js";export*from"./query/parsers.js";export*from"./output.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";export*from"./workspace-transaction.js";export*from"./workspace-transaction-gc.js";export*from"./item-transaction.js";export*from"./item-metadata-index.js";export*from"./structured-mutations.js";export*from"./runtime-primitives.js";export*from"./error-runtime.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./agent/refusal-reachability.js";export*from"./agent/refusal-closure-census.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/refusal-corpus-contracts.js";import{MERGE_SUBCOMMAND_VALUES}from"./cli-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export*from"./agent/subcommand-recovery.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./relationships.js";export*from"./actionability.js";import{runCreate}from"./lifecycle/create.js";import{runPlan}from"./lifecycle/plan.js";import{runAppend}from"./lifecycle/append.js";import{isAlreadyClaimedError,runClaim,runClaimNext,runRelease}from"./lifecycle/claim.js";import{runStartTask,runPauseTask,runCloseTask}from"./lifecycle/task-composition.js";import{runCloseMany}from"./lifecycle/close-many.js";import{runUpdateMany}from"./lifecycle/update-many.js";import{runComments}from"./comments.js";import{runNotes}from"./notes.js";import{runLearnings}from"./learnings.js";import{runUpgrade}from"./governance/upgrade.js";import{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES}from"./lifecycle/plan.js";export*from"./define.js";import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate}from"./runtime.js";import{extensionMigrate,packageMigrate}from"./package-migrations.js";import{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate}from"./runtime.js";import{runStats}from"./stats.js";import{readImprovementLedger,recordImprovementObservation}from"./improvement-ledger.js";import{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics}from"./history-analytics.js";import{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval}from"./eval.js";import{runTelemetry,TELEMETRY_SUBCOMMANDS}from"./telemetry.js";import{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight}from"./test/execution.js";import{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./test/measurements.js";import{runTestAll}from"./test/batch.js";import{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./test/parsers.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch}from"./test/trust.js";import{runStartBackgroundRun,runTestRunsWorker}from"./test/runs.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";export*from"./authoring.js";export*from"./governance.js";export*from"./mcp/discovery.js";export*from"./query.js";export*from"./testing.js";export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,BASELINE_ITEM_FORMAT_VERSION,BUILTIN_CORPUS_SHAPES,BUILTIN_ITEM_TYPE_VALUES,BUILTIN_PROFILES,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIDENCE_TEXT_VALUES,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTEXT_OUTPUT_VALUES,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_EVAL_QUERIES_RELATIVE_PATH,DELETE_FLAG_CONTRACTS,DEPENDENCY_KIND_VALUES,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,EVENTS_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EXECUTABLE_COMMAND_ALIASES,EXIT_CODE,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_EVENT_CLASSIFICATION_VERSION,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,INIT_AGENT_GUIDANCE_MODE_VALUES,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ISSUE_SEVERITY_VALUES,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,ITEM_TYPE_VALUES,LEARNINGS_FLAG_CONTRACTS,LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MAINTENANCE_HISTORY_OPERATIONS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,MERGE_SUBCOMMAND_VALUES,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NEXT_OUTPUT_VALUES,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_CLI_EXPECTED_ERROR_NAME,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_COMMAND_ALIAS_CONTRACTS,PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES,PM_CORPUS_SHAPE_SCHEMA,PM_DEPRECATED_TOOL_ACTIONS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXACT_COVERAGE_METRICS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_GITIGNORE_END,PM_GITIGNORE_START,PM_HISTORY_COMMAND_ALIASES,PM_ITEM_ACTION_SUBCOMMANDS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,PM_MUTATION_ACTION_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_PACKAGE_RESOURCE_KINDS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_RELOCATED_COMMAND_ALIASES,PM_REPRODUCIBLE_PROCESS_ENV,PM_TOOL_ACTIONS,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,PM_WORKSPACE_RECIPE_SCHEMA,PROFILE_FLAG_CONTRACTS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,PROFILE_SUBCOMMANDS,PmCliError,PmClient,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESERVED_ITEM_FIELD_NAMES,RESTORE_FLAG_CONTRACTS,RISK_VALUES,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,SNAPSHOT_SCHEMA,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,STATUS_VALUES,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,SUBSTANTIVE_HISTORY_OPERATIONS,TELEMETRY_FLAG_CONTRACTS,TELEMETRY_SUBCOMMANDS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TEST_RUN_MEASUREMENT_LIMIT,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,WORKSPACE_SNAPSHOT_ACTIONS,_testOnly4 as _testOnly,_testOnlyConfigCommand,_testOnlyHealthCommand,_testOnly3 as _testOnlyInit,_testOnly2 as _testOnlyInitAgentGuidance,_testOnly as _testOnlyTemplates,_testOnlyValidateCommand,acknowledgeLinkedTests,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,acquireLock,aggregate,analyzePmToolActionParity,analyzeSdkActionCoverage,analyzeSdkCliParameterCompleteness,append,appendHistoryEntry,applyBootstrapPagerPolicy,applyInvocationAuthorOverride,applyPathMigrations,applyStandaloneNote,applyStoredExtensionMigrationState,artifactKey,assertInitializedTracker,assertLinkedArtifactMutationIsUnambiguous,assertReadableTrackerRoot,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,auditMergeAttributeFence,buildCorpusShapeItemPlan,buildExtensionDescribeResult,buildExtensionInstallPlan,buildMergeAttributePatterns,buildPmActionToolInputSchema,buildTrackerInitializationRecovery,canonicalDocument,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,clearWorkspaceContractsCache,close,closeItem,closeTask,coalesceRepeatedListFlags,collectPackageExtensionDirectories,comments,commitImportedItem,compactFlagAliasContracts,config,context,copy,countFailureCategories,create,createCorpusShapeMeasurement,createExtensionCommandSdk,createHistoryEntry,createPmCliExpectedError,createPmCliProgram,createPmCommandOutputBudget,createReproducibleProcessRunner,createWorkspaceSnapshot,dedupeLinkedArtifacts,defineCorpusShape,definePmCommandOutputBudget,defineWorkspaceRecipe,deleteItem,deleteWorkspaceSnapshot,deps,deriveSchemaEvolutionMigrationId,describeItemOwnershipConflict,describeProfileComposition,describeProjectProfile,diffTestRunMeasurements,discoverNearbyPmRoot,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureScope,ensureTrackerInitialized,estimatePmOutputTokens,evaluateMutationGuard,evaluateProvenanceCoverage,evaluateSimilarityGovernance,executeWorkspaceRecipe,expandAddGlobEntries,extension,extensionActivate,extensionDeactivate,extensionList,extensionMigrate,extractReferencedPmItemIdsFromCommand,files,filesDiscover,filesLookup,findCoverageDeficits,findDuplicateClusters,findGitWorkspaceRoot,findInstalledNpmPackageCandidate,findPmNamespacedCommand,findSimilarItems,flushTelemetryQueue,focus,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,formatSchemaEvolutionMigrationHuman,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getMutationActionContract,getPmGitignoreBlock,getSettingsPath,getWorkspaceContracts,graph,hasSubcommandFlagContractsForCommand,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,inferPmOutputBudgetClass,init,inspectHistoryAuthorStream,inspectStaleInProgressItems,inspectStaticExtensionInventory,inspectWorkspaceSnapshot,installMergeFence,isAlreadyClaimedError,isErrnoError,isMutationAction,isPmCliExpectedError,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,isRuntimeRecord,isTimestampLiteral,jaccardSimilarity,learnings,limitAnnotationEntries,linkedTestTrustFingerprint,lintProjectProfile,list,listAliasPluralKeys,listAllComplete,listAllItemMetadata,listBuiltinCorpusShapes,listMutationActions,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,listProfiles,listWorkspaceSnapshots,loadCreateTemplateOptions,locateItem,measureCorpusShapePlan,mergeLinkedTestTwoTokenEntries,next,normalizeAnnotationTransportOptions,normalizeBootstrapInvocation,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeLegacyExtensionActionSyntax,normalizeLinkedPath,normalizeProfileName,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageMigrate,packageReload,packageUninstall,parseAddEntries,parseAddGlobEntries,parseAnnotationTextInput,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,parseEvalQuerySet,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,parseMigrateEntries,parseRemoveEntries,parseTags,parseTestRunMeasurements,parseUnknownAuthorHistoryEventCoordinates,pathExists,pauseTask,planExtensionDirectoryCopy,planProfileApplication,planSchemaEvolutionMigration,planUnknownAuthorHistoryAcknowledgment,planWorkspaceSnapshotRestore,prepareSimilarityText,profile,profileApply,profileLint,profileList,profileShow,projectFleetAttributionAnalytics,projectPmDiagnosticOutput,projectPmDiagnosticText,projectProvenanceCoverageAnalytics,projectValidateCounts,queryTestRunMeasurementsBelow,quoteCommandArg,quoteWindowsCommandArg,readAnnotationEntries,readBooleanOption,readCsvListOption,readExtensionMigrationState,readFileIfExists,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readHistoryAnalyticsWindow,readHistorySnapshot,readImprovementLedger,readLocatedItem,readPmPackageManifest,readRequiredString,readSettings,readStringArrayFromCommanderOptions,readStringOption,recordImprovementObservation,refreshMergeAttributeFenceIfInstalled,release,removeFileIfExists,renameArtifactsResultKey,renderCalendarMarkdown,renderCalendarToon,renderExtensionDescribeMarkdown,renderGuideMarkdown,renderPmCommand,renderPmCommandAliasMigrationHint,renderPmCommandVisibilityMarkdown,reopen,resolveAnnotationIndex,resolveAnnotationInput,resolveBuiltinCorpusShape,resolveCalendarOutputFormat,resolveExtensionInstallSourceIdentity,resolveExtensionMigrationStatePath,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolveLinkedTestFailureExitCode,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,resolveMergeInstallContext,resolvePmCommandAlias,resolvePmCommandCapabilityFamily,resolvePmCommandOperation,resolvePmCommandOutputBudget,resolvePmCommandVisibilityTier,resolvePmDiagnosticOutputBudget,resolvePmHistoryOperation,resolvePmPositionalActionFlagContracts,resolvePmRoot,resolvePmToolCustomFieldCollision,resolveProfile,resolveProjectMergeTypeFolders,resolveReproducibleProcessEnvironment,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveStartTaskInProgressStatus,resolveSubcommandFlagContractsForCommand,resolveUnknownAuthorAcknowledgmentSelector,restore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runAnnotationCommand,runAppend,runCalendar,runClaim,runClaimNext,runClose,runCloseMany,runCloseTask,runComments,runCompletion,runConfig,runContext,runCopy,runCreate,runDelete,runDeps,runDocs,runEval,runEvent,runExtension,runExtensionMigrateAction,runExtensionMigrations,runFiles,runFilesDiscover,runFilesLookup,runFleetAttributionAnalytics,runFocus,runGc,runGet,runGuide,runHealth,runInit,runInitAgentGuidance,runLearnings,runLinkedArtifacts,runLinkedTests,runList,runMeet,runMergeInstall,runNext,runNotes,runPauseTask,runPlan,runProfileApply,runProfileLint,runProfileList,runProfileShow,runProvenanceCoverageAnalytics,runReindex,runRelease,runRemind,runRestore,runSchemaEvolutionMigration,runSearch,runSearchRefreshWorkerEntrypoint,runStartBackgroundRun,runStartTask,runStats,runTelemetry,runTemplatesList,runTemplatesSave,runTemplatesShow,runTest,runTestAll,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker,runUpdate,runUpdateMany,runUpgrade,runValidate,runWithActiveExtensions,runWithReproducibleProcessEnvironment,runWithWorkspaceRecipe,scanHistoryAuthorAttribution,scanItemFormatVersions,scanMutationSecrets,scanStaleInProgressItems,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,scorePreparedItemSimilarity,search,selectImportAuthor,serializeItemDocument,similarityAdvisoryWarnings,sortLinkedArtifacts,splitFrontMatter,startTask,stats,stripGlobalBootstrapTokens,summarizeContextPreflight,summarizeInitResult,toCompletionFlagString,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,validateLinkedPaths,verifyToolOptionCliParity,withFlagAliasMetadata,wrapOwnershipConflict,writeFileAtomic};
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @module sdk/lifecycle/plan-mutation-receipt
3
+ * Bounded mutation acknowledgements; full Plan state remains a separate read.
4
+ */
5
+ import type { PlanCommandResult, PlanStepSummary, PlanSubcommand } from "./plan.js";
6
+ import type { PlanMode, PlanStepStatus } from "../../types/index.js";
7
+ /** Stable mutation facts whose size does not grow with unrelated Plan content. */
8
+ export interface PlanMutationReceipt {
9
+ /** Discriminator used by CLI and MCP mutation projection. */
10
+ kind: "plan_mutation";
11
+ /** Operation that completed successfully. */
12
+ action: PlanSubcommand;
13
+ /** Persisted Plan identifier. */
14
+ id: string;
15
+ /** Persisted item lifecycle state. */
16
+ status: string;
17
+ /** Persisted execution mode. */
18
+ mode: PlanMode;
19
+ /** Counts over the complete persisted step collection. */
20
+ steps_summary: PlanStepSummary;
21
+ /** Affected step identity when the operation returns a step. */
22
+ step?: Pick<NonNullable<PlanCommandResult["step"]>, "id" | "order"> & {
23
+ status: PlanStepStatus;
24
+ };
25
+ /** Number of items created by this materialization. */
26
+ materialized_count: number;
27
+ /** Number of already completed or materialized steps skipped. */
28
+ skipped_count: number;
29
+ /** Number of warnings in the full SDK result. */
30
+ warning_count: number;
31
+ /** Up to three warning previews, each bounded to 160 characters. */
32
+ warnings: string[];
33
+ /** Whether any warning content is absent from the previews. */
34
+ warnings_truncated: boolean;
35
+ /** First applicable next action, falling back to read-only inspection. */
36
+ next_action: string;
37
+ /** Read-only recovery for complete steps, evidence and resume context. */
38
+ inspection_command: string;
39
+ /** Explicitly declares that this acknowledgement is not complete Plan state. */
40
+ omission_receipt: {
41
+ /** Full Plan content is intentionally withheld. */
42
+ has_omissions: true;
43
+ /** Projection group count. */
44
+ omitted_field_group_count: 1;
45
+ /** Named omitted group and its safe read-only recovery. */
46
+ omitted_field_groups: {
47
+ name: "plan_detail";
48
+ restore_with: string;
49
+ }[];
50
+ };
51
+ }
52
+ /** Project completed work; omit the root for MCP recovery in the caller's existing workspace context. */
53
+ export declare function buildPlanMutationReceipt(result: PlanCommandResult, pmRoot: string | undefined): PlanMutationReceipt;
@@ -0,0 +1,2 @@
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="fc60339e-561c-5ac3-bdb3-116bd55e35b5")}catch(e2){}})();import{quoteCommandArg,renderPmCommand}from"../command-line.js";function buildPlanMutationReceipt(result,pmRoot){const inspectionCommand=renderPmCommand(["plan","show",result.plan.id,"--depth","deep",...pmRoot===void 0?[]:["--pm-path",pmRoot]]);return{kind:"plan_mutation",action:result.action,id:result.plan.id,status:result.plan.status,mode:result.plan.mode,steps_summary:result.plan.steps_summary,...result.step===void 0?{}:{step:{id:result.step.id,order:result.step.order,status:result.step.status}},materialized_count:result.materialized?.length??0,skipped_count:result.materialize_skipped?.length??0,warning_count:result.warnings.length,warnings:result.warnings.slice(0,3).map(warning=>warning.slice(0,160)),warnings_truncated:result.warnings.length>3||result.warnings.some(warning=>warning.length>160),next_action:result.next_actions?.[0]===void 0?inspectionCommand:pmRoot===void 0?result.next_actions[0]:`${result.next_actions[0]} --pm-path ${quoteCommandArg(pmRoot)}`,inspection_command:inspectionCommand,omission_receipt:{has_omissions:true,omitted_field_group_count:1,omitted_field_groups:[{name:"plan_detail",restore_with:inspectionCommand}]}}}export{buildPlanMutationReceipt};
2
+ //# sourceMappingURL=plan-mutation-receipt.js.map
@@ -1,6 +1,7 @@
1
1
  import { type GlobalOptions } from "../runtime-primitives.js";
2
2
  import type { DependencyKind, ItemMetadata, PlanDecision, PlanDiscovery, PlanHarness, PlanMode, PlanStep, PlanStepStatus, PlanValidationCheck } from "../../types/index.js";
3
3
  import type { MutationMetadataCommandOptions, SharedLinkedResourceOptions } from "./mutation-command-options.js";
4
+ import { type PlanMutationReceipt } from "./plan-mutation-receipt.js";
4
5
  /** Public contract for plan subcommands, shared by SDK and presentation-layer consumers. */
5
6
  export declare const PLAN_SUBCOMMANDS: readonly ["create", "show", "add-step", "update-step", "complete-step", "block-step", "reorder-step", "remove-step", "link", "unlink", "decision", "discovery", "validation", "resume", "approve", "materialize"];
6
7
  /** Restricts plan subcommand values accepted by command, SDK, and storage contracts. */
@@ -126,6 +127,8 @@ export interface PlanCommandOptions extends Omit<MutationMetadataCommandOptions,
126
127
  export type PlanOperationOptions = PlanCommandOptions;
127
128
  /** Documents the plan command result payload exchanged by command, SDK, and package integrations. */
128
129
  export interface PlanCommandResult {
130
+ /** Bounded acknowledgement for mutations; full typed Plan state remains available alongside it. */
131
+ mutation_receipt?: PlanMutationReceipt;
129
132
  /** Value that configures or reports action for this contract. */
130
133
  action: PlanSubcommand;
131
134
  /** Value that configures or reports plan for this contract. */
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="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};
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]="d9a4fa9f-2f70-5ce9-b9c0-24e58b120420")}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";import{buildPlanMutationReceipt}from"./plan-mutation-receipt.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,resultStep}=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,step:resultStep,next_actions:nextActionsFor(itemId,plan),warnings:[],generated_at:nowIso()}}async function planRemoveStep(id,options,ctx,stepRef){const{document,itemId,resultStep}=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],resultStep:step}}});const plan=projectPlan(document.metadata,"standard");return{action:"remove-step",plan,step:resultStep,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);const result=await resolvePlanDispatcher(normalizedInput.subcommand)(normalizedInput,ctx);return result.action==="show"?result:{...result,mutation_receipt:buildPlanMutationReceipt(result,ctx.pmRoot)}}const _testOnlyPlanCommand={changedPlanMetadataFields};export{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,_testOnlyPlanCommand,resolvePlanTemplateSteps,runPlan};
2
2
  //# sourceMappingURL=plan.js.map
@@ -11,6 +11,8 @@ export interface UpdateCommandOptions extends MutationMetadataCommandOptions, Sh
11
11
  description?: string;
12
12
  /** Value that configures or reports body for this contract. */
13
13
  body?: string;
14
+ /** Persisted annotations in a full-item JSON round trip, checked under the item lock. */
15
+ documentAnnotationSnapshot?: Partial<Record<"comments" | "notes" | "learnings", unknown[]>>;
14
16
  /** Lifecycle state reported for status. */
15
17
  status?: string;
16
18
  /** Value that configures or reports close reason for this contract. */