@unbrained/pm-cli 2026.11.14 → 2026.11.15

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 (234) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +1 -1
  3. package/dist/cli/extension-command-help.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/chunk-6UTBX62V.js +2 -0
  6. package/dist/cli-bundle/chunks/{chunk-65SBMIK6.js → chunk-7AODVNHX.js} +2 -2
  7. package/dist/cli-bundle/chunks/chunk-ASGAELBQ.js +9 -0
  8. package/dist/cli-bundle/chunks/{chunk-V2OAXGHK.js → chunk-DBUBX4DL.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-547OEGDR.js → chunk-E4B2HWH7.js} +13 -13
  10. package/dist/cli-bundle/chunks/chunk-E74OMFBZ.js +6 -0
  11. package/dist/cli-bundle/chunks/chunk-FSE624WQ.js +2 -0
  12. package/dist/cli-bundle/chunks/chunk-FYOIH56R.js +20 -0
  13. package/dist/cli-bundle/chunks/chunk-GAFALSR2.js +8 -0
  14. package/dist/cli-bundle/chunks/{chunk-AXTUB74T.js → chunk-GCSKHCYK.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-HMVZSXB4.js +8 -0
  16. package/dist/cli-bundle/chunks/chunk-IXV5UM4U.js +31 -0
  17. package/dist/cli-bundle/chunks/chunk-J6L3Q5J4.js +3 -0
  18. package/dist/cli-bundle/chunks/chunk-KLWGIEDC.js +114 -0
  19. package/dist/cli-bundle/chunks/chunk-KSLPRST2.js +10 -0
  20. package/dist/cli-bundle/chunks/chunk-LC6DL446.js +3 -0
  21. package/dist/cli-bundle/chunks/{chunk-MELSYAFE.js → chunk-NAX554KY.js} +35 -35
  22. package/dist/cli-bundle/chunks/chunk-PMIGRSNZ.js +2 -0
  23. package/dist/cli-bundle/chunks/chunk-Q6GBRK27.js +3 -0
  24. package/dist/cli-bundle/chunks/chunk-QZNDEZYI.js +2 -0
  25. package/dist/cli-bundle/chunks/chunk-S5UXBECQ.js +2 -0
  26. package/dist/cli-bundle/chunks/{chunk-UJMQP2HP.js → chunk-TESRFVGF.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-EXO4PM5J.js → chunk-VWKLTHYQ.js} +74 -70
  28. package/dist/cli-bundle/chunks/chunk-YJNY5MKP.js +2 -0
  29. package/dist/cli-bundle/chunks/chunk-YLPZE2TK.js +2 -0
  30. package/dist/cli-bundle/chunks/{chunk-RSAN2YUU.js → chunk-ZVDXGAYV.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-ZWUS65LN.js +2 -0
  32. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-I6RQGD6Y.js → indexed-receipt-blobs-42Y2CSEQ.js} +2 -2
  33. package/dist/cli-bundle/chunks/item-revision-JCEDTAVX.js +2 -0
  34. package/dist/cli-bundle/chunks/item-transaction-BSMGKZ4S.js +2 -0
  35. package/dist/cli-bundle/chunks/mutation-actor-IQHBRFAJ.js +2 -0
  36. package/dist/cli-bundle/chunks/mutation-admission-DF6BFGG6.js +2 -0
  37. package/dist/cli-bundle/chunks/{register-list-query-MCNOV6ML.js → register-list-query-DNKPQB76.js} +2 -2
  38. package/dist/cli-bundle/chunks/{register-mutation-KYXLYHOK.js → register-mutation-WVTDFLEF.js} +3 -3
  39. package/dist/cli-bundle/chunks/register-operations-NR5MTT5T.js +2 -0
  40. package/dist/cli-bundle/chunks/register-setup-2RTG3LII.js +2 -0
  41. package/dist/cli-bundle/chunks/{settlement-hook-JHXLUBEN.js → settlement-hook-W5ULPKIE.js} +2 -2
  42. package/dist/cli-bundle/chunks/stage-YFNK7U26.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-EAYRYXA6.js → chunk-2UQFFVQK.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-52H6AELE.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-YNYO7PMT.js → chunk-63FM3TIG.js} +6 -6
  46. package/dist/cli-bundle/focused-chunks/{chunk-EH7JKGDH.js → chunk-7GCAZJT4.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-BSY6FZ3Y.js +2 -0
  48. package/dist/cli-bundle/focused-chunks/chunk-CZZKAGHE.js +91 -0
  49. package/dist/cli-bundle/focused-chunks/chunk-DRBXOAGY.js +2 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-DXMQ32EH.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/chunk-EALGFJRP.js +78 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-FK2X6MJY.js +44 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-IDAYTYNN.js → chunk-JE3MFEQZ.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-7KNF6RCV.js → chunk-JRRHN2PZ.js} +12 -12
  55. package/dist/cli-bundle/focused-chunks/chunk-JXA77YIV.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-LQZ5F6LE.js +3 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-LSWUTTE6.js +6 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-QXOFSZR6.js +3 -0
  59. package/dist/cli-bundle/focused-chunks/{chunk-I7A5VP5E.js → chunk-RMCODWHZ.js} +52 -52
  60. package/dist/cli-bundle/focused-chunks/chunk-S6GTALM4.js +24 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-UPUIDGNJ.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-TA4EGVE6.js → chunk-W2KIQ7RF.js} +3 -3
  63. package/dist/cli-bundle/focused-chunks/chunk-WGYR3X6O.js +26 -0
  64. package/dist/cli-bundle/focused-chunks/chunk-WVYXR3YX.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/{chunk-EXCVUBAE.js → chunk-XQZKGTZV.js} +2 -2
  66. package/dist/cli-bundle/focused-chunks/{chunk-3SUKWYR2.js → chunk-YTNUUEY6.js} +2 -2
  67. package/dist/cli-bundle/focused-chunks/chunk-YZUBG4W2.js +6 -0
  68. package/dist/cli-bundle/focused-chunks/chunk-Z6HCQYSW.js +8 -0
  69. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-7XGVHYAO.js → indexed-receipt-blobs-LSBWMXKS.js} +2 -2
  70. package/dist/cli-bundle/focused-chunks/item-revision-YO7YGQYE.js +2 -0
  71. package/dist/cli-bundle/focused-chunks/item-transaction-7A3Q4CAJ.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/mutation-actor-UQHBNHOF.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/mutation-admission-G565NLPE.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/{settlement-hook-H56537UV.js → settlement-hook-UXN76GMA.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/stage-F3YJGNRK.js +2 -0
  76. package/dist/cli-bundle/main.js +7 -7
  77. package/dist/cli-bundle/sdk-authoring.js +1 -1
  78. package/dist/cli-bundle/sdk-contracts.js +3 -3
  79. package/dist/cli-bundle/sdk-core.js +1 -1
  80. package/dist/cli-bundle/sdk-governance.js +1 -1
  81. package/dist/cli-bundle/sdk-graph.js +1 -1
  82. package/dist/cli-bundle/sdk-merge.js +57 -57
  83. package/dist/cli-bundle/sdk-query.js +1 -1
  84. package/dist/cli-bundle/sdk-runtime.js +1 -1
  85. package/dist/cli-bundle/sdk-testing.js +1 -1
  86. package/dist/cli-bundle/sdk.js +11 -11
  87. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  88. package/dist/core/extensions/extension-types.d.ts +30 -0
  89. package/dist/core/extensions/extension-types.js +1 -1
  90. package/dist/core/extensions/index.d.ts +21 -1
  91. package/dist/core/extensions/index.js +1 -1
  92. package/dist/core/extensions/mutation-actor-snapshot.js +2 -0
  93. package/dist/core/extensions/mutation-actor.js +2 -0
  94. package/dist/core/item/deferred-fields.js +2 -0
  95. package/dist/core/item/item-format-version.d.ts +8 -7
  96. package/dist/core/item/item-format-version.js +1 -1
  97. package/dist/core/item/item-format.js +2 -2
  98. package/dist/core/output/output.d.ts +7 -0
  99. package/dist/core/output/output.js +3 -3
  100. package/dist/core/schema/runtime-field-values.d.ts +4 -0
  101. package/dist/core/schema/runtime-field-values.js +1 -1
  102. package/dist/core/shared/item-metadata-contract.js +1 -1
  103. package/dist/core/store/item-store.js +1 -1
  104. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  105. package/dist/sdk/authoring.d.ts +1 -1
  106. package/dist/sdk/authoring.js +1 -1
  107. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  108. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  109. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  110. package/dist/sdk/cli-contracts/registration-helpers.js +1 -1
  111. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +1 -1
  112. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  113. package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +1 -1
  114. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  115. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  116. package/dist/sdk/cli-contracts/tool-schema.d.ts +1 -1
  117. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  118. package/dist/sdk/completion/fish.js +3 -1
  119. package/dist/sdk/completion/zsh.js +3 -1
  120. package/dist/sdk/extension/command-options.d.ts +23 -4
  121. package/dist/sdk/extension/command-options.js +1 -1
  122. package/dist/sdk/extension/native-command-options.js +2 -0
  123. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  124. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  125. package/dist/sdk/governance/health.js +1 -1
  126. package/dist/sdk/governance/lifecycle-dependency-cycles.d.ts +12 -0
  127. package/dist/sdk/governance/lifecycle-dependency-cycles.js +2 -0
  128. package/dist/sdk/governance/validate-deferred-fields.js +2 -0
  129. package/dist/sdk/governance/validate.d.ts +2 -2
  130. package/dist/sdk/governance/validate.js +1 -1
  131. package/dist/sdk/index.d.ts +1 -1
  132. package/dist/sdk/index.js +1 -1
  133. package/dist/sdk/item-transaction.d.ts +2 -2
  134. package/dist/sdk/item-transaction.js +1 -1
  135. package/dist/sdk/lifecycle/close.js +1 -1
  136. package/dist/sdk/lifecycle/copy.js +1 -1
  137. package/dist/sdk/lifecycle/create-deferrals.js +2 -0
  138. package/dist/sdk/lifecycle/create.d.ts +6 -2
  139. package/dist/sdk/lifecycle/create.js +1 -1
  140. package/dist/sdk/lifecycle/restore.js +1 -1
  141. package/dist/sdk/lifecycle/shared-unset-fields.d.ts +7 -1
  142. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  143. package/dist/sdk/merge/three-way.d.ts +1 -1
  144. package/dist/sdk/merge/three-way.js +2 -2
  145. package/dist/sdk/package-import-adapters.d.ts +9 -1
  146. package/dist/sdk/package-import-adapters.js +1 -1
  147. package/dist/sdk/public-surface.json +1 -1
  148. package/dist/sdk/query/complete-list.d.ts +14 -5
  149. package/dist/sdk/query/complete-list.js +1 -1
  150. package/dist/sdk/query/list.js +1 -1
  151. package/dist/sdk/query/projection-contracts.d.ts +6 -0
  152. package/dist/sdk/query/projection-contracts.js +1 -1
  153. package/dist/sdk/read-output/extension.js +1 -1
  154. package/dist/sdk/runtime-input.d.ts +6 -2
  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 +2 -2
  159. package/dist/sdk/runtime.js +1 -1
  160. package/dist/sdk/structured-mutations.js +1 -1
  161. package/dist/sdk/testing.d.ts +15 -2
  162. package/dist/sdk/testing.js +1 -1
  163. package/dist/types.d.ts +8 -0
  164. package/dist/types.js +1 -1
  165. package/docs/COMMANDS.md +9 -0
  166. package/docs/EXTENSIONS.md +1 -1
  167. package/docs/SDK.md +111 -5
  168. package/docs/generated/FLAG_LEXICON_BUDGETS.md +1 -1
  169. package/marketplace.json +1 -1
  170. package/package.json +6 -3
  171. package/packages/pm-beads/package.json +1 -1
  172. package/packages/pm-calendar/extensions/calendar/command-definitions.ts +2 -0
  173. package/packages/pm-calendar/package.json +1 -1
  174. package/packages/pm-command-kit/package.json +1 -1
  175. package/packages/pm-digital-twin/package.json +1 -1
  176. package/packages/pm-governance-audit/package.json +1 -1
  177. package/packages/pm-guide-shell/package.json +1 -1
  178. package/packages/pm-kanban/package.json +1 -1
  179. package/packages/pm-lifecycle-hooks/package.json +1 -1
  180. package/packages/pm-linked-test-adapters/package.json +1 -1
  181. package/packages/pm-search-advanced/package.json +1 -1
  182. package/packages/pm-templates/package.json +1 -1
  183. package/packages/pm-todos/extensions/todos/runtime.ts +3 -0
  184. package/packages/pm-todos/package.json +1 -1
  185. package/packages/pm-vcs/package.json +1 -1
  186. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  187. package/plugins/pm-claude/package.json +1 -1
  188. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  189. package/plugins/pm-codex/package.json +1 -1
  190. package/plugins/pm-codex/plugin.json +1 -1
  191. package/runtime-dependencies.json +1 -1
  192. package/dist/cli-bundle/chunks/chunk-25BUKX4W.js +0 -2
  193. package/dist/cli-bundle/chunks/chunk-27FG6ROB.js +0 -2
  194. package/dist/cli-bundle/chunks/chunk-5TGFB34A.js +0 -2
  195. package/dist/cli-bundle/chunks/chunk-BHH65KLL.js +0 -2
  196. package/dist/cli-bundle/chunks/chunk-C7M54YV6.js +0 -122
  197. package/dist/cli-bundle/chunks/chunk-DMWL3K4A.js +0 -20
  198. package/dist/cli-bundle/chunks/chunk-DVN7CD5B.js +0 -2
  199. package/dist/cli-bundle/chunks/chunk-DZ7CWUVM.js +0 -8
  200. package/dist/cli-bundle/chunks/chunk-FRCNYOTG.js +0 -9
  201. package/dist/cli-bundle/chunks/chunk-HXECILIE.js +0 -31
  202. package/dist/cli-bundle/chunks/chunk-IDFRGH4X.js +0 -3
  203. package/dist/cli-bundle/chunks/chunk-JSTBYDLL.js +0 -3
  204. package/dist/cli-bundle/chunks/chunk-O4ZLEN4T.js +0 -3
  205. package/dist/cli-bundle/chunks/chunk-OTM6PXZQ.js +0 -8
  206. package/dist/cli-bundle/chunks/chunk-PC5DGK3C.js +0 -6
  207. package/dist/cli-bundle/chunks/chunk-PF3V443A.js +0 -2
  208. package/dist/cli-bundle/chunks/chunk-U2HVJVA5.js +0 -2
  209. package/dist/cli-bundle/chunks/chunk-VERRDW3Q.js +0 -2
  210. package/dist/cli-bundle/chunks/item-revision-VGIHIWZM.js +0 -2
  211. package/dist/cli-bundle/chunks/item-transaction-6OB6BGTD.js +0 -2
  212. package/dist/cli-bundle/chunks/mutation-admission-LL6SGQYU.js +0 -2
  213. package/dist/cli-bundle/chunks/register-operations-6RQF6IAE.js +0 -2
  214. package/dist/cli-bundle/chunks/register-setup-XGPOFFD3.js +0 -2
  215. package/dist/cli-bundle/chunks/stage-ZS7WNUD4.js +0 -2
  216. package/dist/cli-bundle/focused-chunks/chunk-2A4JCFMI.js +0 -2
  217. package/dist/cli-bundle/focused-chunks/chunk-2T6MQ7NP.js +0 -3
  218. package/dist/cli-bundle/focused-chunks/chunk-32QYILXW.js +0 -82
  219. package/dist/cli-bundle/focused-chunks/chunk-4WOF3Q6R.js +0 -2
  220. package/dist/cli-bundle/focused-chunks/chunk-5IQPFV4Y.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-6C7NBJ7A.js +0 -26
  222. package/dist/cli-bundle/focused-chunks/chunk-FNLOLNPQ.js +0 -2
  223. package/dist/cli-bundle/focused-chunks/chunk-G6ERMFJ5.js +0 -3
  224. package/dist/cli-bundle/focused-chunks/chunk-HRLGC3P7.js +0 -28
  225. package/dist/cli-bundle/focused-chunks/chunk-JHC3X43E.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-MKYNDWT3.js +0 -91
  227. package/dist/cli-bundle/focused-chunks/chunk-RDTHL44U.js +0 -2
  228. package/dist/cli-bundle/focused-chunks/chunk-UCCLV5GJ.js +0 -8
  229. package/dist/cli-bundle/focused-chunks/chunk-W3RWCLEU.js +0 -2
  230. package/dist/cli-bundle/focused-chunks/chunk-W57DSFSU.js +0 -44
  231. package/dist/cli-bundle/focused-chunks/item-revision-7J7WSCPC.js +0 -2
  232. package/dist/cli-bundle/focused-chunks/item-transaction-F5YMCPRB.js +0 -2
  233. package/dist/cli-bundle/focused-chunks/mutation-admission-2NRQEAOG.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/stage-2KVCKOGC.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]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();import{unicodeSafePrefix}from"../shared/text-normalization.js";import{cloneCommandOptionsSnapshot,cloneContextSnapshot,cloneGlobalOptionsSnapshot,normalizeCommandName}from"./extension-runtime-helpers.js";import{stableValueEquals}from"../shared/serialization.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const DEFAULT_MUTATION_GUARD_TIMEOUT_MS=5e3;async function executeRegisteredHooks(entries,hookName,context){const warnings=[];for(const entry of entries)try{await entry.run(cloneContextSnapshot(context))}catch{warnings.push(`extension_hook_failed:${entry.layer}:${entry.name}:${hookName}`)}return warnings}async function runBeforeCommandHooks(hooks,context){return executeRegisteredHooks(hooks.beforeCommand,"beforeCommand",context)}function enforceMutationGuardDecision(decision,entry,operation){if(decision===void 0)return;if(typeof decision!="object"||decision===null||!("allow"in decision)||decision.allow!==!0&&decision.allow!==!1)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid decision.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(decision.allow)return;const denial=decision,code=typeof denial.code=="string"?denial.code.trim():"",remediation=typeof denial.remediation=="string"?denial.remediation.trim():"";if(code.length===0||remediation.length===0)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid denial.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});const message=typeof denial.message=="string"?denial.message.trim():"";throw new PmCliError(message||`Extension mutation guard ${entry.name} denied ${operation}.`,EXIT_CODE.CONFLICT,{code,reason:`${entry.layer}:${entry.name}`,nextSteps:[remediation]})}async function runBeforeMutationHooks(hooks,context){for(const entry of hooks.beforeMutation??[]){let decision,timeoutHandle;try{const guardPromise=Promise.resolve().then(()=>entry.run({pm_root:context.pm_root,operation:context.operation,before:context.before===null?null:cloneContextSnapshot(context.before),after:context.after===null?null:cloneContextSnapshot(context.after),changed_fields:[...context.changed_fields],sdk:context.sdk}));guardPromise.catch(()=>{}),decision=await Promise.race([guardPromise,new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(new PmCliError(`Extension mutation guard ${entry.name} timed out before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},DEFAULT_MUTATION_GUARD_TIMEOUT_MS),timeoutHandle.unref?.()})])}catch(error){throw error instanceof PmCliError?error:new PmCliError(`Extension mutation guard ${entry.name} failed before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(timeoutHandle)}enforceMutationGuardDecision(decision,entry,context.operation)}}async function runAfterCommandHooks(hooks,context){return executeRegisteredHooks(hooks.afterCommand,"afterCommand",context)}async function runOnWriteHooks(hooks,context){return executeRegisteredHooks(hooks.onWrite,"onWrite",context)}async function runOnReadHooks(hooks,context){return executeRegisteredHooks(hooks.onRead,"onRead",context)}async function runOnIndexHooks(hooks,context){return executeRegisteredHooks(hooks.onIndex,"onIndex",context)}function describeHandlerError(error){let raw="";error instanceof Error&&typeof error.message=="string"?raw=error.message:typeof error=="string"?raw=error:typeof error=="object"&&error!==null&&typeof error.message=="string"&&(raw=error.message);const normalized=raw.replace(/\s+/gu," ").trim();if(normalized.length===0)return"";const maxLength=300;return normalized.length>maxLength?`${unicodeSafePrefix(normalized,maxLength-1)}\u2026`:normalized}function readHandlerStringField(value,field){if(typeof value!="object"||value===null||typeof value[field]!="string")return;const normalized=String(value[field]).replace(/\s+/gu," ").trim();return normalized.length>0?unicodeSafePrefix(normalized,300):void 0}function readHandlerResultExitCode(result){if(typeof result!="object"||result===null||!Object.hasOwn(result,"exit_code"))return;const exitCode=result.exit_code;if(typeof exitCode!="number"||!Number.isInteger(exitCode)||exitCode<1||exitCode>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return exitCode}async function runCommandHandler(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{handled:!1,result:null,warnings:[]};const matched=[...commands.handlers].reverse().find(entry=>entry.command===command);if(!matched)return{handled:!1,result:null,warnings:[]};try{const result=await matched.run({command,args:cloneContextSnapshot(context.args),options:cloneContextSnapshot(context.options),global:cloneContextSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,...context.sdk===void 0?{}:{sdk:context.sdk}});return{handled:!0,result,warnings:[],...Object.fromEntries([["exitCode",readHandlerResultExitCode(result)],["errorCode",readHandlerStringField(result,"code")],["remediation",readHandlerStringField(result,"remediation")]].filter(entry=>entry[1]!==void 0))}}catch(error){const exitCode=typeof error=="object"&&error!==null&&"exitCode"in error?error.exitCode:void 0;if(typeof exitCode=="number"&&Number.isFinite(exitCode))throw error;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${matched.layer}:${matched.name}:${matched.command}`],errorMessage:describeHandlerError(error),...Object.fromEntries([["errorCode",readHandlerStringField(error,"code")],["remediation",readHandlerStringField(error,"remediation")]].filter(entry=>entry[1]!==void 0))},"cause",{value:error,configurable:!0})}}async function runParserOverride(parsers,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};const matched=[...parsers.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};try{const delta=await Promise.resolve(matched.run({command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel}))??{},nextArgs=Array.isArray(delta.args)?cloneContextSnapshot(delta.args):cloneContextSnapshot(context.args),nextOptions=delta.options?cloneCommandOptionsSnapshot(delta.options):cloneCommandOptionsSnapshot(context.options),nextGlobal=delta.global?cloneGlobalOptionsSnapshot(delta.global):cloneGlobalOptionsSnapshot(context.global);return{overridden:!0,context:{command,args:nextArgs,options:nextOptions,global:nextGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[`extension_parser_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}async function runPreflightOverride(preflight,context){const baseContext={command:normalizeCommandName(context.command),args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},baseDecision=cloneContextSnapshot(context.decision),matched=[...preflight.overrides].reverse().find(entry=>!entry.commands?.length||entry.commands.includes(baseContext.command));if(!matched)return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[]};try{const delta=await Promise.resolve(matched.run({command:baseContext.command,args:cloneContextSnapshot(baseContext.args),options:cloneCommandOptionsSnapshot(baseContext.options),global:cloneGlobalOptionsSnapshot(baseContext.global),pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel,decision:cloneContextSnapshot(baseDecision)}))??{},nextContext={command:baseContext.command,args:Array.isArray(delta.args)?cloneContextSnapshot(delta.args):baseContext.args,options:delta.options?cloneCommandOptionsSnapshot(delta.options):baseContext.options,global:delta.global?cloneGlobalOptionsSnapshot(delta.global):baseContext.global,pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel},nextDecision={enforce_item_format_gate:typeof delta.enforce_item_format_gate=="boolean"?delta.enforce_item_format_gate:baseDecision.enforce_item_format_gate,run_preflight_item_format_sync:typeof delta.run_preflight_item_format_sync=="boolean"?delta.run_preflight_item_format_sync:baseDecision.run_preflight_item_format_sync,run_extension_migrations:typeof delta.run_extension_migrations=="boolean"?delta.run_extension_migrations:baseDecision.run_extension_migrations,enforce_mandatory_migration_gate:typeof delta.enforce_mandatory_migration_gate=="boolean"?delta.enforce_mandatory_migration_gate:baseDecision.enforce_mandatory_migration_gate};return{overridden:!0,context:nextContext,decision:nextDecision,warnings:[]}}catch{return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[`extension_preflight_override_failed:${matched.layer}:${matched.name}`]}}}function resolveDefaultServiceResult(context){return{handled:!1,result:context.payload,warnings:[]}}function matchingServiceOverrides(services,service){return[...services.overrides].reverse().filter(entry=>entry.service===service)}function buildServiceOverrideContext(context){return{service:context.service,command:context.command?normalizeCommandName(context.command):void 0,args:context.args?cloneContextSnapshot(context.args):void 0,options:context.options?cloneCommandOptionsSnapshot(context.options):void 0,global:context.global?cloneGlobalOptionsSnapshot(context.global):void 0,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,payload:cloneContextSnapshot(context.payload)}}function isServiceOverrideDecision(value){if(typeof value!="object"||value===null||!Object.hasOwn(value,"handled"))return!1;const handled=value.handled;return handled===!0?Object.hasOwn(value,"result"):handled===!1&&Reflect.ownKeys(value).length===1}function resolveServiceOverrideValue(result,context){return isServiceOverrideDecision(result)?result.handled?{handled:!0,result:result.result}:{handled:!1,result:context.payload}:context.service==="output_format"&&result==null?{handled:!1,result:context.payload}:{handled:!0,result}}function isLegacyOutputPayloadEcho(result,context,serviceContext){return context.service==="output_format"&&typeof result=="object"&&result!==null&&stableValueEquals(result,serviceContext.payload)}function resolveMatchedServiceDecision(matched,decision,warnings){if(decision.handled){if(matched.passThrough===!0){warnings.push(`extension_service_pass_through_contract_violated:${matched.layer}:${matched.name}:${matched.service}`);return}return{handled:!0,result:decision.result,warnings}}}function runServiceOverrideSync(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=matched.run(serviceContext);if(result instanceof Promise){warnings.push(`extension_service_override_async_unsupported:${matched.layer}:${matched.name}:${matched.service}`);continue}if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}async function runServiceOverride(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=await Promise.resolve(matched.run(serviceContext));if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}function runCommandOverride(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,result:context.result,warnings:[]};const matched=[...commands.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,result:context.result,warnings:[]};try{const overrideOptions=cloneCommandOptionsSnapshot(context.options),overrideGlobal=cloneGlobalOptionsSnapshot(context.global),overrideResult=matched.run({command,args:cloneContextSnapshot(context.args),options:overrideOptions,global:overrideGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return overrideResult instanceof Promise?{overridden:!1,result:context.result,warnings:[`extension_command_override_async_unsupported:${matched.layer}:${matched.name}:${matched.command}`]}:{overridden:!0,result:overrideResult,warnings:[]}}catch{return{overridden:!1,result:context.result,warnings:[`extension_command_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}function rendererOwnsContext(entry,command,result){if((entry.commands?.length??0)>0&&!entry.commands?.includes(command))return!1;if(entry.resultDiscriminator===void 0)return!0;try{return entry.resultDiscriminator(cloneContextSnapshot(result))}catch{return!1}}function runRendererOverride(renderers,context){const rendererCommand=typeof context.command=="string"?normalizeCommandName(context.command):"",matched=[...renderers.overrides].reverse().find(entry=>entry.format===context.format&&rendererOwnsContext(entry,rendererCommand,context.result));if(!matched)return{overridden:!1,rendered:null,warnings:[]};try{const rendererArgs=Array.isArray(context.args)?cloneContextSnapshot(context.args):[],rendererOptions=cloneCommandOptionsSnapshot(context.options),rendererGlobal=cloneGlobalOptionsSnapshot(context.global),rendererPmRoot=typeof context.pm_root=="string"?context.pm_root:"",rendered=matched.run({format:context.format,command:rendererCommand,args:rendererArgs,options:rendererOptions,global:rendererGlobal,pm_root:rendererPmRoot,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return rendered==null?{overridden:!1,rendered:null,warnings:[]}:typeof rendered!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${matched.layer}:${matched.name}:${matched.format}`]}:{overridden:!0,rendered,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${matched.layer}:${matched.name}:${matched.format}`]}}}export{runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride,runServiceOverrideSync};
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]="39e653a0-ace9-5fa4-b27c-4f15e2d44c5d")}catch{}})();import{unicodeSafePrefix}from"../shared/text-normalization.js";import{cloneMutationActor}from"./mutation-actor-snapshot.js";import{cloneCommandOptionsSnapshot,cloneContextSnapshot,cloneGlobalOptionsSnapshot,normalizeCommandName}from"./extension-runtime-helpers.js";import{stableValueEquals}from"../shared/serialization.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const DEFAULT_MUTATION_GUARD_TIMEOUT_MS=5e3;async function executeRegisteredHooks(entries,hookName,context){const warnings=[];for(const entry of entries)try{await entry.run(cloneContextSnapshot(context))}catch{warnings.push(`extension_hook_failed:${entry.layer}:${entry.name}:${hookName}`)}return warnings}async function runBeforeCommandHooks(hooks,context){return executeRegisteredHooks(hooks.beforeCommand,"beforeCommand",context)}function enforceMutationGuardDecision(decision,entry,operation){if(decision===void 0)return;if(typeof decision!="object"||decision===null||!("allow"in decision)||decision.allow!==!0&&decision.allow!==!1)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid decision.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(decision.allow)return;const denial=decision,code=typeof denial.code=="string"?denial.code.trim():"",remediation=typeof denial.remediation=="string"?denial.remediation.trim():"";if(code.length===0||remediation.length===0)throw new PmCliError(`Extension mutation guard ${entry.name} returned an invalid denial.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${entry.layer}:${entry.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});const message=typeof denial.message=="string"?denial.message.trim():"";throw new PmCliError(message||`Extension mutation guard ${entry.name} denied ${operation}.`,EXIT_CODE.CONFLICT,{code,reason:`${entry.layer}:${entry.name}`,nextSteps:[remediation]})}async function runBeforeMutationHooks(hooks,context){for(const entry of hooks.beforeMutation??[]){let decision,timeoutHandle;try{const guardPromise=Promise.resolve().then(()=>entry.run({pm_root:context.pm_root,operation:context.operation,before:context.before===null?null:cloneContextSnapshot(context.before),after:context.after===null?null:cloneContextSnapshot(context.after),changed_fields:[...context.changed_fields],actor:cloneMutationActor(context.actor),dry_run:context.dry_run,sdk:context.sdk}));guardPromise.catch(()=>{}),decision=await Promise.race([guardPromise,new Promise((_,reject)=>{timeoutHandle=setTimeout(()=>{reject(new PmCliError(`Extension mutation guard ${entry.name} timed out before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},DEFAULT_MUTATION_GUARD_TIMEOUT_MS),timeoutHandle.unref?.()})])}catch(error){throw error instanceof PmCliError?error:new PmCliError(`Extension mutation guard ${entry.name} failed before ${context.operation}.`,EXIT_CODE.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${entry.layer}:${entry.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(timeoutHandle)}enforceMutationGuardDecision(decision,entry,context.operation)}}async function runAfterCommandHooks(hooks,context){return executeRegisteredHooks(hooks.afterCommand,"afterCommand",context)}async function runOnWriteHooks(hooks,context){return executeRegisteredHooks(hooks.onWrite,"onWrite",context)}async function runOnReadHooks(hooks,context){return executeRegisteredHooks(hooks.onRead,"onRead",context)}async function runOnIndexHooks(hooks,context){return executeRegisteredHooks(hooks.onIndex,"onIndex",context)}function describeHandlerError(error){let raw="";error instanceof Error&&typeof error.message=="string"?raw=error.message:typeof error=="string"?raw=error:typeof error=="object"&&error!==null&&typeof error.message=="string"&&(raw=error.message);const normalized=raw.replace(/\s+/gu," ").trim();if(normalized.length===0)return"";const maxLength=300;return normalized.length>maxLength?`${unicodeSafePrefix(normalized,maxLength-1)}\u2026`:normalized}function readHandlerStringField(value,field){if(typeof value!="object"||value===null||typeof value[field]!="string")return;const normalized=String(value[field]).replace(/\s+/gu," ").trim();return normalized.length>0?unicodeSafePrefix(normalized,300):void 0}function readHandlerResultExitCode(result){if(typeof result!="object"||result===null||!Object.hasOwn(result,"exit_code"))return;const exitCode=result.exit_code;if(typeof exitCode!="number"||!Number.isInteger(exitCode)||exitCode<1||exitCode>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return exitCode}async function runCommandHandler(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{handled:!1,result:null,warnings:[]};const matched=[...commands.handlers].reverse().find(entry=>entry.command===command);if(!matched)return{handled:!1,result:null,warnings:[]};try{const result=await matched.run({command,args:cloneContextSnapshot(context.args),options:cloneContextSnapshot(context.options),global:cloneContextSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,...context.sdk===void 0?{}:{sdk:context.sdk}});return{handled:!0,result,warnings:[],...Object.fromEntries([["exitCode",readHandlerResultExitCode(result)],["errorCode",readHandlerStringField(result,"code")],["remediation",readHandlerStringField(result,"remediation")]].filter(entry=>entry[1]!==void 0))}}catch(error){const exitCode=typeof error=="object"&&error!==null&&"exitCode"in error?error.exitCode:void 0;if(typeof exitCode=="number"&&Number.isFinite(exitCode))throw error;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${matched.layer}:${matched.name}:${matched.command}`],errorMessage:describeHandlerError(error),...Object.fromEntries([["errorCode",readHandlerStringField(error,"code")],["remediation",readHandlerStringField(error,"remediation")]].filter(entry=>entry[1]!==void 0))},"cause",{value:error,configurable:!0})}}async function runParserOverride(parsers,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};const matched=[...parsers.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]};try{const delta=await Promise.resolve(matched.run({command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel}))??{},nextArgs=Array.isArray(delta.args)?cloneContextSnapshot(delta.args):cloneContextSnapshot(context.args),nextOptions=delta.options?cloneCommandOptionsSnapshot(delta.options):cloneCommandOptionsSnapshot(context.options),nextGlobal=delta.global?cloneGlobalOptionsSnapshot(delta.global):cloneGlobalOptionsSnapshot(context.global);return{overridden:!0,context:{command,args:nextArgs,options:nextOptions,global:nextGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command,args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},warnings:[`extension_parser_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}async function runPreflightOverride(preflight,context){const baseContext={command:normalizeCommandName(context.command),args:cloneContextSnapshot(context.args),options:cloneCommandOptionsSnapshot(context.options),global:cloneGlobalOptionsSnapshot(context.global),pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel},baseDecision=cloneContextSnapshot(context.decision),matched=[...preflight.overrides].reverse().find(entry=>!entry.commands?.length||entry.commands.includes(baseContext.command));if(!matched)return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[]};try{const delta=await Promise.resolve(matched.run({command:baseContext.command,args:cloneContextSnapshot(baseContext.args),options:cloneCommandOptionsSnapshot(baseContext.options),global:cloneGlobalOptionsSnapshot(baseContext.global),pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel,decision:cloneContextSnapshot(baseDecision)}))??{},nextContext={command:baseContext.command,args:Array.isArray(delta.args)?cloneContextSnapshot(delta.args):baseContext.args,options:delta.options?cloneCommandOptionsSnapshot(delta.options):baseContext.options,global:delta.global?cloneGlobalOptionsSnapshot(delta.global):baseContext.global,pm_root:baseContext.pm_root,source_workspace_root:baseContext.source_workspace_root,repo_root:baseContext.repo_root,pm_root_rel:baseContext.pm_root_rel},nextDecision={enforce_item_format_gate:typeof delta.enforce_item_format_gate=="boolean"?delta.enforce_item_format_gate:baseDecision.enforce_item_format_gate,run_preflight_item_format_sync:typeof delta.run_preflight_item_format_sync=="boolean"?delta.run_preflight_item_format_sync:baseDecision.run_preflight_item_format_sync,run_extension_migrations:typeof delta.run_extension_migrations=="boolean"?delta.run_extension_migrations:baseDecision.run_extension_migrations,enforce_mandatory_migration_gate:typeof delta.enforce_mandatory_migration_gate=="boolean"?delta.enforce_mandatory_migration_gate:baseDecision.enforce_mandatory_migration_gate};return{overridden:!0,context:nextContext,decision:nextDecision,warnings:[]}}catch{return{overridden:!1,context:baseContext,decision:baseDecision,warnings:[`extension_preflight_override_failed:${matched.layer}:${matched.name}`]}}}function resolveDefaultServiceResult(context){return{handled:!1,result:context.payload,warnings:[]}}function matchingServiceOverrides(services,service){return[...services.overrides].reverse().filter(entry=>entry.service===service)}function buildServiceOverrideContext(context){return{service:context.service,command:context.command?normalizeCommandName(context.command):void 0,args:context.args?cloneContextSnapshot(context.args):void 0,options:context.options?cloneCommandOptionsSnapshot(context.options):void 0,global:context.global?cloneGlobalOptionsSnapshot(context.global):void 0,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,payload:cloneContextSnapshot(context.payload)}}function isServiceOverrideDecision(value){if(typeof value!="object"||value===null||!Object.hasOwn(value,"handled"))return!1;const handled=value.handled;return handled===!0?Object.hasOwn(value,"result"):handled===!1&&Reflect.ownKeys(value).length===1}function resolveServiceOverrideValue(result,context){return isServiceOverrideDecision(result)?result.handled?{handled:!0,result:result.result}:{handled:!1,result:context.payload}:context.service==="output_format"&&result==null?{handled:!1,result:context.payload}:{handled:!0,result}}function isLegacyOutputPayloadEcho(result,context,serviceContext){return context.service==="output_format"&&typeof result=="object"&&result!==null&&stableValueEquals(result,serviceContext.payload)}function resolveMatchedServiceDecision(matched,decision,warnings){if(decision.handled){if(matched.passThrough===!0){warnings.push(`extension_service_pass_through_contract_violated:${matched.layer}:${matched.name}:${matched.service}`);return}return{handled:!0,result:decision.result,warnings}}}function runServiceOverrideSync(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=matched.run(serviceContext);if(result instanceof Promise){warnings.push(`extension_service_override_async_unsupported:${matched.layer}:${matched.name}:${matched.service}`);continue}if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}async function runServiceOverride(services,context){const matches=matchingServiceOverrides(services,context.service);if(matches.length===0)return resolveDefaultServiceResult(context);const warnings=[];for(const matched of matches)try{const serviceContext=buildServiceOverrideContext(context),result=await Promise.resolve(matched.run(serviceContext));if(isLegacyOutputPayloadEcho(result,context,serviceContext)){warnings.push(`extension_output_format_payload_echo_deprecated:${matched.layer}:${matched.name}`);continue}const resolved=resolveMatchedServiceDecision(matched,resolveServiceOverrideValue(result,context),warnings);if(resolved)return resolved}catch{warnings.push(`extension_service_override_failed:${matched.layer}:${matched.name}:${matched.service}`)}return{handled:!1,result:context.payload,warnings}}function runCommandOverride(commands,context){const command=normalizeCommandName(context.command);if(command.length===0)return{overridden:!1,result:context.result,warnings:[]};const matched=[...commands.overrides].reverse().find(entry=>entry.command===command);if(!matched)return{overridden:!1,result:context.result,warnings:[]};try{const overrideOptions=cloneCommandOptionsSnapshot(context.options),overrideGlobal=cloneGlobalOptionsSnapshot(context.global),overrideResult=matched.run({command,args:cloneContextSnapshot(context.args),options:overrideOptions,global:overrideGlobal,pm_root:context.pm_root,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return overrideResult instanceof Promise?{overridden:!1,result:context.result,warnings:[`extension_command_override_async_unsupported:${matched.layer}:${matched.name}:${matched.command}`]}:{overridden:!0,result:overrideResult,warnings:[]}}catch{return{overridden:!1,result:context.result,warnings:[`extension_command_override_failed:${matched.layer}:${matched.name}:${matched.command}`]}}}function rendererOwnsContext(entry,command,result){if((entry.commands?.length??0)>0&&!entry.commands?.includes(command))return!1;if(entry.resultDiscriminator===void 0)return!0;try{return entry.resultDiscriminator(cloneContextSnapshot(result))}catch{return!1}}function runRendererOverride(renderers,context){const rendererCommand=typeof context.command=="string"?normalizeCommandName(context.command):"",matched=[...renderers.overrides].reverse().find(entry=>entry.format===context.format&&rendererOwnsContext(entry,rendererCommand,context.result));if(!matched)return{overridden:!1,rendered:null,warnings:[]};try{const rendererArgs=Array.isArray(context.args)?cloneContextSnapshot(context.args):[],rendererOptions=cloneCommandOptionsSnapshot(context.options),rendererGlobal=cloneGlobalOptionsSnapshot(context.global),rendererPmRoot=typeof context.pm_root=="string"?context.pm_root:"",rendered=matched.run({format:context.format,command:rendererCommand,args:rendererArgs,options:rendererOptions,global:rendererGlobal,pm_root:rendererPmRoot,source_workspace_root:context.source_workspace_root,repo_root:context.repo_root,pm_root_rel:context.pm_root_rel,result:cloneContextSnapshot(context.result)});return rendered==null?{overridden:!1,rendered:null,warnings:[]}:typeof rendered!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${matched.layer}:${matched.name}:${matched.format}`]}:{overridden:!0,rendered,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${matched.layer}:${matched.name}:${matched.format}`]}}}export{runAfterCommandHooks,runBeforeCommandHooks,runBeforeMutationHooks,runCommandHandler,runCommandOverride,runOnIndexHooks,runOnReadHooks,runOnWriteHooks,runParserOverride,runPreflightOverride,runRendererOverride,runServiceOverride,runServiceOverrideSync};
2
2
  //# sourceMappingURL=extension-hook-runtime.js.map
