@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]="9c15250d-7e00-5a62-89b6-f7e820143ee7")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param)]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&&parameter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"next",schema:{const:!0}}],[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Claim an explicit item and move it to its configured in-progress status."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.22.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.11.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
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]="155d79eb-b419-560d-b7b5-c45ccbd86ab0")}catch{}})();import{normalizeUniqueStringList}from"./string-lists.js";import{PM_TOOL_ACTIONS}from"./enum-contracts.js";import{TOOL_CREATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS}from"./tool-option-contracts.js";import{PM_TOOL_PARAMETER_PROPERTIES as BASE_TOOL_PARAMETER_PROPERTIES,PM_TOOL_PARAMETER_METADATA as BASE_TOOL_PARAMETER_METADATA,PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES as BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA,PLAN_ACTION_PARAMETER_PROPERTIES,PLAN_ACTION_PARAMETER_METADATA}from"./tool-parameter-tables.js";import{toUniqueFlagContracts,withFlagAliasMetadata}from"./flag-contracts.js";import{resolveReadOutputSurface}from"../read-output-contracts.js";import{CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS}from"./commander-mutation-options.js";const PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES={...BASE_ACTION_SCOPED_PARAMETER_PROPERTIES,"history-attest":{verify:{type:"object",additionalProperties:!0},output:{not:{}}}},PM_TOOL_PARAMETER_PROPERTIES={...BASE_TOOL_PARAMETER_PROPERTIES,pause:{type:"boolean"},handoff:{type:"string"},releaseAssignment:{type:"boolean"},hashAlgorithm:{type:"string",enum:["sha256","sha512"]}},PM_TOOL_PARAMETER_METADATA={...BASE_TOOL_PARAMETER_METADATA,pause:{description:"Return work to its configured open status before releasing ownership."},handoff:{description:"Release into a configured non-terminal queue with a required evidence message."},releaseAssignment:{description:"Release assignment after recording closure evidence."},hashAlgorithm:{description:"Digest for detached history bundles; defaults to sha256."}},PM_TOOL_GLOBAL_PARAMETER_KEYS=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],PM_TOOL_READ_OUTPUT_PARAMETER_KEYS=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES=new Set(["action","cwd","options",...Object.keys(PM_TOOL_PARAMETER_PROPERTIES).filter(property=>property!=="severity")]);function resolvePmToolCustomFieldCollision(field){const normalized=field.trim().toLowerCase();let property="";for(let index=0;index<normalized.length;index+=1){const character=normalized[index];if(character!=="-"&&character!=="_"){property+=character;continue}let nextIndex=index+1;for(;normalized[nextIndex]==="-"||normalized[nextIndex]==="_";)nextIndex+=1;const nextCharacter=normalized[nextIndex];if(nextCharacter!==void 0&&(nextCharacter>="a"&&nextCharacter<="z"||nextCharacter>="0"&&nextCharacter<="9")){property+=nextCharacter.toUpperCase(),index=nextIndex;continue}property+=normalized.slice(index,nextIndex),index=nextIndex-1}return PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES.has(property)?{field,property,owner:"mcp_tool_input",nested_path:`options.${property}`}:void 0}const PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],claim:["fullChangedFields","idOnly"],release:["fullChangedFields","idOnly"],"start-task":["fullChangedFields","idOnly"],"pause-task":["fullChangedFields","idOnly"],"close-task":["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},PLAN_CREATE_METADATA_PARAMETER_KEYS=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(PM_TOOL_ACTIONS.filter(action=>action==="upgrade"||action==="install"||action==="extension"||action==="package"||action.startsWith("extension-")||action.startsWith("package-")).map(action=>[action,["project","local","global"]]))});function toSchemaKeyList(values){return normalizeUniqueStringList(values)}const CREATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CREATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param)]),UPDATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),...TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS.map(entry=>entry.param),"force"]),UPDATE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),...UPDATE_CONTRACT_PARAMETER_KEYS.filter(key=>key!=="allowMissingParent"&&key!=="completedAt"),"dryRun","rollback","noCheckpoint"]),CLOSE_MANY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),CONTEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_CONTEXT_OPTION_CONTRACTS.map(entry=>entry.param),"past","section"]),ACTIVITY_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_ACTIVITY_OPTION_CONTRACTS.map(entry=>entry.param),"stream"]),LIST_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_LIST_FILTER_OPTION_CONTRACTS.map(entry=>entry.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS=LIST_CONTRACT_PARAMETER_KEYS.filter(parameter=>parameter!=="all"&&parameter!=="status"),LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],AGGREGATE_CONTRACT_PARAMETER_KEYS=toSchemaKeyList([...TOOL_AGGREGATE_OPTION_CONTRACTS.map(entry=>entry.param),"count","completion","includeUnparented"]),SEARCH_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...TOOL_SEARCH_FILTER_OPTION_CONTRACTS.map(entry=>entry.param)]),NEXT_CONTRACT_PARAMETER_KEYS=toSchemaKeyList(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","includeGates","includeContainers","tokenBudget","explainRanking"]),AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","message","force"],CLOSE_ACTION_OPTION_KEYS=["releaseAssignment","text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS=["author","assignee","message","force"],MANAGED_EXTENSION_PACKAGE_OPTION_KEYS=["dryRun","target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","offline","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function managedLifecycleSchemaContracts(prefix){return{[`${prefix}-init`]:{required:["target"],optional:["scope","capability",...prefix==="package"?["declarative"]:[]]},[`${prefix}-install`]:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},[`${prefix}-uninstall`]:{required:["target"],optional:["scope"]},[`${prefix}-explore`]:{optional:["scope"]},[`${prefix}-manage`]:{optional:["scope","runtimeProbe","fixManagedState","offline"]},[`${prefix}-describe`]:{optional:["target","scope","markdown","output"]},[`${prefix}-reload`]:{optional:["scope","watch"]},[`${prefix}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${prefix}-catalog`]:{optional:["scope","fields"]},[`${prefix}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${prefix}-adopt-all`]:{optional:["scope"]},[`${prefix}-activate`]:{required:["target"],optional:["scope"]},[`${prefix}-deactivate`]:{required:["target"],optional:["scope"]},[prefix]:{optional:MANAGED_EXTENSION_PACKAGE_OPTION_KEYS,dependentAnyOfRequired:[{property:"dryRun",value:!0,anyOfRequired:[["install","target"],["install","github"]]}],mutuallyExclusiveWhen:[[{property:"dryRun",schema:{const:!0}},{property:"install",schema:{const:!1}}]]}}}const SCHEDULING_ACTION_SCHEMA_CONTRACT={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},UPGRADE_ACTION_SCHEMA_CONTRACT={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},PM_TOOL_ACTION_SCHEMA_CONTRACTS={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...managedLifecycleSchemaContracts("extension"),...managedLifecycleSchemaContracts("package"),"package-upgrade":UPGRADE_ACTION_SCHEMA_CONTRACT,install:{optional:["target","github","scope","ref","dryRun"],anyOfRequired:[["target"],["github"]]},upgrade:UPGRADE_ACTION_SCHEMA_CONTRACT,create:{required:["title","description","type","status","priority","message"],optional:CREATE_CONTRACT_PARAMETER_KEYS},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-all":{optional:LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-draft":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-open":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-in-progress":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-blocked":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-closed":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},"list-canceled":{optional:FIXED_STATUS_LIST_CONTRACT_PARAMETER_KEYS,mutuallyExclusiveWhen:LIST_WINDOW_MUTUALLY_EXCLUSIVE_GROUPS},aggregate:{optional:AGGREGATE_CONTRACT_PARAMETER_KEYS},guide:{optional:["list","format","depth"]},context:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},ctx:{optional:CONTEXT_CONTRACT_PARAMETER_KEYS},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:SEARCH_CONTRACT_PARAMETER_KEYS,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","preCommitHook","stage","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:SCHEDULING_ACTION_SCHEMA_CONTRACT,event:SCHEDULING_ACTION_SCHEMA_CONTRACT,remind:{required:["title"],optional:["at","text","parent","inheritFocus","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...NEXT_CONTRACT_PARAMETER_KEYS,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-attest":{optional:["verify","output","hashAlgorithm"],mutuallyExclusive:[["verify","hashAlgorithm"]]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance","salvageTail",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["all"]],mutuallyExclusiveWhen:[[{property:"salvageTail",schema:{const:!0}},{property:"all",schema:{const:!0}}],[{property:"salvageTail",schema:{const:!0}},{property:"normalizeProvenance",schema:{const:!0}}]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},schema:{mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"policy-mode"}},{property:"name",schema:{not:{enum:["advise","refuse"]}}}]],required:["subcommand"],optional:["definition","policy","message","name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"policy-put",required:["definition"]},{property:"subcommand",value:"policy-remove",required:["name"]},{property:"subcommand",value:"policy-mode",required:["name"]},{property:"subcommand",value:"policy-check",required:["name"]},{property:"subcommand",value:"policy-approve",required:["name","policy"]},{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","inheritFocus","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...PLAN_CREATE_METADATA_PARAMETER_KEYS,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},activity:{optional:ACTIVITY_CONTRACT_PARAMETER_KEYS},restore:{required:["id","target"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},update:{required:["id"],optional:UPDATE_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:UPDATE_MANY_CONTRACT_PARAMETER_KEYS,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...CLOSE_ACTION_OPTION_KEYS,...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"close-many":{optional:CLOSE_MANY_CONTRACT_PARAMETER_KEYS},delete:{required:["id"],optional:["dryRun",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},append:{required:["id","body"],optional:AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["list","add","addJson","remove","removeIndex","update","updateIndex","setJson","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"update",anyOfRequired:[["setJson"]]},{property:"updateIndex",anyOfRequired:[["setJson"]]},{property:"setJson",anyOfRequired:[["update"],["updateIndex"]]}],mutuallyExclusive:[["update","updateIndex"],["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit","exhaustive"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkCompleteness","checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"risk",required:["definition"]},{property:"subcommand",value:"lineages",required:["definition"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}],mutuallyExclusiveWhen:[[{property:"subcommand",schema:{const:"risk"}},{property:"definition",schema:{not:{required:["policy","change"]}}}],[{property:"subcommand",schema:{const:"lineages"}},{property:"definition",schema:{anyOf:[{required:["change"]},{not:{required:["policy"]}}]}}]]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:CONTRACTS_PROJECTION_MUTUALLY_EXCLUSIVE_GROUPS},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["start","id","next","ifAvailable","maxAttempts","includeDecisions",...NEXT_CONTRACT_PARAMETER_KEYS,...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],oneOfRequired:[["id"],["next"]],mutuallyExclusiveWhen:[[{property:"start",schema:{const:!0}},{property:"next",schema:{const:!0}}],[{property:"start",schema:{const:!0}},{property:"ifAvailable",schema:{const:!0}}]]},release:{required:["id"],optional:["pause","handoff",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS],dependentAnyOfRequired:[{property:"handoff",anyOfRequired:[["message"]]}],mutuallyExclusiveWhen:[[{property:"pause",schema:{const:!0}},{property:"handoff",schema:{type:"string"}}]]},"start-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"pause-task":{required:["id"],optional:LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS},"close-task":{required:["id"],optional:["text","validateClose",...LIFECYCLE_AUTHOR_MESSAGE_FORCE_PARAMETER_KEYS]},"item-reopen":{required:["id","reason"],optional:["status","expectedResult","author","message","force"]}},PM_TOOL_ACTION_PARAMETER_CONTRACTS=Object.freeze(Object.fromEntries(PM_TOOL_ACTIONS.map(action=>[action,PM_TOOL_ACTION_SCHEMA_CONTRACTS[action]])));function fallbackToolParameterDescription(key){return key.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,value=>value.toUpperCase()).concat(".")}function decorateToolParameterDefinition(key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=PM_TOOL_PARAMETER_METADATA[key];return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterMetadata(action,key){if(action==="history-attest"&&key==="verify")return{description:"Compare all retained history streams with a detached JSON proof object. Server-local proof paths are not accepted over MCP."};if(action==="history-attest"&&key==="output")return{description:"Local CLI/SDK only. MCP rejects this field; save the returned JSON bundle on the client."};if(action==="claim"&&key==="start")return{description:"Claim an explicit item and move it to its configured in-progress status."};if((action==="list"||action.startsWith("list-"))&&key==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_METADATA,key))return PLAN_ACTION_PARAMETER_METADATA[key];const actionOverrides=PM_TOOL_ACTION_SCOPED_PARAMETER_METADATA[action];return actionOverrides&&Object.prototype.hasOwnProperty.call(actionOverrides,key)?actionOverrides[key]:PM_TOOL_PARAMETER_METADATA[key]}function decorateActionScopedToolParameterDefinition(action,key,definition){const baseDefinition=typeof definition=="object"&&definition!==null?{...definition}:{},metadata=actionScopedToolParameterMetadata(action,key);return{...baseDefinition,description:metadata?.description??fallbackToolParameterDescription(key),...metadata?.examples?{examples:metadata.examples}:{}}}function actionScopedToolParameterDefinition(action,key){if(action==="claim"&&key==="start")return{type:"boolean"};const actionProperties=PM_TOOL_ACTION_SCOPED_PARAMETER_PROPERTIES[action];return actionProperties&&Object.prototype.hasOwnProperty.call(actionProperties,key)?actionProperties[key]:action==="plan"&&Object.prototype.hasOwnProperty.call(PLAN_ACTION_PARAMETER_PROPERTIES,key)?PLAN_ACTION_PARAMETER_PROPERTIES[key]:(action==="get"||action==="history"||action==="search")&&key==="format"?{type:"string",enum:["json","toon"]}:key==="pause"||key==="handoff"||key==="releaseAssignment"||key==="hashAlgorithm"?PM_TOOL_PARAMETER_PROPERTIES[key]:BASE_TOOL_PARAMETER_PROPERTIES[key]}function buildActionScopedSchemaProperties(action,allowedKeys){const properties={action:{const:action,description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."}};for(const key of allowedKeys){if(key==="action")continue;const definition=actionScopedToolParameterDefinition(action,key);definition&&(properties[key]=decorateActionScopedToolParameterDefinition(action,key,definition))}return properties}function buildOneOfSchemaEntries(action,oneOfRequiredGroups){const allOneOfFields=oneOfRequiredGroups.flat();return oneOfRequiredGroups.map(requiredFields=>{const otherFields=allOneOfFields.filter(field=>!requiredFields.includes(field));return{required:[...requiredFields],...otherFields.length>0?{not:{anyOf:otherFields.map(field=>({required:[field]}))}}:{},...action==="history-repair"&&requiredFields.includes("all")?{properties:{all:{const:!0}}}:action==="claim"&&requiredFields.includes("next")?{properties:{next:{const:!0}}}:{}}})}function schemaPropertyCondition(property,value){return{...value===void 0?{}:{properties:{[property]:{const:value}}},required:[property]}}function buildActionScopedAllOf(contract){const allOf=[];if(contract.conditionalRequired&&contract.conditionalRequired.length>0)for(const entry of contract.conditionalRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{required:entry.required}});if(contract.dependentAnyOfRequired&&contract.dependentAnyOfRequired.length>0)for(const entry of contract.dependentAnyOfRequired)allOf.push({if:schemaPropertyCondition(entry.property,entry.value),then:{anyOf:entry.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))}});if(contract.mutuallyExclusive&&contract.mutuallyExclusive.length>0)for(const group of contract.mutuallyExclusive)allOf.push({not:{required:toSchemaKeyList(group)}});if(contract.mutuallyExclusiveWhen&&contract.mutuallyExclusiveWhen.length>0)for(const group of contract.mutuallyExclusiveWhen)allOf.push({not:{allOf:group.map(condition=>({properties:{[condition.property]:condition.schema},required:[condition.property]}))}});return allOf}function pmToolActionParameterKeys(action){if(!Object.prototype.hasOwnProperty.call(PM_TOOL_ACTION_SCHEMA_CONTRACTS,action))return;const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],mutationParameterKeys=PM_TOOL_ACTION_MUTATION_PARAMETER_KEYS[action]??[];return toSchemaKeyList(["action",...PM_TOOL_GLOBAL_PARAMETER_KEYS,...resolveReadOutputSurface(action)!==void 0?PM_TOOL_READ_OUTPUT_PARAMETER_KEYS:[],...mutationParameterKeys,...contract.required??[],...contract.optional??[]])}function pmToolActionNestedOptionKeys(action){const parameterKeys=pmToolActionParameterKeys(action);if(parameterKeys===void 0)return;const mutationContracts=action==="create"?CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:action==="update"?UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS:[];return toSchemaKeyList([...parameterKeys,...mutationContracts.flatMap(({keys,target})=>[target,...keys]),...PM_TOOL_ACTION_NESTED_OPTION_COMPATIBILITY_KEYS[action]??[]])}function buildActionScopedToolSchema(action){const contract=PM_TOOL_ACTION_SCHEMA_CONTRACTS[action],required=toSchemaKeyList(contract.required??[]),allowedKeys=pmToolActionParameterKeys(action),schema={type:"object",additionalProperties:!1,required:["action",...required],title:`pm action "${action}" parameters`,properties:buildActionScopedSchemaProperties(action,allowedKeys)};contract.anyOfRequired&&contract.anyOfRequired.length>0&&(schema.anyOf=contract.anyOfRequired.map(requiredFields=>({required:[...requiredFields]}))),contract.oneOfRequired&&contract.oneOfRequired.length>0&&(schema.oneOf=buildOneOfSchemaEntries(action,contract.oneOfRequired));const allOf=buildActionScopedAllOf(contract);return allOf.length>0&&(schema.allOf=allOf),schema}function buildPmActionToolInputSchema(action,options={}){const actionSchema=buildActionScopedToolSchema(action),actionProperties={...actionSchema.properties};delete actionProperties.action;const conditionalBranches=[...actionSchema.anyOf??[],...actionSchema.oneOf??[]],required=(options.required??actionSchema.required.map(String)).filter(key=>key==="action"?!1:options.required===void 0?!0:!conditionalBranches.some(branch=>branch.required?.map(String).includes(key))),schema={type:"object",additionalProperties:options.additionalProperties??!0,properties:{...actionProperties,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...options.properties},required};return actionSchema.anyOf!==void 0&&(schema.anyOf=actionSchema.anyOf),actionSchema.oneOf!==void 0&&(schema.oneOf=actionSchema.oneOf),actionSchema.allOf!==void 0&&(schema.allOf=actionSchema.allOf),schema}function createLazyContractSchema(build){let value;const resolve=()=>value??=build();return new Proxy({},{get:(_target,prop)=>resolve()[prop],has:(_target,prop)=>prop in resolve(),ownKeys:()=>Reflect.ownKeys(resolve()),getOwnPropertyDescriptor:(_target,prop)=>{const descriptor=Reflect.getOwnPropertyDescriptor(resolve(),prop);return descriptor&&(descriptor.configurable=!0),descriptor}})}const PM_TOOL_PARAMETERS_SCHEMA_VERSION="4.23.0",PM_TOOL_PARAMETERS_SCHEMA_MAJOR=PM_TOOL_PARAMETERS_SCHEMA_VERSION.split(".")[0],PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION="1.12.0",PM_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${PM_TOOL_PARAMETERS_SCHEMA_MAJOR}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":PM_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",oneOf:PM_TOOL_ACTIONS.map(action=>buildActionScopedToolSchema(action))}));function toProviderCompatibleParameterDefinition(key,definition){const decorated=decorateToolParameterDefinition(key,definition);if(typeof decorated.type=="string")return decorated;const firstTypedVariant=(Array.isArray(decorated.anyOf)?decorated.anyOf:[]).find(variant=>typeof variant.type=="string");if(firstTypedVariant){const{anyOf:_anyOf2,...rest2}=decorated;return{...firstTypedVariant,...rest2}}const{anyOf:_anyOf,...rest}=decorated;return{...rest,type:"string"}}function buildProviderCompatibleToolSchema(){const properties={action:{type:"string",description:PM_TOOL_PARAMETER_METADATA.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(const key of Object.keys(PM_TOOL_PARAMETER_PROPERTIES).sort())properties[key]=toProviderCompatibleParameterDefinition(key,PM_TOOL_PARAMETER_PROPERTIES[key]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,type:"object",additionalProperties:!1,required:["action"],properties}}const PM_PROVIDER_TOOL_PARAMETERS_SCHEMA=createLazyContractSchema(buildProviderCompatibleToolSchema),_testOnlyCliContracts={buildActionScopedToolSchema,buildProviderCompatibleToolSchema,decorateActionScopedToolParameterDefinition,decorateToolParameterDefinition,toolActionSchemaContracts:PM_TOOL_ACTION_SCHEMA_CONTRACTS,toolParameterMetadata:PM_TOOL_PARAMETER_METADATA,toProviderCompatibleParameterDefinition,toUniqueFlagContracts,withFlagAliasMetadata};export{CLOSE_ACTION_OPTION_KEYS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,_testOnlyCliContracts,buildPmActionToolInputSchema,pmToolActionNestedOptionKeys,pmToolActionParameterKeys,resolvePmToolCustomFieldCollision};
2
2
  //# sourceMappingURL=tool-schema.js.map
@@ -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]="b0fbba44-df4b-5cf3-968c-a0e86fd4afb5")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ALL_COMMANDS,ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,NAMESPACE_PREFIXES,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags}from"./shared.js";function escapeFishSource(value){return value.replaceAll("\\","\\\\").replaceAll("'","\\'")}function escapeFishChoices(value){return escapeFishSource(value.replace(/([^a-zA-Z0-9_:./\s-])/gu,"\\$1"))}const FISH_COMMAND_DESCRIPTION_OVERRIDES=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]);function renderFishCommandDescriptions(){return[...COMMAND_COMPLETION_DESCRIPTIONS,["ops","Workspace maintenance and diagnostics"]].filter(([command])=>command!=="help"&&!HIDDEN_COMMAND_ALIASES.has(command)).map(([command,description])=>{const fishDescription=FISH_COMMAND_DESCRIPTION_OVERRIDES.get(command)??description;return`complete -c pm -n __pm_no_subcommand -a ${command.padEnd(16)} -d '${fishDescription}'`}).join(`
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]="cd93f252-35fd-50ed-a8a1-80e2e8aabdbd")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ALL_COMMANDS,ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,NAMESPACE_PREFIXES,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags}from"./shared.js";function escapeFishSource(value){return value.replaceAll("\\","\\\\").replaceAll("'","\\'")}function escapeFishChoices(value){return escapeFishSource(value.replace(/([^a-zA-Z0-9_:./\s-])/gu,"\\$1"))}const FISH_COMMAND_DESCRIPTION_OVERRIDES=new Map([["calendar","Show deadline/reminder calendar views"],["schema","Inspect and manage runtime schema"],["profile","List, show, apply, and lint project profiles (archetype bundles)"],["plan","Agent-optimized Plan workflow (create/show/add-step/update-step/complete-step/link/approve/materialize)"],["start-task","Lifecycle alias to claim and set in-progress"]]);function renderFishCommandDescriptions(){return[...COMMAND_COMPLETION_DESCRIPTIONS,["ops","Workspace maintenance and diagnostics"]].filter(([command])=>command!=="help"&&!HIDDEN_COMMAND_ALIASES.has(command)).map(([command,description])=>{const fishDescription=FISH_COMMAND_DESCRIPTION_OVERRIDES.get(command)??description;return`complete -c pm -n __pm_no_subcommand -a ${command.padEnd(16)} -d '${fishDescription}'`}).join(`
2
2
  `)}function renderFishRuntimeFieldFlagSpecs(commands,runtimeFlags){const normalizedFlags=normalizeRuntimeCompletionFlags(runtimeFlags).map(flag=>flag.slice(2));if(commands.length===0||normalizedFlags.length===0)return"";const lines=[];for(const command of commands){const predicate=NAMESPACE_NOUNS.includes(command)||PM_NAMESPACED_COMMAND_ALIASES.some(entry=>entry.alias===command)?"__pm_history_operation":"__fish_seen_subcommand_from";for(const flag of normalizedFlags)lines.push(`complete -c pm -n '${predicate} ${command}' -l '${escapeFishSource(flag)}' -d 'Runtime schema field flag' -r`)}return`${lines.join(`
3
3
  `)}
4
4
  `}function renderFishDynamicChoiceResolver(kind,command,fallback){const envKind=kind.toUpperCase(),escapedFallback=escapeFishSource(fallback);return`
@@ -461,6 +461,7 @@ complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l include -d 'In
461
461
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l recurrence-lookahead-days -d 'Bound open-ended recurrence lookahead' -r
462
462
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l recurrence-lookback-days -d 'Bound open-ended recurrence lookback' -r
463
463
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l occurrence-limit -d 'Cap occurrences per recurring event' -r
464
+ complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l after -d 'Continue a fixed-window calendar page' -r
464
465
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l limit -d 'Limit returned events' -r
465
466
  complete -c pm -n '__fish_seen_subcommand_from calendar cal' -l format -d 'Output override' -r -a 'markdown toon json'
466
467
  ${fishCalendarRuntimeFieldFlags}
@@ -684,6 +685,7 @@ complete -c pm -n '__pm_history_operation activity activity' -l op -d 'Filter by
684
685
  complete -c pm -n '__pm_history_operation activity activity' -l author -d 'Filter by history author' -r
685
686
  complete -c pm -n '__pm_history_operation activity activity' -l from -d 'Lower timestamp bound (ISO/date string or relative)' -r
686
687
  complete -c pm -n '__pm_history_operation activity activity' -l to -d 'Upper timestamp bound (ISO/date string or relative)' -r
688
+ complete -c pm -n '__pm_history_operation activity activity' -l after -d 'Continue a fixed-window activity page' -r
687
689
  complete -c pm -n '__pm_history_operation activity activity' -l limit -d 'Max activity entries' -r
688
690
  complete -c pm -n '__pm_history_operation activity activity' -l unbounded -d 'Return every matching activity entry'
689
691
  complete -c pm -n '__pm_history_operation activity activity' -l compact -d 'Condensed activity projection'
@@ -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]="d548143c-24be-5420-8185-f52e3941cff3")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags,shellDoubleQuote}from"./shared.js";function escapeZshStaticChoices(value){return value.replace(/([^a-zA-Z0-9_./\s-])/gu,"\\$1").replaceAll("'","'\\''")}function renderZshRuntimeFieldFlagSpecs(runtimeFlags){const normalized=normalizeRuntimeCompletionFlags(runtimeFlags);return normalized.length===0?"":`${normalized.map(flag=>` '${escapeZshStaticChoices(flag)}[Runtime schema field flag]:value' \\`).join(`
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]="53a23313-376f-5cb5-ad59-17cd47be2130")}catch{}})();import{PM_NAMESPACED_COMMAND_ALIASES}from"../cli-contracts.js";import{SCAFFOLD_CAPABILITIES}from"../extension/scaffold.js";import{ATTEST_INVOCATIONS,COMMAND_COMPLETION_DESCRIPTIONS,EXTENSION_LIFECYCLE_ACTIONS,GLOBAL_COMPLETION_INLINE_PATTERNS,GLOBAL_COMPLETION_SWITCH_PATTERNS,GLOBAL_COMPLETION_VALUE_PATTERNS,GUIDE_TOPIC_CHOICES,HIDDEN_COMMAND_ALIASES,NAMESPACE_NOUNS,PACKAGE_LIFECYCLE_ACTIONS,RESTORE_INVOCATIONS,SCHEMA_SUBCOMMAND_CHOICES,completionNamespaceLeaves,completionStatusValues,completionTypeValues,joinCompletionValues,normalizeRuntimeCompletionFlags,shellDoubleQuote}from"./shared.js";function escapeZshStaticChoices(value){return value.replace(/([^a-zA-Z0-9_./\s-])/gu,"\\$1").replaceAll("'","'\\''")}function renderZshRuntimeFieldFlagSpecs(runtimeFlags){const normalized=normalizeRuntimeCompletionFlags(runtimeFlags);return normalized.length===0?"":`${normalized.map(flag=>` '${escapeZshStaticChoices(flag)}[Runtime schema field flag]:value' \\`).join(`
2
2
  `)}
3
3
  `}function renderZshArgumentSpecs(specs,options={}){const trailingContinuation=options.trailingContinuation??!0,lastSpecIndex=specs.length-1;return specs.map((spec,index)=>` ${spec}${trailingContinuation||index!==lastSpecIndex?" \\":""}`).join(`
4
4
  `)}function renderZshCommandDescriptions(){return[...COMMAND_COMPLETION_DESCRIPTIONS,["ops","Workspace maintenance and diagnostics"]].filter(([command])=>!HIDDEN_COMMAND_ALIASES.has(command)).map(([command,description])=>` '${command}:${description}'`).join(`
@@ -374,6 +374,7 @@ ${zshCalendarRuntimeFieldFlags} '--include[Include event sources]:(al
374
374
  '--recurrence-lookahead-days[Bound open-ended recurrence lookahead]:days' \\
375
375
  '--recurrence-lookback-days[Bound open-ended recurrence lookback]:days' \\
376
376
  '--occurrence-limit[Cap occurrences per recurring event]:number' \\
377
+ '--after[Continue a fixed-window calendar page]:cursor' \\
377
378
  '--limit[Limit returned events]:number' \\
378
379
  '--format[Output override]:(markdown toon json)' \\
379
380
  '--json[Output JSON]' \\
@@ -636,6 +637,7 @@ ${renderZshArgumentSpecs(ATTEST_INVOCATIONS.map(flag=>`'${flag.flag}[${flag.desc
636
637
  '--author[Filter by history author]:author' \\
637
638
  '--from[Lower timestamp bound (ISO/date string or relative)]:date' \\
638
639
  '--to[Upper timestamp bound (ISO/date string or relative)]:date' \\
640
+ '--after[Continue a fixed-window activity page]:cursor' \\
639
641
  '--limit[Max entries]:number' \\
640
642
  '--unbounded[Return every matching activity entry]' \\
641
643
  '--compact[Condensed activity projection]' \\
@@ -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]="01eff51c-7656-5c3f-b0c0-28594fca8a1e")}catch{}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{buildItemContextRelevanceCandidates}from"./context-relevance.js";import{readItemMetadataDerivedIndexState}from"./item-metadata-index.js";import{readLatestSubstantiveHistoryEvents}from"../core/history/event-index.js";import{canonicalizeContextRecencyCoordinate}from"./context/recency.js";const CONTEXT_SIGNAL_STORE_FORMAT_VERSION=3,CONTEXT_SIGNAL_SET_VERSION=2,STORED_CONTEXT_SIGNAL_NAMES=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],CONTEXT_RECENCY_SOURCES=new Set(["substantive_history","release_cohort","created_at"]),CONTEXT_SIGNAL_STORE_WARNING_DETAILS={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNormalizedSignal(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1}function compactSignals(signals){const compact={};for(const name of STORED_CONTEXT_SIGNAL_NAMES){const value=signals[name];if(value!==void 0){if(!isNormalizedSignal(value))throw new TypeError(`Context relevance signal ${name} must be a finite number from 0 to 1`);compact[name]=value}}return compact}function normalizedCountsById(items,count){const counts=items.map(item=>[item.id,count(item)]),maximum=Math.max(0,...counts.map(([,value])=>value));return Object.fromEntries(counts.map(([id,value])=>[id,maximum===0?0:value/maximum]))}function deriveGraphProximity(items){const degree=new Map(items.map(item=>[item.id,0])),increment=id=>{degree.set(id,(degree.get(id)??0)+1)};for(const item of items){typeof item.parent=="string"&&item.parent.trim()&&(increment(item.id),increment(item.parent.trim()));for(const dependency of item.dependencies??[])typeof dependency.id!="string"||!dependency.id.trim()||(increment(item.id),increment(dependency.id.trim()))}const maximum=Math.max(0,...degree.values());return Object.fromEntries(items.map(item=>[item.id,maximum===0?0:degree.get(item.id)/maximum]))}function stableSnapshotOptions(items,options){return{...options,activityDensity:options.activityDensity??normalizedCountsById(items,item=>(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0)+(item.test_runs?.length??0)),graphProximity:options.graphProximity??deriveGraphProximity(items)}}function recencyEvidenceFingerprint(candidates){const hash=createHash("sha256");for(const{id,signal_provenance:{recency:evidence}}of[...candidates].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([id,evidence.source,evidence.coordinate,evidence.history_op??null,evidence.event_class??null]));return`sha256:${hash.digest("hex")}`}function parseSnapshotItem(value){if(!isRecord(value))return null;const signalProvenance=value.signal_provenance;if(![typeof value.id=="string",isRecord(value.signals),isRecord(signalProvenance)].every(Boolean))return null;const recency=signalProvenance.recency;if(!isRecord(recency))return null;const coordinate=canonicalizeContextRecencyCoordinate(recency.coordinate);if(coordinate===null)return null;const supportedSignals=new Set(STORED_CONTEXT_SIGNAL_NAMES),signalEntries=Object.entries(value.signals);return!signalEntries.every(([name,signal])=>supportedSignals.has(name)&&isNormalizedSignal(signal))||![typeof recency.source=="string"&&CONTEXT_RECENCY_SOURCES.has(recency.source),["undefined","string"].includes(typeof recency.history_op),[void 0,"substantive","maintenance"].includes(recency.event_class),recency.source==="substantive_history"?recency.event_class===void 0||recency.event_class==="substantive":recency.history_op===void 0&&recency.event_class===void 0].every(Boolean)?null:{id:value.id,signals:Object.fromEntries(signalEntries),signal_provenance:{recency:{source:recency.source,coordinate,history_op:recency.history_op,event_class:recency.event_class}}}}function parseSnapshotItems(values,expectedRecencyEvidenceFingerprint){const items=Array.from(values,parseSnapshotItem);if(items.some(item=>item===null))return null;const validItems=items;return new Set(validItems.map(item=>item.id)).size!==validItems.length||validItems.some(item=>item.id.trim().length===0)||expectedRecencyEvidenceFingerprint!==recencyEvidenceFingerprint(validItems)?null:validItems.sort((left,right)=>left.id.localeCompare(right.id))}function parseContextSignalSnapshot(value){if(!isRecord(value)||value.format_version!==CONTEXT_SIGNAL_STORE_FORMAT_VERSION||value.signal_set_version!==CONTEXT_SIGNAL_SET_VERSION||typeof value.source_cursor!="string"||value.source_cursor.trim().length===0||typeof value.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(value.recency_evidence_fingerprint)||typeof value.generated_at!="string"||!Number.isFinite(Date.parse(value.generated_at))||value.source!=="derived_index"&&value.source!=="scan_fallback"||!Array.isArray(value.items))return null;const items=parseSnapshotItems(value.items,value.recency_evidence_fingerprint);return items===null?null:{format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:value.source_cursor,recency_evidence_fingerprint:value.recency_evidence_fingerprint,generated_at:value.generated_at,source:value.source,items}}function validateSnapshotOptions(options){if(typeof options.sourceCursor!="string"||options.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(options.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(options.source!=="derived_index"&&options.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function snapshotFromCandidates(candidates,options,fingerprint=recencyEvidenceFingerprint(candidates)){const candidateIds=candidates.map(({id})=>id);if(new Set(candidateIds).size!==candidateIds.length||candidateIds.some(id=>id.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");const rows=candidates.map(({id,signals,signal_provenance})=>({id,signals:compactSignals(signals),signal_provenance})).sort((left,right)=>left.id.localeCompare(right.id));return Object.freeze({format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:options.sourceCursor,recency_evidence_fingerprint:fingerprint,generated_at:options.now,source:options.source,items:Object.freeze(rows.map(row=>Object.freeze(row)))})}function buildContextSignalSnapshot(items,options){return validateSnapshotOptions(options),snapshotFromCandidates(buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),options)}class JsonFileContextSignalStoreAdapter{filePath;constructor(filePath){if(typeof filePath!="string"||filePath.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=path.resolve(filePath)}async read(){try{return JSON.parse(await fs.readFile(this.filePath,"utf8"))}catch(error){if(isRecord(error)&&isFileAbsentError(error))return null;throw error}}async write(snapshot){const directory=path.dirname(this.filePath);await fs.mkdir(directory,{recursive:!0});const temporaryPath=path.join(directory,`.${path.basename(this.filePath)}.${randomUUID()}.tmp`);try{await fs.writeFile(temporaryPath,`${JSON.stringify(snapshot)}
2
- `,{encoding:"utf8",flag:"wx"}),await fs.rename(temporaryPath,this.filePath)}finally{try{await fs.rm(temporaryPath,{force:!0})}catch{}}}}class ContextSignalStore{adapter;constructor(adapter){this.adapter=adapter}async readOrRebuild(items,options){validateSnapshotOptions(options);const warnings=[];let snapshot=null;try{const serialized=await this.adapter.read();snapshot=parseContextSignalSnapshot(serialized),serialized!==null&&snapshot===null&&warnings.push("context_signal_store_invalid")}catch{warnings.push("context_signal_store_invalid")}const authoritativeIds=items.map(item=>item.id).sort((left,right)=>left.localeCompare(right)),snapshotIds=snapshot?.items.map(item=>item.id)??[],authoritativeCandidates=buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),authoritativeFingerprint=recencyEvidenceFingerprint(authoritativeCandidates),fresh=snapshot!==null&&snapshot.source_cursor===options.sourceCursor&&snapshot.recency_evidence_fingerprint===authoritativeFingerprint&&snapshot.source===options.source&&snapshotIds.length===authoritativeIds.length&&snapshotIds.every((id,index)=>id===authoritativeIds[index]);let resolvedSnapshot;if(fresh&&snapshot!==null)resolvedSnapshot=snapshot;else{snapshot!==null&&warnings.push("context_signal_store_stale"),resolvedSnapshot=snapshotFromCandidates(authoritativeCandidates,options,authoritativeFingerprint);try{await this.adapter.write(resolvedSnapshot)}catch{warnings.push("context_signal_store_write_failed")}}const snapshotItemsById=new Map(resolvedSnapshot.items.map(item=>[item.id,item]));return{snapshot:resolvedSnapshot,candidates:authoritativeCandidates.map(candidate=>({...candidate,signals:{...candidate.signals,...snapshotItemsById.get(candidate.id)?.signals},signal_provenance:snapshotItemsById.get(candidate.id).signal_provenance})),cache_status:fresh?"fresh":"rebuilt",warnings,warning_details:warnings.map(warning=>CONTEXT_SIGNAL_STORE_WARNING_DETAILS[warning])}}}function fallbackWorkspaceCursor(items){const hash=createHash("sha256");for(const item of[...items].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([item.id,item.updated_at,item.status,item.parent??null,item.priority??null,item.risk??null,(item.dependencies??[]).map(dependency=>dependency.id).sort(),item.comments?.length??0,item.notes?.length??0,item.learnings?.length??0,item.test_runs?.length??0]));return`scan:${hash.digest("hex")}`}async function readWorkspaceContextSignals(items,options){const hasSourceCursor=options.sourceCursor!==void 0,hasSource=options.source!==void 0;if(hasSourceCursor!==hasSource)throw new TypeError("Context signal source and source cursor must be provided together");if(options.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(options.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");const indexState=hasSourceCursor?null:await readItemMetadataDerivedIndexState(options.pmRoot),sourceCursor=options.sourceCursor??indexState?.source_cursor??fallbackWorkspaceCursor(items),source=options.source??(indexState===null?"scan_fallback":"derived_index"),store=new ContextSignalStore(new JsonFileContextSignalStoreAdapter(path.join(options.pmRoot,"runtime",options.storeKey?`context-signals-${options.storeKey}.json`:"context-signals.json"))),recencyEvidence=options.recencyEvidence??Object.fromEntries(Object.entries(await readLatestSubstantiveHistoryEvents(options.pmRoot,items.map(item=>item.id))).map(([id,event])=>[id,{source:"substantive_history",coordinate:event.entry.ts,history_op:event.entry.op,event_class:"substantive"}]));return store.readOrRebuild(items,{...options,recencyEvidence,sourceCursor,source})}export{CONTEXT_SIGNAL_SET_VERSION,CONTEXT_SIGNAL_STORE_FORMAT_VERSION,CONTEXT_SIGNAL_STORE_WARNING_DETAILS,ContextSignalStore,JsonFileContextSignalStoreAdapter,buildContextSignalSnapshot,parseContextSignalSnapshot,readWorkspaceContextSignals};
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]="179e487f-baf9-59d1-a438-3ae0c12b00eb")}catch{}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{buildItemContextRelevanceCandidates}from"./context-relevance.js";import{readItemMetadataDerivedIndexState}from"./item-metadata-index.js";import{readLatestSubstantiveHistoryEvents}from"../core/history/event-index.js";import{canonicalizeContextRecencyCoordinate}from"./context/recency.js";const CONTEXT_SIGNAL_STORE_FORMAT_VERSION=3,CONTEXT_SIGNAL_SET_VERSION=2,STORED_CONTEXT_SIGNAL_NAMES=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],CONTEXT_RECENCY_SOURCES=new Set(["substantive_history","release_cohort","created_at"]),CONTEXT_SIGNAL_STORE_WARNING_DETAILS={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNormalizedSignal(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1}function compactSignals(signals){const compact={};for(const name of STORED_CONTEXT_SIGNAL_NAMES){const value=signals[name];if(value!==void 0){if(!isNormalizedSignal(value))throw new TypeError(`Context relevance signal ${name} must be a finite number from 0 to 1`);compact[name]=value}}return compact}function normalizedCountsById(items,count){const counts=items.map(item=>[item.id,count(item)]),maximum=Math.max(0,...counts.map(([,value])=>value));return Object.fromEntries(counts.map(([id,value])=>[id,maximum===0?0:value/maximum]))}function deriveGraphProximity(items){const degree=new Map(items.map(item=>[item.id,0])),increment=id=>{degree.set(id,(degree.get(id)??0)+1)};for(const item of items){typeof item.parent=="string"&&item.parent.trim()&&(increment(item.id),increment(item.parent.trim()));for(const dependency of item.dependencies??[])typeof dependency.id!="string"||!dependency.id.trim()||(increment(item.id),increment(dependency.id.trim()))}const maximum=Math.max(0,...degree.values());return Object.fromEntries(items.map(item=>[item.id,maximum===0?0:degree.get(item.id)/maximum]))}function stableSnapshotOptions(items,options){return{...options,activityDensity:options.activityDensity??normalizedCountsById(items,item=>(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0)+(item.test_runs?.length??0)),graphProximity:options.graphProximity??deriveGraphProximity(items)}}function recencyEvidenceFingerprint(candidates){const hash=createHash("sha256");for(const{id,signal_provenance:{recency:evidence}}of[...candidates].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([id,evidence.source,evidence.coordinate,evidence.history_op??null,evidence.event_class??null]));return`sha256:${hash.digest("hex")}`}function parseSnapshotItem(value){if(!isRecord(value))return null;const signalProvenance=value.signal_provenance;if(![typeof value.id=="string",isRecord(value.signals),isRecord(signalProvenance)].every(Boolean))return null;const recency=signalProvenance.recency;if(!isRecord(recency))return null;const coordinate=canonicalizeContextRecencyCoordinate(recency.coordinate);if(coordinate===null)return null;const supportedSignals=new Set(STORED_CONTEXT_SIGNAL_NAMES),signalEntries=Object.entries(value.signals);return!signalEntries.every(([name,signal])=>supportedSignals.has(name)&&isNormalizedSignal(signal))||![typeof recency.source=="string"&&CONTEXT_RECENCY_SOURCES.has(recency.source),["undefined","string"].includes(typeof recency.history_op),[void 0,"substantive","maintenance"].includes(recency.event_class),recency.source==="substantive_history"?recency.event_class===void 0||recency.event_class==="substantive":recency.history_op===void 0&&recency.event_class===void 0].every(Boolean)?null:{id:value.id,signals:Object.fromEntries(signalEntries),signal_provenance:{recency:{source:recency.source,coordinate,history_op:recency.history_op,event_class:recency.event_class}}}}function parseSnapshotItems(values,expectedRecencyEvidenceFingerprint){const items=Array.from(values,parseSnapshotItem);if(items.some(item=>item===null))return null;const validItems=items;return new Set(validItems.map(item=>item.id)).size!==validItems.length||validItems.some(item=>item.id.trim().length===0)||expectedRecencyEvidenceFingerprint!==recencyEvidenceFingerprint(validItems)?null:validItems.sort((left,right)=>left.id.localeCompare(right.id))}function parseContextSignalSnapshot(value){if(!isRecord(value)||value.format_version!==CONTEXT_SIGNAL_STORE_FORMAT_VERSION||value.signal_set_version!==CONTEXT_SIGNAL_SET_VERSION||typeof value.source_cursor!="string"||value.source_cursor.trim().length===0||typeof value.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(value.recency_evidence_fingerprint)||typeof value.generated_at!="string"||!Number.isFinite(Date.parse(value.generated_at))||value.source!=="derived_index"&&value.source!=="scan_fallback"||!Array.isArray(value.items))return null;const items=parseSnapshotItems(value.items,value.recency_evidence_fingerprint);return items===null?null:{format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:value.source_cursor,recency_evidence_fingerprint:value.recency_evidence_fingerprint,generated_at:value.generated_at,source:value.source,items}}function validateSnapshotOptions(options){if(typeof options.sourceCursor!="string"||options.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(options.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(options.source!=="derived_index"&&options.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function snapshotFromCandidates(candidates,options,fingerprint=recencyEvidenceFingerprint(candidates)){const candidateIds=candidates.map(({id})=>id);if(new Set(candidateIds).size!==candidateIds.length||candidateIds.some(id=>id.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");const rows=candidates.map(({id,signals,signal_provenance})=>({id,signals:compactSignals(signals),signal_provenance})).sort((left,right)=>left.id.localeCompare(right.id));return Object.freeze({format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:options.sourceCursor,recency_evidence_fingerprint:fingerprint,generated_at:options.now,source:options.source,items:Object.freeze(rows.map(row=>Object.freeze(row)))})}function buildContextSignalSnapshot(items,options){return validateSnapshotOptions(options),snapshotFromCandidates(buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),options)}class JsonFileContextSignalStoreAdapter{filePath;constructor(filePath){if(typeof filePath!="string"||filePath.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=path.resolve(filePath)}async read(){try{return JSON.parse(await fs.readFile(this.filePath,"utf8"))}catch(error){if(isRecord(error)&&isFileAbsentError(error))return null;throw error}}async write(snapshot){const directory=path.dirname(this.filePath);await fs.mkdir(directory,{recursive:!0});const temporaryPath=path.join(directory,`.${path.basename(this.filePath)}.${randomUUID()}.tmp`);try{await fs.writeFile(temporaryPath,`${JSON.stringify(snapshot)}
2
+ `,{encoding:"utf8",flag:"wx"}),await fs.rename(temporaryPath,this.filePath)}finally{try{await fs.rm(temporaryPath,{force:!0})}catch{}}}}class ContextSignalStore{adapter;constructor(adapter){this.adapter=adapter}async readOrRebuild(items,options){validateSnapshotOptions(options);const warnings=[];let snapshot=null;try{const serialized=await this.adapter.read();snapshot=parseContextSignalSnapshot(serialized),serialized!==null&&snapshot===null&&warnings.push("context_signal_store_invalid")}catch{warnings.push("context_signal_store_invalid")}const authoritativeIds=items.map(item=>item.id).sort((left,right)=>left.localeCompare(right)),snapshotIds=snapshot?.items.map(item=>item.id)??[],authoritativeCandidates=buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),authoritativeFingerprint=recencyEvidenceFingerprint(authoritativeCandidates),fresh=snapshot!==null&&snapshot.source_cursor===options.sourceCursor&&snapshot.recency_evidence_fingerprint===authoritativeFingerprint&&snapshot.source===options.source&&snapshotIds.length===authoritativeIds.length&&snapshotIds.every((id,index)=>id===authoritativeIds[index]);let resolvedSnapshot;if(fresh&&snapshot!==null)resolvedSnapshot=snapshot;else{resolvedSnapshot=snapshotFromCandidates(authoritativeCandidates,options,authoritativeFingerprint);try{await this.adapter.write(resolvedSnapshot)}catch{warnings.push("context_signal_store_write_failed")}}const snapshotItemsById=new Map(resolvedSnapshot.items.map(item=>[item.id,item]));return{snapshot:resolvedSnapshot,candidates:authoritativeCandidates.map(candidate=>({...candidate,signals:{...candidate.signals,...snapshotItemsById.get(candidate.id)?.signals},signal_provenance:snapshotItemsById.get(candidate.id).signal_provenance})),cache_status:fresh?"fresh":"rebuilt",warnings,warning_details:warnings.map(warning=>CONTEXT_SIGNAL_STORE_WARNING_DETAILS[warning])}}}function fallbackWorkspaceCursor(items){const hash=createHash("sha256");for(const item of[...items].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([item.id,item.updated_at,item.status,item.parent??null,item.priority??null,item.risk??null,(item.dependencies??[]).map(dependency=>dependency.id).sort(),item.comments?.length??0,item.notes?.length??0,item.learnings?.length??0,item.test_runs?.length??0]));return`scan:${hash.digest("hex")}`}async function readWorkspaceContextSignals(items,options){const hasSourceCursor=options.sourceCursor!==void 0,hasSource=options.source!==void 0;if(hasSourceCursor!==hasSource)throw new TypeError("Context signal source and source cursor must be provided together");if(options.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(options.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");const indexState=hasSourceCursor?null:await readItemMetadataDerivedIndexState(options.pmRoot),sourceCursor=options.sourceCursor??indexState?.source_cursor??fallbackWorkspaceCursor(items),source=options.source??(indexState===null?"scan_fallback":"derived_index"),store=new ContextSignalStore(new JsonFileContextSignalStoreAdapter(path.join(options.pmRoot,"runtime",options.storeKey?`context-signals-${options.storeKey}.json`:"context-signals.json"))),recencyEvidence=options.recencyEvidence??Object.fromEntries(Object.entries(await readLatestSubstantiveHistoryEvents(options.pmRoot,items.map(item=>item.id))).map(([id,event])=>[id,{source:"substantive_history",coordinate:event.entry.ts,history_op:event.entry.op,event_class:"substantive"}]));return store.readOrRebuild(items,{...options,recencyEvidence,sourceCursor,source})}export{CONTEXT_SIGNAL_SET_VERSION,CONTEXT_SIGNAL_STORE_FORMAT_VERSION,CONTEXT_SIGNAL_STORE_WARNING_DETAILS,ContextSignalStore,JsonFileContextSignalStoreAdapter,buildContextSignalSnapshot,parseContextSignalSnapshot,readWorkspaceContextSignals};
3
3
  //# sourceMappingURL=context-signal-store.js.map
@@ -14,4 +14,4 @@ export { applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseRe
14
14
  export type { PmReadOutputBudgetExceeded,PmReadOutputContinuation,PmReadOutputCursorEnvelope,PmReadOutputDimension,PmReadOutputLegacyAlias,PmReadOutputOptions,PmReadOutputProducerContinuation,PmReadOutputReceipt,PmReadOutputMetadata,PmReadOutputResult,PmReadOutputResultFor,PmReadOutputSessionResult,PmReadOutputSurface,PmReadOutputSurfaceContract,} from "./read-output-contracts.js";
15
15
  export type { PmReadOutputSessionReceipt,PmReadOutputSessionReference,PmReadOutputSessionState,} from "./read-output-session.js";
16
16
  export type { ItemDocument,ItemMetadata,ItemStatus,ItemType,PmSettings,} from "../types/index.js";
17
- export type { CloseEvidenceFollowUp } from "./lifecycle-policy.js";
17
+ export type { CloseCompletionReceipt,CloseEvidenceFollowUp } from "./lifecycle-policy.js";
package/dist/sdk/core.js CHANGED
@@ -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]="8aaf0090-c67a-540b-b631-800aa480fb0b")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,validateReadOutputOptions};
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]="4e66557f-67f1-51a2-9e42-cf2781d1a569")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,update,updateLinkedTest,validateReadOutputOptions};
2
2
  //# sourceMappingURL=core.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d5644cc3-0f22-5f67-b1b3-e829f9d7e96c")}catch{}})();import{createHash}from"node:crypto";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory}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{asRecordOrNull}from"../core/shared/primitives.js";import{stableValueEquals}from"../core/shared/serialization.js";import{getSettingsPath}from"../core/store/paths.js";import{mergeSettings,readSettings,runWithConfigurationOnlySettings,serializeSettings}from"../core/store/settings.js";import{clearSettingsReadCache}from"../core/store/settings-read-cache.js";import{validateSettings}from"../core/store/settings-validator.js";import{isPmCliExpectedError}from"./errors.js";import{getItemAt}from"./history-read.js";import{RelationshipEventLog,RelationshipEventStore}from"./relationship-history.js";import{analyzeGraphImpact}from"./relationship-analytics.js";import{RelationshipGraph,createRelationshipKindRegistry}from"./relationships.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function buildRelationshipKindRegistry(definitions){const registry=createRelationshipKindRegistry();for(const definition of definitions)registry.register(definition);return registry}function replaceOwnedSettingsSubtrees(raw,next,paths=[]){if(paths.length===0)return raw;const persisted=JSON.parse(raw),canonical=JSON.parse(serializeSettings(next));for(const ownedPath of paths){const segments=ownedPath.split(".");let source=canonical;for(const segment of segments){const sourceObject=asRecordOrNull(source);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(segment)||["constructor","prototype","__proto__"].includes(segment)||sourceObject===null||!Object.hasOwn(sourceObject,segment))throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);source=sourceObject[segment]}if(asRecordOrNull(source)===null)throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);let destination=persisted,canonicalParent=canonical;for(const segment of segments.slice(0,-1)){const value=destination[segment];canonicalParent=canonicalParent[segment],value===void 0&&Object.defineProperty(destination,segment,{value:structuredClone(canonicalParent),enumerable:!0,writable:!0,configurable:!0}),destination=destination[segment]}Object.defineProperty(destination,segments.at(-1),{value:source,enumerable:!0,writable:!0,configurable:!0})}return stableValueEquals(persisted,JSON.parse(raw))?raw:`${JSON.stringify(persisted,null,2)}
2
- `}function createExtensionCommandSdk(pmRoot,client,invocationAuthor,invocationCommand){return{client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),openRelationshipEventStore:options=>RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}}),createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot}),mutateWorkspaceSettings:async options=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(options.operationId))throw new PmCliError("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",EXIT_CODE.USAGE);const settings=options.dryRun===!0?await runWithConfigurationOnlySettings(pmRoot,()=>readSettings(pmRoot)):await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:getSettingsPath(pmRoot),op:"extension:pm:settings",idempotencyKey:invocationCommand===void 0?options.operationId:`${createHash("sha256").update(invocationCommand).digest("hex").slice(0,16)}:${options.operationId}`,author:resolveAuthor(invocationAuthor,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,dryRun:options.dryRun===!0,mutate:async beforeRaw=>{const current=beforeRaw===null?null:JSON.parse(beforeRaw),validatedCurrent=validateSettings(current);if(!validatedCurrent.success)throw new PmCliError("Workspace settings mutation requires a valid initialized settings.json.",EXIT_CODE.USAGE);const currentSettings=mergeSettings(validatedCurrent.data),next=await options.mutate(structuredClone(currentSettings));if(!validateSettings(next).success)throw new PmCliError("Workspace settings mutation returned invalid settings.json.",EXIT_CODE.USAGE);let raw=stableValueEquals(currentSettings,next)?beforeRaw:serializeSettings(next,{source:{raw:current,validated:validatedCurrent.data}});raw=replaceOwnedSettingsSubtrees(raw,next,options.replaceSubtrees);const validatedResult=validateSettings(JSON.parse(raw));if(!validatedResult.success)throw new PmCliError("Workspace settings mutation serialized invalid settings.json.",EXIT_CODE.USAGE);return{raw,result:options.includePreview===!0?mergeSettings(validatedResult.data):void 0}}});return mutation.changed&&options.dryRun!==!0&&await runActiveOnWriteHooks({path:getSettingsPath(pmRoot),scope:"project",op:"extension:pm:settings"}),{changed:mutation.changed,dry_run:options.dryRun===!0,replayed:mutation.replayed===!0,...mutation.result===void 0?{}:{preview:mutation.result}}}finally{clearSettingsReadCache(pmRoot)}}}}export{createExtensionCommandSdk};
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]="620b7ff7-6953-5ef3-908a-1ef205cf00c5")}catch{}})();import{createHash}from"node:crypto";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{mutateWorkspaceJsonWithHistory}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{asRecordOrNull}from"../core/shared/primitives.js";import{stableValueEquals}from"../core/shared/serialization.js";import{getSettingsPath}from"../core/store/paths.js";import{mergeSettings,readSettings,runWithConfigurationOnlySettings,serializeSettings}from"../core/store/settings.js";import{clearSettingsReadCache}from"../core/store/settings-read-cache.js";import{validateSettings}from"../core/store/settings-validator.js";import{isPmCliExpectedError}from"./errors.js";import{getItemAt}from"./history-read.js";import{fitOutputEnvelope}from"./output/fit-envelope.js";import{RelationshipEventLog,RelationshipEventStore}from"./relationship-history.js";import{analyzeGraphImpact}from"./relationship-analytics.js";import{RelationshipGraph,createRelationshipKindRegistry}from"./relationships.js";import{commitWorkspaceTransaction}from"./workspace-transaction.js";function buildRelationshipKindRegistry(definitions){const registry=createRelationshipKindRegistry();for(const definition of definitions)registry.register(definition);return registry}function replaceOwnedSettingsSubtrees(raw,next,paths=[]){if(paths.length===0)return raw;const persisted=JSON.parse(raw),canonical=JSON.parse(serializeSettings(next));for(const ownedPath of paths){const segments=ownedPath.split(".");let source=canonical;for(const segment of segments){const sourceObject=asRecordOrNull(source);if(!/^[a-zA-Z][a-zA-Z0-9_]*$/u.test(segment)||["constructor","prototype","__proto__"].includes(segment)||sourceObject===null||!Object.hasOwn(sourceObject,segment))throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);source=sourceObject[segment]}if(asRecordOrNull(source)===null)throw new PmCliError(`Invalid owned settings subtree: ${ownedPath}. Select a declared inline object path.`,EXIT_CODE.USAGE);let destination=persisted,canonicalParent=canonical;for(const segment of segments.slice(0,-1)){const value=destination[segment];canonicalParent=canonicalParent[segment],value===void 0&&Object.defineProperty(destination,segment,{value:structuredClone(canonicalParent),enumerable:!0,writable:!0,configurable:!0}),destination=destination[segment]}Object.defineProperty(destination,segments.at(-1),{value:source,enumerable:!0,writable:!0,configurable:!0})}return stableValueEquals(persisted,JSON.parse(raw))?raw:`${JSON.stringify(persisted,null,2)}
2
+ `}function createExtensionCommandSdk(pmRoot,client,invocationAuthor,invocationCommand){return{fitOutputEnvelope,client,isItemNotFoundError:error=>isPmCliExpectedError(error)&&error.exitCode===EXIT_CODE.NOT_FOUND,getItemAt:(id,target)=>getItemAt(id,target,{pmRoot}),openRelationshipEventStore:options=>RelationshipEventStore.open({pmRoot,nodes:options.nodes,registry:buildRelationshipKindRegistry(options.definitions),...options.relativePath===void 0?{}:{relativePath:options.relativePath}}),createRelationshipGraph:options=>new RelationshipGraph(options.nodes,options.edges,buildRelationshipKindRegistry(options.definitions)),analyzeRelationshipImpact:(graph,root,options)=>analyzeGraphImpact(graph,root,options),validateRelationshipEvents:options=>{const log=new RelationshipEventLog(options.nodes,{registry:buildRelationshipKindRegistry(options.definitions)});return options.events.map(event=>log.append({...event,expectedVersion:log.version}))},commitWorkspaceTransaction:options=>commitWorkspaceTransaction({...options,pmRoot}),mutateWorkspaceSettings:async options=>{if(!/^[a-zA-Z0-9._-]{1,128}$/u.test(options.operationId))throw new PmCliError("Workspace settings operationId must be 1-128 letters, digits, dots, underscores, or hyphens.",EXIT_CODE.USAGE);const settings=options.dryRun===!0?await runWithConfigurationOnlySettings(pmRoot,()=>readSettings(pmRoot)):await readSettings(pmRoot);try{const mutation=await mutateWorkspaceJsonWithHistory({pmRoot,filePath:getSettingsPath(pmRoot),op:"extension:pm:settings",idempotencyKey:invocationCommand===void 0?options.operationId:`${createHash("sha256").update(invocationCommand).digest("hex").slice(0,16)}:${options.operationId}`,author:resolveAuthor(invocationAuthor,settings.author_default),lockTtlSeconds:settings.locks.ttl_seconds,lockWaitMs:settings.locks.wait_ms,recordCreation:!1,dryRun:options.dryRun===!0,mutate:async beforeRaw=>{const current=beforeRaw===null?null:JSON.parse(beforeRaw),validatedCurrent=validateSettings(current);if(!validatedCurrent.success)throw new PmCliError("Workspace settings mutation requires a valid initialized settings.json.",EXIT_CODE.USAGE);const currentSettings=mergeSettings(validatedCurrent.data),next=await options.mutate(structuredClone(currentSettings));if(!validateSettings(next).success)throw new PmCliError("Workspace settings mutation returned invalid settings.json.",EXIT_CODE.USAGE);let raw=stableValueEquals(currentSettings,next)?beforeRaw:serializeSettings(next,{source:{raw:current,validated:validatedCurrent.data}});raw=replaceOwnedSettingsSubtrees(raw,next,options.replaceSubtrees);const validatedResult=validateSettings(JSON.parse(raw));if(!validatedResult.success)throw new PmCliError("Workspace settings mutation serialized invalid settings.json.",EXIT_CODE.USAGE);return{raw,result:options.includePreview===!0?mergeSettings(validatedResult.data):void 0}}});return mutation.changed&&options.dryRun!==!0&&await runActiveOnWriteHooks({path:getSettingsPath(pmRoot),scope:"project",op:"extension:pm:settings"}),{changed:mutation.changed,dry_run:options.dryRun===!0,replayed:mutation.replayed===!0,...mutation.result===void 0?{}:{preview:mutation.result}}}finally{clearSettingsReadCache(pmRoot)}}}}export{createExtensionCommandSdk};
3
3
  //# sourceMappingURL=extension-command-context.js.map