@unbrained/pm-cli 2026.10.24 → 2026.10.26

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 (222) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +48 -0
  3. package/dist/cli/error-guidance.d.ts +5 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/extension-command-help.js +2 -2
  6. package/dist/cli/register-history-activity.js +1 -1
  7. package/dist/cli/register-mutation.js +2 -2
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-25MTQAHX.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-57YPOOED.js +2 -0
  11. package/dist/cli-bundle/chunks/{chunk-YEI4N4A6.js → chunk-7UDQAINZ.js} +22 -22
  12. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-ER7RLJW5.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-CSE47ZAN.js → chunk-MWCG25PO.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-N6FTEILW.js +20 -0
  15. package/dist/cli-bundle/chunks/{chunk-CDR5ES7Q.js → chunk-NGKTROAO.js} +90 -86
  16. package/dist/cli-bundle/chunks/chunk-OCDRHIVQ.js +6 -0
  17. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-ONC4BBQP.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-URZB3USE.js → chunk-OUDR2HWR.js} +42 -42
  19. package/dist/cli-bundle/chunks/{chunk-FASDGYQC.js → chunk-T7T4WLUY.js} +3 -3
  20. package/dist/cli-bundle/chunks/{chunk-Z62RXNHW.js → chunk-TGOG5BFM.js} +2 -2
  21. package/dist/cli-bundle/chunks/chunk-UF6EXZSP.js +2 -0
  22. package/dist/cli-bundle/chunks/chunk-VS2IIV3F.js +128 -0
  23. package/dist/cli-bundle/chunks/chunk-XAIR53QZ.js +2 -0
  24. package/dist/cli-bundle/chunks/{chunk-VSSHB6XI.js → chunk-Y42DYMZX.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-MA7SNKYK.js → chunk-YJBIPNDL.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-4PNAUT2E.js → chunk-Z35XAHUN.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-ZLVFUZI4.js +30 -0
  28. package/dist/cli-bundle/chunks/{chunk-3VI4XDP2.js → chunk-ZT64RDMF.js} +2 -2
  29. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-NWQIDTH7.js} +2 -2
  30. package/dist/cli-bundle/chunks/{mutation-admission-NVTBZ7DH.js → mutation-admission-VTNV6JV2.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-list-query-2FE6K7FQ.js → register-list-query-LZDWUZS4.js} +3 -3
  32. package/dist/cli-bundle/chunks/register-mutation-M2A7PH42.js +20 -0
  33. package/dist/cli-bundle/chunks/register-operations-E7P2JTXM.js +2 -0
  34. package/dist/cli-bundle/chunks/{register-setup-P3VLCTDY.js → register-setup-DOV7KGSH.js} +2 -2
  35. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-SVD6CO7U.js} +2 -2
  36. package/dist/cli-bundle/chunks/stage-LYLEOAQB.js +2 -0
  37. package/dist/cli-bundle/focused-chunks/chunk-226XKW3W.js +8 -0
  38. package/dist/cli-bundle/focused-chunks/chunk-ABMNYWV6.js +2 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-RSEGFZTY.js → chunk-ADSBGYLW.js} +54 -54
  40. package/dist/cli-bundle/focused-chunks/{chunk-JYXA4JIP.js → chunk-B266DDBJ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-BH7RE2ZY.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-BL77VCRB.js +22 -0
  43. package/dist/cli-bundle/focused-chunks/chunk-CSCZYSNZ.js +2 -0
  44. package/dist/cli-bundle/focused-chunks/{chunk-6HJCSHBG.js → chunk-D5YQ4KAE.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-TAHSXKAT.js → chunk-E5C24MCV.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-SHUPX6G2.js → chunk-I7H3XF25.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-IF6C43IP.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-KERJNFXY.js +2 -0
  49. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-KTXU5WU6.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/chunk-NE27VCU7.js +91 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-NFN2P4TW.js +2 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-7RQOFHMH.js → chunk-NLZUI234.js} +4 -4
  53. package/dist/cli-bundle/focused-chunks/chunk-PK5FJIVA.js +12 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-IUAYTD2S.js → chunk-UHWTPOM4.js} +24 -24
  55. package/dist/cli-bundle/focused-chunks/{chunk-ES2NGVHZ.js → chunk-UP765R2V.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-POLMFGPQ.js → chunk-WDWHUJQW.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-NX7TVNUM.js → chunk-YQKLKRMW.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/chunk-YTEC2EPM.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-RVUGTIIU.js → chunk-YW5GHQN2.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YFDNGHCM.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{mutation-admission-PB6YFY7S.js → mutation-admission-L42E3U5U.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-3CADO4XZ.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/stage-TUQHWU7N.js +2 -0
  64. package/dist/cli-bundle/main.js +19 -19
  65. package/dist/cli-bundle/sdk-authoring.js +1 -1
  66. package/dist/cli-bundle/sdk-contracts.js +2 -2
  67. package/dist/cli-bundle/sdk-core.js +23 -23
  68. package/dist/cli-bundle/sdk-governance.js +1 -1
  69. package/dist/cli-bundle/sdk-graph.js +1 -1
  70. package/dist/cli-bundle/sdk-merge.js +57 -58
  71. package/dist/cli-bundle/sdk-query.js +1 -1
  72. package/dist/cli-bundle/sdk-runtime.js +1 -1
  73. package/dist/cli-bundle/sdk-testing.js +1 -1
  74. package/dist/cli-bundle/sdk.js +9 -9
  75. package/dist/core/diagnostics/remediation.js +1 -1
  76. package/dist/core/extensions/extension-types.d.ts +3 -0
  77. package/dist/core/extensions/extension-types.js +1 -1
  78. package/dist/core/output/mutation-projection.js +1 -1
  79. package/dist/core/policy/workflow-policy-store.js +1 -1
  80. package/dist/core/shared/errors.d.ts +22 -0
  81. package/dist/core/shared/errors.js +1 -1
  82. package/dist/core/shared/secret-rules.d.ts +17 -0
  83. package/dist/core/shared/secret-rules.js +2 -1
  84. package/dist/core/store/item-mutation-precondition.d.ts +8 -0
  85. package/dist/core/store/item-mutation-precondition.js +1 -1
  86. package/dist/core/store/item-store.js +1 -1
  87. package/dist/core/store/settings.js +2 -2
  88. package/dist/sdk/agent/command-recovery.js +1 -1
  89. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  90. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  91. package/dist/sdk/cli-contracts/completeness.js +1 -1
  92. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  93. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  94. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  95. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  96. package/dist/sdk/cli-contracts/registration-helpers.d.ts +3 -1
  97. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  98. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  99. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +4 -0
  100. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  101. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  102. package/dist/sdk/cli-contracts/tool-schema.d.ts +2 -2
  103. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  104. package/dist/sdk/completion/fish.js +3 -1
  105. package/dist/sdk/completion/zsh.js +3 -1
  106. package/dist/sdk/context-signal-store.js +2 -2
  107. package/dist/sdk/core.d.ts +1 -1
  108. package/dist/sdk/core.js +1 -1
  109. package/dist/sdk/extension-command-context.js +2 -2
  110. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  111. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  112. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  113. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  114. package/dist/sdk/governance/health.js +1 -1
  115. package/dist/sdk/index.d.ts +3 -2
  116. package/dist/sdk/index.js +1 -1
  117. package/dist/sdk/item-transaction.js +1 -1
  118. package/dist/sdk/lifecycle/close-many.d.ts +3 -0
  119. package/dist/sdk/lifecycle/close-many.js +1 -1
  120. package/dist/sdk/lifecycle/close.d.ts +3 -1
  121. package/dist/sdk/lifecycle/close.js +1 -1
  122. package/dist/sdk/lifecycle/create.d.ts +2 -0
  123. package/dist/sdk/lifecycle/create.js +1 -1
  124. package/dist/sdk/lifecycle/plan.d.ts +2 -0
  125. package/dist/sdk/lifecycle/plan.js +1 -1
  126. package/dist/sdk/lifecycle/restore.js +1 -1
  127. package/dist/sdk/lifecycle-policy.d.ts +11 -0
  128. package/dist/sdk/lifecycle-policy.js +1 -1
  129. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  130. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  131. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  132. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  133. package/dist/sdk/merge/stage.js +1 -1
  134. package/dist/sdk/merge/three-way.js +1 -1
  135. package/dist/sdk/mutation-guard.d.ts +6 -1
  136. package/dist/sdk/mutation-guard.js +1 -1
  137. package/dist/sdk/output/fit-envelope.d.ts +98 -0
  138. package/dist/sdk/output/fit-envelope.js +2 -0
  139. package/dist/sdk/public-surface.json +1 -1
  140. package/dist/sdk/query/activity.d.ts +14 -2
  141. package/dist/sdk/query/activity.js +1 -1
  142. package/dist/sdk/query/calendar.d.ts +16 -0
  143. package/dist/sdk/query/calendar.js +3 -3
  144. package/dist/sdk/query/context.js +2 -2
  145. package/dist/sdk/query/get.js +1 -1
  146. package/dist/sdk/query/list.js +1 -1
  147. package/dist/sdk/query/search-contracts.js +1 -1
  148. package/dist/sdk/query/window-pagination.d.ts +20 -0
  149. package/dist/sdk/query/window-pagination.js +2 -0
  150. package/dist/sdk/query.d.ts +1 -0
  151. package/dist/sdk/query.js +1 -1
  152. package/dist/sdk/read-output-contracts.js +1 -1
  153. package/dist/sdk/read-output-session.d.ts +1 -1
  154. package/dist/sdk/read-output-session.js +1 -1
  155. package/dist/sdk/runtime-input.js +1 -1
  156. package/dist/sdk/runtime-primitives.d.ts +1 -1
  157. package/dist/sdk/runtime-primitives.js +1 -1
  158. package/dist/sdk/runtime.d.ts +3 -3
  159. package/dist/sdk/runtime.js +1 -1
  160. package/dist/sdk/scheduling-shortcuts.d.ts +2 -0
  161. package/dist/sdk/scheduling-shortcuts.js +1 -1
  162. package/dist/sdk/schema-migration.js +2 -2
  163. package/dist/sdk/templates.d.ts +7 -1
  164. package/dist/sdk/templates.js +2 -2
  165. package/dist/sdk/workspace-transaction.d.ts +3 -1
  166. package/dist/sdk/workspace-transaction.js +2 -2
  167. package/docs/COMMANDS.md +21 -2
  168. package/docs/EXTENSIONS.md +1 -1
  169. package/docs/MERGE_SAFETY.md +28 -0
  170. package/docs/MUTATION_INTEGRITY.md +33 -0
  171. package/docs/QUALITY_EVIDENCE.md +9 -0
  172. package/docs/READ_OUTPUT_CONTRACTS.md +55 -1
  173. package/docs/SDK.md +173 -12
  174. package/docs/WORKFLOW_POLICIES.md +14 -1
  175. package/docs/agent-task-token-baseline.json +1 -1
  176. package/docs/agent-task-transcripts.json +1 -1
  177. package/docs/generated/FLAG_LEXICON_BUDGETS.md +4 -4
  178. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  179. package/marketplace.json +1 -1
  180. package/package.json +1 -1
  181. package/packages/pm-beads/package.json +1 -1
  182. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  183. package/packages/pm-calendar/extensions/calendar/shortcuts.ts +2 -2
  184. package/packages/pm-calendar/package.json +1 -1
  185. package/packages/pm-command-kit/package.json +1 -1
  186. package/packages/pm-digital-twin/package.json +1 -1
  187. package/packages/pm-governance-audit/package.json +1 -1
  188. package/packages/pm-guide-shell/package.json +1 -1
  189. package/packages/pm-kanban/package.json +1 -1
  190. package/packages/pm-lifecycle-hooks/package.json +1 -1
  191. package/packages/pm-linked-test-adapters/package.json +1 -1
  192. package/packages/pm-search-advanced/package.json +1 -1
  193. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  194. package/packages/pm-templates/package.json +1 -1
  195. package/packages/pm-todos/package.json +1 -1
  196. package/packages/pm-vcs/package.json +1 -1
  197. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  198. package/plugins/pm-claude/package.json +1 -1
  199. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  200. package/plugins/pm-codex/package.json +1 -1
  201. package/plugins/pm-codex/plugin.json +1 -1
  202. package/runtime-dependencies.json +1 -1
  203. package/dist/cli-bundle/chunks/chunk-CNEUJHA4.js +0 -2
  204. package/dist/cli-bundle/chunks/chunk-HZNFNETE.js +0 -127
  205. package/dist/cli-bundle/chunks/chunk-KGZGXC7T.js +0 -30
  206. package/dist/cli-bundle/chunks/chunk-TZYQ4JDZ.js +0 -6
  207. package/dist/cli-bundle/chunks/chunk-UY5UHI4I.js +0 -2
  208. package/dist/cli-bundle/chunks/chunk-VPMQEVU6.js +0 -20
  209. package/dist/cli-bundle/chunks/register-mutation-KZXQUZUH.js +0 -20
  210. package/dist/cli-bundle/chunks/register-operations-BOCBWNKJ.js +0 -2
  211. package/dist/cli-bundle/chunks/stage-WRDTMCCF.js +0 -2
  212. package/dist/cli-bundle/focused-chunks/chunk-3QYTS4OY.js +0 -12
  213. package/dist/cli-bundle/focused-chunks/chunk-5MKNVJCM.js +0 -2
  214. package/dist/cli-bundle/focused-chunks/chunk-AGCEWJ27.js +0 -21
  215. package/dist/cli-bundle/focused-chunks/chunk-CEEOWDB7.js +0 -8
  216. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-NFFPNMTH.js +0 -2
  218. package/dist/cli-bundle/focused-chunks/chunk-SBJ2IKTH.js +0 -3
  219. package/dist/cli-bundle/focused-chunks/chunk-X5YRJMAY.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-ZMWLV2CE.js +0 -91
  222. package/dist/cli-bundle/focused-chunks/stage-MQE4PFWT.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="32a58612-e3d0-5164-8f1b-3f32d39ae932")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{createEmptyExtensionCommandRegistry,createEmptyExtensionHookRegistry,createEmptyExtensionParserRegistry,createEmptyExtensionPreflightRegistry,createEmptyExtensionRegistrationRegistry,createEmptyExtensionRendererRegistry,createEmptyExtensionServiceRegistry}from"../core/extensions/extension-registries.js";import{activateExtensions,deactivateExtensions,loadExtensions,runActiveCommandHandler,runWithIsolatedExtensionRuntime,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{pathExists}from"../core/fs/fs-utils.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{HOISTED_ACTION_OPTION_KEYS}from"./runtime-input.js";import{createAsyncReadWriteGate}from"../core/shared/serial-queue.js";import{getSettingsPath,resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{PM_TOOL_ACTIONS}from"./cli-contracts/enum-contracts.js";import{runContracts}from"./cli-contracts/runtime-contracts.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{runWithDiscoveredContextIntentContracts}from"./context-intent-runtime.js";import{finalizeContextUsageEgress}from"./context/usage-egress.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{INIT_INVOCATION_CWD}from"./init.js";import{certifyCompleteListResult,createCompleteListOptions}from"./query/complete-list.js";import{listClientItemMetadataLight}from"./query/light-metadata.js";import{normalizeReadOutputIncludeModeOptions,validateReadOutputOptions}from"./read-output-contracts.js";import{SDK_ACTION_ALIASES}from"./runtime-action-aliases.js";import{closeManyOptionsFromFlat,extensionOptionsFromArgs,actionGlobalOptions as globalOptions,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,readRuntimeScalarString as readScalarString,readRuntimeScalarStringAllowBlank as readScalarStringAllowBlank,readRuntimeString as readString,readRuntimeStringArray as readStringArray,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"./runtime-input.js";import{SDK_ACTION_HANDLERS}from"./runtime/actions.js";import{getOwnHandler,readRequiredString}from"./runtime/context.js";import{clearWorkspaceContractsCache}from"./workspace-contracts-cache.js";import{PM_GITIGNORE_END,PM_GITIGNORE_START,ensurePmGitignore,getPmGitignoreBlock}from"./workspace.js";import{SEARCH_EXTENSION_FLAG_DEFINITIONS}from"./extension-contracts.js";export*from"./cli-contracts/agent-output-contracts.js";import{PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult as certifyCompleteListResult2,createCompleteListOptions as createCompleteListOptions2,inspectCompleteListResult}from"./query/complete-list.js";import{getWorkspaceContracts}from"./query/workspace-contracts.js";import{clearWorkspaceContractsCache as clearWorkspaceContractsCache2}from"./workspace-contracts-cache.js";export*from"./governance/workflow-policy.js";import{runCloseTask,runPauseTask,runStartTask}from"./lifecycle/task-composition.js";import{getActiveExtensionRegistrations,runActiveOnReadHooks,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists as pathExists2,readFileIfExists,removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,classifyHistoryEvent}from"../core/history/event-classification.js";import{generateItemId,normalizeItemId,normalizeRawItemId}from"../core/item/id.js";import{readBooleanOption,readCsvListOption,readStringOption}from"./package-runtime-options.js";import{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isPmCliExpectedError}from"./errors.js";import{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString}from"./package-import-adapters.js";import{canonicalDocument,normalizeItemMetadata,serializeItemDocument,splitFrontMatter}from"../core/item/item-format.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,scanItemFormatVersions}from"../core/item/item-format-version.js";import{parseTags}from"../core/item/parse.js";import{isTerminalStatus,normalizeStatusInput}from"../core/item/status.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{acquireLock,acquireLockLease}from"../core/lock/lock.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{PmCliError as PmCliError2}from"../core/shared/errors.js";import{isTimestampLiteral,nowIso}from"../core/shared/time.js";import{jaccardSimilarity,normalizeSimilarityText,scoreItemSimilarity,tokenizeSimilarityText}from"./similarity-scoring.js";import{listAllItemMetadata,listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{getHistoryPath,getItemPath,getSettingsPath as getSettingsPath2,resolveImplicitPmRoot,resolvePmRoot as resolvePmRoot2}from"../core/store/paths.js";import{readSettings as readSettings2}from"../core/store/settings.js";import{runAggregate}from"./query/aggregate.js";import{CONTEXT_OUTPUT_VALUES,runContext}from"./query/context.js";import{runGet}from"./query/get.js";import{runList}from"./query/list.js";import{closeItem,runClose}from"./lifecycle/close.js";import{runCopy}from"./lifecycle/copy.js";import{runDelete}from"./lifecycle/delete.js";import{runFocus}from"./lifecycle/focus.js";import{runRestore}from"./lifecycle/restore.js";import{DEFAULT_TERMINAL_TRANSITION_POLICY,applyTerminalOrderingPolicy,requireTerminalReason,resolveTerminalReason}from"./lifecycle-policy.js";import{runUpdate}from"./lifecycle/update.js";import{runReopen}from"./lifecycle/reopen.js";import{NEXT_OUTPUT_VALUES,runNext}from"./query/next.js";import{runSearch}from"./query/search.js";import{runStats}from"./stats.js";import{runDuplicates}from"./duplicates.js";import{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar}from"./query/calendar.js";import{renderGuideMarkdown,resolveGuideOutputFormat,runGuide}from"./guide.js";import{runCompletion}from"./completion.js";import{runReindex}from"./governance/reindex.js";import{loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow}from"./templates.js";import{runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop}from"./test/runs.js";import{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,DEPENDENCY_KIND_VALUES,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,RISK_VALUES,STATUS_VALUES}from"../types/index.js";const ACTIVE_EXTENSION_HOST_CONTEXT=Symbol("pm.active-extension-host-context");function splitFullClientMutationOptions(options){return{fullChangedFields:!0,options}}class PmClient{defaults;constructor(options={}){this.defaults={...options.pmRoot===void 0?{}:{path:options.pmRoot},...options.cwd===void 0?{}:{cwd:options.cwd},...options.author===void 0?{}:{author:options.author},...options.noExtensions===void 0?{}:{noExtensions:options.noExtensions}}}static forActiveExtensionHost(options){const client=new PmClient({...options,noExtensions:!0});return client.defaults[ACTIVE_EXTENSION_HOST_CONTEXT]=!0,client}run(action,args={}){return runAction({...this.defaults,...args,action})}runTyped(action,args={}){return this.run(action,args)}context(options={}){return this.runTyped("context",{options})}listAllItemMetadataLight(){return listClientItemMetadataLight(this.defaults.path,this.defaults.cwd)}list(options={}){return this.runTyped("list",{options})}async listAllComplete(options={}){return certifyCompleteListResult(await this.list(createCompleteListOptions(options)))}search(query,options={}){return this.runTyped("search",{query,options})}get(id,options={}){return this.runTyped("get",{id,options})}next(options={}){return this.runTyped("next",{options})}aggregate(options={}){return this.runTyped("aggregate",{options})}stats(options={}){return this.runTyped("stats",{options})}duplicates(options={}){return this.runTyped("duplicates",{options})}comments(id,options={}){return this.runTyped("comments",{id,options})}notes(id,options={}){return this.runTyped("notes",{id,options})}learnings(id,options={}){return this.runTyped("learnings",{id,options})}files(id,options={}){return this.runTyped("files",{id,options})}filesDiscover(id,options={}){return this.runTyped("files-discover",{id,options})}filesLookup(options){return this.runTyped("files-lookup",{options})}docs(id,options={}){return this.runTyped("docs",{id,options})}deps(id,options={}){return this.runTyped("deps",{id,options})}graph(subcommand,ids={},options={}){return this.runTyped("graph",{subcommand,...ids,options})}append(id,body,options={}){return this.runTyped("append",{id,...splitFullClientMutationOptions(mutationOptionsWithOverrides(options,{body}))})}init(prefix,options={}){return this.runTyped("init",{...prefix===void 0?{}:{prefix},options})}config(scope,configAction,key,value,options={}){return this.runTyped("config",{scope,configAction,...key===void 0?{}:{key},...value===void 0?{}:{value},options})}schema(subcommand,options={}){return this.runTyped("schema",{options:{...options,subcommand}})}workflowPolicy(action,name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:action}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(name){return this.runTyped("schema",{name,options:{subcommand:"show"}})}schemaAddType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-type"}})}schemaRemoveType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-type"}})}schemaAddStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-status"}})}schemaRemoveStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-status"}})}schemaAddField(name,options={}){const{type,...mutationOptions}=options;return this.runTyped("schema",{name,options:{...mutationOptions,fieldType:type,subcommand:"add-field"}})}schemaRemoveField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(name){return this.runTyped("schema",{name,options:{subcommand:"show-field"}})}schemaApplyPreset(typePreset,options={}){return this.runTyped("schema",{typePreset,options:{...options,subcommand:"apply-preset"}})}schemaInferTypes(options={}){return this.runTyped("schema",{options:{...options,subcommand:"add-type",infer:!0}})}schemaRenameType(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-type",to}})}schemaRenameField(from,to,options,type){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-field",to,...type?{fieldTypeScope:type}:{}}})}schemaRemapStatus(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"remap-status",to}})}schemaShowStatus(name){return this.runTyped("schema",{name,options:{subcommand:"show-status"}})}profile(subcommand,options={}){return this.runTyped("profile",{options:{...options,subcommand}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(name){return this.runTyped("profile",{name,options:{subcommand:"show"}})}profileApply(name,options={}){return this.runTyped("profile",{name,options:{...options,subcommand:"apply"}})}profileLint(name){return this.runTyped("profile",{name,options:{subcommand:"lint"}})}validate(options={}){return this.runTyped("validate",{options})}health(options={}){return this.runTyped("health",{options})}gc(options={}){return this.runTyped("gc",{options})}assurance(input){return this.runTyped("assurance",{options:{...input,subcommand:input.action}})}historyRedact(id,options){return this.runTyped("history-redact",{id,options})}historyRepair(id,options={}){return this.runTyped("history-repair",{id,options})}historyRepairAll(options={}){return this.runTyped("history-repair",{options:{...options,all:!0}})}historyAttest(options={}){return this.runTyped("history-attest",{options})}historyCompact(id,options={}){return this.runTyped("history-compact",{id,options})}historyCompactBulk(options){return this.runTyped("history-compact",{options})}historyAuthorAcknowledge(options){return this.runTyped("history-author-acknowledge",{historyEvent:(options.events??[]).map(event=>`${event.item_id}:${String(event.line)}`),allActionable:options.all_actionable===!0,dryRun:options.dry_run===!0,planFingerprint:options.plan_fingerprint,limit:options.coordinate_limit,attributedAuthor:options.attributed_author,reviewer:options.reviewer,reason:options.reason})}plan(subcommand,id,options={},stepRef,reorderTo){return this.runTyped("plan",{fullChangedFields:!0,...id===void 0?{}:{id},...stepRef===void 0?{}:{stepRef},...reorderTo===void 0?{}:{reorderTo},options:mutationOptionsWithOverrides(options,{subcommand})})}planCreate(options){return this.plan("create",void 0,options)}planShow(id,options={}){return this.plan("show",id,options)}planAddStep(id,options){return this.plan("add-step",id,options)}planUpdateStep(id,stepRef,options){return this.plan("update-step",id,options,stepRef)}planCompleteStep(id,stepRef,options={}){return this.plan("complete-step",id,options,stepRef)}planBlockStep(id,stepRef,options){return this.plan("block-step",id,options,stepRef)}planReorderStep(id,stepRef,reorderTo,options={}){return this.plan("reorder-step",id,options,stepRef,reorderTo)}planRemoveStep(id,stepRef,options={}){return this.plan("remove-step",id,options,stepRef)}planLink(id,stepRef,options){return this.plan("link",id,options,stepRef)}planUnlink(id,stepRef,options){return this.plan("unlink",id,options,stepRef)}planDecision(id,options){return this.plan("decision",id,options)}planDiscovery(id,options){return this.plan("discovery",id,options)}planValidation(id,options){return this.plan("validation",id,options)}planResume(id,options){return this.plan("resume",id,options)}planApprove(id,options={}){return this.plan("approve",id,options)}planMaterialize(id,options){return this.plan("materialize",id,options)}create(options={}){return this.runTyped("create",splitFullClientMutationOptions(options))}update(id,options={}){return this.runTyped("update",{id,...splitFullClientMutationOptions(options)})}reopen(id,reason,options={}){return this.runTyped("item-reopen",{id,reason,fullChangedFields:!0,options})}close(id,reason,options={}){return this.runTyped("close",{id,reason,...splitFullClientMutationOptions(options)})}claim(id,options={}){return this.runTyped("claim",{id,...splitFullClientMutationOptions(options)})}claimNext(options={}){return this.runTyped("claim",{next:!0,...splitFullClientMutationOptions(options)})}release(id,options={}){return this.runTyped("release",{id,...splitFullClientMutationOptions(options)})}copy(id,options={}){return this.runTyped("copy",{id,...splitFullClientMutationOptions(options)})}delete(id,options={}){return this.runTyped("delete",{id,...splitFullClientMutationOptions(options)})}restore(id,target,options={}){return this.runTyped("restore",{fullChangedFields:!0,id,options:{...options,target}})}focus(id,options={}){return this.runTyped("focus",{...id===void 0?{}:{id},...splitFullClientMutationOptions(options)})}startTask(id,options={}){return this.runTyped("start-task",{id,...splitFullClientMutationOptions(options)})}pauseTask(id,options={}){return this.runTyped("pause-task",{id,...splitFullClientMutationOptions(options)})}closeTask(id,reason,options={}){return this.runTyped("close-task",{id,reason,...splitFullClientMutationOptions(options)})}extension(target,options={}){return this.runTyped("extension",{...target===void 0?{}:{target},options})}extensionList(options={}){return this.extension("list",options)}extensionActivate(target,options={}){return this.runTyped("extension-activate",{target,options})}extensionDeactivate(target,options={}){return this.runTyped("extension-deactivate",{target,options})}package(target,options={}){return this.runTyped("package",{...target===void 0?{}:{target},options:{...options,vocabulary:"package"}})}packageList(options={}){return this.package("list",options)}packageInstall(target,options={}){return this.runTyped("package-install",{target,options})}packageUninstall(target,options={}){return this.runTyped("package-uninstall",{target,options})}packageDoctor(options={}){return this.runTyped("package-doctor",{options})}packageManage(target,options={}){return this.runTyped("package-manage",{...target===void 0?{}:{target},options})}packageDescribe(target,options={}){return this.runTyped("package-describe",{...target===void 0?{}:{target},options})}packageReload(options={}){return this.runTyped("package-reload",{options})}packageCatalog(options={}){return this.runTyped("package-catalog",{options})}packageActivate(target,options={}){return this.runTyped("package-activate",{target,options})}packageDeactivate(target,options={}){return this.runTyped("package-deactivate",{target,options})}packageMigrate(options={}){return this.package(void 0,{...options,migrate:!0})}upgrade(target,options={}){return this.runTyped("upgrade",{...target===void 0?{}:{target},options})}}function context(options={},clientOptions={}){return new PmClient(clientOptions).context(options)}function list(options={},clientOptions={}){return new PmClient(clientOptions).list(options)}function listAllComplete(options={},clientOptions={}){return new PmClient(clientOptions).listAllComplete(options)}function search(query,options={},clientOptions={}){return new PmClient(clientOptions).search(query,options)}function get(id,options={},clientOptions={}){return new PmClient(clientOptions).get(id,options)}function next(options={},clientOptions={}){return new PmClient(clientOptions).next(options)}function aggregate(options={},clientOptions={}){return new PmClient(clientOptions).aggregate(options)}function stats(options={},clientOptions={}){return new PmClient(clientOptions).stats(options)}function duplicates(options={},clientOptions={}){return new PmClient(clientOptions).duplicates(options)}function comments(id,options={},clientOptions={}){return new PmClient(clientOptions).comments(id,options)}function notes(id,options={},clientOptions={}){return new PmClient(clientOptions).notes(id,options)}function learnings(id,options={},clientOptions={}){return new PmClient(clientOptions).learnings(id,options)}function files(id,options={},clientOptions={}){return new PmClient(clientOptions).files(id,options)}function filesDiscover(id,options={},clientOptions={}){return new PmClient(clientOptions).filesDiscover(id,options)}function filesLookup(options,clientOptions={}){return new PmClient(clientOptions).filesLookup(options)}function docs(id,options={},clientOptions={}){return new PmClient(clientOptions).docs(id,options)}function deps(id,options={},clientOptions={}){return new PmClient(clientOptions).deps(id,options)}function graph(subcommand,ids={},options={},clientOptions={}){return new PmClient(clientOptions).graph(subcommand,ids,options)}function append(id,body,options={},clientOptions={}){return new PmClient(clientOptions).append(id,body,options)}function init(prefix,options={},clientOptions={}){return new PmClient(clientOptions).init(prefix,options)}function config(scope,configAction,key,value,options={},clientOptions={}){return new PmClient(clientOptions).config(scope,configAction,key,value,options)}function schema(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).schema(subcommand,options)}function schemaList(clientOptions={}){return new PmClient(clientOptions).schemaList()}function schemaShow(name,clientOptions={}){return new PmClient(clientOptions).schemaShow(name)}function schemaAddType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddType(name,options)}function schemaRemoveType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveType(name,options)}function schemaAddStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddStatus(name,options)}function schemaRemoveStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveStatus(name,options)}function schemaAddField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddField(name,options)}function schemaRemoveField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveField(name,options)}function schemaListFields(clientOptions={}){return new PmClient(clientOptions).schemaListFields()}function schemaShowField(name,clientOptions={}){return new PmClient(clientOptions).schemaShowField(name)}function schemaApplyPreset(typePreset,options={},clientOptions={}){return new PmClient(clientOptions).schemaApplyPreset(typePreset,options)}function schemaInferTypes(options={},clientOptions={}){return new PmClient(clientOptions).schemaInferTypes(options)}function schemaRenameType(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRenameType(from,to,options)}function schemaRenameField(from,to,options,type,clientOptions={}){return new PmClient(clientOptions).schemaRenameField(from,to,options,type)}function schemaRemapStatus(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRemapStatus(from,to,options)}function schemaShowStatus(name,clientOptions={}){return new PmClient(clientOptions).schemaShowStatus(name)}function profile(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).profile(subcommand,options)}function profileList(clientOptions={}){return new PmClient(clientOptions).profileList()}function profileShow(name,clientOptions={}){return new PmClient(clientOptions).profileShow(name)}function profileApply(name,options={},clientOptions={}){return new PmClient(clientOptions).profileApply(name,options)}function profileLint(name,clientOptions={}){return new PmClient(clientOptions).profileLint(name)}function validate(options={},clientOptions={}){return new PmClient(clientOptions).validate(options)}function health(options={},clientOptions={}){return new PmClient(clientOptions).health(options)}function gc(options={},clientOptions={}){return new PmClient(clientOptions).gc(options)}function historyRedact(id,options,clientOptions={}){return new PmClient(clientOptions).historyRedact(id,options)}function historyRepair(id,options={},clientOptions={}){return new PmClient(clientOptions).historyRepair(id,options)}function historyRepairAll(options={},clientOptions={}){return new PmClient(clientOptions).historyRepairAll(options)}function historyCompact(id,options={},clientOptions={}){return new PmClient(clientOptions).historyCompact(id,options)}function historyCompactBulk(options,clientOptions={}){return new PmClient(clientOptions).historyCompactBulk(options)}function create(options={},clientOptions={}){return new PmClient(clientOptions).create(options)}function update(id,options={},clientOptions={}){return new PmClient(clientOptions).update(id,options)}function reopen(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).reopen(id,reason,options)}function close(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).close(id,reason,options)}function claim(id,options={},clientOptions={}){return new PmClient(clientOptions).claim(id,options)}function claimNext(options={},clientOptions={}){return new PmClient(clientOptions).claimNext(options)}function release(id,options={},clientOptions={}){return new PmClient(clientOptions).release(id,options)}function copy(id,options={},clientOptions={}){return new PmClient(clientOptions).copy(id,options)}function deleteItem(id,options={},clientOptions={}){return new PmClient(clientOptions).delete(id,options)}function restore(id,target,options={},clientOptions={}){return new PmClient(clientOptions).restore(id,target,options)}function focus(id,options={},clientOptions={}){return new PmClient(clientOptions).focus(id,options)}function startTask(id,options={},clientOptions={}){return new PmClient(clientOptions).startTask(id,options)}function pauseTask(id,options={},clientOptions={}){return new PmClient(clientOptions).pauseTask(id,options)}function closeTask(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).closeTask(id,reason,options)}function extension(target,options={},clientOptions={}){return new PmClient(clientOptions).extension(target,options)}function extensionList(options={},clientOptions={}){return new PmClient(clientOptions).extensionList(options)}function extensionActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionActivate(target,options)}function extensionDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionDeactivate(target,options)}function packageLifecycle(target,options={},clientOptions={}){return new PmClient(clientOptions).package(target,options)}function packageList(options={},clientOptions={}){return new PmClient(clientOptions).packageList(options)}function packageInstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageInstall(target,options)}function packageUninstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageUninstall(target,options)}function packageDoctor(options={},clientOptions={}){return new PmClient(clientOptions).packageDoctor(options)}function packageManage(target,options={},clientOptions={}){return new PmClient(clientOptions).packageManage(target,options)}function packageDescribe(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDescribe(target,options)}function packageReload(options={},clientOptions={}){return new PmClient(clientOptions).packageReload(options)}function packageCatalog(options={},clientOptions={}){return new PmClient(clientOptions).packageCatalog(options)}function packageActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageActivate(target,options)}function packageDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDeactivate(target,options)}function upgrade(target,options={},clientOptions={}){return new PmClient(clientOptions).upgrade(target,options)}async function getContracts(pmRootOrOptions,options={}){const resolvedOptions=typeof pmRootOrOptions=="string"?{...options,pmRoot:pmRootOrOptions}:pmRootOrOptions??options,global2={json:!0,quiet:resolvedOptions.quiet??!0,noExtensions:resolvedOptions.noExtensions??!1,noPager:!0,profile:resolvedOptions.profile??!1,path:resolvedOptions.pmRoot};return runContracts(resolvedOptions,global2)}const extensionActivationGate=createAsyncReadWriteGate(),activeExtensionScope=new AsyncLocalStorage;function resetActiveExtensionRegistries(){setActiveExtensionHooks(createEmptyExtensionHookRegistry()),setActiveExtensionCommands(createEmptyExtensionCommandRegistry()),setActiveExtensionParsers(createEmptyExtensionParserRegistry()),setActiveExtensionPreflight(createEmptyExtensionPreflightRegistry()),setActiveExtensionServices(createEmptyExtensionServiceRegistry()),setActiveExtensionRenderers(createEmptyExtensionRendererRegistry()),setActiveExtensionRegistrations(createEmptyExtensionRegistrationRegistry())}async function withActiveExtensions(global2,explicitCwd,resolutionCwd,run){return runWithIsolatedExtensionRuntime(()=>explicitCwd===void 0?extensionActivationGate.read(()=>withActiveExtensionsExclusively(global2,resolutionCwd,run)):extensionActivationGate.write(()=>withCwd(explicitCwd,()=>withActiveExtensionsExclusively(global2,resolutionCwd,run))))}async function runWithActiveExtensions(options,run){const explicitCwd=options.cwd;if(activeExtensionScope.getStore()===!0&&explicitCwd===void 0&&options.noExtensions===!0){const pmRoot=resolvePmRoot(process.cwd(),options.path);return runWithIsolatedExtensionRuntime(()=>runWithDiscoveredContextIntentContracts({pmRoot},run))}const resolutionCwd=explicitCwd??process.cwd();return withActiveExtensions(globalOptions({path:options.path,noExtensions:options.noExtensions}),explicitCwd,resolutionCwd,()=>activeExtensionScope.run(!0,run))}async function withActiveExtensionsExclusively(global2,cwd,run){const pmRoot=resolvePmRoot(cwd,global2.path);if(global2.noExtensions)return resetActiveExtensionRegistries(),runWithDiscoveredContextIntentContracts({pmRoot},()=>run(null));if(!await pathExists(getSettingsPath(pmRoot)))return resetActiveExtensionRegistries(),run(null);let active=null,activated;try{const settings=await readSettings(pmRoot),loadResult=await loadExtensions({pmRoot,settings,cwd,noExtensions:!1}),activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});activated={loadResult,activationResult},setActiveExtensionHooks(activationResult.hooks),setActiveExtensionCommands(activationResult.commands),setActiveExtensionParsers(activationResult.parsers),setActiveExtensionPreflight(activationResult.preflight),setActiveExtensionServices(activationResult.services),setActiveExtensionRenderers(activationResult.renderers),setActiveExtensionRegistrations(activationResult.registrations),active={registrations:activationResult.registrations,commands:activationResult.commands,pmRoot,packages:loadResult.loaded}}catch(error){resetActiveExtensionRegistries(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",error)}try{return await runWithDiscoveredContextIntentContracts({pmRoot,packages:active?.packages},()=>run(active))}finally{resetActiveExtensionRegistries(),activated&&await deactivateExtensions(activated.loadResult,activated.activationResult).catch(()=>{})}}function resolveActiveExtensionActionCommand(action,active){const normalizedAction=normalizeActionName(action);return active?.registrations.commands.find(entry=>normalizeActionName(entry.action)===normalizedAction)?.command??active?.commands.handlers.find(entry=>normalizeActionName(entry.command)===normalizedAction)?.command}async function dispatchActiveExtensionAction(action,args,options,global2,active){if(!active)throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE);const command=resolveActiveExtensionActionCommand(action,active);if(!command)throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE);const extensionAuthor=typeof options.author=="string"?options.author:global2.author,handlerResult=await runActiveCommandHandler({command:normalizeCommandPath(command),args:readStringArray(options.args??args.args),options:extensionOptionsFromArgs(args,options),global:{...global2,author:extensionAuthor},pm_root:active.pmRoot,sdk:createExtensionCommandSdk(active.pmRoot,PmClient.forActiveExtensionHost({pmRoot:active.pmRoot,author:extensionAuthor}),extensionAuthor,normalizeCommandPath(command))});if(!handlerResult.handled){const suffix=handlerResult.warnings.length>0?` (${handlerResult.warnings.join(", ")})`:"";throw new PmCliError(`Unsupported native pm action: ${action}${suffix}`,EXIT_CODE.USAGE)}return handlerResult.result}async function withCwd(cwd,run){const previous=process.cwd();process.chdir(cwd);try{return await run()}finally{process.chdir(previous)}}function resolveSdkActionInput(args){const rawAction=readRequiredString(args,"action"),normalizedAction=normalizeActionName(rawAction),alias=getOwnHandler(SDK_ACTION_ALIASES,normalizedAction),action=alias?.action??normalizedAction,resolvedArgs={...args,action};return alias?.options!==void 0&&(resolvedArgs.options={...alias.options,...asRecordClone(args.options)}),action==="package"&&(resolvedArgs.options={...asRecordClone(resolvedArgs.options),vocabulary:"package"}),{action,args:resolvedArgs}}async function runAction(args){const resolved=resolveSdkActionInput(args),global2=globalOptions(resolved.args),invalidateWorkspaceContractsCache=shouldInvalidateWorkspaceContractsCacheAfterAction(resolved.action),explicitCwd=readString(resolved.args,"cwd"),resolutionCwd=explicitCwd??process.cwd();resolved.action==="init"&&(global2[INIT_INVOCATION_CWD]=resolutionCwd),(resolved.action!=="init"||global2.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(global2.path=resolvePmRoot(resolutionCwd,global2.path));try{return resolved.action==="history-attest"?await dispatchAction(resolved.action,resolved.args,global2,null):args[ACTIVE_EXTENSION_HOST_CONTEXT]===!0||activeExtensionScope.getStore()===!0?await dispatchAction(resolved.action,resolved.args,global2,null):await withActiveExtensions(global2,explicitCwd,resolutionCwd,activeExtensions=>dispatchAction(resolved.action,resolved.args,global2,activeExtensions))}finally{invalidateWorkspaceContractsCache&&clearWorkspaceContractsCache()}}function analyzeSdkActionCoverage(actions=PM_TOOL_ACTIONS){return actions.map(action=>{const normalized=normalizeActionName(action),alias=getOwnHandler(SDK_ACTION_ALIASES,normalized),resolvedAction=alias?.action??normalized,covered=getOwnHandler(SDK_ACTION_HANDLERS,resolvedAction)!==void 0;return{action,resolved_action:resolvedAction,covered,route:covered?alias?"alias":"native":"missing"}})}async function dispatchAction(action,args,global2,activeExtensions){const options=optionsWithAuthor(args,action);if(action==="create"||action==="update"){const{assertNativeMutationOptions}=await import("./runtime/mutation-admission.js");await assertNativeMutationOptions(action,args,options,global2.path,HOISTED_ACTION_OPTION_KEYS[action])}const handler=getOwnHandler(SDK_ACTION_HANDLERS,action),extensionCommand=handler?void 0:resolveActiveExtensionActionCommand(action,activeExtensions),readCommand=extensionCommand===void 0?action:`extension:${extensionCommand}`;validateReadOutputOptions(readCommand,options),normalizeReadOutputIncludeModeOptions(readCommand,options);const ctx={action,args,options,id:readString(args,"id"),force:args.force===!0||options.force===!0,global:global2,activeExtensions},result=handler?await handler(ctx):await dispatchActiveExtensionAction(action,args,options,global2,activeExtensions);if(action==="history-attest")return result;{const projected=attachReadOutputContracts(readCommand,options,result);return await finalizeContextUsageEgress(resolvePmRoot(process.cwd(),global2.path),projected),projected}}const actionRunnerTestHooks={closeManyOptionsFromFlat,extensionOptionsFromArgs,globalOptions,mutationListOptions,normalizeActionName,normalizeCommandPath,normalizeMcpUpdateOptions,normalizeMcpOptionsArrays,optionsWithAuthor,readRequiredString,readScalarString,readScalarStringAllowBlank,readStringArray,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=actionRunnerTestHooks);import{readRequiredString as readRequiredString2}from"./runtime/context.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_OUTPUT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_TERMINAL_TRANSITION_POLICY,DEPENDENCY_KIND_VALUES,EXIT_CODE,HISTORY_EVENT_CLASSIFICATION_VERSION,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,MAINTENANCE_HISTORY_OPERATIONS,NEXT_OUTPUT_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_GITIGNORE_END,PM_GITIGNORE_START,PmCliError2 as PmCliError,PmClient,PmCompleteListValidationError,RISK_VALUES,SEARCH_EXTENSION_FLAG_DEFINITIONS,STATUS_VALUES,SUBSTANTIVE_HISTORY_OPERATIONS,acquireLock,acquireLockLease,aggregate,analyzeSdkActionCoverage,append,appendHistoryEntry,applyTerminalOrderingPolicy,assertCompleteListResult,canonicalDocument,certifyCompleteListResult2 as certifyCompleteListResult,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,clearWorkspaceContractsCache2 as clearWorkspaceContractsCache,close,closeItem,closeTask,comments,commitImportedItem,config,context,copy,create,createCompleteListOptions2 as createCompleteListOptions,createHistoryEntry,createPmCliExpectedError,deleteItem,deps,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureTrackerInitialized,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getPmGitignoreBlock,getSettingsPath2 as getSettingsPath,getWorkspaceContracts,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,inspectCompleteListResult,isPmCliExpectedError,isTerminalStatus,isTimestampLiteral,jaccardSimilarity,learnings,list,listAllComplete,listAllItemMetadata,listAllItemMetadataLight,loadCreateTemplateOptions,locateItem,next,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,parseTags,pathExists2 as pathExists,pauseTask,profile,profileApply,profileLint,profileList,profileShow,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString2 as readRequiredString,readSettings2 as readSettings,readStringOption,release,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,reopen,requireTerminalReason,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolvePmRoot2 as resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveTerminalReason,restore,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runCalendar,runClose,runCloseTask,runCompletion,runContext,runCopy,runDelete,runDuplicates,runFocus,runGet,runGuide,runList,runNext,runPauseTask,runReindex,runReopen,runRestore,runSearch,runStartTask,runStats,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runUpdate,runWithActiveExtensions,scanItemFormatVersions,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,search,selectImportAuthor,serializeItemDocument,splitFrontMatter,startTask,stats,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,writeFileAtomic};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="33ef03e4-e05b-5b80-b750-35b026af21b0")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{createEmptyExtensionCommandRegistry,createEmptyExtensionHookRegistry,createEmptyExtensionParserRegistry,createEmptyExtensionPreflightRegistry,createEmptyExtensionRegistrationRegistry,createEmptyExtensionRendererRegistry,createEmptyExtensionServiceRegistry}from"../core/extensions/extension-registries.js";import{activateExtensions,deactivateExtensions,loadExtensions,runActiveCommandHandler,runWithIsolatedExtensionRuntime,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices}from"../core/extensions/index.js";import{pathExists}from"../core/fs/fs-utils.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{asRecordClone}from"../core/shared/primitives.js";import{HOISTED_ACTION_OPTION_KEYS}from"./runtime-input.js";import{createAsyncReadWriteGate}from"../core/shared/serial-queue.js";import{getSettingsPath,resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{PM_TOOL_ACTIONS}from"./cli-contracts/enum-contracts.js";import{runContracts}from"./cli-contracts/runtime-contracts.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{runWithDiscoveredContextIntentContracts}from"./context-intent-runtime.js";import{finalizeContextUsageEgress}from"./context/usage-egress.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{INIT_INVOCATION_CWD}from"./init.js";import{certifyCompleteListResult,createCompleteListOptions}from"./query/complete-list.js";import{listClientItemMetadataLight}from"./query/light-metadata.js";import{normalizeReadOutputIncludeModeOptions,validateReadOutputOptions}from"./read-output-contracts.js";import{SDK_ACTION_ALIASES}from"./runtime-action-aliases.js";import{closeManyOptionsFromFlat,extensionOptionsFromArgs,actionGlobalOptions as globalOptions,mutationListOptions,mutationOptionsWithOverrides,normalizeActionName,normalizeCommandPath,normalizeMcpOptionsArrays,normalizeMcpUpdateOptions,optionsWithAuthor,readRuntimeScalarString as readScalarString,readRuntimeScalarStringAllowBlank as readScalarStringAllowBlank,readRuntimeString as readString,readRuntimeStringArray as readStringArray,shouldInvalidateWorkspaceContractsCacheAfterAction,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction}from"./runtime-input.js";import{SDK_ACTION_HANDLERS}from"./runtime/actions.js";import{getOwnHandler,readRequiredString}from"./runtime/context.js";import{clearWorkspaceContractsCache}from"./workspace-contracts-cache.js";import{PM_GITIGNORE_END,PM_GITIGNORE_START,ensurePmGitignore,getPmGitignoreBlock}from"./workspace.js";import{SEARCH_EXTENSION_FLAG_DEFINITIONS}from"./extension-contracts.js";export*from"./cli-contracts/agent-output-contracts.js";import{PmCompleteListValidationError,assertCompleteListResult,certifyCompleteListResult as certifyCompleteListResult2,createCompleteListOptions as createCompleteListOptions2,inspectCompleteListResult}from"./query/complete-list.js";import{getWorkspaceContracts}from"./query/workspace-contracts.js";import{clearWorkspaceContractsCache as clearWorkspaceContractsCache2}from"./workspace-contracts-cache.js";export*from"./governance/workflow-policy.js";import{runCloseTask,runPauseTask,runStartTask}from"./lifecycle/task-composition.js";import{getActiveExtensionRegistrations,runActiveOnReadHooks,runActiveOnWriteHooks}from"../core/extensions/index.js";import{pathExists as pathExists2,readFileIfExists,removeFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendHistoryEntry,createHistoryEntry}from"../core/history/history.js";import{HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS,classifyHistoryEvent}from"../core/history/event-classification.js";import{generateItemId,normalizeItemId,normalizeRawItemId}from"../core/item/id.js";import{readBooleanOption,readCsvListOption,readStringOption}from"./package-runtime-options.js";import{PM_CLI_EXPECTED_ERROR_NAME,createPmCliExpectedError,isPmCliExpectedError}from"./errors.js";import{commitImportedItem,emptyImportedDocument,ensureTrackerInitialized,selectImportAuthor,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString}from"./package-import-adapters.js";import{canonicalDocument,normalizeItemMetadata,serializeItemDocument,splitFrontMatter}from"../core/item/item-format.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,scanItemFormatVersions}from"../core/item/item-format-version.js";import{parseTags}from"../core/item/parse.js";import{isTerminalStatus,normalizeStatusInput}from"../core/item/status.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{acquireLock,acquireLockLease}from"../core/lock/lock.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{PmCliError as PmCliError2}from"../core/shared/errors.js";import{isTimestampLiteral,nowIso}from"../core/shared/time.js";import{jaccardSimilarity,normalizeSimilarityText,scoreItemSimilarity,tokenizeSimilarityText}from"./similarity-scoring.js";import{listAllItemMetadata,listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{getHistoryPath,getItemPath,getSettingsPath as getSettingsPath2,resolveImplicitPmRoot,resolvePmRoot as resolvePmRoot2}from"../core/store/paths.js";import{readSettings as readSettings2}from"../core/store/settings.js";import{runAggregate}from"./query/aggregate.js";import{CONTEXT_OUTPUT_VALUES,runContext}from"./query/context.js";import{runGet}from"./query/get.js";import{runList}from"./query/list.js";import{closeItem,runClose}from"./lifecycle/close.js";import{runCopy}from"./lifecycle/copy.js";import{runDelete}from"./lifecycle/delete.js";import{runFocus}from"./lifecycle/focus.js";import{runRestore}from"./lifecycle/restore.js";import{DEFAULT_TERMINAL_TRANSITION_POLICY,applyTerminalOrderingPolicy,requireTerminalReason,resolveTerminalReason}from"./lifecycle-policy.js";import{runUpdate}from"./lifecycle/update.js";import{runReopen}from"./lifecycle/reopen.js";import{NEXT_OUTPUT_VALUES,runNext}from"./query/next.js";import{runSearch}from"./query/search.js";import{runStats}from"./stats.js";import{runDuplicates}from"./duplicates.js";import{renderCalendarMarkdown,renderCalendarToon,resolveCalendarOutputFormat,runCalendar}from"./query/calendar.js";import{renderGuideMarkdown,resolveGuideOutputFormat,runGuide}from"./guide.js";import{runCompletion}from"./completion.js";import{runReindex}from"./governance/reindex.js";import{loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow}from"./templates.js";import{runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop}from"./test/runs.js";import{BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,DEPENDENCY_KIND_VALUES,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,RISK_VALUES,STATUS_VALUES}from"../types/index.js";const ACTIVE_EXTENSION_HOST_CONTEXT=Symbol("pm.active-extension-host-context");function splitFullClientMutationOptions(options){return{fullChangedFields:!0,options}}class PmClient{defaults;constructor(options={}){this.defaults={...options.pmRoot===void 0?{}:{path:options.pmRoot},...options.cwd===void 0?{}:{cwd:options.cwd},...options.author===void 0?{}:{author:options.author},...options.noExtensions===void 0?{}:{noExtensions:options.noExtensions}}}static forActiveExtensionHost(options){const client=new PmClient({...options,noExtensions:!0});return client.defaults[ACTIVE_EXTENSION_HOST_CONTEXT]=!0,client}run(action,args={}){return runAction({...this.defaults,...args,action})}runTyped(action,args={}){return this.run(action,args)}context(options={}){return this.runTyped("context",{options})}listAllItemMetadataLight(){return listClientItemMetadataLight(this.defaults.path,this.defaults.cwd)}list(options={}){return this.runTyped("list",{options})}async listAllComplete(options={}){return certifyCompleteListResult(await this.list(createCompleteListOptions(options)))}search(query,options={}){return this.runTyped("search",{query,options})}get(id,options={}){return this.runTyped("get",{id,options})}next(options={}){return this.runTyped("next",{options})}aggregate(options={}){return this.runTyped("aggregate",{options})}stats(options={}){return this.runTyped("stats",{options})}duplicates(options={}){return this.runTyped("duplicates",{options})}comments(id,options={}){return this.runTyped("comments",{id,options})}notes(id,options={}){return this.runTyped("notes",{id,options})}learnings(id,options={}){return this.runTyped("learnings",{id,options})}files(id,options={}){return this.runTyped("files",{id,options})}filesDiscover(id,options={}){return this.runTyped("files-discover",{id,options})}filesLookup(options){return this.runTyped("files-lookup",{options})}docs(id,options={}){return this.runTyped("docs",{id,options})}deps(id,options={}){return this.runTyped("deps",{id,options})}graph(subcommand,ids={},options={}){return this.runTyped("graph",{subcommand,...ids,options})}append(id,body,options={}){return this.runTyped("append",{id,...splitFullClientMutationOptions(mutationOptionsWithOverrides(options,{body}))})}init(prefix,options={}){return this.runTyped("init",{...prefix===void 0?{}:{prefix},options})}config(scope,configAction,key,value,options={}){return this.runTyped("config",{scope,configAction,...key===void 0?{}:{key},...value===void 0?{}:{value},options})}schema(subcommand,options={}){return this.runTyped("schema",{options:{...options,subcommand}})}workflowPolicy(action,name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:action}})}schemaList(){return this.runTyped("schema",{options:{subcommand:"list"}})}schemaShow(name){return this.runTyped("schema",{name,options:{subcommand:"show"}})}schemaAddType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-type"}})}schemaRemoveType(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-type"}})}schemaAddStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"add-status"}})}schemaRemoveStatus(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-status"}})}schemaAddField(name,options={}){const{type,...mutationOptions}=options;return this.runTyped("schema",{name,options:{...mutationOptions,fieldType:type,subcommand:"add-field"}})}schemaRemoveField(name,options={}){return this.runTyped("schema",{name,options:{...options,subcommand:"remove-field"}})}schemaListFields(){return this.runTyped("schema",{options:{subcommand:"list-fields"}})}schemaShowField(name){return this.runTyped("schema",{name,options:{subcommand:"show-field"}})}schemaApplyPreset(typePreset,options={}){return this.runTyped("schema",{typePreset,options:{...options,subcommand:"apply-preset"}})}schemaInferTypes(options={}){return this.runTyped("schema",{options:{...options,subcommand:"add-type",infer:!0}})}schemaRenameType(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-type",to}})}schemaRenameField(from,to,options,type){return this.runTyped("schema",{name:from,options:{...options,subcommand:"rename-field",to,...type?{fieldTypeScope:type}:{}}})}schemaRemapStatus(from,to,options){return this.runTyped("schema",{name:from,options:{...options,subcommand:"remap-status",to}})}schemaShowStatus(name){return this.runTyped("schema",{name,options:{subcommand:"show-status"}})}profile(subcommand,options={}){return this.runTyped("profile",{options:{...options,subcommand}})}profileList(){return this.runTyped("profile",{options:{subcommand:"list"}})}profileShow(name){return this.runTyped("profile",{name,options:{subcommand:"show"}})}profileApply(name,options={}){return this.runTyped("profile",{name,options:{...options,subcommand:"apply"}})}profileLint(name){return this.runTyped("profile",{name,options:{subcommand:"lint"}})}validate(options={}){return this.runTyped("validate",{options})}health(options={}){return this.runTyped("health",{options})}gc(options={}){return this.runTyped("gc",{options})}assurance(input){return this.runTyped("assurance",{options:{...input,subcommand:input.action}})}historyRedact(id,options){return this.runTyped("history-redact",{id,options})}historyRepair(id,options={}){return this.runTyped("history-repair",{id,options})}historyRepairAll(options={}){return this.runTyped("history-repair",{options:{...options,all:!0}})}historyAttest(options={}){return this.runTyped("history-attest",{options})}historyCompact(id,options={}){return this.runTyped("history-compact",{id,options})}historyCompactBulk(options){return this.runTyped("history-compact",{options})}historyAuthorAcknowledge(options){return this.runTyped("history-author-acknowledge",{historyEvent:(options.events??[]).map(event=>`${event.item_id}:${String(event.line)}`),allActionable:options.all_actionable===!0,dryRun:options.dry_run===!0,planFingerprint:options.plan_fingerprint,limit:options.coordinate_limit,attributedAuthor:options.attributed_author,reviewer:options.reviewer,reason:options.reason})}plan(subcommand,id,options={},stepRef,reorderTo){return this.runTyped("plan",{fullChangedFields:!0,...id===void 0?{}:{id},...stepRef===void 0?{}:{stepRef},...reorderTo===void 0?{}:{reorderTo},options:mutationOptionsWithOverrides(options,{subcommand})})}planCreate(options){return this.plan("create",void 0,options)}planShow(id,options={}){return this.plan("show",id,options)}planAddStep(id,options){return this.plan("add-step",id,options)}planUpdateStep(id,stepRef,options){return this.plan("update-step",id,options,stepRef)}planCompleteStep(id,stepRef,options={}){return this.plan("complete-step",id,options,stepRef)}planBlockStep(id,stepRef,options){return this.plan("block-step",id,options,stepRef)}planReorderStep(id,stepRef,reorderTo,options={}){return this.plan("reorder-step",id,options,stepRef,reorderTo)}planRemoveStep(id,stepRef,options={}){return this.plan("remove-step",id,options,stepRef)}planLink(id,stepRef,options){return this.plan("link",id,options,stepRef)}planUnlink(id,stepRef,options){return this.plan("unlink",id,options,stepRef)}planDecision(id,options){return this.plan("decision",id,options)}planDiscovery(id,options){return this.plan("discovery",id,options)}planValidation(id,options){return this.plan("validation",id,options)}planResume(id,options){return this.plan("resume",id,options)}planApprove(id,options={}){return this.plan("approve",id,options)}planMaterialize(id,options){return this.plan("materialize",id,options)}create(options={}){return this.runTyped("create",splitFullClientMutationOptions(options))}update(id,options={}){return this.runTyped("update",{id,...splitFullClientMutationOptions(options)})}reopen(id,reason,options={}){return this.runTyped("item-reopen",{id,reason,fullChangedFields:!0,options})}close(id,reason,options={}){return this.runTyped("close",{id,reason,...splitFullClientMutationOptions(options)})}claim(id,options={}){return this.runTyped("claim",{id,...splitFullClientMutationOptions(options)})}claimNext(options={}){return this.runTyped("claim",{next:!0,...splitFullClientMutationOptions(options)})}release(id,options={}){return this.runTyped("release",{id,...splitFullClientMutationOptions(options)})}copy(id,options={}){return this.runTyped("copy",{id,...splitFullClientMutationOptions(options)})}delete(id,options={}){return this.runTyped("delete",{id,...splitFullClientMutationOptions(options)})}restore(id,target,options={}){return this.runTyped("restore",{fullChangedFields:!0,id,options:{...options,target}})}focus(id,options={}){return this.runTyped("focus",{...id===void 0?{}:{id},...splitFullClientMutationOptions(options)})}startTask(id,options={}){return this.runTyped("start-task",{id,...splitFullClientMutationOptions(options)})}pauseTask(id,options={}){return this.runTyped("pause-task",{id,...splitFullClientMutationOptions(options)})}closeTask(id,reason,options={}){return this.runTyped("close-task",{id,reason,...splitFullClientMutationOptions(options)})}extension(target,options={}){return this.runTyped("extension",{...target===void 0?{}:{target},options})}extensionList(options={}){return this.extension("list",options)}extensionActivate(target,options={}){return this.runTyped("extension-activate",{target,options})}extensionDeactivate(target,options={}){return this.runTyped("extension-deactivate",{target,options})}package(target,options={}){return this.runTyped("package",{...target===void 0?{}:{target},options:{...options,vocabulary:"package"}})}packageList(options={}){return this.package("list",options)}packageInstall(target,options={}){return this.runTyped("package-install",{target,options})}packageUninstall(target,options={}){return this.runTyped("package-uninstall",{target,options})}packageDoctor(options={}){return this.runTyped("package-doctor",{options})}packageManage(target,options={}){return this.runTyped("package-manage",{...target===void 0?{}:{target},options})}packageDescribe(target,options={}){return this.runTyped("package-describe",{...target===void 0?{}:{target},options})}packageReload(options={}){return this.runTyped("package-reload",{options})}packageCatalog(options={}){return this.runTyped("package-catalog",{options})}packageActivate(target,options={}){return this.runTyped("package-activate",{target,options})}packageDeactivate(target,options={}){return this.runTyped("package-deactivate",{target,options})}packageMigrate(options={}){return this.package(void 0,{...options,migrate:!0})}upgrade(target,options={}){return this.runTyped("upgrade",{...target===void 0?{}:{target},options})}}function context(options={},clientOptions={}){return new PmClient(clientOptions).context(options)}function list(options={},clientOptions={}){return new PmClient(clientOptions).list(options)}function listAllComplete(options={},clientOptions={}){return new PmClient(clientOptions).listAllComplete(options)}function search(query,options={},clientOptions={}){return new PmClient(clientOptions).search(query,options)}function get(id,options={},clientOptions={}){return new PmClient(clientOptions).get(id,options)}function next(options={},clientOptions={}){return new PmClient(clientOptions).next(options)}function aggregate(options={},clientOptions={}){return new PmClient(clientOptions).aggregate(options)}function stats(options={},clientOptions={}){return new PmClient(clientOptions).stats(options)}function duplicates(options={},clientOptions={}){return new PmClient(clientOptions).duplicates(options)}function comments(id,options={},clientOptions={}){return new PmClient(clientOptions).comments(id,options)}function notes(id,options={},clientOptions={}){return new PmClient(clientOptions).notes(id,options)}function learnings(id,options={},clientOptions={}){return new PmClient(clientOptions).learnings(id,options)}function files(id,options={},clientOptions={}){return new PmClient(clientOptions).files(id,options)}function filesDiscover(id,options={},clientOptions={}){return new PmClient(clientOptions).filesDiscover(id,options)}function filesLookup(options,clientOptions={}){return new PmClient(clientOptions).filesLookup(options)}function docs(id,options={},clientOptions={}){return new PmClient(clientOptions).docs(id,options)}function deps(id,options={},clientOptions={}){return new PmClient(clientOptions).deps(id,options)}function graph(subcommand,ids={},options={},clientOptions={}){return new PmClient(clientOptions).graph(subcommand,ids,options)}function append(id,body,options={},clientOptions={}){return new PmClient(clientOptions).append(id,body,options)}function init(prefix,options={},clientOptions={}){return new PmClient(clientOptions).init(prefix,options)}function config(scope,configAction,key,value,options={},clientOptions={}){return new PmClient(clientOptions).config(scope,configAction,key,value,options)}function schema(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).schema(subcommand,options)}function schemaList(clientOptions={}){return new PmClient(clientOptions).schemaList()}function schemaShow(name,clientOptions={}){return new PmClient(clientOptions).schemaShow(name)}function schemaAddType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddType(name,options)}function schemaRemoveType(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveType(name,options)}function schemaAddStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddStatus(name,options)}function schemaRemoveStatus(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveStatus(name,options)}function schemaAddField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaAddField(name,options)}function schemaRemoveField(name,options={},clientOptions={}){return new PmClient(clientOptions).schemaRemoveField(name,options)}function schemaListFields(clientOptions={}){return new PmClient(clientOptions).schemaListFields()}function schemaShowField(name,clientOptions={}){return new PmClient(clientOptions).schemaShowField(name)}function schemaApplyPreset(typePreset,options={},clientOptions={}){return new PmClient(clientOptions).schemaApplyPreset(typePreset,options)}function schemaInferTypes(options={},clientOptions={}){return new PmClient(clientOptions).schemaInferTypes(options)}function schemaRenameType(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRenameType(from,to,options)}function schemaRenameField(from,to,options,type,clientOptions={}){return new PmClient(clientOptions).schemaRenameField(from,to,options,type)}function schemaRemapStatus(from,to,options,clientOptions={}){return new PmClient(clientOptions).schemaRemapStatus(from,to,options)}function schemaShowStatus(name,clientOptions={}){return new PmClient(clientOptions).schemaShowStatus(name)}function profile(subcommand,options={},clientOptions={}){return new PmClient(clientOptions).profile(subcommand,options)}function profileList(clientOptions={}){return new PmClient(clientOptions).profileList()}function profileShow(name,clientOptions={}){return new PmClient(clientOptions).profileShow(name)}function profileApply(name,options={},clientOptions={}){return new PmClient(clientOptions).profileApply(name,options)}function profileLint(name,clientOptions={}){return new PmClient(clientOptions).profileLint(name)}function validate(options={},clientOptions={}){return new PmClient(clientOptions).validate(options)}function health(options={},clientOptions={}){return new PmClient(clientOptions).health(options)}function gc(options={},clientOptions={}){return new PmClient(clientOptions).gc(options)}function historyRedact(id,options,clientOptions={}){return new PmClient(clientOptions).historyRedact(id,options)}function historyRepair(id,options={},clientOptions={}){return new PmClient(clientOptions).historyRepair(id,options)}function historyRepairAll(options={},clientOptions={}){return new PmClient(clientOptions).historyRepairAll(options)}function historyCompact(id,options={},clientOptions={}){return new PmClient(clientOptions).historyCompact(id,options)}function historyCompactBulk(options,clientOptions={}){return new PmClient(clientOptions).historyCompactBulk(options)}function create(options={},clientOptions={}){return new PmClient(clientOptions).create(options)}function update(id,options={},clientOptions={}){return new PmClient(clientOptions).update(id,options)}function reopen(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).reopen(id,reason,options)}function close(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).close(id,reason,options)}function claim(id,options={},clientOptions={}){return new PmClient(clientOptions).claim(id,options)}function claimNext(options={},clientOptions={}){return new PmClient(clientOptions).claimNext(options)}function release(id,options={},clientOptions={}){return new PmClient(clientOptions).release(id,options)}function copy(id,options={},clientOptions={}){return new PmClient(clientOptions).copy(id,options)}function deleteItem(id,options={},clientOptions={}){return new PmClient(clientOptions).delete(id,options)}function restore(id,target,options={},clientOptions={}){return new PmClient(clientOptions).restore(id,target,options)}function focus(id,options={},clientOptions={}){return new PmClient(clientOptions).focus(id,options)}function startTask(id,options={},clientOptions={}){return new PmClient(clientOptions).startTask(id,options)}function pauseTask(id,options={},clientOptions={}){return new PmClient(clientOptions).pauseTask(id,options)}function closeTask(id,reason,options={},clientOptions={}){return new PmClient(clientOptions).closeTask(id,reason,options)}function extension(target,options={},clientOptions={}){return new PmClient(clientOptions).extension(target,options)}function extensionList(options={},clientOptions={}){return new PmClient(clientOptions).extensionList(options)}function extensionActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionActivate(target,options)}function extensionDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).extensionDeactivate(target,options)}function packageLifecycle(target,options={},clientOptions={}){return new PmClient(clientOptions).package(target,options)}function packageList(options={},clientOptions={}){return new PmClient(clientOptions).packageList(options)}function packageInstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageInstall(target,options)}function packageUninstall(target,options={},clientOptions={}){return new PmClient(clientOptions).packageUninstall(target,options)}function packageDoctor(options={},clientOptions={}){return new PmClient(clientOptions).packageDoctor(options)}function packageManage(target,options={},clientOptions={}){return new PmClient(clientOptions).packageManage(target,options)}function packageDescribe(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDescribe(target,options)}function packageReload(options={},clientOptions={}){return new PmClient(clientOptions).packageReload(options)}function packageCatalog(options={},clientOptions={}){return new PmClient(clientOptions).packageCatalog(options)}function packageActivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageActivate(target,options)}function packageDeactivate(target,options={},clientOptions={}){return new PmClient(clientOptions).packageDeactivate(target,options)}function upgrade(target,options={},clientOptions={}){return new PmClient(clientOptions).upgrade(target,options)}async function getContracts(pmRootOrOptions,options={}){const resolvedOptions=typeof pmRootOrOptions=="string"?{...options,pmRoot:pmRootOrOptions}:pmRootOrOptions??options,global2={json:!0,quiet:resolvedOptions.quiet??!0,noExtensions:resolvedOptions.noExtensions??!1,noPager:!0,profile:resolvedOptions.profile??!1,path:resolvedOptions.pmRoot};return runContracts(resolvedOptions,global2)}const extensionActivationGate=createAsyncReadWriteGate(),activeExtensionScope=new AsyncLocalStorage;function resetActiveExtensionRegistries(){setActiveExtensionHooks(createEmptyExtensionHookRegistry()),setActiveExtensionCommands(createEmptyExtensionCommandRegistry()),setActiveExtensionParsers(createEmptyExtensionParserRegistry()),setActiveExtensionPreflight(createEmptyExtensionPreflightRegistry()),setActiveExtensionServices(createEmptyExtensionServiceRegistry()),setActiveExtensionRenderers(createEmptyExtensionRendererRegistry()),setActiveExtensionRegistrations(createEmptyExtensionRegistrationRegistry())}async function withActiveExtensions(global2,explicitCwd,resolutionCwd,run){return runWithIsolatedExtensionRuntime(()=>explicitCwd===void 0?extensionActivationGate.read(()=>withActiveExtensionsExclusively(global2,resolutionCwd,run)):extensionActivationGate.write(()=>withCwd(explicitCwd,()=>withActiveExtensionsExclusively(global2,resolutionCwd,run))))}async function runWithActiveExtensions(options,run){const explicitCwd=options.cwd;if(activeExtensionScope.getStore()===!0&&explicitCwd===void 0&&options.noExtensions===!0){const pmRoot=resolvePmRoot(process.cwd(),options.path);return runWithIsolatedExtensionRuntime(()=>runWithDiscoveredContextIntentContracts({pmRoot},run))}const resolutionCwd=explicitCwd??process.cwd();return withActiveExtensions(globalOptions({path:options.path,noExtensions:options.noExtensions}),explicitCwd,resolutionCwd,()=>activeExtensionScope.run(!0,run))}async function withActiveExtensionsExclusively(global2,cwd,run){const pmRoot=resolvePmRoot(cwd,global2.path);if(global2.noExtensions)return resetActiveExtensionRegistries(),runWithDiscoveredContextIntentContracts({pmRoot},()=>run(null));if(!await pathExists(getSettingsPath(pmRoot)))return resetActiveExtensionRegistries(),run(null);let active=null,activated;try{const settings=await readSettings(pmRoot),loadResult=await loadExtensions({pmRoot,settings,cwd,noExtensions:!1}),activationResult=await activateExtensions({...loadResult,loaded:loadResult.loaded});activated={loadResult,activationResult},setActiveExtensionHooks(activationResult.hooks),setActiveExtensionCommands(activationResult.commands),setActiveExtensionParsers(activationResult.parsers),setActiveExtensionPreflight(activationResult.preflight),setActiveExtensionServices(activationResult.services),setActiveExtensionRenderers(activationResult.renderers),setActiveExtensionRegistrations(activationResult.registrations),active={registrations:activationResult.registrations,commands:activationResult.commands,pmRoot,packages:loadResult.loaded}}catch(error){resetActiveExtensionRegistries(),console.error("[pm-sdk] extension activation failed; continuing without active extensions:",error)}try{return await runWithDiscoveredContextIntentContracts({pmRoot,packages:active?.packages},()=>run(active))}finally{resetActiveExtensionRegistries(),activated&&await deactivateExtensions(activated.loadResult,activated.activationResult).catch(()=>{})}}function resolveActiveExtensionActionCommand(action,active){const normalizedAction=normalizeActionName(action);return active?.registrations.commands.find(entry=>normalizeActionName(entry.action)===normalizedAction)?.command??active?.commands.handlers.find(entry=>normalizeActionName(entry.command)===normalizedAction)?.command}async function dispatchActiveExtensionAction(action,args,options,global2,active){if(!active)throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE);const command=resolveActiveExtensionActionCommand(action,active);if(!command)throw new PmCliError(`Unsupported native pm action: ${action}`,EXIT_CODE.USAGE);const extensionAuthor=typeof options.author=="string"?options.author:global2.author,handlerResult=await runActiveCommandHandler({command:normalizeCommandPath(command),args:readStringArray(options.args??args.args),options:extensionOptionsFromArgs(args,options),global:{...global2,author:extensionAuthor},pm_root:active.pmRoot,sdk:createExtensionCommandSdk(active.pmRoot,PmClient.forActiveExtensionHost({pmRoot:active.pmRoot,author:extensionAuthor}),extensionAuthor,normalizeCommandPath(command))});if(!handlerResult.handled){const suffix=handlerResult.warnings.length>0?` (${handlerResult.warnings.join(", ")})`:"";throw new PmCliError(`Unsupported native pm action: ${action}${suffix}`,EXIT_CODE.USAGE)}return handlerResult.result}async function withCwd(cwd,run){const previous=process.cwd();process.chdir(cwd);try{return await run()}finally{process.chdir(previous)}}function resolveSdkActionInput(args){const rawAction=readRequiredString(args,"action"),normalizedAction=normalizeActionName(rawAction),alias=getOwnHandler(SDK_ACTION_ALIASES,normalizedAction),action=alias?.action??normalizedAction,resolvedArgs={...args,action};return alias?.options!==void 0&&(resolvedArgs.options={...alias.options,...asRecordClone(args.options)}),action==="package"&&(resolvedArgs.options={...asRecordClone(resolvedArgs.options),vocabulary:"package"}),{action,args:resolvedArgs}}async function runAction(args){const resolved=resolveSdkActionInput(args),global2=globalOptions(resolved.args),invalidateWorkspaceContractsCache=shouldInvalidateWorkspaceContractsCacheAfterAction(resolved.action),explicitCwd=readString(resolved.args,"cwd"),resolutionCwd=explicitCwd??process.cwd();resolved.action==="init"&&(global2[INIT_INVOCATION_CWD]=resolutionCwd),(resolved.action!=="init"||global2.path!==void 0||(process.env.PM_PATH?.trim().length??0)>0)&&(global2.path=resolvePmRoot(resolutionCwd,global2.path));try{return resolved.action==="history-attest"?await dispatchAction(resolved.action,resolved.args,global2,null):args[ACTIVE_EXTENSION_HOST_CONTEXT]===!0||activeExtensionScope.getStore()===!0?await dispatchAction(resolved.action,resolved.args,global2,null):await withActiveExtensions(global2,explicitCwd,resolutionCwd,activeExtensions=>dispatchAction(resolved.action,resolved.args,global2,activeExtensions))}finally{invalidateWorkspaceContractsCache&&clearWorkspaceContractsCache()}}function analyzeSdkActionCoverage(actions=PM_TOOL_ACTIONS){return actions.map(action=>{const normalized=normalizeActionName(action),alias=getOwnHandler(SDK_ACTION_ALIASES,normalized),resolvedAction=alias?.action??normalized,covered=getOwnHandler(SDK_ACTION_HANDLERS,resolvedAction)!==void 0;return{action,resolved_action:resolvedAction,covered,route:covered?alias?"alias":"native":"missing"}})}async function dispatchAction(action,args,global2,activeExtensions){const options=optionsWithAuthor(args,action);if(action==="create"||action==="update"){const{assertNativeMutationOptions}=await import("./runtime/mutation-admission.js");await assertNativeMutationOptions(action,args,options,global2.path,HOISTED_ACTION_OPTION_KEYS[action])}const handler=getOwnHandler(SDK_ACTION_HANDLERS,action),extensionCommand=handler?void 0:resolveActiveExtensionActionCommand(action,activeExtensions),readCommand=extensionCommand===void 0?action:`extension:${extensionCommand}`;validateReadOutputOptions(readCommand,options),normalizeReadOutputIncludeModeOptions(readCommand,options);const ctx={action,args,options,id:readString(args,"id"),force:args.force===!0||options.force===!0,global:global2,activeExtensions},result=handler?await handler(ctx):await dispatchActiveExtensionAction(action,args,options,global2,activeExtensions);if(action==="history-attest")return result;{const projected=attachReadOutputContracts(readCommand,options,result);return await finalizeContextUsageEgress(resolvePmRoot(process.cwd(),global2.path),projected),projected}}const actionRunnerTestHooks={closeManyOptionsFromFlat,extensionOptionsFromArgs,globalOptions,mutationListOptions,normalizeActionName,normalizeCommandPath,normalizeMcpUpdateOptions,normalizeMcpOptionsArrays,optionsWithAuthor,readRequiredString,readScalarString,readScalarStringAllowBlank,readStringArray,updateManyOptionsFromFlat,withAddNoteOption,withFilesDiscoveryOptions,withMutationCompaction};(process.env.NODE_ENV==="test"||process.env.VITEST!==void 0||process.env.VITEST_WORKER_ID!==void 0)&&(globalThis.__pmCliActionRunnerTestHooks=actionRunnerTestHooks);import{readRequiredString as readRequiredString2}from"./runtime/context.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CONTEXT_OUTPUT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_TERMINAL_TRANSITION_POLICY,DEPENDENCY_KIND_VALUES,EXIT_CODE,HISTORY_EVENT_CLASSIFICATION_VERSION,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,MAINTENANCE_HISTORY_OPERATIONS,NEXT_OUTPUT_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_GITIGNORE_END,PM_GITIGNORE_START,PmCliError2 as PmCliError,PmClient,PmCompleteListValidationError,RISK_VALUES,SEARCH_EXTENSION_FLAG_DEFINITIONS,STATUS_VALUES,SUBSTANTIVE_HISTORY_OPERATIONS,acquireLock,acquireLockLease,aggregate,analyzeSdkActionCoverage,append,appendHistoryEntry,applyTerminalOrderingPolicy,assertCompleteListResult,canonicalDocument,certifyCompleteListResult2 as certifyCompleteListResult,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,clearWorkspaceContractsCache2 as clearWorkspaceContractsCache,close,closeItem,closeTask,comments,commitImportedItem,config,context,copy,create,createCompleteListOptions2 as createCompleteListOptions,createHistoryEntry,createPmCliExpectedError,deleteItem,deps,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureTrackerInitialized,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getPmGitignoreBlock,getSettingsPath2 as getSettingsPath,getWorkspaceContracts,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,inspectCompleteListResult,isPmCliExpectedError,isTerminalStatus,isTimestampLiteral,jaccardSimilarity,learnings,list,listAllComplete,listAllItemMetadata,listAllItemMetadataLight,loadCreateTemplateOptions,locateItem,next,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,parseTags,pathExists2 as pathExists,pauseTask,profile,profileApply,profileLint,profileList,profileShow,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString2 as readRequiredString,readSettings2 as readSettings,readStringOption,release,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,reopen,requireTerminalReason,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemTypeRegistry,resolvePmRoot2 as resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveTerminalReason,restore,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runCalendar,runClose,runCloseTask,runCompletion,runContext,runCopy,runDelete,runDuplicates,runFocus,runGet,runGuide,runList,runNext,runPauseTask,runReindex,runReopen,runRestore,runSearch,runStartTask,runStats,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runUpdate,runWithActiveExtensions,scanItemFormatVersions,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,search,selectImportAuthor,serializeItemDocument,splitFrontMatter,startTask,stats,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,upgrade,validate,writeFileAtomic};