@@ -346,6 +346,32 @@ export interface ExtensionMutationGuardSdk{
346
346
  get(id:string):Promise<{item:ItemMetadata;body:string;}|null>;
347
347
  /** List item metadata from the guard's host-bound tracker. */
348
348
  list():Promise<ItemMetadata[]>;}
349
+ /** Detected agent provenance a mutation records with its history entry, when an agent harness was resolved. */
350
+ export interface MutationActorAgent{
351
+ /** Normalized harness namespace, for example `claude-code`. */
352
+ harness?:string;
353
+ /** Model identifier observed from a bounded runtime signal. */
354
+ model?:string;
355
+ /** Signal class that supplied `model`. */
356
+ model_source?:string;
357
+ /** Privacy-safe fingerprint of the current harness invocation. */
358
+ instance?:string;}
359
+ /**
360
+ * The identity a mutation is performed as (GH-1719). The host resolves it from
361
+ * the same author and identity state that the mutation's history entry records,
362
+ * so a guard judges exactly the identity that will be written. It is never a
363
+ * placeholder: an unattributed mutation reports `author: "unknown"` with
364
+ * `author_source: "unknown"`.
365
+ */
366
+ export interface MutationActor{
367
+ /** Author written to the mutation's history entry. */
368
+ author:string;
369
+ /** How the author was selected: asserted (explicit), configured, detected (harness) or unknown. */
370
+ author_source:"asserted"|"configured"|"detected"|"unknown";
371
+ /** Ownership principal compared with an item's `claim_principal` (or `assignee`) by the ownership check. */
372
+ principal:string;
373
+ /** Agent provenance recorded with the history entry; absent when no harness was resolved. */
374
+ agent?:MutationActorAgent;}
349
375
  /** Proposed item transition supplied before either the item or history artifact is persisted. */
350
376
  export interface BeforeMutationHookContext{
351
377
  /** Tracker root owning the transaction. */
@@ -358,6 +384,10 @@ before:ItemDocument|null;
358
384
  after:ItemDocument|null;
359
385
  /** Canonical fields the transaction proposes to change. */
360
386
  changed_fields:readonly string[];
387
+ /** Read-only identity the mutation is performed as; identical in a preview and the write it previews. */
388
+ actor:Readonly<MutationActor>;
389
+ /** True when the host evaluates the guard for a preview or dry run that persists nothing. */
390
+ dry_run:boolean;
361
391
  /** Host-bound read-only SDK services. */
362
392
  sdk:ExtensionMutationGuardSdk;}
363
393
  /** Stable decision returned by a transactional extension mutation guard. */
@@ -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]="937c31e4-62a2-5815-8c7b-3640688b43b9")}catch{}})();const KNOWN_EXTENSION_CAPABILITIES=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],EXTENSION_CAPABILITY_CONTRACT_VERSION=2,EXTENSION_CAPABILITY_LEGACY_ALIASES=Object.freeze({migration:"schema",validation:"schema"}),EXTENSION_CAPABILITY_CONTRACT=Object.freeze({version:2,capabilities:[...KNOWN_EXTENSION_CAPABILITIES],legacy_aliases:{...EXTENSION_CAPABILITY_LEGACY_ALIASES}}),KNOWN_EXTENSION_POLICY_MODES=["off","warn","enforce"],KNOWN_EXTENSION_TRUST_MODES=["off","warn","enforce"],KNOWN_EXTENSION_SANDBOX_PROFILES=["none","restricted","strict"],KNOWN_PM_MAX_VERSION_EXCEEDED_MODES=["block","warn"],KNOWN_EXTENSION_POLICY_SURFACES=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"],KNOWN_EXTENSION_SERVICE_NAMES=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function createDefaultExtensionGovernancePolicy(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}export{EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,KNOWN_EXTENSION_CAPABILITIES,KNOWN_EXTENSION_POLICY_MODES,KNOWN_EXTENSION_POLICY_SURFACES,KNOWN_EXTENSION_SANDBOX_PROFILES,KNOWN_EXTENSION_SERVICE_NAMES,KNOWN_EXTENSION_TRUST_MODES,KNOWN_PM_MAX_VERSION_EXCEEDED_MODES,createDefaultExtensionGovernancePolicy};
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]="1a939ceb-fa6a-5a95-a82a-e09c8e5cf5d7")}catch{}})();const KNOWN_EXTENSION_CAPABILITIES=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],EXTENSION_CAPABILITY_CONTRACT_VERSION=2,EXTENSION_CAPABILITY_LEGACY_ALIASES=Object.freeze({migration:"schema",validation:"schema"}),EXTENSION_CAPABILITY_CONTRACT=Object.freeze({version:2,capabilities:[...KNOWN_EXTENSION_CAPABILITIES],legacy_aliases:{...EXTENSION_CAPABILITY_LEGACY_ALIASES}}),KNOWN_EXTENSION_POLICY_MODES=["off","warn","enforce"],KNOWN_EXTENSION_TRUST_MODES=["off","warn","enforce"],KNOWN_EXTENSION_SANDBOX_PROFILES=["none","restricted","strict"],KNOWN_PM_MAX_VERSION_EXCEEDED_MODES=["block","warn"],KNOWN_EXTENSION_POLICY_SURFACES=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore","services.assuranceprovider"],KNOWN_EXTENSION_SERVICE_NAMES=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function createDefaultExtensionGovernancePolicy(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",allowed_extensions:[],blocked_extensions:[],allowed_capabilities:[],blocked_capabilities:[],allowed_surfaces:[],blocked_surfaces:[],allowed_commands:[],blocked_commands:[],allowed_actions:[],blocked_actions:[],allowed_services:[],blocked_services:[],extension_overrides:[]}}export{EXTENSION_CAPABILITY_CONTRACT,EXTENSION_CAPABILITY_CONTRACT_VERSION,EXTENSION_CAPABILITY_LEGACY_ALIASES,KNOWN_EXTENSION_CAPABILITIES,KNOWN_EXTENSION_POLICY_MODES,KNOWN_EXTENSION_POLICY_SURFACES,KNOWN_EXTENSION_SANDBOX_PROFILES,KNOWN_EXTENSION_SERVICE_NAMES,KNOWN_EXTENSION_TRUST_MODES,KNOWN_PM_MAX_VERSION_EXCEEDED_MODES,createDefaultExtensionGovernancePolicy};
2
2
  //# sourceMappingURL=extension-types.js.map