2
2
  //# sourceMappingURL=runtime.js.map
@@ -9,6 +9,8 @@ import { type CreateResult } from "./lifecycle/create.js";
9
9
  export interface SchedulingShortcutCommonOptions {
10
10
  /** Optional parent item id. */
11
11
  parent?:string;
12
+ /** Opt into saved session focus when no explicit parent is supplied. */
13
+ inheritFocus?:boolean;
12
14
  /** Permit a parent that has not been created yet. */
13
15
  allowMissingParent?:boolean;
14
16
  /** Comma-separated item tags. */
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="015a3a52-f631-5ab7-b5c5-10a54a0b750c")}catch{}})();import{transferMutationStdinTokenPolicy}from"./runtime-primitives.js";import{runCreate}from"./lifecycle/create.js";const DEFAULT_DURATION="1h",DEFAULT_START="now",DEFAULT_REMINDER_AT="+1d";function appendQuotedPair(pairs,key,value){value!==void 0&&pairs.push(`${key}="${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function buildCommonOptions(type,title,options){const createOptions={type,title,schedulePreset:"lightweight",parent:options.parent,allowMissingParent:options.allowMissingParent,tags:options.tags,priority:options.priority,body:options.body,description:options.description,author:options.author,message:options.message};return transferMutationStdinTokenPolicy(options,createOptions)}async function createMeetingOrEvent(type,title,options,global2){const createOptions=buildCommonOptions(type,title,options),pairs=[];return appendQuotedPair(pairs,"start",options.start??DEFAULT_START),options.end!==void 0?appendQuotedPair(pairs,"end",options.end):appendQuotedPair(pairs,"duration",options.duration??DEFAULT_DURATION),appendQuotedPair(pairs,"location",options.location),appendQuotedPair(pairs,"timezone",options.timezone),options.allDay===!0&&appendQuotedPair(pairs,"all_day","true"),createOptions.event=[pairs.join(",")],runCreate(createOptions,global2)}function runMeet(title,options,global2){return createMeetingOrEvent("Meeting",title,options,global2)}function runEvent(title,options,global2){return createMeetingOrEvent("Event",title,options,global2)}function runRemind(title,options,global2){const createOptions=buildCommonOptions("Reminder",title,options),pairs=[];return appendQuotedPair(pairs,"at",options.at??DEFAULT_REMINDER_AT),appendQuotedPair(pairs,"text",options.text??title),createOptions.reminder=[pairs.join(",")],runCreate(createOptions,global2)}export{runEvent,runMeet,runRemind};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8e3b8e8c-5c05-5c68-bfe2-cb3ca0a17a20")}catch{}})();import{transferMutationStdinTokenPolicy}from"./runtime-primitives.js";import{runCreate}from"./lifecycle/create.js";const DEFAULT_DURATION="1h",DEFAULT_START="now",DEFAULT_REMINDER_AT="+1d";function appendQuotedPair(pairs,key,value){value!==void 0&&pairs.push(`${key}="${value.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`)}function buildCommonOptions(type,title,options){const createOptions={type,title,schedulePreset:"lightweight",parent:options.parent,inheritFocus:options.inheritFocus,allowMissingParent:options.allowMissingParent,tags:options.tags,priority:options.priority,body:options.body,description:options.description,author:options.author,message:options.message};return transferMutationStdinTokenPolicy(options,createOptions)}async function createMeetingOrEvent(type,title,options,global2){const createOptions=buildCommonOptions(type,title,options),pairs=[];return appendQuotedPair(pairs,"start",options.start??DEFAULT_START),options.end!==void 0?appendQuotedPair(pairs,"end",options.end):appendQuotedPair(pairs,"duration",options.duration??DEFAULT_DURATION),appendQuotedPair(pairs,"location",options.location),appendQuotedPair(pairs,"timezone",options.timezone),options.allDay===!0&&appendQuotedPair(pairs,"all_day","true"),createOptions.event=[pairs.join(",")],runCreate(createOptions,global2)}function runMeet(title,options,global2){return createMeetingOrEvent("Meeting",title,options,global2)}function runEvent(title,options,global2){return createMeetingOrEvent("Event",title,options,global2)}function runRemind(title,options,global2){const createOptions=buildCommonOptions("Reminder",title,options),pairs=[];return appendQuotedPair(pairs,"at",options.at??DEFAULT_REMINDER_AT),appendQuotedPair(pairs,"text",options.text??title),createOptions.reminder=[pairs.join(",")],runCreate(createOptions,global2)}export{runEvent,runMeet,runRemind};
2
2
  //# sourceMappingURL=scheduling-shortcuts.js.map
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="8d04c087-62e4-51d3-8832-6cbcfd3ed993")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{createHash}from"node:crypto";import fs from"node:fs/promises";import path from"node:path";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendWorkspaceHistoryChange}from"../core/history/workspace-history.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{parseFieldsFile,serializeFieldsFile}from"../core/schema/fields-file.js";import{parseItemTypesFile,serializeItemTypesFile}from"../core/schema/item-types-file.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{parseStatusDefsFile,serializeStatusDefsFile}from"../core/schema/status-defs-file.js";import{normalizeStatusToken}from"../core/schema/status-token.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{listAllItemMetadataLight,locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{toErrorMessage}from"../core/shared/primitives.js";import{readItemMetadataDerivedIndexState,queryItemMetadataIndex}from"./item-metadata-index.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function requiredText(value,field){if(typeof value!="string"||value.trim().length===0)throw new TypeError(`Schema migration ${field} must be non-empty`);return value.trim()}function requiredMigrationId(value){const migrationId=requiredText(value,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(migrationId))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return migrationId}function deriveSchemaEvolutionMigrationId(requestInput,migrationScope){const request=normalizedRequest(requestInput),scope=requiredText(migrationScope,"migrationScope");return`auto-${createHash("sha256").update(JSON.stringify({scope,request})).digest("hex").slice(0,20)}`}function normalizedRequest(request){const normalized=request.kind==="rename-type"?{kind:request.kind,from:requiredText(request.from,"source"),to:requiredText(request.to,"target")}:request.kind==="rename-field"?{kind:request.kind,from:normalizeStatusToken(requiredText(request.from,"source")),to:normalizeStatusToken(requiredText(request.to,"target")),...request.type===void 0?{}:{type:requiredText(request.type,"type")}}:{kind:request.kind,from:normalizeStatusToken(requiredText(request.from,"source")),to:normalizeStatusToken(requiredText(request.to,"target"))};if(normalized.from.toLowerCase()===normalized.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return normalized}function schemaSectionFor(request){return request.kind==="rename-type"?"types":request.kind==="rename-field"?"fields":"statuses"}function schemaPathFor(pmRoot,settings,request){const schema=normalizeRuntimeSchemaSettings(settings.schema),section=schemaSectionFor(request);return filePathForSchemaSection(pmRoot,schema.files[section],DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section])}function planStoragePath(pmRoot,migrationId){return path.join(pmRoot,"transactions","schema",`${migrationId}-plan.json`)}function parseSchemaAuditValue(raw){return raw.length===0?null:JSON.parse(raw)}async function readSchemaFileSnapshot(filePath){const raw=await readFileIfExists(filePath);return{exists:raw!==null,raw:raw??""}}async function restoreSchemaFileSnapshot(filePath,snapshot){snapshot.exists?await writeFileAtomic(filePath,snapshot.raw):await fs.rm(filePath,{force:!0})}function mutateTypeDefinition(raw,request,phase){const file=parseItemTypesFile(raw),sourceIndex=file.definitions.findIndex(definition=>definition.name.trim().toLowerCase()===request.from.toLowerCase()),targetIndex=file.definitions.findIndex(definition=>definition.name.trim().toLowerCase()===request.to.toLowerCase());if(phase==="stage"){if(targetIndex>=0)return serializeItemTypesFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom type "${request.from}".`);file.definitions.push({...file.definitions[sourceIndex],name:request.to})}else sourceIndex>=0&&file.definitions.splice(sourceIndex,1);return serializeItemTypesFile(file)}function mutateFieldDefinition(raw,request,phase){const file=parseFieldsFile(raw),sourceIndex=file.fields.findIndex(definition=>definition.key===request.from),targetIndex=file.fields.findIndex(definition=>definition.key===request.to);if(phase==="stage"){if(targetIndex>=0)return serializeFieldsFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom field "${request.from}".`);const source=file.fields[sourceIndex];file.fields.push({...source,key:request.to,metadata_key:request.to,front_matter_key:request.to,cli_flag:request.to.replaceAll("_","-")})}else sourceIndex>=0&&file.fields.splice(sourceIndex,1);return serializeFieldsFile(file)}function mutateStatusDefinition(raw,request,phase){const file=parseStatusDefsFile(raw),sourceIndex=file.statuses.findIndex(definition=>definition.id===request.from),targetIndex=file.statuses.findIndex(definition=>definition.id===request.to);if(phase==="stage"){if(targetIndex>=0)return serializeStatusDefsFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom status "${request.from}".`);file.statuses.push({...file.statuses[sourceIndex],id:request.to})}else sourceIndex>=0&&file.statuses.splice(sourceIndex,1);return serializeStatusDefsFile(file)}function mutateSchemaDefinition(raw,request,phase){return request.kind==="rename-type"?mutateTypeDefinition(raw,request,phase):request.kind==="rename-field"?mutateFieldDefinition(raw,request,phase):mutateStatusDefinition(raw,request,phase)}function replaceMatchingToken(value,request){return typeof value=="string"&&value.trim().toLowerCase()===request.from.toLowerCase()?request.to:value}function objectRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function objectRecordList(value){return Array.isArray(value)?value.map(candidate=>objectRecord(candidate)).filter(candidate=>candidate!==void 0):[]}function mutateTypeReferences(parsed,request){for(const field of objectRecordList(parsed.fields))Array.isArray(field.required_types)&&(field.required_types=field.required_types.map(value=>replaceMatchingToken(value,request)));for(const workflow of objectRecordList(parsed.type_workflows))workflow.type=replaceMatchingToken(workflow.type,request)}function mutateStatusReferences(parsed,request){for(const definition of objectRecordList(parsed.definitions))definition.default_status=replaceMatchingToken(definition.default_status,request);const workflow=objectRecord(parsed.workflow);if(workflow)for(const[key,value]of Object.entries(workflow))workflow[key]=replaceMatchingToken(value,request);for(const typeWorkflow of objectRecordList(parsed.type_workflows))Array.isArray(typeWorkflow.allowed_transitions)&&(typeWorkflow.allowed_transitions=typeWorkflow.allowed_transitions.map(pair=>Array.isArray(pair)?pair.map(value=>replaceMatchingToken(value,request)):pair))}function mutateFieldReferences(parsed,request){for(const definition of objectRecordList(parsed.definitions)){for(const key of["required_create_fields","required_create_repeatables"])Array.isArray(definition[key])&&(definition[key]=definition[key].map(value=>replaceMatchingToken(value,request)));for(const key of["options","command_option_policies"])for(const option of objectRecordList(definition[key])){const fieldKey=key==="options"?"key":"option";option[fieldKey]=replaceMatchingToken(option[fieldKey],request)}}}function mutateTemplateReferences(parsed,request){const options=objectRecord(parsed.options);if(!options)return;if(request.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(options,request.from))return;if(Object.prototype.hasOwnProperty.call(options,request.to))throw new TypeError(`Schema migration collision in saved template "${String(parsed.name??"unknown")}": target field "${request.to}" already exists.`);options[request.to]=options[request.from],delete options[request.from];return}const key=request.kind==="rename-type"?"type":"status";options[key]=replaceMatchingToken(options[key],request)}function mutateSchemaReferences(raw,request){const parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return raw;const record=parsed;return request.kind==="rename-type"?mutateTypeReferences(record,request):request.kind==="rename-field"?mutateFieldReferences(record,request):mutateStatusReferences(record,request),mutateTemplateReferences(record,request),`${JSON.stringify(record,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="09d88765-6283-5287-b293-43300251833f")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{createHash}from"node:crypto";import fs from"node:fs/promises";import path from"node:path";import{isFileMissingError,readFileIfExists,writeFileAtomic}from"../core/fs/fs-utils.js";import{appendWorkspaceHistoryChange}from"../core/history/workspace-history.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{parseFieldsFile,serializeFieldsFile}from"../core/schema/fields-file.js";import{parseItemTypesFile,serializeItemTypesFile}from"../core/schema/item-types-file.js";import{DEFAULT_RUNTIME_SCHEMA_FILE_PATHS,filePathForSchemaSection,normalizeRuntimeSchemaSettings}from"../core/schema/runtime-schema.js";import{parseStatusDefsFile,serializeStatusDefsFile}from"../core/schema/status-defs-file.js";import{normalizeStatusToken}from"../core/schema/status-token.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{listAllItemMetadataLight,locateItem,mutateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolveAuthor}from"../core/shared/author.js";import{toErrorMessage}from"../core/shared/primitives.js";import{readItemMetadataDerivedIndexState,queryItemMetadataIndex}from"./item-metadata-index.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function requiredText(value,field){if(typeof value!="string"||value.trim().length===0)throw new TypeError(`Schema migration ${field} must be non-empty`);return value.trim()}function requiredMigrationId(value){const migrationId=requiredText(value,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(migrationId))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return migrationId}function deriveSchemaEvolutionMigrationId(requestInput,migrationScope){const request=normalizedRequest(requestInput),scope=requiredText(migrationScope,"migrationScope");return`auto-${createHash("sha256").update(JSON.stringify({scope,request})).digest("hex").slice(0,20)}`}function normalizedRequest(request){const normalized=request.kind==="rename-type"?{kind:request.kind,from:requiredText(request.from,"source"),to:requiredText(request.to,"target")}:request.kind==="rename-field"?{kind:request.kind,from:normalizeStatusToken(requiredText(request.from,"source")),to:normalizeStatusToken(requiredText(request.to,"target")),...request.type===void 0?{}:{type:requiredText(request.type,"type")}}:{kind:request.kind,from:normalizeStatusToken(requiredText(request.from,"source")),to:normalizeStatusToken(requiredText(request.to,"target"))};if(normalized.from.toLowerCase()===normalized.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return normalized}function schemaSectionFor(request){return request.kind==="rename-type"?"types":request.kind==="rename-field"?"fields":"statuses"}function schemaPathFor(pmRoot,settings,request){const schema=normalizeRuntimeSchemaSettings(settings.schema),section=schemaSectionFor(request);return filePathForSchemaSection(pmRoot,schema.files[section],DEFAULT_RUNTIME_SCHEMA_FILE_PATHS[section])}function planStoragePath(pmRoot,migrationId){return path.join(pmRoot,"transactions","schema",`${migrationId}-plan.json`)}function parseSchemaAuditValue(raw){return raw.length===0?null:JSON.parse(raw)}async function readSchemaFileSnapshot(filePath){const raw=await readFileIfExists(filePath);return{exists:raw!==null,raw:raw??""}}async function restoreSchemaFileSnapshot(filePath,snapshot){snapshot.exists?await writeFileAtomic(filePath,snapshot.raw):await fs.rm(filePath,{force:!0})}function mutateTypeDefinition(raw,request,phase){const file=parseItemTypesFile(raw),sourceIndex=file.definitions.findIndex(definition=>definition.name.trim().toLowerCase()===request.from.toLowerCase()),targetIndex=file.definitions.findIndex(definition=>definition.name.trim().toLowerCase()===request.to.toLowerCase());if(phase==="stage"){if(targetIndex>=0)return serializeItemTypesFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom type "${request.from}".`);file.definitions.push({...file.definitions[sourceIndex],name:request.to})}else sourceIndex>=0&&file.definitions.splice(sourceIndex,1);return serializeItemTypesFile(file)}function mutateFieldDefinition(raw,request,phase){const file=parseFieldsFile(raw),sourceIndex=file.fields.findIndex(definition=>definition.key===request.from),targetIndex=file.fields.findIndex(definition=>definition.key===request.to);if(phase==="stage"){if(targetIndex>=0)return serializeFieldsFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom field "${request.from}".`);const source=file.fields[sourceIndex];file.fields.push({...source,key:request.to,metadata_key:request.to,front_matter_key:request.to,cli_flag:request.to.replaceAll("_","-")})}else sourceIndex>=0&&file.fields.splice(sourceIndex,1);return serializeFieldsFile(file)}function mutateStatusDefinition(raw,request,phase){const file=parseStatusDefsFile(raw),sourceIndex=file.statuses.findIndex(definition=>definition.id===request.from),targetIndex=file.statuses.findIndex(definition=>definition.id===request.to);if(phase==="stage"){if(targetIndex>=0)return serializeStatusDefsFile(file);if(sourceIndex<0)throw new TypeError(`Unknown custom status "${request.from}".`);file.statuses.push({...file.statuses[sourceIndex],id:request.to})}else sourceIndex>=0&&file.statuses.splice(sourceIndex,1);return serializeStatusDefsFile(file)}function mutateSchemaDefinition(raw,request,phase){return request.kind==="rename-type"?mutateTypeDefinition(raw,request,phase):request.kind==="rename-field"?mutateFieldDefinition(raw,request,phase):mutateStatusDefinition(raw,request,phase)}function replaceMatchingToken(value,request){return typeof value=="string"&&value.trim().toLowerCase()===request.from.toLowerCase()?request.to:value}function objectRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:void 0}function objectRecordList(value){return Array.isArray(value)?value.map(candidate=>objectRecord(candidate)).filter(candidate=>candidate!==void 0):[]}function mutateTypeReferences(parsed,request){for(const field of objectRecordList(parsed.fields))Array.isArray(field.required_types)&&(field.required_types=field.required_types.map(value=>replaceMatchingToken(value,request)));for(const workflow of objectRecordList(parsed.type_workflows))workflow.type=replaceMatchingToken(workflow.type,request)}function mutateStatusReferences(parsed,request){for(const definition of objectRecordList(parsed.definitions))definition.default_status=replaceMatchingToken(definition.default_status,request);const workflow=objectRecord(parsed.workflow);if(workflow)for(const[key,value]of Object.entries(workflow))workflow[key]=replaceMatchingToken(value,request);for(const typeWorkflow of objectRecordList(parsed.type_workflows))Array.isArray(typeWorkflow.allowed_transitions)&&(typeWorkflow.allowed_transitions=typeWorkflow.allowed_transitions.map(pair=>Array.isArray(pair)?pair.map(value=>replaceMatchingToken(value,request)):pair))}function mutateFieldReferences(parsed,request){for(const definition of objectRecordList(parsed.definitions)){for(const key of["required_create_fields","required_create_repeatables"])Array.isArray(definition[key])&&(definition[key]=definition[key].map(value=>replaceMatchingToken(value,request)));for(const key of["options","command_option_policies"])for(const option of objectRecordList(definition[key])){const fieldKey=key==="options"?"key":"option";option[fieldKey]=replaceMatchingToken(option[fieldKey],request)}}}function mutateTemplateReferences(parsed,request){const options=objectRecord(parsed.options);if(!options)return;if(request.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(options,request.from))return;if(Object.prototype.hasOwnProperty.call(options,request.to))throw new TypeError(`Schema migration collision in saved template "${String(parsed.name??"unknown")}": target field "${request.to}" already exists.`);options[request.to]=options[request.from],delete options[request.from];return}const key=request.kind==="rename-type"?"type":"status";options[key]=replaceMatchingToken(options[key],request)}function mutateSchemaReferences(raw,request){const parsed=JSON.parse(raw);if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return raw;const record=parsed;return request.kind==="rename-type"?mutateTypeReferences(record,request):request.kind==="rename-field"?mutateFieldReferences(record,request):mutateStatusReferences(record,request),mutateTemplateReferences(record,request),`${JSON.stringify(record,null,2)}
2
2
  `}function schemaDefinitionState(raw,request){if(request.kind==="rename-type"){const definitions2=parseItemTypesFile(raw).definitions;return{source:definitions2.some(entry=>entry.name.trim().toLowerCase()===request.from.toLowerCase()),target:definitions2.some(entry=>entry.name.trim().toLowerCase()===request.to.toLowerCase())}}if(request.kind==="rename-field"){const definitions2=parseFieldsFile(raw).fields;return{source:definitions2.some(entry=>entry.key===request.from),target:definitions2.some(entry=>entry.key===request.to)}}const definitions=parseStatusDefsFile(raw).statuses;return{source:definitions.some(entry=>entry.id===request.from),target:definitions.some(entry=>entry.id===request.to)}}function changedFieldsForItem(item,request){const record=item;return request.kind==="rename-type"?item.type.toLowerCase()===request.to.toLowerCase()?[]:["type"]:request.kind==="remap-status"?item.status.toLowerCase()===request.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(record,request.to)&&!Object.prototype.hasOwnProperty.call(record,request.from)?[]:[request.from,request.to]}function planItem(item,request){if(request.kind==="rename-type")return item.type.toLowerCase()===request.from.toLowerCase()?{id:item.id,changes:[{field:"type",before:item.type,after:request.to}]}:null;if(request.kind==="remap-status")return item.status.toLowerCase()===request.from.toLowerCase()?{id:item.id,changes:[{field:"status",before:item.status,after:request.to}]}:null;if(request.type!==void 0&&item.type.toLowerCase()!==request.type.toLowerCase())return null;const record=item;if(!Object.prototype.hasOwnProperty.call(record,request.from))return null;if(Object.prototype.hasOwnProperty.call(record,request.to))throw new TypeError(`Schema migration collision on item "${item.id}": target field "${request.to}" already exists.`);return{id:item.id,changes:[{field:request.from,before:record[request.from],after:void 0},{field:request.to,before:void 0,after:record[request.from]}]}}function planSchemaEvolutionMigration(items,options){const request=normalizedRequest(options.request),migrationId=options.migrationId===void 0?deriveSchemaEvolutionMigrationId(request,options.migrationScope??"plan"):requiredMigrationId(options.migrationId),completeItems=items.map(item=>planItem(item,request)).filter(entry=>entry!==null).sort((left,right)=>left.id.localeCompare(right.id)),fingerprint=createHash("sha256").update(JSON.stringify({migrationId,request,items:completeItems})).digest("hex"),completed=new Set([...options.completedItemIds??[]].map(id=>id.trim()).filter(id=>id.length>0)),pendingItems=completeItems.filter(entry=>!completed.has(entry.id));return Object.freeze({migration_id:migrationId,request,fingerprint,affected_item_count:completeItems.length,pending_item_count:pendingItems.length,skipped_completed_count:completeItems.length-pendingItems.length,items:Object.freeze(pendingItems)})}async function candidateItems(params){const typeRegistry=resolveItemTypeRegistry(params.settings,getActiveExtensionRegistrations()),folders=[...new Set(Object.values(typeRegistry.type_to_folder))],indexState=await readItemMetadataDerivedIndexState(params.pmRoot,folders),query=params.request.kind==="rename-type"?{types:[params.request.from]}:params.request.kind==="remap-status"?{statuses:[params.request.from]}:{metadataKeys:[params.request.from],...params.request.type===void 0?{}:{types:[params.request.type]}},indexed=indexState?await queryItemMetadataIndex({pmRoot:params.pmRoot,expectedSourceCursor:indexState.source_cursor,query}):null;return indexed?{items:indexed.items,selectionSource:"derived_index",typeToFolder:typeRegistry.type_to_folder}:{items:await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,typeRegistry.type_to_folder,[],params.settings.schema),selectionSource:"scan",typeToFolder:typeRegistry.type_to_folder}}async function readStoredPlan(pmRoot,migrationId){const raw=await readFileIfExists(planStoragePath(pmRoot,migrationId));if(raw===null)return null;try{const stored=JSON.parse(raw);if(stored.schema_version!==1||stored.plan.migration_id!==migrationId||!Array.isArray(stored.plan.items))throw new TypeError("invalid plan envelope");return stored.plan}catch(error){throw new PmCliError(`Stored schema migration plan "${migrationId}" is invalid: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE)}}async function writeStoredPlan(pmRoot,plan){const target=planStoragePath(pmRoot,plan.migration_id);await fs.mkdir(path.dirname(target),{recursive:!0});const stored={schema_version:1,plan,created_at:new Date().toISOString()};await writeFileAtomic(target,`${JSON.stringify(stored,null,2)}
3
- `)}function requestsEqual(left,right){return JSON.stringify(left)===JSON.stringify(right)}async function readCurrentItem(params){const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Schema migration item "${params.id}" no longer exists.`,EXIT_CODE.NOT_FOUND);return(await readLocatedItem(located,{schema:params.settings.schema})).document.metadata}function applyItemRequest(document,request,direction){const source=direction==="forward"?request.from:request.to,target=direction==="forward"?request.to:request.from;if(request.kind==="rename-type"){if(document.metadata.type.toLowerCase()===target.toLowerCase())return[];if(document.metadata.type.toLowerCase()!==source.toLowerCase())throw new TypeError(`Schema migration expected type "${source}" on item "${document.metadata.id}".`);return document.metadata.type=target,["type"]}if(request.kind==="remap-status"){if(document.metadata.status.toLowerCase()===target.toLowerCase())return[];if(document.metadata.status.toLowerCase()!==source.toLowerCase())throw new TypeError(`Schema migration expected status "${source}" on item "${document.metadata.id}".`);return document.metadata.status=target,["status"]}const record=document.metadata;if(Object.prototype.hasOwnProperty.call(record,target)&&!Object.prototype.hasOwnProperty.call(record,source))return[];if(!Object.prototype.hasOwnProperty.call(record,source)||Object.prototype.hasOwnProperty.call(record,target))throw new TypeError(`Schema migration field state changed concurrently on item "${document.metadata.id}".`);return record[target]=record[source],delete record[source],[source,target]}function schemaStep(params){return{id:params.id,inspect:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath),state=schemaDefinitionState(snapshot.raw,params.request),applied=params.phase==="stage"?state.source&&state.target:!state.source&&state.target;return{state:applied?"applied":"pending",...applied?{result:{phase:params.phase}}:{}}},prepareCompensation:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{exists:snapshot.exists,raw:snapshot.raw}},apply:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return await writeFileAtomic(params.filePath,mutateSchemaDefinition(snapshot.raw,params.request,params.phase)),{phase:params.phase}},compensate:async data=>{if(typeof data!="object"||data===null||Array.isArray(data)||typeof data.exists!="boolean"||typeof data.raw!="string")throw new TypeError(`Missing schema snapshot for ${params.id} compensation.`);await restoreSchemaFileSnapshot(params.filePath,{exists:data.exists,raw:data.raw})}}}function schemaReferenceStep(params){return{id:params.stepId,inspect:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{state:mutateSchemaReferences(snapshot.raw,params.request)===snapshot.raw?"applied":"pending"}},prepareCompensation:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{exists:snapshot.exists,raw:snapshot.raw}},apply:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return await writeFileAtomic(params.filePath,mutateSchemaReferences(snapshot.raw,params.request)),{file:params.filePath}},compensate:async data=>{if(typeof data!="object"||data===null||Array.isArray(data)||typeof data.exists!="boolean"||typeof data.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${params.stepId} compensation.`);await restoreSchemaFileSnapshot(params.filePath,{exists:data.exists,raw:data.raw})}}}function itemStep(params){return{id:`item-${params.id}`,inspect:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,item=await readCurrentItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id}),applied=changedFieldsForItem(item,params.request).length===0;return{state:applied?"applied":"pending",...applied?{result:{item_id:params.id}}:{}}},apply:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,result=await mutateItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id,op:`schema_${params.request.kind.replaceAll("-","_")}`,author:params.author,message:`Schema migration ${params.request.kind}: ${params.request.from} -> ${params.request.to}`,force:params.force,skipNoop:!0,mutate(document){return{changedFields:applyItemRequest(document,params.request,"forward")}}});return{item_id:params.id,changed_fields:result.changedFields}},compensate:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder;await mutateItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id,op:`schema_${params.request.kind.replaceAll("-","_")}_compensate`,author:params.author,message:`Compensate schema migration ${params.request.kind}: ${params.request.to} -> ${params.request.from}`,force:!0,skipNoop:!0,mutate(document){return{changedFields:applyItemRequest(document,params.request,"reverse")}}})}}}async function resolveMigrationPlan(params){const storedPlan=await readStoredPlan(params.pmRoot,params.migrationId);if(storedPlan){if(!requestsEqual(storedPlan.request,params.request))throw new PmCliError(`Schema migration id "${params.migrationId}" already belongs to a different request.`,EXIT_CODE.CONFLICT);return{plan:storedPlan,stored:!0}}const candidates=await candidateItems({pmRoot:params.pmRoot,settings:params.settings,request:params.request});return{plan:{...planSchemaEvolutionMigration(candidates.items,{migrationId:params.migrationId,request:params.request}),selection_source:candidates.selectionSource},stored:!1}}async function validateAndStoreMigrationPlan(params){const definitionState=schemaDefinitionState(await readFileIfExists(params.schemaPath)??"",params.request);if(!definitionState.source)throw new PmCliError(`Schema migration source "${params.request.from}" is not a custom definition.`,EXIT_CODE.NOT_FOUND);if(definitionState.target)throw new PmCliError(`Schema migration target "${params.request.to}" already exists.`,EXIT_CODE.CONFLICT);await writeStoredPlan(params.pmRoot,params.plan)}async function collectSchemaReferenceState(params){const normalizedSchema=normalizeRuntimeSchemaSettings(params.settings.schema),paths=[...new Set([["types",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types],["fields",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields],["workflows",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows]].map(([section,fallback])=>filePathForSchemaSection(params.pmRoot,normalizedSchema.files[section],fallback)).filter(filePath=>filePath!==params.schemaPath))];try{const templatesPath=path.join(params.pmRoot,"templates"),templateEntries=await fs.readdir(templatesPath,{withFileTypes:!0});paths.push(...templateEntries.filter(entry=>entry.isFile()&&entry.name.toLowerCase().endsWith(".json")).map(entry=>path.join(templatesPath,entry.name)))}catch(error){if(typeof error!="object"||error===null||!("code"in error)||!isFileMissingError(error))throw error}paths.sort((left,right)=>left.localeCompare(right));const snapshots=[];for(const filePath of paths){const beforeRaw=await readFileIfExists(filePath);beforeRaw!==null&&mutateSchemaReferences(beforeRaw,params.request)!==beforeRaw&&snapshots.push({filePath,beforeRaw})}return{paths,snapshots}}async function appendSchemaReferenceHistory(params){for(const reference of params.snapshots){const afterRaw=await fs.readFile(reference.filePath,"utf8"),relativePath=path.relative(params.pmRoot,reference.filePath).replaceAll("\\","/");await appendWorkspaceHistoryChange({pmRoot:params.pmRoot,author:params.author,documentPath:relativePath,before:parseSchemaAuditValue(reference.beforeRaw),after:parseSchemaAuditValue(afterRaw),op:"schema_migration_reference",idempotencyKey:`${params.plan.migration_id}:${params.plan.fingerprint}:${relativePath}`,message:`${params.request.kind}: ${params.request.from} -> ${params.request.to}`,lockTtlSeconds:params.settings.locks.ttl_seconds,lockWaitMs:params.settings.locks.wait_ms})}}async function runSchemaEvolutionMigration(requestInput,options,global2){const request=normalizedRequest(requestInput),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const migrationId=options.migrationId===void 0?deriveSchemaEvolutionMigrationId(request,await fs.realpath(pmRoot)):requiredMigrationId(options.migrationId),settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),resolvedPlan=await resolveMigrationPlan({pmRoot,settings,migrationId,request}),plan=resolvedPlan.plan;if(options.dryRun===!0)return{...plan,action:request.kind,applied:!1,recovered:!1,migrated_item_count:0};const schemaPath=schemaPathFor(pmRoot,settings,request),schemaBefore=await fs.readFile(schemaPath,"utf8");resolvedPlan.stored||await validateAndStoreMigrationPlan({pmRoot,schemaPath,request,plan});const references=await collectSchemaReferenceState({pmRoot,schemaPath,settings,request}),steps=[schemaStep({id:"stage-schema",filePath:schemaPath,request,phase:"stage"}),...references.paths.map((filePath,index)=>schemaReferenceStep({filePath,request,stepId:`reference-${String(index+1).padStart(4,"0")}`})),...plan.items.map(entry=>itemStep({pmRoot,id:entry.id,request,author,force:options.force===!0})),schemaStep({id:"retire-source",filePath:schemaPath,request,phase:"retire"})],committed=await commitWorkspaceTransaction({pmRoot,transactionId:`schema-${migrationId}`,author,steps,lockTtlSeconds:Math.max(settings.locks.ttl_seconds,300),lockWaitMs:settings.locks.wait_ms}),schemaAfter=await fs.readFile(schemaPath,"utf8"),{historyPath}=await appendWorkspaceHistoryChange({pmRoot,author,documentPath:path.relative(pmRoot,schemaPath).replaceAll("\\","/"),before:parseSchemaAuditValue(schemaBefore),after:parseSchemaAuditValue(schemaAfter),op:"schema_migration",idempotencyKey:`${plan.migration_id}:${plan.fingerprint}`,message:`${request.kind}: ${request.from} -> ${request.to}; affected=${plan.affected_item_count}`,lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms});return await appendSchemaReferenceHistory({pmRoot,author,settings,request,plan,snapshots:references.snapshots}),{...plan,action:request.kind,applied:!0,recovered:committed.recovered,migrated_item_count:plan.affected_item_count,workspace_history_path:historyPath}}function formatSchemaEvolutionMigrationHuman(result){const mode=result.applied?"applied":"dry-run",recovery=result.recovered?" (recovered)":"";return[`${result.action}: ${result.request.from} -> ${result.request.to} [${mode}${recovery}]`,`migration_id: ${result.migration_id}`,`affected: ${result.affected_item_count}`,`pending: ${result.pending_item_count}`,`fingerprint: ${result.fingerprint}`].join(`
3
+ `)}function requestsEqual(left,right){return JSON.stringify(left)===JSON.stringify(right)}async function readCurrentItem(params){const located=await locateItem(params.pmRoot,params.id,params.settings.id_prefix,params.settings.item_format,params.typeToFolder);if(!located)throw new PmCliError(`Schema migration item "${params.id}" no longer exists.`,EXIT_CODE.NOT_FOUND);return(await readLocatedItem(located,{schema:params.settings.schema})).document.metadata}function applyItemRequest(document,request,direction){const source=direction==="forward"?request.from:request.to,target=direction==="forward"?request.to:request.from;if(request.kind==="rename-type"){if(document.metadata.type.toLowerCase()===target.toLowerCase())return[];if(document.metadata.type.toLowerCase()!==source.toLowerCase())throw new TypeError(`Schema migration expected type "${source}" on item "${document.metadata.id}".`);return document.metadata.type=target,["type"]}if(request.kind==="remap-status"){if(document.metadata.status.toLowerCase()===target.toLowerCase())return[];if(document.metadata.status.toLowerCase()!==source.toLowerCase())throw new TypeError(`Schema migration expected status "${source}" on item "${document.metadata.id}".`);return document.metadata.status=target,["status"]}const record=document.metadata;if(Object.prototype.hasOwnProperty.call(record,target)&&!Object.prototype.hasOwnProperty.call(record,source))return[];if(!Object.prototype.hasOwnProperty.call(record,source)||Object.prototype.hasOwnProperty.call(record,target))throw new TypeError(`Schema migration field state changed concurrently on item "${document.metadata.id}".`);return record[target]=record[source],delete record[source],[source,target]}function schemaStep(params){return{id:params.id,inspect:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath),state=schemaDefinitionState(snapshot.raw,params.request),applied=params.phase==="stage"?state.source&&state.target:!state.source&&state.target;return{state:applied?"applied":"pending",...applied?{result:{phase:params.phase}}:{}}},prepareCompensation:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{exists:snapshot.exists,raw:snapshot.raw}},apply:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return await writeFileAtomic(params.filePath,mutateSchemaDefinition(snapshot.raw,params.request,params.phase)),{phase:params.phase}},compensate:async data=>{if(typeof data!="object"||data===null||Array.isArray(data)||typeof data.exists!="boolean"||typeof data.raw!="string")throw new TypeError(`Missing schema snapshot for ${params.id} compensation.`);await restoreSchemaFileSnapshot(params.filePath,{exists:data.exists,raw:data.raw})}}}function schemaReferenceStep(params){return{id:params.stepId,inspect:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{state:mutateSchemaReferences(snapshot.raw,params.request)===snapshot.raw?"applied":"pending"}},prepareCompensation:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return{exists:snapshot.exists,raw:snapshot.raw}},apply:async()=>{const snapshot=await readSchemaFileSnapshot(params.filePath);return await writeFileAtomic(params.filePath,mutateSchemaReferences(snapshot.raw,params.request)),{file:params.filePath}},compensate:async data=>{if(typeof data!="object"||data===null||Array.isArray(data)||typeof data.exists!="boolean"||typeof data.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${params.stepId} compensation.`);await restoreSchemaFileSnapshot(params.filePath,{exists:data.exists,raw:data.raw})}}}function itemStep(params){return{id:`item-${params.id}`,inspect:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,item=await readCurrentItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id}),applied=changedFieldsForItem(item,params.request).length===0;return{state:applied?"applied":"pending",...applied?{result:{item_id:params.id}}:{}}},apply:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,result=await mutateItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id,op:`schema_${params.request.kind.replaceAll("-","_")}`,author:params.author,message:`Schema migration ${params.request.kind}: ${params.request.from} -> ${params.request.to}`,force:params.force,skipNoop:!0,mutate(document){return{changedFields:applyItemRequest(document,params.request,"forward")}}});return{item_id:params.id,changed_fields:result.changedFields}},compensate:async()=>{const settings=await readSettings(params.pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder;await mutateItem({pmRoot:params.pmRoot,settings,typeToFolder,id:params.id,op:`schema_${params.request.kind.replaceAll("-","_")}_compensate`,author:params.author,message:`Compensate schema migration ${params.request.kind}: ${params.request.to} -> ${params.request.from}`,force:!0,skipNoop:!0,mutate(document){return{changedFields:applyItemRequest(document,params.request,"reverse")}}})}}}async function resolveMigrationPlan(params){const storedPlan=await readStoredPlan(params.pmRoot,params.migrationId);if(storedPlan){if(!requestsEqual(storedPlan.request,params.request))throw new PmCliError(`Schema migration id "${params.migrationId}" already belongs to a different request.`,EXIT_CODE.CONFLICT);return{plan:storedPlan,stored:!0}}const candidates=await candidateItems({pmRoot:params.pmRoot,settings:params.settings,request:params.request});return{plan:{...planSchemaEvolutionMigration(candidates.items,{migrationId:params.migrationId,request:params.request}),selection_source:candidates.selectionSource},stored:!1}}async function validateAndStoreMigrationPlan(params){const definitionState=schemaDefinitionState(await readFileIfExists(params.schemaPath)??"",params.request);if(!definitionState.source)throw new PmCliError(`Schema migration source "${params.request.from}" is not a custom definition.`,EXIT_CODE.NOT_FOUND);if(definitionState.target)throw new PmCliError(`Schema migration target "${params.request.to}" already exists.`,EXIT_CODE.CONFLICT);await writeStoredPlan(params.pmRoot,params.plan)}async function collectSchemaReferenceState(params){const normalizedSchema=normalizeRuntimeSchemaSettings(params.settings.schema),paths=[...new Set([["types",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.types],["fields",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.fields],["workflows",DEFAULT_RUNTIME_SCHEMA_FILE_PATHS.workflows]].map(([section,fallback])=>filePathForSchemaSection(params.pmRoot,normalizedSchema.files[section],fallback)).filter(filePath=>filePath!==params.schemaPath))];try{const templatesPath=path.join(params.pmRoot,"templates"),templateEntries=await fs.readdir(templatesPath,{withFileTypes:!0});paths.push(...templateEntries.filter(entry=>entry.isFile()&&entry.name.toLowerCase().endsWith(".json")).map(entry=>path.join(templatesPath,entry.name)))}catch(error){if(typeof error!="object"||error===null||!("code"in error)||!isFileMissingError(error))throw error}paths.sort((left,right)=>left.localeCompare(right));const snapshots=[];for(const filePath of paths){const beforeRaw=await readFileIfExists(filePath);beforeRaw!==null&&mutateSchemaReferences(beforeRaw,params.request)!==beforeRaw&&snapshots.push({filePath,beforeRaw})}return{paths,snapshots}}async function appendSchemaReferenceHistory(params){for(const reference of params.snapshots){const afterRaw=await fs.readFile(reference.filePath,"utf8"),relativePath=path.relative(params.pmRoot,reference.filePath).replaceAll("\\","/");await appendWorkspaceHistoryChange({pmRoot:params.pmRoot,author:params.author,documentPath:relativePath,before:parseSchemaAuditValue(reference.beforeRaw),after:parseSchemaAuditValue(afterRaw),op:"schema_migration_reference",idempotencyKey:`${params.plan.migration_id}:${params.plan.fingerprint}:${relativePath}`,message:`${params.request.kind}: ${params.request.from} -> ${params.request.to}`,lockTtlSeconds:params.settings.locks.ttl_seconds,lockWaitMs:params.settings.locks.wait_ms})}}async function runSchemaEvolutionMigration(requestInput,options,global2){const request=normalizedRequest(requestInput),pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const migrationId=options.migrationId===void 0?deriveSchemaEvolutionMigrationId(request,await fs.realpath(pmRoot)):requiredMigrationId(options.migrationId),settings=await readSettings(pmRoot),author=resolveAuthor(options.author,settings.author_default),resolvedPlan=await resolveMigrationPlan({pmRoot,settings,migrationId,request}),plan=resolvedPlan.plan;if(options.dryRun===!0)return{...plan,action:request.kind,applied:!1,recovered:!1,migrated_item_count:0};const schemaPath=schemaPathFor(pmRoot,settings,request),schemaBefore=await readFileIfExists(schemaPath)??"";resolvedPlan.stored||await validateAndStoreMigrationPlan({pmRoot,schemaPath,request,plan});const references=await collectSchemaReferenceState({pmRoot,schemaPath,settings,request}),steps=[schemaStep({id:"stage-schema",filePath:schemaPath,request,phase:"stage"}),...references.paths.map((filePath,index)=>schemaReferenceStep({filePath,request,stepId:`reference-${String(index+1).padStart(4,"0")}`})),...plan.items.map(entry=>itemStep({pmRoot,id:entry.id,request,author,force:options.force===!0})),schemaStep({id:"retire-source",filePath:schemaPath,request,phase:"retire"})],committed=await commitWorkspaceTransaction({pmRoot,transactionId:`schema-${migrationId}`,author,steps,lockTtlSeconds:Math.max(settings.locks.ttl_seconds,300),lockWaitMs:settings.locks.wait_ms}),schemaAfter=await fs.readFile(schemaPath,"utf8"),{historyPath}=await appendWorkspaceHistoryChange({pmRoot,author,documentPath:path.relative(pmRoot,schemaPath).replaceAll("\\","/"),before:parseSchemaAuditValue(schemaBefore),after:parseSchemaAuditValue(schemaAfter),op:"schema_migration",idempotencyKey:`${plan.migration_id}:${plan.fingerprint}`,message:`${request.kind}: ${request.from} -> ${request.to}; affected=${plan.affected_item_count}`,lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms});return await appendSchemaReferenceHistory({pmRoot,author,settings,request,plan,snapshots:references.snapshots}),{...plan,action:request.kind,applied:!0,recovered:committed.recovered,migrated_item_count:plan.affected_item_count,workspace_history_path:historyPath}}function formatSchemaEvolutionMigrationHuman(result){const mode=result.applied?"applied":"dry-run",recovery=result.recovered?" (recovered)":"";return[`${result.action}: ${result.request.from} -> ${result.request.to} [${mode}${recovery}]`,`migration_id: ${result.migration_id}`,`affected: ${result.affected_item_count}`,`pending: ${result.pending_item_count}`,`fingerprint: ${result.fingerprint}`].join(`
4
4
  `)}const schemaMigrationTestOnly={normalizedRequest,parseSchemaAuditValue,readSchemaFileSnapshot,mutateSchemaDefinition,mutateSchemaReferences,changedFieldsForItem,applyItemRequest,schemaStep,schemaReferenceStep,validateAndStoreMigrationPlan};export{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration,schemaMigrationTestOnly};
5
5
  //# sourceMappingURL=schema-migration.js.map
@@ -2,6 +2,11 @@ import type { GlobalOptions } from "../core/shared/command-types.js";
2
2
  type TemplateOptionValue = string | string[];
3
3
  /** Restricts create template options values accepted by command, SDK, and storage contracts. */
4
4
  export type CreateTemplateOptions = Record<string,TemplateOptionValue>;
5
+ /** Template save inputs retain extension-defined string options and normalize priority before storage. */
6
+ export interface TemplatesSaveOptions extends Record<string,unknown> {
7
+ /** Integer 0..4, numeric string, or named priority accepted by create. Stored as a numeric string. */
8
+ priority?:string | number;
9
+ }
5
10
  /** Restricts template source values accepted by command, SDK, and storage contracts. */
6
11
  export type TemplateSource = "builtin" | "user";
7
12
  interface StoredCreateTemplateDocument {
@@ -58,6 +63,7 @@ path:string;
58
63
  options:CreateTemplateOptions;
59
64
  }
60
65
  declare function normalizeTemplateName(rawName:string):string;
66
+ /** Normalize core priority and collect compatible string/list options before any persistence. */
61
67
  declare function extractTemplateOptions(rawOptions:Record<string,unknown>):CreateTemplateOptions;
62
68
  declare function parseStoredTemplateDocument(raw:string,normalizedName:string):StoredCreateTemplateDocument;
63
69
  declare function builtinTemplateDocument(normalizedName:string):StoredCreateTemplateDocument | null;
@@ -65,7 +71,7 @@ declare function readStoredTemplateDocument(pmRoot:string,normalizedName:string)
65
71
  /** Implements load create template options for the public runtime surface of this module. */
66
72
  export declare function loadCreateTemplateOptions(pmRoot:string,rawTemplateName:string):Promise<CreateTemplateOptions>;
67
73
  /** Implements run templates save for the public runtime surface of this module. */
68
- export declare function runTemplatesSave(rawTemplateName:string,options:Record<string,unknown>,global:GlobalOptions):Promise<TemplatesSaveResult>;
74
+ export declare function runTemplatesSave(rawTemplateName:string,options:TemplatesSaveOptions,global:GlobalOptions):Promise<TemplatesSaveResult>;
69
75
  /** Implements run templates list for the public runtime surface of this module. */
70
76
  export declare function runTemplatesList(global:GlobalOptions):Promise<TemplatesListResult>;
71
77
  /** Implements run templates show for the public runtime surface of this module. */
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ac2020a4-78bf-5aa3-a5c4-88d3196dfb1f")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{resolveAuthor}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}from"./cli-contracts.js";const TEMPLATE_DIRECTORY_NAME="templates",TEMPLATE_FILE_EXTENSION=".json",TEMPLATE_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,TEMPLATE_OPTION_REPEATABLE_KEYS=CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS.map(entry=>entry.target).filter(target=>target!=="acceptanceCriteria"),TEMPLATE_OPTION_REPEATABLE_KEY_SET=new Set(TEMPLATE_OPTION_REPEATABLE_KEYS),BUILTIN_TEMPLATE_TIMESTAMP="1970-01-01T00:00:00.000Z",BUILTIN_TEMPLATES={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4e476a2f-8735-53e9-88c3-b43bfc34e1f5")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import fs from"node:fs/promises";import path from"node:path";import{pathExists,readFileIfExists}from"../core/fs/fs-utils.js";import{writeWorkspaceJsonWithHistory}from"../core/history/workspace-history.js";import{resolveAuthor}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{resolvePriority}from"../core/item/priority.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS}from"./cli-contracts.js";const TEMPLATE_DIRECTORY_NAME="templates",TEMPLATE_FILE_EXTENSION=".json",TEMPLATE_NAME_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,TEMPLATE_OPTION_REPEATABLE_KEYS=CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS.map(entry=>entry.target).filter(target=>target!=="acceptanceCriteria"),TEMPLATE_OPTION_REPEATABLE_KEY_SET=new Set(TEMPLATE_OPTION_REPEATABLE_KEYS),BUILTIN_TEMPLATE_TIMESTAMP="1970-01-01T00:00:00.000Z",BUILTIN_TEMPLATES={bug:{type:"Issue",priority:"1",tags:"bug",acceptanceCriteria:"Bug no longer reproduces with the steps below and a regression test guards it.",expectedResult:"Describe the correct behavior.",actualResult:"Describe the observed (buggy) behavior.",body:`## Repro steps
2
2
  1.
3
3
  2.
4
4
  3.
@@ -22,6 +22,6 @@
22
22
  `},chore:{type:"Chore",priority:"3",tags:"chore",acceptanceCriteria:"Maintenance task done with no behavior change and green checks.",body:`## What
23
23
 
24
24
  ## Why
25
- `}},_testOnly={normalizeTemplateName,extractTemplateOptions,parseStoredTemplateDocument,builtinTemplateDocument,readStoredTemplateDocument};function normalizeTemplateName(rawName){const name=rawName.trim();if(!TEMPLATE_NAME_PATTERN.test(name))throw new PmCliError(`Invalid template name "${rawName}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,EXIT_CODE.USAGE);return name}function templatesDirectory(pmRoot){return path.join(pmRoot,TEMPLATE_DIRECTORY_NAME)}function templatePath(pmRoot,normalizedName){return path.join(templatesDirectory(pmRoot),`${normalizedName}${TEMPLATE_FILE_EXTENSION}`)}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function sortTemplateOptions(options){return Object.fromEntries(Object.entries(options).sort(([left],[right])=>left.localeCompare(right)))}function extractTemplateOptions(rawOptions){const next={};for(const[key,value]of Object.entries(rawOptions))if(value!==void 0){if(TEMPLATE_OPTION_REPEATABLE_KEY_SET.has(key)){if(typeof value=="string"){next[key]=[value];continue}if(!Array.isArray(value))continue;const values=value.filter(entry=>typeof entry=="string");values.length>0&&(next[key]=values);continue}if(typeof value=="string"){next[key]=value;continue}Array.isArray(value)&&value.every(entry=>typeof entry=="string")&&(next[key]=[...value])}return sortTemplateOptions(next)}function parseStoredTemplateOptions(rawOptions,templateName){if(typeof rawOptions!="object"||rawOptions===null||Array.isArray(rawOptions))throw new PmCliError(`Template "${templateName}" has invalid options payload.`,EXIT_CODE.GENERIC_FAILURE);const optionsRecord=rawOptions,normalized={};for(const[key,value]of Object.entries(optionsRecord)){const normalizedKey=key.trim();if(normalizedKey.length===0)throw new PmCliError(`Template "${templateName}" contains an empty option key.`,EXIT_CODE.GENERIC_FAILURE);if(typeof value=="string"){normalized[normalizedKey]=value;continue}if(Array.isArray(value)&&value.every(entry=>typeof entry=="string")){normalized[normalizedKey]=[...value];continue}throw new PmCliError(`Template "${templateName}" contains invalid value for option "${normalizedKey}".`,EXIT_CODE.GENERIC_FAILURE)}return sortTemplateOptions(normalized)}function parseStoredTemplateDocument(raw,normalizedName){let parsed;try{parsed=JSON.parse(raw)}catch{throw new PmCliError(`Template "${normalizedName}" contains invalid JSON.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError(`Template "${normalizedName}" has invalid document shape.`,EXIT_CODE.GENERIC_FAILURE);const record=parsed,options=parseStoredTemplateOptions(record.options,normalizedName),now=nowIso();return{name:typeof record.name=="string"&&record.name.trim().length>0?record.name.trim():normalizedName,created_at:typeof record.created_at=="string"?record.created_at:now,updated_at:typeof record.updated_at=="string"?record.updated_at:now,options}}function builtinTemplateDocument(normalizedName){const options=BUILTIN_TEMPLATES[normalizedName];return options?{name:normalizedName,created_at:BUILTIN_TEMPLATE_TIMESTAMP,updated_at:BUILTIN_TEMPLATE_TIMESTAMP,options:sortTemplateOptions({...options})}:null}async function resolveTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw!==null)return{document:parseStoredTemplateDocument(raw,normalizedName),source:"user"};const builtin=builtinTemplateDocument(normalizedName);if(builtin)return{document:builtin,source:"builtin"};throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND)}async function readStoredTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw===null)throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND);return parseStoredTemplateDocument(raw,normalizedName)}async function loadCreateTemplateOptions(pmRoot,rawTemplateName){const normalizedName=normalizeTemplateName(rawTemplateName),{document}=await resolveTemplateDocument(pmRoot,normalizedName);return document.options}async function runTemplatesSave(rawTemplateName,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const normalizedName=normalizeTemplateName(rawTemplateName),nextOptions=extractTemplateOptions(options);if(Object.keys(nextOptions).length===0)throw new PmCliError("templates save requires at least one create option flag",EXIT_CODE.USAGE);const now=nowIso(),storedPath=templatePath(pmRoot,normalizedName);let createdAt=now;await pathExists(storedPath)&&(createdAt=(await readStoredTemplateDocument(pmRoot,normalizedName)).created_at);const document={name:normalizedName,created_at:createdAt,updated_at:now,options:nextOptions},settings=await readSettings(pmRoot);return await fs.mkdir(templatesDirectory(pmRoot),{recursive:!0}),await writeWorkspaceJsonWithHistory({pmRoot,filePath:storedPath,raw:`${JSON.stringify(document,null,2)}
25
+ `}},_testOnly={normalizeTemplateName,extractTemplateOptions,parseStoredTemplateDocument,builtinTemplateDocument,readStoredTemplateDocument};function normalizeTemplateName(rawName){const name=rawName.trim();if(!TEMPLATE_NAME_PATTERN.test(name))throw new PmCliError(`Invalid template name "${rawName}". Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._-]*.`,EXIT_CODE.USAGE);return name}function templatesDirectory(pmRoot){return path.join(pmRoot,TEMPLATE_DIRECTORY_NAME)}function templatePath(pmRoot,normalizedName){return path.join(templatesDirectory(pmRoot),`${normalizedName}${TEMPLATE_FILE_EXTENSION}`)}async function ensureTrackerInitialized(pmRoot){await assertInitializedTracker(pmRoot)}function sortTemplateOptions(options){return Object.fromEntries(Object.entries(options).sort(([left],[right])=>left.localeCompare(right)))}function extractTemplateOptions(rawOptions){const next={};for(const[key,value]of Object.entries(rawOptions))if(value!==void 0){if(key==="priority"){next[key]=String(resolvePriority(value));continue}if(TEMPLATE_OPTION_REPEATABLE_KEY_SET.has(key)){if(typeof value=="string"){next[key]=[value];continue}if(!Array.isArray(value))continue;const values=value.filter(entry=>typeof entry=="string");values.length>0&&(next[key]=values);continue}if(typeof value=="string"){next[key]=value;continue}Array.isArray(value)&&value.every(entry=>typeof entry=="string")&&(next[key]=[...value])}return sortTemplateOptions(next)}function parseStoredTemplateOptions(rawOptions,templateName){if(typeof rawOptions!="object"||rawOptions===null||Array.isArray(rawOptions))throw new PmCliError(`Template "${templateName}" has invalid options payload.`,EXIT_CODE.GENERIC_FAILURE);const optionsRecord=rawOptions,normalized={};for(const[key,value]of Object.entries(optionsRecord)){const normalizedKey=key.trim();if(normalizedKey.length===0)throw new PmCliError(`Template "${templateName}" contains an empty option key.`,EXIT_CODE.GENERIC_FAILURE);if(typeof value=="string"){normalized[normalizedKey]=value;continue}if(Array.isArray(value)&&value.every(entry=>typeof entry=="string")){normalized[normalizedKey]=[...value];continue}throw new PmCliError(`Template "${templateName}" contains invalid value for option "${normalizedKey}".`,EXIT_CODE.GENERIC_FAILURE)}return sortTemplateOptions(normalized)}function parseStoredTemplateDocument(raw,normalizedName){let parsed;try{parsed=JSON.parse(raw)}catch{throw new PmCliError(`Template "${normalizedName}" contains invalid JSON.`,EXIT_CODE.GENERIC_FAILURE)}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError(`Template "${normalizedName}" has invalid document shape.`,EXIT_CODE.GENERIC_FAILURE);const record=parsed,options=parseStoredTemplateOptions(record.options,normalizedName),now=nowIso();return{name:typeof record.name=="string"&&record.name.trim().length>0?record.name.trim():normalizedName,created_at:typeof record.created_at=="string"?record.created_at:now,updated_at:typeof record.updated_at=="string"?record.updated_at:now,options}}function builtinTemplateDocument(normalizedName){const options=BUILTIN_TEMPLATES[normalizedName];return options?{name:normalizedName,created_at:BUILTIN_TEMPLATE_TIMESTAMP,updated_at:BUILTIN_TEMPLATE_TIMESTAMP,options:sortTemplateOptions({...options})}:null}async function resolveTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw!==null)return{document:parseStoredTemplateDocument(raw,normalizedName),source:"user"};const builtin=builtinTemplateDocument(normalizedName);if(builtin)return{document:builtin,source:"builtin"};throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND)}async function readStoredTemplateDocument(pmRoot,normalizedName){const raw=await readFileIfExists(templatePath(pmRoot,normalizedName));if(raw===null)throw new PmCliError(`Template "${normalizedName}" not found`,EXIT_CODE.NOT_FOUND);return parseStoredTemplateDocument(raw,normalizedName)}async function loadCreateTemplateOptions(pmRoot,rawTemplateName){const normalizedName=normalizeTemplateName(rawTemplateName),{document}=await resolveTemplateDocument(pmRoot,normalizedName);return document.options}async function runTemplatesSave(rawTemplateName,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const normalizedName=normalizeTemplateName(rawTemplateName),nextOptions=extractTemplateOptions(options);if(Object.keys(nextOptions).length===0)throw new PmCliError("templates save requires at least one create option flag",EXIT_CODE.USAGE);const now=nowIso(),storedPath=templatePath(pmRoot,normalizedName);let createdAt=now;await pathExists(storedPath)&&(createdAt=(await readStoredTemplateDocument(pmRoot,normalizedName)).created_at);const document={name:normalizedName,created_at:createdAt,updated_at:now,options:nextOptions},settings=await readSettings(pmRoot);return await fs.mkdir(templatesDirectory(pmRoot),{recursive:!0}),await writeWorkspaceJsonWithHistory({pmRoot,filePath:storedPath,raw:`${JSON.stringify(document,null,2)}
26
26
  `,op:"templates:save",author:resolveAuthor(void 0,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms}),{name:document.name,created_at:document.created_at,updated_at:document.updated_at,path:storedPath,options:document.options}}async function readUserTemplateNames(pmRoot){const dirPath=templatesDirectory(pmRoot);return await pathExists(dirPath)?(await fs.readdir(dirPath)).filter(entry=>entry.toLowerCase().endsWith(TEMPLATE_FILE_EXTENSION)).map(entry=>entry.slice(0,-TEMPLATE_FILE_EXTENSION.length)).filter(entry=>TEMPLATE_NAME_PATTERN.test(entry)):[]}async function runTemplatesList(global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const userTemplates=await readUserTemplateNames(pmRoot),userTemplateSet=new Set(userTemplates),builtinTemplates=Object.keys(BUILTIN_TEMPLATES).filter(name=>!userTemplateSet.has(name)),sortedUser=[...userTemplates].sort((left,right)=>left.localeCompare(right)),sortedBuiltin=[...builtinTemplates].sort((left,right)=>left.localeCompare(right)),templates=[...new Set([...sortedUser,...sortedBuiltin])].sort((left,right)=>left.localeCompare(right));return{templates,count:templates.length,builtin_templates:sortedBuiltin,user_templates:sortedUser}}async function runTemplatesShow(rawTemplateName,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await ensureTrackerInitialized(pmRoot);const normalizedName=normalizeTemplateName(rawTemplateName),{document,source}=await resolveTemplateDocument(pmRoot,normalizedName);return{name:document.name,source,created_at:document.created_at,updated_at:document.updated_at,path:source==="builtin"?`builtin:${normalizedName}`:templatePath(pmRoot,normalizedName),options:document.options}}export{_testOnly,loadCreateTemplateOptions,runTemplatesList,runTemplatesSave,runTemplatesShow};
27
27
  //# sourceMappingURL=templates.js.map
@@ -19,9 +19,11 @@ id:string;
19
19
  inspect():Promise<WorkspaceTransactionStepInspection>;
20
20
  /** Capture journal-safe pre-mutation data required by compensation. */
21
21
  prepareCompensation?():Promise<WorkspaceTransactionJsonValue | undefined>;
22
+ /** Opt in when compensation can reconcile partial apply effects still inspected as pending. */
23
+ compensatePending?:boolean;
22
24
  /** Apply the forward mutation and return a journal-safe result, or store nothing. */
23
25
  apply():Promise<WorkspaceTransactionJsonValue | undefined>;
24
- /** Idempotently reconcile only this step's exact forward mutation when present. */
26
+ /** Idempotently reconcile this step's effects; opt-in adapters also handle pending partial apply failures. */
25
27
  compensate(data?:WorkspaceTransactionJsonValue):Promise<void>;
26
28
  }
27
29
  /** Observable transition points available to diagnostics and failure injection. */
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1fae5539-4eb8-5eba-bfd6-a191c89448ec")}catch{}})();import{mkdir,readFile}from"node:fs/promises";import path from"node:path";import{acquireLock}from"../core/lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{nowIso}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";class WorkspaceTransactionInterruptedError extends Error{constructor(message="Workspace transaction interrupted"){super(message),this.name="WorkspaceTransactionInterruptedError"}}const WORKSPACE_TRANSACTION_LOCK_ID="sdk-workspace-transaction",TRANSACTION_ID_PATTERN=/^[a-zA-Z0-9._-]+$/,DEFAULT_LOCK_TTL_SECONDS=30,DEFAULT_LOCK_WAIT_MS=3e3;function requiredIdentifier(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized||!TRANSACTION_ID_PATTERN.test(normalized))throw new TypeError(`${label} must match [a-zA-Z0-9._-]+`);return normalized}function requiredText(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized)throw new TypeError(`${label} must be non-empty`);return normalized}function validateWorkspaceTransactionIdentity(options){return{pmRoot:requiredText(options.pmRoot,"Transaction pmRoot"),transactionId:requiredIdentifier(options.transactionId,"Transaction id"),author:requiredText(options.author,"Transaction author")}}function positiveInteger(value,fallback,label){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<=0)throw new TypeError(`${label} must be a positive integer`);return resolved}function journalPath(pmRoot,transactionId){return path.join(pmRoot,"transactions","sdk",`${transactionId}.json`)}async function writeJournal(pmRoot,journal){journal.updatedAt=nowIso();const target=journalPath(pmRoot,journal.transactionId);await mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,`${JSON.stringify(journal,null,2)}
2
- `)}function hasValidJournalMetadata(journal){return Number.isInteger(journal.attempt)&&typeof journal.author=="string"&&typeof journal.createdAt=="string"&&typeof journal.updatedAt=="string"}function createResultMap(source){return Object.assign(Object.create(null),source)}function cloneJournalValue(value,label){try{const serialized=JSON.stringify(value,(_key,nestedValue)=>{if(typeof nestedValue=="number"&&!Number.isFinite(nestedValue))throw new TypeError(`${label} contains a non-finite number`);if(nestedValue===void 0||typeof nestedValue=="function"||typeof nestedValue=="symbol")throw new TypeError(`${label} contains a non-JSON value`);return nestedValue});return JSON.parse(serialized)}catch(error){throw new TypeError(`${label} must be JSON serializable`,{cause:error})}}function cloneOptionalJournalValue(value,label){return value===void 0?void 0:cloneJournalValue(value,label)}function setJournalEntry(target,stepId,value,label){const cloned=cloneOptionalJournalValue(value,label);cloned===void 0?delete target[stepId]:target[stepId]=cloned}function isJournalMap(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasUniqueKnownStepIds(value,stepIds){return Array.isArray(value)&&new Set(value).size===value.length&&value.every(stepId=>typeof stepId=="string"&&stepIds.includes(stepId))}function hasValidJournalLifecycle(journal,stepIds){if(!hasUniqueKnownStepIds(journal.startedStepIds,stepIds)||!hasUniqueKnownStepIds(journal.completedStepIds,stepIds)||!isJournalMap(journal.results)||!isJournalMap(journal.compensationData))return!1;const startedStepIds=journal.startedStepIds,started=new Set(startedStepIds),completedStepIds=journal.completedStepIds,completed=new Set(completedStepIds);return Object.keys(journal.compensationData).some(stepId=>!started.has(stepId))||Object.keys(journal.results).some(stepId=>!completed.has(stepId))?!1:journal.status==="committed"?stepIds.every(stepId=>completed.has(stepId)):journal.status!=="compensated"||completed.size===0&&started.size===0}function invalidJournal(transactionId,detail){return new PmCliError(`Workspace transaction ${transactionId} journal is invalid (${detail})`,EXIT_CODE.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function journalPlanMismatch(transactionId){return new PmCliError(`Workspace transaction ${transactionId} journal does not match the supplied plan`,EXIT_CODE.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function parseJournal(raw,transactionId,stepIds){let parsed;try{parsed=JSON.parse(raw)}catch{throw invalidJournal(transactionId,"invalid JSON")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw invalidJournal(transactionId,"expected an object");const journal=parsed;if(!(journal.schemaVersion===1&&journal.transactionId===transactionId))throw invalidJournal(transactionId,"schema version or transaction id does not match the journal file");const recordedStepIds=journal.stepIds;if(!Array.isArray(recordedStepIds)||!hasUniqueKnownStepIds(recordedStepIds,recordedStepIds)||!hasValidJournalLifecycle(journal,recordedStepIds)||!hasValidJournalMetadata(journal)||typeof journal.status!="string"||!["applying","compensating","compensated","committed"].includes(journal.status))throw invalidJournal(transactionId,"invalid lifecycle, metadata, status or step ids");if(!(journal.status==="compensated"||recordedStepIds.length===stepIds.length&&recordedStepIds.every((stepId,index)=>stepId===stepIds[index])))throw journalPlanMismatch(transactionId);return{...journal,results:createResultMap(journal.results),compensationData:createResultMap(journal.compensationData)}}async function prepareJournalForApply(options,transactionId,author,stepIds,existing){let journal=existing;const recovered=journal!==void 0;if(journal?.status==="compensating"&&await compensateAppliedSteps(options,journal),journal===void 0||journal.status==="compensated"){const timestamp=nowIso();journal={schemaVersion:1,transactionId,author,status:"applying",attempt:(journal?.attempt??0)+1,createdAt:journal?.createdAt??timestamp,updatedAt:timestamp,stepIds,startedStepIds:[],completedStepIds:[],results:createResultMap(),compensationData:createResultMap()},await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"prepared")}return{journal,recovered}}async function applyPreparedTransaction(options,journal,recovered){try{await discoverAppliedSteps(journal,options.steps),await writeJournal(options.pmRoot,journal);const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of options.steps){if(completed.has(step.id))continue;const inspection=await step.inspect();let result=cloneOptionalJournalValue(inspection.result,`Step ${step.id} result`);if(inspection.state!=="applied"){const compensationData=await step.prepareCompensation?.();setJournalEntry(journal.compensationData,step.id,compensationData,`Step ${step.id} compensation data`),started.add(step.id),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),await writeJournal(options.pmRoot,journal);const appliedResult=await step.apply();result=cloneOptionalJournalValue(appliedResult,`Step ${step.id} result`)}await emitTransition(options,journal,"step_applied",step.id),completed.add(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),setJournalEntry(journal.results,step.id,result,`Step ${step.id} result`),await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_recorded",step.id)}return await emitTransition(options,journal,"committing"),journal.status="committed",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"committed"),{transactionId:journal.transactionId,status:"committed",recovered,results:createResultMap(journal.results)}}catch(error){if(error instanceof WorkspaceTransactionInterruptedError||journal.status==="committed")throw error;try{await compensateAppliedSteps(options,journal)}catch(compensationError){throw new AggregateError([error,compensationError],`Workspace transaction failed and compensation failed: ${String(compensationError)}`,{cause:compensationError})}throw error}}async function loadJournal(pmRoot,transactionId,stepIds){try{return parseJournal(await readFile(journalPath(pmRoot,transactionId),"utf8"),transactionId,stepIds)}catch(error){if(error!==null&&typeof error=="object"&&"code"in error&&isFileMissingError(error))return;throw error}}async function emitTransition(options,journal,transition,stepId){await options.onTransition?.({transactionId:journal.transactionId,attempt:journal.attempt,transition,...stepId===void 0?{}:{stepId}})}async function discoverAppliedSteps(journal,steps){const completed=new Set,results=createResultMap();for(const step of steps){const inspection=await step.inspect();inspection.state==="applied"&&(completed.add(step.id),setJournalEntry(results,step.id,inspection.result,`Step ${step.id} result`))}journal.results=results,journal.completedStepIds=steps.map(step=>step.id).filter(stepId=>completed.has(stepId))}async function compensateAppliedSteps(options,journal){journal.status="compensating",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensating");const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of[...options.steps].reverse()){if(!started.has(step.id)&&!completed.has(step.id))continue;let shouldCompensate;try{shouldCompensate=started.has(step.id)&&(await step.inspect()).state==="applied"}catch{shouldCompensate=started.has(step.id)}shouldCompensate&&(await emitTransition(options,journal,"step_compensating",step.id),await step.compensate(journal.compensationData[step.id])),completed.delete(step.id),started.delete(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),delete journal.results[step.id],delete journal.compensationData[step.id],await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_compensated",step.id)}journal.status="compensated",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensated")}async function commitWorkspaceTransaction(options){const{pmRoot,transactionId,author}=validateWorkspaceTransactionIdentity(options),lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),steps=[...options.steps];if(steps.length===0)throw new TypeError("Workspace transaction requires at least one step");const stepIds=steps.map(step=>{const stepId=requiredIdentifier(step.id,"Transaction step id");if(stepId!==step.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return stepId});if(new Set(stepIds).size!==stepIds.length)throw new TypeError("Workspace transaction step ids must be unique");const stableOptions={...options,pmRoot,transactionId,author,steps,lockTtlSeconds,lockWaitMs},release=await acquireLock(pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs);try{const existing=await loadJournal(pmRoot,transactionId,stepIds),recovered=existing!==void 0;if(existing?.status==="committed")return{transactionId,status:"committed",recovered:!0,results:createResultMap(existing.results)};const prepared=await prepareJournalForApply(stableOptions,transactionId,author,stepIds,existing);return await applyPreparedTransaction(stableOptions,prepared.journal,recovered||prepared.recovered)}finally{await release()}}export{WorkspaceTransactionInterruptedError,commitWorkspaceTransaction,validateWorkspaceTransactionIdentity};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d913251a-fc99-5767-b19d-ae9473adc138")}catch{}})();import{mkdir,readFile}from"node:fs/promises";import path from"node:path";import{acquireLock}from"../core/lock/lock.js";import{isFileMissingError,writeFileAtomic}from"../core/fs/fs-utils.js";import{nowIso}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";class WorkspaceTransactionInterruptedError extends Error{constructor(message="Workspace transaction interrupted"){super(message),this.name="WorkspaceTransactionInterruptedError"}}const WORKSPACE_TRANSACTION_LOCK_ID="sdk-workspace-transaction",TRANSACTION_ID_PATTERN=/^[a-zA-Z0-9._-]+$/,DEFAULT_LOCK_TTL_SECONDS=30,DEFAULT_LOCK_WAIT_MS=3e3;function requiredIdentifier(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized||!TRANSACTION_ID_PATTERN.test(normalized))throw new TypeError(`${label} must match [a-zA-Z0-9._-]+`);return normalized}function requiredText(value,label){if(typeof value!="string")throw new TypeError(`${label} must be a string`);const normalized=value.trim();if(!normalized)throw new TypeError(`${label} must be non-empty`);return normalized}function validateWorkspaceTransactionIdentity(options){return{pmRoot:requiredText(options.pmRoot,"Transaction pmRoot"),transactionId:requiredIdentifier(options.transactionId,"Transaction id"),author:requiredText(options.author,"Transaction author")}}function positiveInteger(value,fallback,label){const resolved=value??fallback;if(!Number.isInteger(resolved)||resolved<=0)throw new TypeError(`${label} must be a positive integer`);return resolved}function journalPath(pmRoot,transactionId){return path.join(pmRoot,"transactions","sdk",`${transactionId}.json`)}async function writeJournal(pmRoot,journal){journal.updatedAt=nowIso();const target=journalPath(pmRoot,journal.transactionId);await mkdir(path.dirname(target),{recursive:!0}),await writeFileAtomic(target,`${JSON.stringify(journal,null,2)}
2
+ `)}function hasValidJournalMetadata(journal){return Number.isInteger(journal.attempt)&&typeof journal.author=="string"&&typeof journal.createdAt=="string"&&typeof journal.updatedAt=="string"}function createResultMap(source){return Object.assign(Object.create(null),source)}function cloneJournalValue(value,label){try{const serialized=JSON.stringify(value,(_key,nestedValue)=>{if(typeof nestedValue=="number"&&!Number.isFinite(nestedValue))throw new TypeError(`${label} contains a non-finite number`);if(nestedValue===void 0||typeof nestedValue=="function"||typeof nestedValue=="symbol")throw new TypeError(`${label} contains a non-JSON value`);return nestedValue});return JSON.parse(serialized)}catch(error){throw new TypeError(`${label} must be JSON serializable`,{cause:error})}}function cloneOptionalJournalValue(value,label){return value===void 0?void 0:cloneJournalValue(value,label)}function setJournalEntry(target,stepId,value,label){const cloned=cloneOptionalJournalValue(value,label);cloned===void 0?delete target[stepId]:target[stepId]=cloned}function isJournalMap(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}function hasUniqueKnownStepIds(value,stepIds){return Array.isArray(value)&&new Set(value).size===value.length&&value.every(stepId=>typeof stepId=="string"&&stepIds.includes(stepId))}function hasValidJournalLifecycle(journal,stepIds){if(!hasUniqueKnownStepIds(journal.startedStepIds,stepIds)||!hasUniqueKnownStepIds(journal.completedStepIds,stepIds)||!isJournalMap(journal.results)||!isJournalMap(journal.compensationData))return!1;const startedStepIds=journal.startedStepIds,started=new Set(startedStepIds),completedStepIds=journal.completedStepIds,completed=new Set(completedStepIds);return Object.keys(journal.compensationData).some(stepId=>!started.has(stepId))||Object.keys(journal.results).some(stepId=>!completed.has(stepId))?!1:journal.status==="committed"?stepIds.every(stepId=>completed.has(stepId)):journal.status!=="compensated"||completed.size===0&&started.size===0}function invalidJournal(transactionId,detail){return new PmCliError(`Workspace transaction ${transactionId} journal is invalid (${detail})`,EXIT_CODE.CONFLICT,{code:"transaction_journal_invalid",required:"A valid durable journal is required before transaction recovery can continue.",why:"Corrupt journal data cannot establish which steps applied or still require compensation.",nextSteps:["Preserve the journal and inspect its integrity or restore a verified backup before retrying.","Do not switch to a new transaction id to bypass an unreadable journal; previously applied work may remain."]})}function journalPlanMismatch(transactionId){return new PmCliError(`Workspace transaction ${transactionId} journal does not match the supplied plan`,EXIT_CODE.CONFLICT,{code:"transaction_plan_mismatch",required:"Replay the exact plan that started this transaction, or start a new transaction with a different id.",why:"A journal records the plan it is resuming; applying a different plan under the same id could skip or duplicate steps.",nextSteps:["Re-run with the original document to resume or replay it.","Pass --transaction-id <new-id> (or a new transactionId over MCP) to commit the changed plan as its own transaction.","Run pm ops gc --scope transactions --dry-run to inspect abandoned journals before pruning them."]})}function parseJournal(raw,transactionId,stepIds){let parsed;try{parsed=JSON.parse(raw)}catch{throw invalidJournal(transactionId,"invalid JSON")}if(!parsed||typeof parsed!="object"||Array.isArray(parsed))throw invalidJournal(transactionId,"expected an object");const journal=parsed;if(!(journal.schemaVersion===1&&journal.transactionId===transactionId))throw invalidJournal(transactionId,"schema version or transaction id does not match the journal file");const recordedStepIds=journal.stepIds;if(!Array.isArray(recordedStepIds)||!hasUniqueKnownStepIds(recordedStepIds,recordedStepIds)||!hasValidJournalLifecycle(journal,recordedStepIds)||!hasValidJournalMetadata(journal)||typeof journal.status!="string"||!["applying","compensating","compensated","committed"].includes(journal.status))throw invalidJournal(transactionId,"invalid lifecycle, metadata, status or step ids");if(!(journal.status==="compensated"||recordedStepIds.length===stepIds.length&&recordedStepIds.every((stepId,index)=>stepId===stepIds[index])))throw journalPlanMismatch(transactionId);return{...journal,results:createResultMap(journal.results),compensationData:createResultMap(journal.compensationData)}}async function prepareJournalForApply(options,transactionId,author,stepIds,existing){let journal=existing;const recovered=journal!==void 0;if(journal?.status==="compensating"&&await compensateAppliedSteps(options,journal),journal===void 0||journal.status==="compensated"){const timestamp=nowIso();journal={schemaVersion:1,transactionId,author,status:"applying",attempt:(journal?.attempt??0)+1,createdAt:journal?.createdAt??timestamp,updatedAt:timestamp,stepIds,startedStepIds:[],completedStepIds:[],results:createResultMap(),compensationData:createResultMap()},await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"prepared")}return{journal,recovered}}async function applyPreparedTransaction(options,journal,recovered){try{await discoverAppliedSteps(journal,options.steps),await writeJournal(options.pmRoot,journal);const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of options.steps){if(completed.has(step.id))continue;const inspection=await step.inspect();let result=cloneOptionalJournalValue(inspection.result,`Step ${step.id} result`);if(inspection.state!=="applied"){const compensationData=await step.prepareCompensation?.();setJournalEntry(journal.compensationData,step.id,compensationData,`Step ${step.id} compensation data`),started.add(step.id),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),await writeJournal(options.pmRoot,journal);const appliedResult=await step.apply();result=cloneOptionalJournalValue(appliedResult,`Step ${step.id} result`)}await emitTransition(options,journal,"step_applied",step.id),completed.add(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),setJournalEntry(journal.results,step.id,result,`Step ${step.id} result`),await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_recorded",step.id)}return await emitTransition(options,journal,"committing"),journal.status="committed",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"committed"),{transactionId:journal.transactionId,status:"committed",recovered,results:createResultMap(journal.results)}}catch(error){if(error instanceof WorkspaceTransactionInterruptedError||journal.status==="committed")throw error;try{await compensateAppliedSteps(options,journal)}catch(compensationError){throw new AggregateError([error,compensationError],`Workspace transaction failed and compensation failed: ${String(compensationError)}`,{cause:compensationError})}throw error}}async function loadJournal(pmRoot,transactionId,stepIds){try{return parseJournal(await readFile(journalPath(pmRoot,transactionId),"utf8"),transactionId,stepIds)}catch(error){if(error!==null&&typeof error=="object"&&"code"in error&&isFileMissingError(error))return;throw error}}async function emitTransition(options,journal,transition,stepId){await options.onTransition?.({transactionId:journal.transactionId,attempt:journal.attempt,transition,...stepId===void 0?{}:{stepId}})}async function discoverAppliedSteps(journal,steps){const completed=new Set,results=createResultMap();for(const step of steps){const inspection=await step.inspect();inspection.state==="applied"&&(completed.add(step.id),setJournalEntry(results,step.id,inspection.result,`Step ${step.id} result`))}journal.results=results,journal.completedStepIds=steps.map(step=>step.id).filter(stepId=>completed.has(stepId))}async function compensateAppliedSteps(options,journal){journal.status="compensating",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensating");const completed=new Set(journal.completedStepIds),started=new Set(journal.startedStepIds);for(const step of[...options.steps].reverse()){if(!started.has(step.id)&&!completed.has(step.id))continue;let shouldCompensate;try{const state=(await step.inspect()).state;shouldCompensate=started.has(step.id)&&(state==="applied"||state==="pending"&&step.compensatePending===!0)}catch{shouldCompensate=started.has(step.id)}shouldCompensate&&(await emitTransition(options,journal,"step_compensating",step.id),await step.compensate(journal.compensationData[step.id])),completed.delete(step.id),started.delete(step.id),journal.completedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>completed.has(stepId)),journal.startedStepIds=options.steps.map(candidate=>candidate.id).filter(stepId=>started.has(stepId)),delete journal.results[step.id],delete journal.compensationData[step.id],await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"step_compensated",step.id)}journal.status="compensated",await writeJournal(options.pmRoot,journal),await emitTransition(options,journal,"compensated")}async function commitWorkspaceTransaction(options){const{pmRoot,transactionId,author}=validateWorkspaceTransactionIdentity(options),lockTtlSeconds=positiveInteger(options.lockTtlSeconds,DEFAULT_LOCK_TTL_SECONDS,"Transaction lock TTL"),lockWaitMs=positiveInteger(options.lockWaitMs,DEFAULT_LOCK_WAIT_MS,"Transaction lock wait"),steps=[...options.steps];if(steps.length===0)throw new TypeError("Workspace transaction requires at least one step");const stepIds=steps.map(step=>{const stepId=requiredIdentifier(step.id,"Transaction step id");if(stepId!==step.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return stepId});if(new Set(stepIds).size!==stepIds.length)throw new TypeError("Workspace transaction step ids must be unique");const stableOptions={...options,pmRoot,transactionId,author,steps,lockTtlSeconds,lockWaitMs},release=await acquireLock(pmRoot,WORKSPACE_TRANSACTION_LOCK_ID,lockTtlSeconds,author,!1,!1,lockWaitMs);try{const existing=await loadJournal(pmRoot,transactionId,stepIds),recovered=existing!==void 0;if(existing?.status==="committed")return{transactionId,status:"committed",recovered:!0,results:createResultMap(existing.results)};const prepared=await prepareJournalForApply(stableOptions,transactionId,author,stepIds,existing);return await applyPreparedTransaction(stableOptions,prepared.journal,recovered||prepared.recovered)}finally{await release()}}export{WorkspaceTransactionInterruptedError,commitWorkspaceTransaction,validateWorkspaceTransactionIdentity};
3
3
  //# sourceMappingURL=workspace-transaction.js.map
package/docs/COMMANDS.md CHANGED
@@ -818,7 +818,8 @@ pm focus --clear # clear focus; new items stop inheriting a parent
818
818
  Behavior and guarantees:
819
819
 
820
820
  - Focus is **session-local**: it is stored in `.agents/pm/runtime/session.json`, which is gitignored, so it never affects teammates or the tracker's git history.
821
- - When a focus is set and `pm create` is run **without** `--parent`, the new item inherits the focused item as its parent and the result includes `"parent_source": "focus"` so agents can see the parent was inherited.
821
+ - When a focus is set and `pm create` or `pm plan create` is run **without** `--parent`, the new item inherits the focused item as its parent. With `--full-changed-fields`, `pm create` reports `"parent_source": "focus"`; `pm plan create` exposes the effective parent as `plan.parent`.
822
+ - `--no-inherit-focus` or `--parent none` suppresses inheritance (`pm create` also accepts `--unset parent`). SDK and MCP creates, including plans, default to ignoring saved focus and opt in with `inheritFocus: true` ([pm-gh1577](https://github.com/unbraind/pm-cli/blob/main/.agents/pm/issues/pm-gh1577.toon); this tracker record is repository-only and excluded from npm).
822
823
  - An explicit `--parent` always overrides focus, including `--parent none` (create with no parent). An explicit but unresolvable focused parent produces the same missing-parent error/warning as an explicit stale `--parent` (it flows through the same `validation.parent_reference` policy).
823
824
  - `pm focus <id>` validates the item exists and fails fast with a not-found error otherwise. `pm focus --clear <id>` is a usage error (choose either set or clear).
824
825
 
@@ -1041,6 +1042,14 @@ MCP tool via `options.fields`.
1041
1042
  `pm context --format ndjson` concatenates the bounded high-level, low-level, and blocked-fallback focus rows in deterministic ranking order. Like list/search NDJSON, it emits no wrapper and no trailing count object. SDK and MCP callers retain the structured arrays; package authors can use the exported `serializeNdjsonRows` primitive when their transport needs line framing.
1042
1043
 
1043
1044
  `calendar` defaults to markdown for human and agent readability. Other commands default to TOON unless configured otherwise.
1045
+ Calendar results publish matching `total_count`, returned `count`, zero-based
1046
+ `page_start`, remaining `omitted_count`, and `has_more`. `summary_scope` is
1047
+ `returned_rows`: summaries and day buckets cover this page. Repeat the original
1048
+ query with `--after <next_cursor>` to recover subsequent bounded pages; changing
1049
+ `--limit` is allowed. Relative bounds keep the first page's clock. Changed
1050
+ matching content refuses the cursor; restart without `--after`. With `--limit 0`,
1051
+ counts remain available; use `--limit 1` or larger to retrieve rows.
1052
+
1044
1053
  For `--include events` without explicit `--to`, `--recurrence-lookahead-days`, or `--occurrence-limit`, recurring expansion is intentionally capped to a bounded default window and emits a warning with retry hints for broader windows.
1045
1054
 
1046
1055
  ## Validation and Maintenance
@@ -1219,7 +1228,17 @@ as its compatibility spelling, `--full` for events with patch payloads, or
1219
1228
  `--provenance` for patch-free provenance rows. Every mode reports total and
1220
1229
  omitted row counts plus the applied bound. Use `--limit` for a deliberate cap,
1221
1230
  or `--unbounded` for an explicitly unlimited read; the two flags are mutually
1222
- exclusive.
1231
+ exclusive. Continue a limited result by repeating the same query with
1232
+ `--after <next_cursor>`; `page_start` gives the page offset and `omitted_count`
1233
+ counts rows remaining after that page. `window` publishes the original anchor,
1234
+ inclusive lower bound, and exclusive upper bound. Bounded reads pin an omitted
1235
+ upper bound to the first page's clock. Later writes outside that window are
1236
+ excluded. Changed filters, projection, workspace, or matching content refuse
1237
+ continuation; restart without `--after`. Digest rows join current metadata, so
1238
+ metadata changes may also require a restart. Continuation does not retain a
1239
+ persisted or atomic cross-file snapshot. Use `--from` for a starting timestamp;
1240
+ `--since` refusals suggest that correction. Use an envelope (for example `--json`
1241
+ without `--stream`) when paging: stream mode emits rows without cursor metadata.
1223
1242
  Workspace-scoped mutations to settings, schema, profiles, init state, and
1224
1243
  extension/package activation are recorded in
1225
1244
  `.agents/pm/history/_workspace.jsonl` using the same patch/hash format.
@@ -306,7 +306,7 @@ Use the public SDK barrel. Do not deep-import from `src/core` or `dist/core`.
306
306
  - `api.extension` is a read-only identity (`name`, `layer`, `version`, `capabilities`, `pm_min_version?`, `pm_max_version?`, `source_package?`) for self-identifying logs and version gating without re-reading the manifest.
307
307
  - `api.registerCommand(definition)` adds package-owned commands; `read_output` opts readers into the [SDK output contract](SDK.md#minimal-command-extension).
308
308
  - `api.registerFlags(command, flags)` adds runtime command flags. A flag may declare `value_type` (canonical; the legacy `type` alias is honored only when `value_type` is absent), `list: true` to accumulate repeated/comma-joined values like core `--tags`, a `default` applied when the flag is omitted, and `value_validation: "strict"` to refuse malformed `number`/`boolean` tokens before the handler runs (the default `"coerce"` forwards the raw token). See [Flag Contracts](SDK.md#flag-contracts).
309
- - `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers.
309
+ - `api.registerItemFields(fields)` adds custom metadata fields. Agents can set declared fields with repeatable `pm create --field name=value` and `pm update <id> --field name=value`; undeclared names are rejected. `SchemaFieldDefinition.type` is the same closed union used by `pm schema add-field`: `string | number | boolean | string_array | array | object`. Unsupported values fail at compile time for TypeScript authors and at activation for JavaScript packages, with a did-you-mean hint on typos. `string_array` is the repeatable string collection; `array` and `object` require JSON containers. Active fields support `get`, `list` and `search` projections with `--fields name` or `--fields item.name`, preserving declared value types through `PmClient` and CLI reads. Disabled packages do not contribute selectors. Tracked by [pm-gh1571](../.agents/pm/issues/pm-gh1571.toon).
310
310
  - Custom fields whose camel-case option name is already owned by a canonical MCP input remain usable through `options.<name>`, but authoring surfaces report the collision instead of allowing silent top-level shadowing. `pm schema add-field`, `pm profile lint`, and `pm package doctor` name the field, canonical `mcp_tool_input` owner, and nested recovery path. SDK authors can preflight the same rule with `resolvePmToolCustomFieldCollision`.
311
311
  - `api.registerItemTypes(types)` adds custom item types.
312
312
  - `api.registerRelationshipKinds(definitions)` adds validated graph semantics. Definitions declare direction, inverse spelling, ordering/precedence, hierarchy, cardinality, lifecycle, aliases, payload schema, compatibility version, and self-edge policy. Active definitions govern CLI, MCP, and SDK dependency mutation admission as well as workspace graph assembly; mutation aliases are stored canonically. Requires the `schema` capability and is governed by the `schema.relationshipkinds` policy surface. See [relationship mutation admission](RELATIONSHIP_GRAPH.md#contract), tracked by [pm-7dsolo](../.agents/pm/issues/pm-7dsolo.toon).