@@ -58,8 +58,28 @@ export declare function consumeAfterCommandAffectedItems():AfterCommandAffectedI
58
58
  export declare function clearActiveExtensionHooks():void;
59
59
  /** Implements run active on write hooks for the public runtime surface of this module. */
60
60
  export declare function runActiveOnWriteHooks(context:OnWriteHookContext):Promise<string[]>;
61
+ /**
62
+ * What a mutation site supplies to the transactional guards. The host resolves
63
+ * the guard-facing actor from `author`, the same value the mutation's history
64
+ * entry records, so no caller can hand a guard a different identity (GH-1719).
65
+ */
66
+ export type BeforeMutationHookInput=Omit<BeforeMutationHookContext,"actor"|"dry_run">&{
67
+ /** Author the mutation is attributed to in history. */
68
+ author:string;
69
+ /** True when the evaluation previews a write that persists nothing. */
70
+ dry_run?:boolean;};
71
+ /**
72
+ * Run a staged preview with the caller's transactional mutation guards active
73
+ * as dry-run guards (GH-1719). A staged preview executes in an extension-free
74
+ * runtime, so without this no guard could judge it; inside `run`, only the
75
+ * guards of `hooks` are evaluated, each with `dry_run: true`, and every other
76
+ * hook kind stays suppressed.
77
+ */
78
+ export declare function runWithPreviewMutationGuards<T>(hooks:ExtensionHookRegistry|null,run:()=> Promise<T>):Promise<T>;
79
+ /** Return the hook registry active for the current request, or null when none is active. */
80
+ export declare function getActiveExtensionHooks():ExtensionHookRegistry|null;
61
81
  /** Run active transactional mutation guards before any item or history write. */
62
- export declare function runActiveBeforeMutationHooks(context:BeforeMutationHookContext):Promise<void>;
82
+ export declare function runActiveBeforeMutationHooks(input:BeforeMutationHookInput):Promise<void>;
63
83
  /** Implements run active on read hooks for the public runtime surface of this module. */
64
84
  export declare function runActiveOnReadHooks(context:OnReadHookContext):Promise<string[]>;
65
85
  /** Synchronous fast-path predicate: true only when at least one onRead hook is registered. Bulk readers (e.g. the metadata cache scanning hundreds of files) use this to skip per-file `await runActiveOnReadHooks(...)` calls entirely when no extension observes reads, avoiding hundreds of needless microtasks. */
@@ -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]="7c2e7a35-cbf9-5bb6-abfd-f1ae75c6afc2")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}async function runActiveBeforeMutationHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;hooks&&await runBeforeMutationHooks(hooks,context)}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionRegistrations,hasActiveOnReadHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
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]="4829d26d-26fb-56b2-9dd7-58a170e1e71e")}catch{}})();import{existsSync}from"node:fs";import{AsyncLocalStorage}from"node:async_hooks";import path from"node:path";import{runCommandHandler,runBeforeMutationHooks,runCommandOverride,runOnIndexHooks,runParserOverride,runPreflightOverride,runOnReadHooks,runRendererOverride,runServiceOverride,runServiceOverrideSync,runOnWriteHooks}from"./loader.js";let activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult,activeAfterCommandAffectedItems=[];const isolatedExtensionRuntime=new AsyncLocalStorage;function runtimeState(){return isolatedExtensionRuntime.getStore()}function runWithIsolatedExtensionRuntime(run){return isolatedExtensionRuntime.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},run)}const AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function findSourceRepositoryRoot(candidate){let cursor=path.resolve(candidate);for(;;){if(existsSync(path.join(cursor,".git")))return cursor;const parent=path.dirname(cursor);if(parent===cursor)return;cursor=parent}}function resolvePortableWorkspaceContext(pmRoot){const sourceCandidate=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),sourceWorkspaceRoot=findSourceRepositoryRoot(sourceCandidate)??path.resolve(sourceCandidate),repoRoot=findSourceRepositoryRoot(sourceWorkspaceRoot);if(!pmRoot)return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{}};const relativePmRoot=path.relative(sourceWorkspaceRoot,path.resolve(pmRoot)),contained=relativePmRoot.length>0&&!relativePmRoot.startsWith(`..${path.sep}`)&&relativePmRoot!==".."&&!path.isAbsolute(relativePmRoot);return{source_workspace_root:sourceWorkspaceRoot,...repoRoot?{repo_root:repoRoot}:{},...contained?{pm_root_rel:relativePmRoot.split(path.sep).join("/")}:{}}}function setActiveExtensionHooks(hooks){const state=runtimeState();if(state){state.hooks=hooks;return}activeExtensionHooks=hooks}function setActiveExtensionCommands(commands){const state=runtimeState();if(state){state.commands=commands;return}activeExtensionCommands=commands}function setActiveExtensionParsers(parsers){const state=runtimeState();if(state){state.parsers=parsers;return}activeExtensionParsers=parsers}function setActiveExtensionPreflight(preflight){const state=runtimeState();if(state){state.preflight=preflight;return}activeExtensionPreflight=preflight}function setActiveExtensionServices(services){const state=runtimeState();if(state){state.services=services;return}activeExtensionServices=services}function setActiveExtensionRenderers(renderers){const state=runtimeState();if(state){state.renderers=renderers;return}activeExtensionRenderers=renderers}function setActiveExtensionRegistrations(registrations){const state=runtimeState();if(state){state.registrations=registrations;return}activeExtensionRegistrations=registrations}function getActiveExtensionRegistrations(){const state=runtimeState();return state?state.registrations:activeExtensionRegistrations}function resetActiveExtensionRuntimeState(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=null,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=null}function setActiveCommandContext(context){const resolved=context?{...context,...resolvePortableWorkspaceContext(context.pm_root)}:null,state=runtimeState();if(state){state.commandContext=resolved;return}activeCommandContext=resolved}function getActiveCommandContext(){const state=runtimeState(),context=state?state.commandContext:activeCommandContext;return context?{...context,args:[...context.args],options:context.options?{...context.options}:{},global:context.global?{...context.global}:void 0}:null}function isActiveCommandUnextended(command){const state=runtimeState()??{commandContext:activeCommandContext,hooks:activeExtensionHooks,commands:activeExtensionCommands,parsers:activeExtensionParsers,preflight:activeExtensionPreflight,services:activeExtensionServices,renderers:activeExtensionRenderers,registrations:activeExtensionRegistrations};return state.commandContext?.command!==command||[state.hooks,state.preflight,state.services,state.renderers].some(registry=>Object.values(registry??{}).some(entries=>entries.length>0))||[state.commands,state.parsers].some(registry=>Object.values(registry??{}).some(entries=>entries.some(entry=>entry.command===command)))?!1:!Object.entries(state.registrations??{}).some(([key,entries])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(key)&&entries.length>0)}function setActiveCommandResult(result){const state=runtimeState();if(state){state.commandResult=result;return}activeCommandResult=result}function getActiveCommandResult(){const state=runtimeState();return state?state.commandResult:activeCommandResult}function recordAfterCommandAffectedItem(item){if(!item)return;const state=runtimeState();state?state.affectedItems.push(item):activeAfterCommandAffectedItems.push(item)}function projectAfterCommandItemSnapshot(metadata,changedFields){if(!metadata||!metadata.id)return{};const snapshot={id:metadata.id,type:metadata.type,status:metadata.status};if(!Array.isArray(changedFields))return snapshot;const source=metadata;for(const field of changedFields){if(typeof field!="string")continue;const actualField=field.startsWith("unset:")?field.slice(6):field;actualField==="id"||actualField==="type"||actualField==="status"||AFTER_COMMAND_SNAPSHOT_OMITTED_FIELDS.has(actualField)||Object.hasOwn(source,actualField)&&source[actualField]!==void 0&&(snapshot[actualField]=source[actualField])}return snapshot}function consumeAfterCommandAffectedItems(){const state=runtimeState(),affectedItems=state?.affectedItems??activeAfterCommandAffectedItems;if(affectedItems.length===0)return;const affected=affectedItems;return state?state.affectedItems=[]:activeAfterCommandAffectedItems=[],affected}function clearActiveExtensionHooks(){const state=runtimeState();if(state){state.hooks=null,state.commands=null,state.parsers=null,state.preflight=null,state.services=null,state.renderers=null,state.registrations=null,state.commandContext=null,state.commandResult=void 0,state.affectedItems=[];return}activeExtensionHooks=null,activeExtensionCommands=null,activeExtensionParsers=null,activeExtensionPreflight=null,activeExtensionServices=null,activeExtensionRenderers=null,activeExtensionRegistrations=null,activeCommandContext=null,activeCommandResult=void 0,activeAfterCommandAffectedItems=[]}async function runActiveOnWriteHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnWriteHooks(hooks,context):[]}const previewMutationGuards=new AsyncLocalStorage;function runWithPreviewMutationGuards(hooks,run){return!hooks||(hooks.beforeMutation?.length??0)===0?run():previewMutationGuards.run(hooks,run)}function getActiveExtensionHooks(){const state=runtimeState();return state?state.hooks:activeExtensionHooks}async function runActiveBeforeMutationHooks(input){const preview=previewMutationGuards.getStore(),hooks=preview??getActiveExtensionHooks();if(!hooks)return;const{resolveMutationActor}=await import("./mutation-actor.js"),{author,dry_run:dryRun,...context}=input;await runBeforeMutationHooks(hooks,{...context,actor:resolveMutationActor(author),dry_run:preview!==void 0||dryRun===!0})}async function runActiveOnReadHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnReadHooks(hooks,context):[]}function hasActiveOnReadHooks(){const state=runtimeState();return((state?state.hooks:activeExtensionHooks)?.onRead?.length??0)>0}async function runActiveOnIndexHooks(context){const state=runtimeState(),hooks=state?state.hooks:activeExtensionHooks;return hooks?runOnIndexHooks(hooks,context):[]}function runActiveCommandOverride(result){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands,commandContext=state?state.commandContext:activeCommandContext;return!commands||!commandContext?{overridden:!1,result,warnings:[]}:runCommandOverride(commands,{command:commandContext.command,args:[...commandContext.args],options:commandContext.options?{...commandContext.options}:{},global:commandContext.global?{...commandContext.global}:void 0,pm_root:commandContext.pm_root,source_workspace_root:commandContext.source_workspace_root,repo_root:commandContext.repo_root,pm_root_rel:commandContext.pm_root_rel,result})}async function runActiveCommandHandler(context){const state=runtimeState(),commands=state?state.commands:activeExtensionCommands;return commands?runCommandHandler(commands,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{handled:!1,result:null,warnings:[]}}async function runActiveParserOverride(context){const state=runtimeState(),parsers=state?state.parsers:activeExtensionParsers;return parsers?runParserOverride(parsers,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},warnings:[]}}async function runActivePreflightOverride(context){const state=runtimeState(),preflight=state?state.preflight:activeExtensionPreflight;return preflight?runPreflightOverride(preflight,{...context,...resolvePortableWorkspaceContext(context.pm_root)}):{overridden:!1,context:{command:context.command,args:[...context.args],options:{...context.options},global:{...context.global},pm_root:context.pm_root},decision:{...context.decision},warnings:[]}}function runActiveRendererOverride(format,result){const state=runtimeState(),renderers=state?state.renderers:activeExtensionRenderers,commandContext=state?state.commandContext:activeCommandContext;return renderers?runRendererOverride(renderers,{format,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,result}):{overridden:!1,rendered:null,warnings:[]}}function buildServiceContext(service,payload){const state=runtimeState(),commandContext=state?state.commandContext:activeCommandContext;return{service,command:commandContext?.command,args:commandContext?[...commandContext.args]:[],options:commandContext?.options?{...commandContext.options}:{},global:commandContext?.global?{...commandContext.global}:void 0,pm_root:commandContext?.pm_root,source_workspace_root:commandContext?.source_workspace_root,repo_root:commandContext?.repo_root,pm_root_rel:commandContext?.pm_root_rel,payload}}async function runActiveServiceOverride(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverride(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}function runActiveServiceOverrideSync(service,payload){const state=runtimeState(),services=state?state.services:activeExtensionServices;return services?runServiceOverrideSync(services,buildServiceContext(service,payload)):{handled:!1,result:payload,warnings:[]}}export*from"./loader.js";export*from"./command-hook-context.js";import{createSerialQueue}from"../shared/serial-queue.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"./capability-usage.js";export{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,clearActiveExtensionHooks,collectUsedExtensionCapabilities,consumeAfterCommandAffectedItems,createSerialQueue,getActiveCommandContext,getActiveCommandResult,getActiveExtensionHooks,getActiveExtensionRegistrations,hasActiveOnReadHooks,isActiveCommandUnextended,projectAfterCommandItemSnapshot,reconcileExtensionCapabilityUsage,recordAfterCommandAffectedItem,resetActiveExtensionRuntimeState,resolvePortableWorkspaceContext,runActiveBeforeMutationHooks,runActiveCommandHandler,runActiveCommandOverride,runActiveOnIndexHooks,runActiveOnReadHooks,runActiveOnWriteHooks,runActiveParserOverride,runActivePreflightOverride,runActiveRendererOverride,runActiveServiceOverride,runActiveServiceOverrideSync,runWithIsolatedExtensionRuntime,runWithPreviewMutationGuards,setActiveCommandContext,setActiveCommandResult,setActiveExtensionCommands,setActiveExtensionHooks,setActiveExtensionParsers,setActiveExtensionPreflight,setActiveExtensionRegistrations,setActiveExtensionRenderers,setActiveExtensionServices};
2
2
  //# sourceMappingURL=index.js.map
@@ -0,0 +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]="f1f31504-c958-5bb1-a3b9-5339a09ad876")}catch{}})();function cloneMutationActor(actor){return Object.freeze({author:actor.author,author_source:actor.author_source,principal:actor.principal,...actor.agent===void 0?{}:{agent:Object.freeze({...actor.agent})}})}export{cloneMutationActor};
2
+ //# sourceMappingURL=mutation-actor-snapshot.js.map
@@ -0,0 +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]="44d57a71-ac49-5db8-b461-ce985801bb3c")}catch{}})();import{resolveClaimPrincipal,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";function resolveMutationActor(author){const identity=resolveHistoryAgentIdentity(author),agent={...identity.harness===void 0?{}:{harness:identity.harness},...identity.model===void 0?{}:{model:identity.model},...identity.model_source===void 0?{}:{model_source:identity.model_source},...identity.instance===void 0?{}:{instance:identity.instance}};return Object.freeze({author,author_source:resolveHistoryAuthorSource(author),principal:resolveClaimPrincipal(author),...Object.keys(agent).length===0?{}:{agent:Object.freeze(agent)}})}export{resolveMutationActor};
2
+ //# sourceMappingURL=mutation-actor.js.map
@@ -0,0 +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]="b24a4ce2-c356-56ee-8a34-f48a78507ac4")}catch{}})();const DEFERRABLE_ITEM_FIELDS=[{field:"acceptance_criteria",option:"acceptanceCriteria",flag:"--acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","acceptancecriteria","ac"]},{field:"assignee",option:"assignee",flag:"--assignee",aliases:["assignee"]},{field:"deadline",option:"deadline",flag:"--deadline",aliases:["deadline"]},{field:"estimated_minutes",option:"estimatedMinutes",flag:"--estimate",aliases:["estimated_minutes","estimated-minutes","estimatedminutes","estimate"]}],DEFERRABLE_BY_FIELD=new Map(DEFERRABLE_ITEM_FIELDS.map(entry=>[entry.field,entry])),DEFERRABLE_BY_ALIAS=new Map(DEFERRABLE_ITEM_FIELDS.flatMap(entry=>entry.aliases.map(alias=>[alias,entry])));function resolveDeferrableItemField(input){return DEFERRABLE_BY_ALIAS.get(input.trim().toLowerCase())}function deferrableItemFieldByKey(field){return DEFERRABLE_BY_FIELD.get(field)}function hasConcreteItemFieldValue(metadata,field){const value=metadata[field];return typeof value=="string"?value.trim().length>0:typeof value=="number"?Number.isFinite(value):value!=null}function outstandingDeferredFields(metadata){return(metadata.deferred_fields??[]).filter(entry=>!hasConcreteItemFieldValue(metadata,entry.field))}function pruneResolvedDeferredFields(metadata){const entries=metadata.deferred_fields;if(entries===void 0||entries.length===0)return!1;const outstanding=outstandingDeferredFields(metadata);return outstanding.length===entries.length?!1:(outstanding.length===0?delete metadata.deferred_fields:metadata.deferred_fields=outstanding,!0)}function describeInvalidDeferredFields(value){if(value===void 0)return;if(!Array.isArray(value))return"deferred_fields must be an array";const seen=new Set;for(const[index,entry]of value.entries()){if(typeof entry!="object"||entry===null||Array.isArray(entry))return`deferred_fields[${index}] must be an object`;const{field,reason}=entry;if(typeof field!="string"||!DEFERRABLE_BY_FIELD.has(field))return`deferred_fields[${index}].field must be one of ${DEFERRABLE_ITEM_FIELDS.map(item=>item.field).join(", ")}`;if(typeof reason!="string"||reason.trim().length===0)return`deferred_fields[${index}].reason must be a non-empty string`;if(seen.has(field))return`deferred_fields lists ${field} more than once`;seen.add(field)}}function normalizeDeferredFields(values){if(!(values===void 0||values.length===0))return values.map(entry=>({field:entry.field,reason:entry.reason.trim()})).sort((left,right)=>left.field.localeCompare(right.field))}export{DEFERRABLE_ITEM_FIELDS,deferrableItemFieldByKey,describeInvalidDeferredFields,hasConcreteItemFieldValue,normalizeDeferredFields,outstandingDeferredFields,pruneResolvedDeferredFields,resolveDeferrableItemField};
2
+ //# sourceMappingURL=deferred-fields.js.map
@@ -20,14 +20,15 @@ import type{ItemMetadata}from "../../types/index.js";
20
20
  export declare const BASELINE_ITEM_FORMAT_VERSION=1;
21
21
  /**
22
22
  * Highest item format understood by this runtime. Ordinary records retain the
23
- * implicit baseline; linked-test editor stamps require format 2 and linked-test
24
- * setup entries (GH-1671) require format 3, so earlier published hosts refuse
25
- * before dropping fields from their canonical hashes. Reading legacy records
26
- * never changes their format or immutable commitments.
23
+ * implicit baseline; linked-test editor stamps require format 2, linked-test
24
+ * setup entries (GH-1671) require format 3 and deferred strict-required fields
25
+ * (GH-1713) require format 4, so earlier published hosts refuse before dropping
26
+ * fields from their canonical hashes. Reading legacy records never changes
27
+ * their format or immutable commitments.
27
28
  */
28
- export declare const CURRENT_ITEM_FORMAT_VERSION=3;
29
- /** Resolve the minimum format needed to retain persisted linked-test editor metadata and setup phases. */
30
- export declare function requiredItemFormatVersion(metadata:Pick<ItemMetadata,"tests"|"pm_format_version">):number;
29
+ export declare const CURRENT_ITEM_FORMAT_VERSION=4;
30
+ /** Resolve the minimum format needed to retain persisted linked-test editor metadata, setup phases and field deferrals. */
31
+ export declare function requiredItemFormatVersion(metadata:Pick<ItemMetadata,"tests"|"pm_format_version"|"deferred_fields">):number;
31
32
  /**
32
33
  * Resolve the format version an item is effectively stored at. A present,
33
34
  * positive-integer `pm_format_version` is taken verbatim (including versions
@@ -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]="0ec3052f-5466-5db8-8f59-04095adcb6f0")}catch{}})();const BASELINE_ITEM_FORMAT_VERSION=1,CURRENT_ITEM_FORMAT_VERSION=3;function requiredItemFormatVersion(metadata){const tests=metadata.tests??[],linkedTestFormat=tests.some(test=>test.phase==="setup")?3:tests.some(test=>test.updated_by!==void 0||test.updated_at!==void 0)?2:1;return Math.max(effectiveItemFormatVersion(metadata),linkedTestFormat)}function effectiveItemFormatVersion(metadata){const raw=metadata.pm_format_version;return typeof raw=="number"&&Number.isInteger(raw)&&raw>=1?raw:1}function normalizeItemFormatVersion(value){if(!(typeof value!="number"||!Number.isInteger(value)||value<=1))return value}function classifyItemFormatVersion(version,current=3,minimum=current){return version<minimum?"outdated":version>current?"ahead":"current"}function scanItemFormatVersions(entries,current=3,minimum=current){const outdated=[],ahead=[];for(const entry of entries){const status=classifyItemFormatVersion(entry.version,current,minimum);status==="outdated"?outdated.push(entry.ref):status==="ahead"&&ahead.push(entry.ref)}return{outdated:outdated.sort((left,right)=>left.localeCompare(right)),ahead:ahead.sort((left,right)=>left.localeCompare(right))}}export{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,requiredItemFormatVersion,scanItemFormatVersions};
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]="ec8ac553-25db-5fb1-bf2f-555815d7b283")}catch{}})();const BASELINE_ITEM_FORMAT_VERSION=1,CURRENT_ITEM_FORMAT_VERSION=4;function requiredItemFormatVersion(metadata){const tests=metadata.tests??[],linkedTestFormat=tests.some(test=>test.phase==="setup")?3:tests.some(test=>test.updated_by!==void 0||test.updated_at!==void 0)?2:1,deferralFormat=(metadata.deferred_fields?.length??0)>0?4:1;return Math.max(effectiveItemFormatVersion(metadata),linkedTestFormat,deferralFormat)}function effectiveItemFormatVersion(metadata){const raw=metadata.pm_format_version;return typeof raw=="number"&&Number.isInteger(raw)&&raw>=1?raw:1}function normalizeItemFormatVersion(value){if(!(typeof value!="number"||!Number.isInteger(value)||value<=1))return value}function classifyItemFormatVersion(version,current=4,minimum=current){return version<minimum?"outdated":version>current?"ahead":"current"}function scanItemFormatVersions(entries,current=4,minimum=current){const outdated=[],ahead=[];for(const entry of entries){const status=classifyItemFormatVersion(entry.version,current,minimum);status==="outdated"?outdated.push(entry.ref):status==="ahead"&&ahead.push(entry.ref)}return{outdated:outdated.sort((left,right)=>left.localeCompare(right)),ahead:ahead.sort((left,right)=>left.localeCompare(right))}}export{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,requiredItemFormatVersion,scanItemFormatVersions};
2
2
  //# sourceMappingURL=item-format-version.js.map
@@ -1,5 +1,5 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d3b37ee1-8cff-5785-a63a-1434b88ac54f")}catch{}})();import{encode as encodeToon}from"@toon-format/toon";import{isDeepStrictEqual}from"node:util";import{CONFIDENCE_TEXT_VALUES,ISSUE_SEVERITY_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,STATUS_VALUES,weekdayOrderIndex}from"../../types/index.js";import{coerceRuntimeFieldValue}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,effectiveItemFormatVersion,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isRfc3339DateTime,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto","none"]),LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]),LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]),PLAN_STEP_STATUS_SET=new Set(PLAN_STEP_STATUS_VALUES);function normalizePathValue(value){return value.replaceAll("\\","/")}function firstNonZeroComparison(comparisons){for(const comparison of comparisons)if(comparison!==0)return comparison;return 0}function deleteUndefinedFields(record){for(const[key,value]of Object.entries(record))value===void 0&&delete record[key]}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"],STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(options?.schema)return{statusRegistry:resolveRuntimeStatusRegistry(options.schema),fieldRegistry:resolveRuntimeFieldRegistry(options.schema),unknownFieldPolicy:options.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(options.extensionFieldNames??[]),onWarning:options.onWarning}}function runtimeFieldRequiredForType(definition,typeName){return definition.required?definition.required_types.length===0?!0:definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase()):!1}function validationError(message){const field=message.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new PmCliError(`Invalid item metadata: ${message}`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:message.includes("required")?"missing_required_field":"schema_validation_error",...field?{field}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:message})}function documentSyntaxError(format,message){throw new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format,required:`Provide a syntactically valid ${format==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function assertSupportedItemFormat(metadata,required){if(!required||typeof metadata!="object"||metadata===null)return;const formatVersion=effectiveItemFormatVersion(metadata);if(!(formatVersion<=CURRENT_ITEM_FORMAT_VERSION))throw new PmCliError(`Stored item uses format version ${formatVersion}; this runtime supports up to ${CURRENT_ITEM_FORMAT_VERSION}. Upgrade pm before reading or changing this item.`,EXIT_CODE.CONFLICT,{code:"item_format_version_unsupported",format_version:formatVersion,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function buildKnownItemMetadataKeys(runtimeContext){const knownKeys=new Set(STATIC_ITEM_METADATA_FIELD_SET);for(const definition of runtimeContext.fieldRegistry?.definitions??[])knownKeys.add(definition.metadata_key);for(const fieldName of runtimeContext.extensionFieldNames)knownKeys.add(fieldName);return knownKeys}function assertItemMetadataCondition(condition,message){condition||validationError(message)}function requireItemMetadataRecord(value,message){return(typeof value!="object"||value===null||Array.isArray(value))&&validationError(message),value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue=="string",`${fieldName} must be a string`),assertItemMetadataCondition(isTimestampLiteral(rawValue),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&(assertItemMetadataCondition(typeof value=="string",`${messagePrefix} must be a string`),assertItemMetadataCondition(isTimestampLiteral(value),`${messagePrefix} must be a valid ISO timestamp`))}function assertRecurrenceWeekdays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_weekday must be an array");for(const weekday of value){assertItemMetadataCondition(typeof weekday=="string","event.recurrence.by_weekday entries must be strings");const normalizedWeekday=weekday.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday),`event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`)}}}function assertRecurrenceMonthDays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_month_day must be an array");for(const day of value)assertItemMetadataCondition(typeof day=="number"&&Number.isInteger(day)&&day>=1&&day<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function assertRecurrenceExdates(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.exdates must be an array");for(const exdate of value)assertItemMetadataCondition(typeof exdate=="string","event.recurrence.exdates entries must be strings"),assertItemMetadataCondition(isTimestampLiteral(exdate),"event.recurrence.exdates entries must be valid ISO timestamps")}}function assertValidRecurrenceRule(recurrence){const recurrenceRecord=requireItemMetadataRecord(recurrence,"event.recurrence must be an object");assertItemMetadataCondition(typeof recurrenceRecord.freq=="string","event.recurrence.freq must be a string");const frequency=recurrenceRecord.freq.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency),`event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`),assertPositiveIntegerField(recurrenceRecord,"interval","event.recurrence.interval"),assertPositiveIntegerField(recurrenceRecord,"count","event.recurrence.count"),assertOptionalTimestampString(recurrenceRecord,"until","event.recurrence.until"),assertRecurrenceWeekdays(recurrenceRecord.by_weekday),assertRecurrenceMonthDays(recurrenceRecord.by_month_day),assertRecurrenceExdates(recurrenceRecord.exdates)}function assertRequiredItemMetadataFields(record){for(const fieldName of REQUIRED_STRING_FIELDS)assertItemMetadataCondition(typeof record[fieldName]=="string",`${fieldName} is required and must be a string`);const itemType=record.type;assertItemMetadataCondition(typeof itemType=="string"&&itemType.trim().length>0,"type must be a non-empty string");const formatVersion=record.pm_format_version;return formatVersion!==void 0&&assertItemMetadataCondition(typeof formatVersion=="number"&&Number.isInteger(formatVersion)&&formatVersion>=BASELINE_ITEM_FORMAT_VERSION,`pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`),itemType}function assertStatusItemMetadataField(record,runtimeContext){const status=record.status;assertItemMetadataCondition(typeof status=="string"&&status.trim().length>0,"status must be a non-empty string");const statusRegistry=runtimeContext?.statusRegistry,normalizedStatus=normalizeStatusInput(status,statusRegistry),statusDomain=statusRegistry?statusRegistry.definitions.map(definition=>definition.id):[...STATUS_VALUES];assertItemMetadataCondition(normalizedStatus!==void 0,`status must be one of: ${statusDomain.join(", ")}`)}function assertPriorityAndTags(record){const priority=record.priority;assertItemMetadataCondition(typeof priority=="number"&&Number.isInteger(priority)&&[0,1,2,3,4].includes(priority),"priority must be an integer 0..4");const tags=record.tags;assertItemMetadataCondition(Array.isArray(tags),"tags must be an array");for(const tag of tags)assertItemMetadataCondition(typeof tag=="string","tags entries must be strings")}function assertConfidenceItemMetadataField(record){const confidence=record.confidence;if(confidence!==void 0){if(typeof confidence=="number"){assertItemMetadataCondition(Number.isInteger(confidence)&&confidence>=0&&confidence<=100,"confidence number value must be an integer 0..100");return}if(typeof confidence=="string"){const normalizedConfidence=confidence.trim().toLowerCase(),isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(!1,"confidence must be a number or string")}}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0)return;typeof severity!="string"&&validationError("severity must be a string");const normalizedSeverity=severity.trim().toLowerCase(),isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){record.regression!==void 0&&typeof record.regression!="boolean"&&validationError("regression must be a boolean")}function assertReminderEntries(record){const reminders=record.reminders;if(reminders!==void 0){assertItemMetadataCondition(Array.isArray(reminders),"reminders must be an array");for(const reminder of reminders){const reminderRecord=requireItemMetadataRecord(reminder,"reminders entries must be objects");assertItemMetadataCondition(typeof reminderRecord.at=="string","reminder.at must be a string"),assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at),"reminder.at must be a valid ISO timestamp"),assertItemMetadataCondition(typeof reminderRecord.text=="string","reminder.text must be a string"),assertItemMetadataCondition(reminderRecord.text.trim().length>0,"reminder.text must not be empty")}}}function assertEventStringFields(eventRecord){for(const stringField of["title","description","location","timezone"])eventRecord[stringField]!==void 0&&(assertItemMetadataCondition(typeof eventRecord[stringField]=="string",`event.${stringField} must be a string`),assertItemMetadataCondition(eventRecord[stringField].trim().length>0,`event.${stringField} must not be empty`))}function assertEventRecurrence(eventRecord){eventRecord.recurrence!==void 0&&(assertValidRecurrenceRule(eventRecord.recurrence),eventRecord.recurrence.until!==void 0&&assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until,eventRecord.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function assertCalendarEventEntry(event){const eventRecord=requireItemMetadataRecord(event,"events entries must be objects");assertItemMetadataCondition(typeof eventRecord.start_at=="string","event.start_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at),"event.start_at must be a valid ISO timestamp"),eventRecord.end_at!==void 0&&(assertItemMetadataCondition(typeof eventRecord.end_at=="string","event.end_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at),"event.end_at must be a valid ISO timestamp"),assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at,eventRecord.start_at)>0,"event.end_at must be after event.start_at")),assertEventStringFields(eventRecord),eventRecord.all_day!==void 0&&assertItemMetadataCondition(typeof eventRecord.all_day=="boolean","event.all_day must be a boolean"),assertEventRecurrence(eventRecord)}function assertCalendarEvents(record){const events=record.events;if(events!==void 0){assertItemMetadataCondition(Array.isArray(events),"events must be an array");for(const event of events)assertCalendarEventEntry(event)}}function assertOptionalStringFields(record){for(const fieldName of["source_type","source_owner","design","external_ref"]){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="string",`${fieldName} must be a string`)}}function assertTypeOptionsField(record){const typeOptions=record.type_options;if(typeOptions===void 0)return;const typeOptionsRecord=requireItemMetadataRecord(typeOptions,"type_options must be an object");for(const[optionKey,optionValue]of Object.entries(typeOptionsRecord))assertItemMetadataCondition(optionKey.trim().length>0,"type_options keys must be non-empty"),assertItemMetadataCondition(typeof optionValue=="string","type_options values must be strings"),assertItemMetadataCondition(optionValue.trim().length>0,"type_options values must be non-empty strings")}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(runtimeContext?.fieldRegistry)for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){runtimeFieldRequiredForType(definition,itemType)&&validationError(`missing required schema field: ${definition.metadata_key}`);continue}try{record[definition.metadata_key]=coerceRuntimeFieldValue(definition,fieldValue,`metadata field "${definition.metadata_key}"`,"metadata")}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length!==0&&(runtimeContext.unknownFieldPolicy==="reject"?validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`):runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`))}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object"),itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext),assertPriorityAndTags(record),assertConfidenceItemMetadataField(record),assertSeverityItemMetadataField(record),assertRegressionItemMetadataField(record),assertTimestampField(record,"created_at"),assertTimestampField(record,"updated_at"),record.deadline!==void 0&&assertTimestampField(record,"deadline"),assertReminderEntries(record),assertCalendarEvents(record),assertOptionalTimestampString(record,"closed_at","closed_at"),assertOptionalTimestampString(record,"completed_at","completed_at"),assertOptionalStringFields(record),assertTypeOptionsField(record),coerceRuntimeItemMetadataFields(record,itemType,runtimeContext),assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!(!values||values.length===0))return[...values].map((value,index)=>(assertItemMetadataCondition(value.created_at===void 0||typeof value.created_at=="string"&&isRfc3339DateTime(value.created_at),`dependencies.${index}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:value.id.trim(),kind:value.kind,created_at:value.created_at,author:value.author?.trim()||void 0,source_kind:value.source_kind?.trim()||void 0,author_source:value.author_source})).sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at??"",b.created_at??"");if(byCreated!==0)return byCreated;const byId=a.id.localeCompare(b.id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);return byKind!==0?byKind:(a.source_kind??"").localeCompare(b.source_kind??"")})}const CANONICALLY_ORDERED_LOG_COLLECTIONS=new Set(["comments","notes","learnings"]),UNCONVERTIBLE_LOG_SORT_KEY="[unconvertible]";function logSortField(entry,key){try{return String(entry?.[key])}catch{return UNCONVERTIBLE_LOG_SORT_KEY}}function compareLogValues(a,b){const byCreated=compareTimestampStrings(logSortField(a,"created_at"),logSortField(b,"created_at"));if(byCreated!==0)return byCreated;const byText=logSortField(a,"text").localeCompare(logSortField(b,"text"));return byText!==0?byText:logSortField(a,"author").localeCompare(logSortField(b,"author"))}function sortLogValues(values){if(!(!values||values.length===0))return[...values].sort(compareLogValues)}function sortReminders(values){if(!values||values.length===0)return;const normalized=[...values].map(value=>({at:value.at,text:value.text.trim()})).filter(value=>value.text.length>0).sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);return byAt!==0?byAt:a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value)return;const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency))return;const byWeekday=Array.from(new Set((value.by_weekday??[]).map(weekday=>weekday.trim().toLowerCase()).filter(weekday=>RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a,b)=>weekdayOrderIndex(a)-weekdayOrderIndex(b)),byMonthDay=Array.from(new Set((value.by_month_day??[]).filter(day=>Number.isInteger(day)&&day>=1&&day<=31).map(day=>day))).sort((a,b)=>a-b),exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b)),normalized={freq:normalizedFrequency,interval:value.interval!==void 0&&value.interval>1?value.interval:void 0,count:value.count,until:value.until?.trim()||void 0,by_weekday:byWeekday.length>0?byWeekday:void 0,by_month_day:byMonthDay.length>0?byMonthDay:void 0,exdates:exdates.length>0?exdates:void 0};for(const[key,fieldValue]of Object.entries(normalized))fieldValue===void 0&&delete normalized[key];return normalized}function sortEvents(values){return!Array.isArray(values)||values.length===0?void 0:[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents)}function normalizeCalendarEvent(value){const event={start_at:value.start_at,end_at:value.end_at||void 0,title:value.title?.trim()||void 0,description:value.description?.trim()||void 0,location:value.location?.trim()||void 0,all_day:value.all_day,timezone:value.timezone?.trim()||void 0,recurrence:normalizeRecurrenceRule(value.recurrence)};return deleteUndefinedFields(event),event}function compareCalendarEvents(a,b){return firstNonZeroComparison([compareTimestampStrings(a.start_at,b.start_at),(a.end_at??"").localeCompare(b.end_at??""),(a.title??"").localeCompare(b.title??""),+!!a.all_day-+!!b.all_day,(a.timezone??"").localeCompare(b.timezone??""),(a.location??"").localeCompare(b.location??""),(a.description??"").localeCompare(b.description??""),JSON.stringify(a.recurrence??{}).localeCompare(JSON.stringify(b.recurrence??{}))])}function normalizeFiles(values){if(!(!values||values.length===0))return values.map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0}))}function normalizeTestRunSummaries(values){if(!values||values.length===0)return;const normalized=values.map(normalizeTestRunSummary).filter(value=>value.run_id.length>0&&value.started_at.length>0&&value.finished_at.length>0&&value.recorded_at.length>0).sort((a,b)=>firstNonZeroComparison([compareTimestampStrings(a.recorded_at,b.recorded_at),a.run_id.localeCompare(b.run_id),a.kind.localeCompare(b.kind)]));return normalized.length>0?normalized:void 0}function normalizeNonNegativeInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):void 0}function normalizePositiveInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=1?Math.floor(value):void 0}function stringOrEmpty(value){return typeof value=="string"?value:""}function normalizeTestRunMeasurements(value){if(!Array.isArray(value))return;const normalized=value.filter(measurement=>measurement!==null&&typeof measurement=="object"&&typeof measurement.name=="string"&&measurement.name.trim().length>0&&typeof measurement.value=="number"&&Number.isFinite(measurement.value)&&typeof measurement.recorded_at=="string"&&measurement.recorded_at.trim().length>0).map(measurement=>({name:measurement.name.trim(),value:measurement.value,unit:typeof measurement.unit=="string"&&measurement.unit.trim()||void 0,threshold:typeof measurement.threshold=="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()})),deduplicated=[...new Map(normalized.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,32);return deduplicated.length>0?deduplicated:void 0}function normalizeTestRunEnum(value,allowedValues){return typeof value=="string"&&allowedValues.has(value)?value:void 0}function normalizeTestRunExecutions(values){if(!Array.isArray(values))return;const executions=values.filter(execution=>execution&&typeof execution.command=="string"&&execution.command.trim().length>0).slice(0,32).map(execution=>({command:execution.command.trim(),requested_pm_context_mode:normalizeTestRunEnum(execution.requested_pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),pm_context_mode:normalizeTestRunEnum(execution.pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),workspace_context_mode:normalizeTestRunEnum(execution.workspace_context_mode,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),trust_reason:normalizeTestRunEnum(execution.trust_reason,LINKED_TEST_TRUST_REASON_VALUES)}));return executions.length>0?executions:void 0}function normalizeTestRunSummary(value){const runId=typeof value.run_id=="string"?value.run_id.trim():"",kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test",status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed",summary={run_id:runId,kind,status,started_at:stringOrEmpty(value.started_at),finished_at:stringOrEmpty(value.finished_at),recorded_at:stringOrEmpty(value.recorded_at),attempt:normalizePositiveInteger(value.attempt),resumed_from:value.resumed_from?.trim()||void 0,passed:normalizeNonNegativeInteger(value.passed)??0,failed:normalizeNonNegativeInteger(value.failed)??0,skipped:normalizeNonNegativeInteger(value.skipped)??0,items:normalizeNonNegativeInteger(value.items),linked_tests:normalizeNonNegativeInteger(value.linked_tests),fail_on_skipped_triggered:value.fail_on_skipped_triggered===!0?!0:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};return deleteUndefinedFields(summary),summary}function sortTests(values){if(!(!Array.isArray(values)||values.length===0))return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value))return;const normalized=[...new Set(value.filter(entry=>typeof entry=="string").map(entry=>entry.trim()).filter(entry=>entry.length>0))].sort((a,b)=>a.localeCompare(b));return normalized.length>0?normalized:void 0}function isPlainObjectRecord(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isUnsafeObjectKey(key){return key==="__proto__"||key==="constructor"||key==="prototype"}function normalizeStringRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),String(recordValue).trim()]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&recordValue.length>0).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeNumericRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),Number(recordValue)]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&Number.isFinite(recordValue)).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeLinkedTestContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===!0)return{provenance_invalid:!0};if(value===void 0)return{};if(!isPlainObjectRecord(value))return{provenance_invalid:!0};const author=trimStringOrUndefined(value.author),createdAt=trimStringOrUndefined(value.created_at),sourceKind=value.source_kind;return!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"?{provenance_invalid:!0}:{provenance:{author,created_at:createdAt,source_kind:sourceKind,source_ref:trimStringOrUndefined(value.source_ref)}}}function normalizeLinkedTest(value){const test={command:value.command?.trim()||void 0,path:value.path?normalizePathValue(value.path):void 0,scope:value.scope,timeout_seconds:typeof value.timeout_seconds=="number"&&Number.isFinite(value.timeout_seconds)&&value.timeout_seconds>0?value.timeout_seconds:void 0,pm_context_mode:normalizeLinkedTestContextMode(value.pm_context_mode),workspace_context_mode:normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),...normalizeLinkedTestProvenance(value.provenance,value.provenance_invalid),updated_by:trimStringOrUndefined(value.updated_by),updated_at:trimStringOrUndefined(value.updated_at),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===!0?!0:void 0,assert_stdout_contains:normalizeTrimmedStringList(value.assert_stdout_contains),assert_stdout_regex:normalizeTrimmedStringList(value.assert_stdout_regex),assert_stderr_contains:normalizeTrimmedStringList(value.assert_stderr_contains),assert_stderr_regex:normalizeTrimmedStringList(value.assert_stderr_regex),assert_stdout_min_lines:normalizeNonNegativeInteger(value.assert_stdout_min_lines),assert_json_field_equals:normalizeStringRecord(value.assert_json_field_equals),assert_json_field_gte:normalizeNumericRecord(value.assert_json_field_gte),note:value.note?.trim()||void 0,phase:value.phase==="setup"?"setup":void 0};return deleteUndefinedFields(test),test}function sortDocs(values){if(!(!values||values.length===0))return[...values].map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0})).sort((a,b)=>{const byScope=a.scope.localeCompare(b.scope);if(byScope!==0)return byScope;const byPath=a.path.localeCompare(b.path);return byPath!==0?byPath:(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,id=trimStringOrUndefined(record.id),kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind},note=trimStringOrUndefined(record.note);note&&(link.note=note),record.required_before_step===!0&&(link.required_before_step=!0),out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(file.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(file.note=note),out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,command=trimStringOrUndefined(record.command),path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};command&&(test.command=command),path&&(test.path=normalizePathValue(path));const note=trimStringOrUndefined(record.note);note&&(test.note=note),out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(doc.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(doc.note=note),out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!="object")return;const record=entry,id=trimStringOrUndefined(record.id),title=trimStringOrUndefined(record.title),statusRaw=trimStringOrUndefined(record.status),status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0,order=coerceFiniteNumber(record.order)??Number.NaN,created_at=typeof record.created_at=="string"?record.created_at:"",updated_at=typeof record.updated_at=="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at)return;const step={id,order,title,status,created_at,updated_at};return applyPlanStepOptionalFields(step,record),step}function applyPlanStepOptionalFields(step,record){const stringFields=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[target,source]of stringFields){const value=trimStringOrUndefined(record[source]);value&&(step[target]=value)}const completedAt=typeof record.completed_at=="string"?record.completed_at:void 0;completedAt&&completedAt.length>0&&(step.completed_at=completedAt);const collectionFields=[["linked_items","linked_items",normalizePlanStepLinks],["files","files",normalizePlanStepFiles],["tests","tests",normalizePlanStepTests],["docs","docs",normalizePlanStepDocs]];for(const[target,source,normalize]of collectionFields){const value=normalize(record[source]);value&&(step[target]=value)}}function normalizePlanSteps(value){if(!Array.isArray(value))return;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});return out.sort((left,right)=>left.order-right.order),out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision},rationale=trimStringOrUndefined(record.rationale);rationale&&(item.rationale=rationale);const evidence=trimStringOrUndefined(record.evidence);evidence&&(item.evidence=evidence);const stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text},stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,text=trimStringOrUndefined(record.text);if(!text)continue;const item={text},command=trimStringOrUndefined(record.command);command&&(item.command=command);const expected=trimStringOrUndefined(record.expected);expected&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values)return;const normalizedEntries=Object.entries(values).map(([key,value])=>[key.trim(),value.trim()]).filter(([key,value])=>key.length>0&&value.length>0).sort((left,right)=>left[0].localeCompare(right[0]));if(normalizedEntries.length!==0)return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;for(;start<body.length&&body[start]===`
2
- `;)start+=1;return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0)return;if(typeof value=="number")return value;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(CONFIDENCE_TEXT_VALUES.includes(normalized))return normalized}function normalizeSeverityValue(value){if(value===void 0)return;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(ISSUE_SEVERITY_VALUES.includes(normalized))return normalized}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized,sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord))isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0||(targetRecord[key]=value)}function coerceNormalizedRuntimeFields(normalized,runtimeContext){if(!runtimeContext?.fieldRegistry)return;const record=normalized;for(const definition of runtimeContext.fieldRegistry.definitions){const currentValue=record[definition.metadata_key];currentValue!==void 0&&(record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`,"metadata"))}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(normalized).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"&&validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`),unknownKeys.length>0&&runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options),normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status,tags=Array.from(new Set((Array.isArray(itemMetadata.tags)?itemMetadata.tags:[]).filter(tag=>typeof tag=="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean))).sort((a,b)=>a.localeCompare(b)),normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};return copyExtensionItemMetadataFields(normalized,itemMetadata),coerceNormalizedRuntimeFields(normalized,runtimeContext),assertNormalizedUnknownFields(normalized,runtimeContext),deleteUndefinedFields(normalized),normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0,inString=!1,escaped=!1;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=!1;continue}if(char==="\\"){escaped=!0;continue}char==='"'&&(inString=!1);continue}if(char==='"'){inString=!0;continue}if(char==="{"){depth+=1;continue}if(char==="}"&&(depth-=1,depth===0))return i}return-1}function splitFrontMatter(content){if(!content.startsWith("{"))return{frontMatter:"",body:content};const end=findJsonObjectEnd(content);if(end<0)return{frontMatter:"",body:content};const frontMatter=content.slice(0,end+1),body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content,opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener)return{content:normalizedContent,stripped:!1};let cursor=opener[0].length;for(;cursor<normalizedContent.length;){const nextNewline=normalizedContent.indexOf(`
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]="5eaa8bf7-ef0a-51a2-a206-274e9d4c5f82")}catch{}})();import{encode as encodeToon}from"@toon-format/toon";import{isDeepStrictEqual}from"node:util";import{CONFIDENCE_TEXT_VALUES,ISSUE_SEVERITY_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,STATUS_VALUES,weekdayOrderIndex}from"../../types/index.js";import{coerceRuntimeFieldValue}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,effectiveItemFormatVersion,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{describeInvalidDeferredFields,normalizeDeferredFields}from"./deferred-fields.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isRfc3339DateTime,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto","none"]),LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]),LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]),PLAN_STEP_STATUS_SET=new Set(PLAN_STEP_STATUS_VALUES);function normalizePathValue(value){return value.replaceAll("\\","/")}function firstNonZeroComparison(comparisons){for(const comparison of comparisons)if(comparison!==0)return comparison;return 0}function deleteUndefinedFields(record){for(const[key,value]of Object.entries(record))value===void 0&&delete record[key]}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"],STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(options?.schema)return{statusRegistry:resolveRuntimeStatusRegistry(options.schema),fieldRegistry:resolveRuntimeFieldRegistry(options.schema),unknownFieldPolicy:options.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(options.extensionFieldNames??[]),onWarning:options.onWarning}}function runtimeFieldRequiredForType(definition,typeName){return definition.required?definition.required_types.length===0?!0:definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase()):!1}function validationError(message){const field=message.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new PmCliError(`Invalid item metadata: ${message}`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:message.includes("required")?"missing_required_field":"schema_validation_error",...field?{field}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:message})}function documentSyntaxError(format,message){throw new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format,required:`Provide a syntactically valid ${format==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function assertSupportedItemFormat(metadata,required){if(!required||typeof metadata!="object"||metadata===null)return;const formatVersion=effectiveItemFormatVersion(metadata);if(!(formatVersion<=CURRENT_ITEM_FORMAT_VERSION))throw new PmCliError(`Stored item uses format version ${formatVersion}; this runtime supports up to ${CURRENT_ITEM_FORMAT_VERSION}. Upgrade pm before reading or changing this item.`,EXIT_CODE.CONFLICT,{code:"item_format_version_unsupported",format_version:formatVersion,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function buildKnownItemMetadataKeys(runtimeContext){const knownKeys=new Set(STATIC_ITEM_METADATA_FIELD_SET);for(const definition of runtimeContext.fieldRegistry?.definitions??[])knownKeys.add(definition.metadata_key);for(const fieldName of runtimeContext.extensionFieldNames)knownKeys.add(fieldName);return knownKeys}function assertItemMetadataCondition(condition,message){condition||validationError(message)}function requireItemMetadataRecord(value,message){return(typeof value!="object"||value===null||Array.isArray(value))&&validationError(message),value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue=="string",`${fieldName} must be a string`),assertItemMetadataCondition(isTimestampLiteral(rawValue),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&(assertItemMetadataCondition(typeof value=="string",`${messagePrefix} must be a string`),assertItemMetadataCondition(isTimestampLiteral(value),`${messagePrefix} must be a valid ISO timestamp`))}function assertRecurrenceWeekdays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_weekday must be an array");for(const weekday of value){assertItemMetadataCondition(typeof weekday=="string","event.recurrence.by_weekday entries must be strings");const normalizedWeekday=weekday.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday),`event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`)}}}function assertRecurrenceMonthDays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_month_day must be an array");for(const day of value)assertItemMetadataCondition(typeof day=="number"&&Number.isInteger(day)&&day>=1&&day<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function assertRecurrenceExdates(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.exdates must be an array");for(const exdate of value)assertItemMetadataCondition(typeof exdate=="string","event.recurrence.exdates entries must be strings"),assertItemMetadataCondition(isTimestampLiteral(exdate),"event.recurrence.exdates entries must be valid ISO timestamps")}}function assertValidRecurrenceRule(recurrence){const recurrenceRecord=requireItemMetadataRecord(recurrence,"event.recurrence must be an object");assertItemMetadataCondition(typeof recurrenceRecord.freq=="string","event.recurrence.freq must be a string");const frequency=recurrenceRecord.freq.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency),`event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`),assertPositiveIntegerField(recurrenceRecord,"interval","event.recurrence.interval"),assertPositiveIntegerField(recurrenceRecord,"count","event.recurrence.count"),assertOptionalTimestampString(recurrenceRecord,"until","event.recurrence.until"),assertRecurrenceWeekdays(recurrenceRecord.by_weekday),assertRecurrenceMonthDays(recurrenceRecord.by_month_day),assertRecurrenceExdates(recurrenceRecord.exdates)}function assertRequiredItemMetadataFields(record){for(const fieldName of REQUIRED_STRING_FIELDS)assertItemMetadataCondition(typeof record[fieldName]=="string",`${fieldName} is required and must be a string`);const itemType=record.type;assertItemMetadataCondition(typeof itemType=="string"&&itemType.trim().length>0,"type must be a non-empty string");const formatVersion=record.pm_format_version;return formatVersion!==void 0&&assertItemMetadataCondition(typeof formatVersion=="number"&&Number.isInteger(formatVersion)&&formatVersion>=BASELINE_ITEM_FORMAT_VERSION,`pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`),itemType}function assertStatusItemMetadataField(record,runtimeContext){const status=record.status;assertItemMetadataCondition(typeof status=="string"&&status.trim().length>0,"status must be a non-empty string");const statusRegistry=runtimeContext?.statusRegistry,normalizedStatus=normalizeStatusInput(status,statusRegistry),statusDomain=statusRegistry?statusRegistry.definitions.map(definition=>definition.id):[...STATUS_VALUES];assertItemMetadataCondition(normalizedStatus!==void 0,`status must be one of: ${statusDomain.join(", ")}`)}function assertPriorityAndTags(record){const priority=record.priority;assertItemMetadataCondition(typeof priority=="number"&&Number.isInteger(priority)&&[0,1,2,3,4].includes(priority),"priority must be an integer 0..4");const tags=record.tags;assertItemMetadataCondition(Array.isArray(tags),"tags must be an array");for(const tag of tags)assertItemMetadataCondition(typeof tag=="string","tags entries must be strings")}function assertConfidenceItemMetadataField(record){const confidence=record.confidence;if(confidence!==void 0){if(typeof confidence=="number"){assertItemMetadataCondition(Number.isInteger(confidence)&&confidence>=0&&confidence<=100,"confidence number value must be an integer 0..100");return}if(typeof confidence=="string"){const normalizedConfidence=confidence.trim().toLowerCase(),isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(!1,"confidence must be a number or string")}}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0)return;typeof severity!="string"&&validationError("severity must be a string");const normalizedSeverity=severity.trim().toLowerCase(),isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){record.regression!==void 0&&typeof record.regression!="boolean"&&validationError("regression must be a boolean")}function assertReminderEntries(record){const reminders=record.reminders;if(reminders!==void 0){assertItemMetadataCondition(Array.isArray(reminders),"reminders must be an array");for(const reminder of reminders){const reminderRecord=requireItemMetadataRecord(reminder,"reminders entries must be objects");assertItemMetadataCondition(typeof reminderRecord.at=="string","reminder.at must be a string"),assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at),"reminder.at must be a valid ISO timestamp"),assertItemMetadataCondition(typeof reminderRecord.text=="string","reminder.text must be a string"),assertItemMetadataCondition(reminderRecord.text.trim().length>0,"reminder.text must not be empty")}}}function assertEventStringFields(eventRecord){for(const stringField of["title","description","location","timezone"])eventRecord[stringField]!==void 0&&(assertItemMetadataCondition(typeof eventRecord[stringField]=="string",`event.${stringField} must be a string`),assertItemMetadataCondition(eventRecord[stringField].trim().length>0,`event.${stringField} must not be empty`))}function assertEventRecurrence(eventRecord){eventRecord.recurrence!==void 0&&(assertValidRecurrenceRule(eventRecord.recurrence),eventRecord.recurrence.until!==void 0&&assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until,eventRecord.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function assertCalendarEventEntry(event){const eventRecord=requireItemMetadataRecord(event,"events entries must be objects");assertItemMetadataCondition(typeof eventRecord.start_at=="string","event.start_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at),"event.start_at must be a valid ISO timestamp"),eventRecord.end_at!==void 0&&(assertItemMetadataCondition(typeof eventRecord.end_at=="string","event.end_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at),"event.end_at must be a valid ISO timestamp"),assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at,eventRecord.start_at)>0,"event.end_at must be after event.start_at")),assertEventStringFields(eventRecord),eventRecord.all_day!==void 0&&assertItemMetadataCondition(typeof eventRecord.all_day=="boolean","event.all_day must be a boolean"),assertEventRecurrence(eventRecord)}function assertCalendarEvents(record){const events=record.events;if(events!==void 0){assertItemMetadataCondition(Array.isArray(events),"events must be an array");for(const event of events)assertCalendarEventEntry(event)}}function assertOptionalStringFields(record){for(const fieldName of["source_type","source_owner","design","external_ref"]){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="string",`${fieldName} must be a string`)}}function assertTypeOptionsField(record){const typeOptions=record.type_options;if(typeOptions===void 0)return;const typeOptionsRecord=requireItemMetadataRecord(typeOptions,"type_options must be an object");for(const[optionKey,optionValue]of Object.entries(typeOptionsRecord))assertItemMetadataCondition(optionKey.trim().length>0,"type_options keys must be non-empty"),assertItemMetadataCondition(typeof optionValue=="string","type_options values must be strings"),assertItemMetadataCondition(optionValue.trim().length>0,"type_options values must be non-empty strings")}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(runtimeContext?.fieldRegistry)for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){runtimeFieldRequiredForType(definition,itemType)&&validationError(`missing required schema field: ${definition.metadata_key}`);continue}try{record[definition.metadata_key]=coerceRuntimeFieldValue(definition,fieldValue,`metadata field "${definition.metadata_key}"`,"metadata")}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length!==0&&(runtimeContext.unknownFieldPolicy==="reject"?validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`):runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`))}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object"),itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext),assertPriorityAndTags(record),assertConfidenceItemMetadataField(record),assertSeverityItemMetadataField(record),assertRegressionItemMetadataField(record),assertTimestampField(record,"created_at"),assertTimestampField(record,"updated_at"),record.deadline!==void 0&&assertTimestampField(record,"deadline"),assertReminderEntries(record),assertCalendarEvents(record),assertOptionalTimestampString(record,"closed_at","closed_at"),assertOptionalTimestampString(record,"completed_at","completed_at"),assertOptionalStringFields(record),assertTypeOptionsField(record);const invalidDeferral=describeInvalidDeferredFields(record.deferred_fields);assertItemMetadataCondition(invalidDeferral===void 0,invalidDeferral??""),coerceRuntimeItemMetadataFields(record,itemType,runtimeContext),assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!(!values||values.length===0))return[...values].map((value,index)=>(assertItemMetadataCondition(value.created_at===void 0||typeof value.created_at=="string"&&isRfc3339DateTime(value.created_at),`dependencies.${index}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:value.id.trim(),kind:value.kind,created_at:value.created_at,author:value.author?.trim()||void 0,source_kind:value.source_kind?.trim()||void 0,author_source:value.author_source})).sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at??"",b.created_at??"");if(byCreated!==0)return byCreated;const byId=a.id.localeCompare(b.id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);return byKind!==0?byKind:(a.source_kind??"").localeCompare(b.source_kind??"")})}const CANONICALLY_ORDERED_LOG_COLLECTIONS=new Set(["comments","notes","learnings"]),UNCONVERTIBLE_LOG_SORT_KEY="[unconvertible]";function logSortField(entry,key){try{return String(entry?.[key])}catch{return UNCONVERTIBLE_LOG_SORT_KEY}}function compareLogValues(a,b){const byCreated=compareTimestampStrings(logSortField(a,"created_at"),logSortField(b,"created_at"));if(byCreated!==0)return byCreated;const byText=logSortField(a,"text").localeCompare(logSortField(b,"text"));return byText!==0?byText:logSortField(a,"author").localeCompare(logSortField(b,"author"))}function sortLogValues(values){if(!(!values||values.length===0))return[...values].sort(compareLogValues)}function sortReminders(values){if(!values||values.length===0)return;const normalized=[...values].map(value=>({at:value.at,text:value.text.trim()})).filter(value=>value.text.length>0).sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);return byAt!==0?byAt:a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value)return;const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency))return;const byWeekday=Array.from(new Set((value.by_weekday??[]).map(weekday=>weekday.trim().toLowerCase()).filter(weekday=>RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a,b)=>weekdayOrderIndex(a)-weekdayOrderIndex(b)),byMonthDay=Array.from(new Set((value.by_month_day??[]).filter(day=>Number.isInteger(day)&&day>=1&&day<=31).map(day=>day))).sort((a,b)=>a-b),exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b)),normalized={freq:normalizedFrequency,interval:value.interval!==void 0&&value.interval>1?value.interval:void 0,count:value.count,until:value.until?.trim()||void 0,by_weekday:byWeekday.length>0?byWeekday:void 0,by_month_day:byMonthDay.length>0?byMonthDay:void 0,exdates:exdates.length>0?exdates:void 0};for(const[key,fieldValue]of Object.entries(normalized))fieldValue===void 0&&delete normalized[key];return normalized}function sortEvents(values){return!Array.isArray(values)||values.length===0?void 0:[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents)}function normalizeCalendarEvent(value){const event={start_at:value.start_at,end_at:value.end_at||void 0,title:value.title?.trim()||void 0,description:value.description?.trim()||void 0,location:value.location?.trim()||void 0,all_day:value.all_day,timezone:value.timezone?.trim()||void 0,recurrence:normalizeRecurrenceRule(value.recurrence)};return deleteUndefinedFields(event),event}function compareCalendarEvents(a,b){return firstNonZeroComparison([compareTimestampStrings(a.start_at,b.start_at),(a.end_at??"").localeCompare(b.end_at??""),(a.title??"").localeCompare(b.title??""),+!!a.all_day-+!!b.all_day,(a.timezone??"").localeCompare(b.timezone??""),(a.location??"").localeCompare(b.location??""),(a.description??"").localeCompare(b.description??""),JSON.stringify(a.recurrence??{}).localeCompare(JSON.stringify(b.recurrence??{}))])}function normalizeFiles(values){if(!(!values||values.length===0))return values.map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0}))}function normalizeTestRunSummaries(values){if(!values||values.length===0)return;const normalized=values.map(normalizeTestRunSummary).filter(value=>value.run_id.length>0&&value.started_at.length>0&&value.finished_at.length>0&&value.recorded_at.length>0).sort((a,b)=>firstNonZeroComparison([compareTimestampStrings(a.recorded_at,b.recorded_at),a.run_id.localeCompare(b.run_id),a.kind.localeCompare(b.kind)]));return normalized.length>0?normalized:void 0}function normalizeNonNegativeInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):void 0}function normalizePositiveInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=1?Math.floor(value):void 0}function stringOrEmpty(value){return typeof value=="string"?value:""}function normalizeTestRunMeasurements(value){if(!Array.isArray(value))return;const normalized=value.filter(measurement=>measurement!==null&&typeof measurement=="object"&&typeof measurement.name=="string"&&measurement.name.trim().length>0&&typeof measurement.value=="number"&&Number.isFinite(measurement.value)&&typeof measurement.recorded_at=="string"&&measurement.recorded_at.trim().length>0).map(measurement=>({name:measurement.name.trim(),value:measurement.value,unit:typeof measurement.unit=="string"&&measurement.unit.trim()||void 0,threshold:typeof measurement.threshold=="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()})),deduplicated=[...new Map(normalized.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,32);return deduplicated.length>0?deduplicated:void 0}function normalizeTestRunEnum(value,allowedValues){return typeof value=="string"&&allowedValues.has(value)?value:void 0}function normalizeTestRunExecutions(values){if(!Array.isArray(values))return;const executions=values.filter(execution=>execution&&typeof execution.command=="string"&&execution.command.trim().length>0).slice(0,32).map(execution=>({command:execution.command.trim(),requested_pm_context_mode:normalizeTestRunEnum(execution.requested_pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),pm_context_mode:normalizeTestRunEnum(execution.pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),workspace_context_mode:normalizeTestRunEnum(execution.workspace_context_mode,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),trust_reason:normalizeTestRunEnum(execution.trust_reason,LINKED_TEST_TRUST_REASON_VALUES)}));return executions.length>0?executions:void 0}function normalizeTestRunSummary(value){const runId=typeof value.run_id=="string"?value.run_id.trim():"",kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test",status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed",summary={run_id:runId,kind,status,started_at:stringOrEmpty(value.started_at),finished_at:stringOrEmpty(value.finished_at),recorded_at:stringOrEmpty(value.recorded_at),attempt:normalizePositiveInteger(value.attempt),resumed_from:value.resumed_from?.trim()||void 0,passed:normalizeNonNegativeInteger(value.passed)??0,failed:normalizeNonNegativeInteger(value.failed)??0,skipped:normalizeNonNegativeInteger(value.skipped)??0,items:normalizeNonNegativeInteger(value.items),linked_tests:normalizeNonNegativeInteger(value.linked_tests),fail_on_skipped_triggered:value.fail_on_skipped_triggered===!0?!0:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};return deleteUndefinedFields(summary),summary}function sortTests(values){if(!(!Array.isArray(values)||values.length===0))return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value))return;const normalized=[...new Set(value.filter(entry=>typeof entry=="string").map(entry=>entry.trim()).filter(entry=>entry.length>0))].sort((a,b)=>a.localeCompare(b));return normalized.length>0?normalized:void 0}function isPlainObjectRecord(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isUnsafeObjectKey(key){return key==="__proto__"||key==="constructor"||key==="prototype"}function normalizeStringRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),String(recordValue).trim()]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&recordValue.length>0).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeNumericRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),Number(recordValue)]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&Number.isFinite(recordValue)).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeLinkedTestContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===!0)return{provenance_invalid:!0};if(value===void 0)return{};if(!isPlainObjectRecord(value))return{provenance_invalid:!0};const author=trimStringOrUndefined(value.author),createdAt=trimStringOrUndefined(value.created_at),sourceKind=value.source_kind;return!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"?{provenance_invalid:!0}:{provenance:{author,created_at:createdAt,source_kind:sourceKind,source_ref:trimStringOrUndefined(value.source_ref)}}}function normalizeLinkedTest(value){const test={command:value.command?.trim()||void 0,path:value.path?normalizePathValue(value.path):void 0,scope:value.scope,timeout_seconds:typeof value.timeout_seconds=="number"&&Number.isFinite(value.timeout_seconds)&&value.timeout_seconds>0?value.timeout_seconds:void 0,pm_context_mode:normalizeLinkedTestContextMode(value.pm_context_mode),workspace_context_mode:normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),...normalizeLinkedTestProvenance(value.provenance,value.provenance_invalid),updated_by:trimStringOrUndefined(value.updated_by),updated_at:trimStringOrUndefined(value.updated_at),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===!0?!0:void 0,assert_stdout_contains:normalizeTrimmedStringList(value.assert_stdout_contains),assert_stdout_regex:normalizeTrimmedStringList(value.assert_stdout_regex),assert_stderr_contains:normalizeTrimmedStringList(value.assert_stderr_contains),assert_stderr_regex:normalizeTrimmedStringList(value.assert_stderr_regex),assert_stdout_min_lines:normalizeNonNegativeInteger(value.assert_stdout_min_lines),assert_json_field_equals:normalizeStringRecord(value.assert_json_field_equals),assert_json_field_gte:normalizeNumericRecord(value.assert_json_field_gte),note:value.note?.trim()||void 0,phase:value.phase==="setup"?"setup":void 0};return deleteUndefinedFields(test),test}function sortDocs(values){if(!(!values||values.length===0))return[...values].map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0})).sort((a,b)=>{const byScope=a.scope.localeCompare(b.scope);if(byScope!==0)return byScope;const byPath=a.path.localeCompare(b.path);return byPath!==0?byPath:(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,id=trimStringOrUndefined(record.id),kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind},note=trimStringOrUndefined(record.note);note&&(link.note=note),record.required_before_step===!0&&(link.required_before_step=!0),out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(file.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(file.note=note),out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,command=trimStringOrUndefined(record.command),path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};command&&(test.command=command),path&&(test.path=normalizePathValue(path));const note=trimStringOrUndefined(record.note);note&&(test.note=note),out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(doc.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(doc.note=note),out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!="object")return;const record=entry,id=trimStringOrUndefined(record.id),title=trimStringOrUndefined(record.title),statusRaw=trimStringOrUndefined(record.status),status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0,order=coerceFiniteNumber(record.order)??Number.NaN,created_at=typeof record.created_at=="string"?record.created_at:"",updated_at=typeof record.updated_at=="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at)return;const step={id,order,title,status,created_at,updated_at};return applyPlanStepOptionalFields(step,record),step}function applyPlanStepOptionalFields(step,record){const stringFields=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[target,source]of stringFields){const value=trimStringOrUndefined(record[source]);value&&(step[target]=value)}const completedAt=typeof record.completed_at=="string"?record.completed_at:void 0;completedAt&&completedAt.length>0&&(step.completed_at=completedAt);const collectionFields=[["linked_items","linked_items",normalizePlanStepLinks],["files","files",normalizePlanStepFiles],["tests","tests",normalizePlanStepTests],["docs","docs",normalizePlanStepDocs]];for(const[target,source,normalize]of collectionFields){const value=normalize(record[source]);value&&(step[target]=value)}}function normalizePlanSteps(value){if(!Array.isArray(value))return;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});return out.sort((left,right)=>left.order-right.order),out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision},rationale=trimStringOrUndefined(record.rationale);rationale&&(item.rationale=rationale);const evidence=trimStringOrUndefined(record.evidence);evidence&&(item.evidence=evidence);const stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text},stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,text=trimStringOrUndefined(record.text);if(!text)continue;const item={text},command=trimStringOrUndefined(record.command);command&&(item.command=command);const expected=trimStringOrUndefined(record.expected);expected&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values)return;const normalizedEntries=Object.entries(values).map(([key,value])=>[key.trim(),value.trim()]).filter(([key,value])=>key.length>0&&value.length>0).sort((left,right)=>left[0].localeCompare(right[0]));if(normalizedEntries.length!==0)return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;for(;start<body.length&&body[start]===`
2
+ `;)start+=1;return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0)return;if(typeof value=="number")return value;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(CONFIDENCE_TEXT_VALUES.includes(normalized))return normalized}function normalizeSeverityValue(value){if(value===void 0)return;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(ISSUE_SEVERITY_VALUES.includes(normalized))return normalized}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized,sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord))isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0||(targetRecord[key]=value)}function coerceNormalizedRuntimeFields(normalized,runtimeContext){if(!runtimeContext?.fieldRegistry)return;const record=normalized;for(const definition of runtimeContext.fieldRegistry.definitions){const currentValue=record[definition.metadata_key];currentValue!==void 0&&(record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`,"metadata"))}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(normalized).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"&&validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`),unknownKeys.length>0&&runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options),normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status,tags=Array.from(new Set((Array.isArray(itemMetadata.tags)?itemMetadata.tags:[]).filter(tag=>typeof tag=="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean))).sort((a,b)=>a.localeCompare(b)),normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,deferred_fields:normalizeDeferredFields(itemMetadata.deferred_fields),design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};return copyExtensionItemMetadataFields(normalized,itemMetadata),coerceNormalizedRuntimeFields(normalized,runtimeContext),assertNormalizedUnknownFields(normalized,runtimeContext),deleteUndefinedFields(normalized),normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0,inString=!1,escaped=!1;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=!1;continue}if(char==="\\"){escaped=!0;continue}char==='"'&&(inString=!1);continue}if(char==='"'){inString=!0;continue}if(char==="{"){depth+=1;continue}if(char==="}"&&(depth-=1,depth===0))return i}return-1}function splitFrontMatter(content){if(!content.startsWith("{"))return{frontMatter:"",body:content};const end=findJsonObjectEnd(content);if(end<0)return{frontMatter:"",body:content};const frontMatter=content.slice(0,end+1),body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content,opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener)return{content:normalizedContent,stripped:!1};let cursor=opener[0].length;for(;cursor<normalizedContent.length;){const nextNewline=normalizedContent.indexOf(`
3
3
  `,cursor),lineEnd=nextNewline===-1?normalizedContent.length:nextNewline,line=normalizedContent.slice(cursor,lineEnd).replace(/\r$/,""),afterLine=nextNewline===-1?lineEnd:lineEnd+1;if(line.trim()==="---")return{content:normalizedContent.slice(afterLine).replace(/^\s+/,""),stripped:!0};cursor=afterLine}return{content:normalizedContent,stripped:!1}}function normalizeParsedItemMetadata(itemMetadata,options){return normalizeItemMetadata(itemMetadata,{...options,onWarning:void 0})}function parseJsonMarkdownItemDocument(content,runtimeContext,options={}){const normalized=stripLeadingYamlDocument(content);normalized.stripped&&options.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");const{frontMatter,body}=splitFrontMatter(normalized.content);frontMatter||(content.trimStart().startsWith("{")&&documentSyntaxError("json_markdown","JSON front matter is not valid JSON"),documentSyntaxError("json_markdown","JSON Markdown item document is missing JSON front matter"));let parsed;try{parsed=JSON.parse(frontMatter)}catch{documentSyntaxError("json_markdown","JSON front matter is not valid JSON")}return assertSupportedItemFormat(parsed,options.requireSupportedFormat),assertValidItemMetadata(parsed,runtimeContext),{metadata:normalizeParsedItemMetadata(parsed,options),body:normalizeBody(body)}}function parseToonItemDocument(content,runtimeContext,options={}){let parsed;try{parsed=decodeToonItemContent(content).value}catch{documentSyntaxError("toon","TOON item document is not valid TOON")}assertItemMetadataCondition(typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed),"TOON item document must be an object");const record=parsed;if(assertSupportedItemFormat(Object.prototype.hasOwnProperty.call(record,"front_matter")?record.front_matter:record,options.requireSupportedFormat),!REQUIRED_STRING_FIELDS.some(fieldName=>Object.prototype.hasOwnProperty.call(record,fieldName))&&!Object.prototype.hasOwnProperty.call(record,"front_matter")&&documentSyntaxError("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(record,"front_matter"))return assertValidItemMetadata(record.front_matter,runtimeContext),assertItemMetadataCondition(record.body===void 0||typeof record.body=="string","TOON item document body must be a string"),{metadata:normalizeParsedItemMetadata(record.front_matter,options),body:normalizeBody(typeof record.body=="string"?record.body:"")};const{body,...itemMetadataRecord}=record;return assertItemMetadataCondition(body===void 0||typeof body=="string","TOON item document body must be a string"),assertValidItemMetadata(itemMetadataRecord,runtimeContext),{metadata:normalizeParsedItemMetadata(itemMetadataRecord,options),body:normalizeBody(typeof body=="string"?body:"")}}function serializeJsonMarkdownItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options),orderedMetadata=orderItemMetadata(normalizedMetadata),normalizedBody=normalizeBody(document.body??"");assertWellFormedItemText(JSON.parse(JSON.stringify(orderedMetadata))),assertWellFormedItemText({body:normalizedBody});const serializedMetadata=JSON.stringify(orderedMetadata,null,2);return normalizedBody?`${serializedMetadata}
4
4
 
5
5
  ${normalizedBody}
@@ -71,6 +71,13 @@ preserveEmptyItemCollections?:boolean;
71
71
  positionalRowPaths?:readonly string[];}
72
72
  /** Resolve command ownership and suppression before projecting and rendering the result. */
73
73
  export declare function formatOutput(result:unknown,options:OutputOptions):string;
74
+ /**
75
+ * The mutation-receipt projection `printResult` applies before command-result
76
+ * overrides, services and rendering run: `--id-only`, `--full-changed-fields`,
77
+ * `--no-changed-fields`, or the compact envelope by default. Shared with the
78
+ * extension test harness so its read-output admission judges the same value.
79
+ */
80
+ export declare function projectPrintedResult(result:unknown,options:Pick<OutputOptions,"idOnly"|"fullChangedFields"|"noChangedFields">):unknown;
74
81
  /** Apply declared exit codes and mutation projection before writing a nonquiet result. */
75
82
  export declare function printResult(result:unknown,options:OutputOptions):void;
76
83
  /** Apply the error service override and emit one newline-terminated diagnostic. */