@unbrained/pm-cli 2026.11.7 → 2026.11.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (241) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +69 -48
  3. package/dist/cli/extension-command-help.js +4 -3
  4. package/dist/cli/help-json-payload.js +1 -1
  5. package/dist/cli/main.js +1 -1
  6. package/dist/cli/register-annotations.js +1 -1
  7. package/dist/cli/register-list-query.js +5 -5
  8. package/dist/cli/runtime/annotation-option-retry.js +2 -0
  9. package/dist/cli/runtime/invocation-options.js +1 -1
  10. package/dist/cli-bundle/bundle-manifest.json +1 -1
  11. package/dist/cli-bundle/chunks/chunk-3A5DJZCC.js +116 -0
  12. package/dist/cli-bundle/chunks/chunk-4BMPGUTG.js +9 -0
  13. package/dist/cli-bundle/chunks/{chunk-RFI4O6NU.js → chunk-7GC6WIDR.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-VM6OGNQC.js → chunk-7V6I6X4G.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-MQOZNGPS.js → chunk-AFZS6WFV.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-OIBSKKCO.js → chunk-C4MQFWCM.js} +2 -2
  17. package/dist/cli-bundle/chunks/chunk-CP43BHX3.js +31 -0
  18. package/dist/cli-bundle/chunks/{chunk-WS2N4TQW.js → chunk-DOHZKPPC.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-ETHAZC3F.js → chunk-HESIRIVX.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-JZWFZH2K.js → chunk-JAE5MWLX.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-KPAVZILX.js → chunk-L5BU5FYN.js} +2 -2
  22. package/dist/cli-bundle/chunks/{chunk-3DI6CEF3.js → chunk-LI2HP5OX.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-D53G3NOE.js → chunk-LLTRUVKK.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-BQ5O3CBF.js → chunk-MKW5LGVQ.js} +69 -65
  25. package/dist/cli-bundle/chunks/chunk-NH7QX2M2.js +8 -0
  26. package/dist/cli-bundle/chunks/{chunk-OJZG7Y6S.js → chunk-NKO42JMT.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-XSEDESNW.js → chunk-PE6CZ3PE.js} +2 -2
  28. package/dist/cli-bundle/chunks/chunk-RC6SSFOF.js +2 -0
  29. package/dist/cli-bundle/chunks/{chunk-TGQPCNAD.js → chunk-S4IZIMAO.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-WXVMPLBY.js → chunk-XBUZENP4.js} +2 -2
  31. package/dist/cli-bundle/chunks/chunk-YGUUJHSR.js +2 -0
  32. package/dist/cli-bundle/chunks/{chunk-F3B2ULHB.js → chunk-YUTFMHSG.js} +6 -6
  33. package/dist/cli-bundle/chunks/{chunk-QG6FLDM4.js → chunk-Z3LWNF7C.js} +2 -2
  34. package/dist/cli-bundle/chunks/{item-revision-SPEKTFBB.js → item-revision-TUGZYYXX.js} +2 -2
  35. package/dist/cli-bundle/chunks/item-transaction-2RRBAQN3.js +2 -0
  36. package/dist/cli-bundle/chunks/{mutation-admission-LUXUKISJ.js → mutation-admission-FJ3D66PV.js} +2 -2
  37. package/dist/cli-bundle/chunks/register-list-query-GXP77CX7.js +11 -0
  38. package/dist/cli-bundle/chunks/register-mutation-XJ2DROUM.js +20 -0
  39. package/dist/cli-bundle/chunks/{register-operations-AHDWE2G3.js → register-operations-O5LERXM7.js} +2 -2
  40. package/dist/cli-bundle/chunks/{register-setup-7BGG3CI3.js → register-setup-4VOTYLL2.js} +2 -2
  41. package/dist/cli-bundle/chunks/{stage-S5BYWLGY.js → stage-ZDJL3FGL.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/chunk-2A3QZELL.js +26 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-JRJOFMI7.js → chunk-3HFENALW.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-4UOXVFJZ.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-LW4TN5ZM.js → chunk-5YPX3QKU.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-4EXRRSDS.js → chunk-6U5HP6L3.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/chunk-DIEBSC76.js +3 -0
  48. package/dist/cli-bundle/focused-chunks/{chunk-BIDF4KO7.js → chunk-I4YUZW3J.js} +8 -8
  49. package/dist/cli-bundle/focused-chunks/{chunk-AJ2I377F.js → chunk-KBRSA4OK.js} +26 -26
  50. package/dist/cli-bundle/focused-chunks/{chunk-IYJRFJHT.js → chunk-KNF2QTEZ.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-LTPT5TE7.js +24 -0
  52. package/dist/cli-bundle/focused-chunks/chunk-O7K3X4LH.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-P4EHEH4C.js +2 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-P6TG33FV.js +82 -0
  55. package/dist/cli-bundle/focused-chunks/chunk-PL6EO4GJ.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-LTTMERPN.js → chunk-PSLDGAEY.js} +3 -3
  57. package/dist/cli-bundle/focused-chunks/chunk-SZ2BKK3M.js +2 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-TSHRBPTI.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-ULTSMJYF.js +91 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-UNNLBJRI.js +2 -0
  61. package/dist/cli-bundle/focused-chunks/chunk-UUVRYIKA.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{chunk-G2VIY6XA.js → chunk-WPXMPGTY.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/chunk-Z2QWZRSL.js +26 -0
  64. package/dist/cli-bundle/focused-chunks/item-revision-XNSRDTFB.js +2 -0
  65. package/dist/cli-bundle/focused-chunks/item-transaction-Q2Z7DDCR.js +2 -0
  66. package/dist/cli-bundle/focused-chunks/mutation-admission-QWC6MLTZ.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/stage-NKH5SKSZ.js +2 -0
  68. package/dist/cli-bundle/main.js +32 -31
  69. package/dist/cli-bundle/sdk-authoring.js +1 -1
  70. package/dist/cli-bundle/sdk-contracts.js +4 -4
  71. package/dist/cli-bundle/sdk-core.js +1 -1
  72. package/dist/cli-bundle/sdk-governance.js +1 -1
  73. package/dist/cli-bundle/sdk-graph.js +1 -1
  74. package/dist/cli-bundle/sdk-merge.js +57 -57
  75. package/dist/cli-bundle/sdk-query.js +1 -1
  76. package/dist/cli-bundle/sdk-runtime.js +1 -1
  77. package/dist/cli-bundle/sdk-testing.js +1 -1
  78. package/dist/cli-bundle/sdk.js +12 -12
  79. package/dist/core/extensions/flag-definition-validation.js +1 -1
  80. package/dist/core/extensions/reserved-host-flags.js +1 -1
  81. package/dist/core/history/history-stream-policy.d.ts +12 -3
  82. package/dist/core/history/history-stream-policy.js +1 -1
  83. package/dist/core/history/projection.d.ts +7 -2
  84. package/dist/core/history/projection.js +1 -1
  85. package/dist/core/item/item-format.d.ts +5 -1
  86. package/dist/core/item/item-format.js +2 -2
  87. package/dist/core/lock/lock.d.ts +1 -1
  88. package/dist/core/lock/lock.js +1 -1
  89. package/dist/core/output/output.d.ts +10 -1
  90. package/dist/core/output/output.js +7 -7
  91. package/dist/core/search/providers.d.ts +3 -2
  92. package/dist/core/search/providers.js +1 -1
  93. package/dist/core/search/vector-stores.d.ts +3 -2
  94. package/dist/core/search/vector-stores.js +1 -1
  95. package/dist/core/sentry/instrument.d.ts +2 -1
  96. package/dist/core/sentry/instrument.js +1 -1
  97. package/dist/mcp/tool-definitions.js +1 -1
  98. package/dist/sdk/annotations.d.ts +44 -1
  99. package/dist/sdk/annotations.js +1 -1
  100. package/dist/sdk/authoring.d.ts +6 -0
  101. package/dist/sdk/authoring.js +1 -1
  102. package/dist/sdk/cli-contracts/flag-contracts.d.ts +15 -0
  103. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  104. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  105. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -0
  106. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  107. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  108. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  109. package/dist/sdk/command-line.d.ts +2 -1
  110. package/dist/sdk/command-line.js +1 -1
  111. package/dist/sdk/comments.d.ts +4 -2
  112. package/dist/sdk/comments.js +1 -1
  113. package/dist/sdk/completion/bash.js +1 -1
  114. package/dist/sdk/completion/fish.js +2 -1
  115. package/dist/sdk/completion/zsh.js +4 -1
  116. package/dist/sdk/context-intent-contracts.d.ts +5 -1
  117. package/dist/sdk/context-intent-contracts.js +1 -1
  118. package/dist/sdk/contracts.d.ts +3 -0
  119. package/dist/sdk/contracts.js +1 -1
  120. package/dist/sdk/core.d.ts +14 -0
  121. package/dist/sdk/core.js +1 -1
  122. package/dist/sdk/corpus-shape.d.ts +2 -2
  123. package/dist/sdk/corpus-shape.js +1 -1
  124. package/dist/sdk/define.d.ts +14 -8
  125. package/dist/sdk/define.js +1 -1
  126. package/dist/sdk/extension/command-options.d.ts +123 -0
  127. package/dist/sdk/extension/command-options.js +2 -0
  128. package/dist/sdk/extension-contracts.d.ts +1 -2
  129. package/dist/sdk/extension-contracts.js +1 -1
  130. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  131. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  132. package/dist/sdk/governance.d.ts +8 -0
  133. package/dist/sdk/governance.js +1 -1
  134. package/dist/sdk/graph.d.ts +5 -0
  135. package/dist/sdk/graph.js +1 -1
  136. package/dist/sdk/index.d.ts +61 -1
  137. package/dist/sdk/index.js +1 -1
  138. package/dist/sdk/learnings.d.ts +4 -2
  139. package/dist/sdk/learnings.js +1 -1
  140. package/dist/sdk/lifecycle/restore.d.ts +1 -1
  141. package/dist/sdk/merge.d.ts +3 -0
  142. package/dist/sdk/merge.js +1 -1
  143. package/dist/sdk/notes.d.ts +4 -2
  144. package/dist/sdk/notes.js +1 -1
  145. package/dist/sdk/public-surface.json +1 -1
  146. package/dist/sdk/query/list.d.ts +5 -1
  147. package/dist/sdk/query/list.js +1 -1
  148. package/dist/sdk/query/search/semantic.d.ts +11 -3
  149. package/dist/sdk/query/search/semantic.js +1 -1
  150. package/dist/sdk/query/search-rendering.d.ts +9 -3
  151. package/dist/sdk/query/search-rendering.js +1 -1
  152. package/dist/sdk/query.d.ts +11 -0
  153. package/dist/sdk/query.js +1 -1
  154. package/dist/sdk/read-output/continuation.d.ts +8 -0
  155. package/dist/sdk/read-output/continuation.js +1 -1
  156. package/dist/sdk/read-output/options.d.ts +1 -1
  157. package/dist/sdk/read-output/options.js +1 -1
  158. package/dist/sdk/read-output/surfaces.js +1 -1
  159. package/dist/sdk/read-output/tail-retention.d.ts +34 -0
  160. package/dist/sdk/read-output/tail-retention.js +2 -0
  161. package/dist/sdk/read-output-budget.d.ts +14 -2
  162. package/dist/sdk/read-output-budget.js +1 -1
  163. package/dist/sdk/read-output-contracts.d.ts +20 -4
  164. package/dist/sdk/read-output-contracts.js +1 -1
  165. package/dist/sdk/read-output-rows.d.ts +7 -3
  166. package/dist/sdk/read-output-rows.js +1 -1
  167. package/dist/sdk/runtime-input.js +1 -1
  168. package/dist/sdk/runtime.d.ts +26 -3
  169. package/dist/sdk/runtime.js +1 -1
  170. package/dist/sdk/test/execution.d.ts +29 -2
  171. package/dist/sdk/test/execution.js +1 -1
  172. package/dist/sdk/testing.d.ts +14 -1
  173. package/dist/sdk/testing.js +1 -1
  174. package/dist/sdk/traceability/source-traceability.d.ts +4 -1
  175. package/dist/sdk/traceability/source-traceability.js +1 -1
  176. package/dist/sdk/workspace-recipe.d.ts +2 -2
  177. package/dist/sdk/workspace-recipe.js +1 -1
  178. package/docs/ARCHITECTURE.md +2 -1
  179. package/docs/COMMANDS.md +4 -1
  180. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +1 -1
  181. package/docs/EXTENSIONS.md +1 -1
  182. package/docs/MCP_OPTION_CONFORMANCE.md +13 -0
  183. package/docs/README.md +1 -1
  184. package/docs/READ_OUTPUT_CONTRACTS.md +78 -0
  185. package/docs/SDK.md +100 -2
  186. package/docs/SDK_CONTEXT_INTEGRITY.md +2 -0
  187. package/docs/agent-task-token-baseline.json +1 -1
  188. package/docs/generated/FLAG_LEXICON_BUDGETS.md +6 -6
  189. package/marketplace.json +1 -1
  190. package/package.json +2 -1
  191. package/packages/pm-beads/package.json +1 -1
  192. package/packages/pm-calendar/package.json +1 -1
  193. package/packages/pm-command-kit/package.json +1 -1
  194. package/packages/pm-digital-twin/package.json +1 -1
  195. package/packages/pm-governance-audit/package.json +1 -1
  196. package/packages/pm-guide-shell/package.json +1 -1
  197. package/packages/pm-kanban/package.json +1 -1
  198. package/packages/pm-lifecycle-hooks/package.json +1 -1
  199. package/packages/pm-linked-test-adapters/package.json +1 -1
  200. package/packages/pm-search-advanced/package.json +1 -1
  201. package/packages/pm-templates/package.json +1 -1
  202. package/packages/pm-todos/package.json +1 -1
  203. package/packages/pm-vcs/package.json +1 -1
  204. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  205. package/plugins/pm-claude/package.json +1 -1
  206. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  207. package/plugins/pm-codex/package.json +1 -1
  208. package/plugins/pm-codex/plugin.json +1 -1
  209. package/runtime-dependencies.json +1 -1
  210. package/dist/cli/extension-command-options.js +0 -2
  211. package/dist/cli-bundle/chunks/chunk-4PPWVIIT.js +0 -2
  212. package/dist/cli-bundle/chunks/chunk-5KHLV7JU.js +0 -116
  213. package/dist/cli-bundle/chunks/chunk-COKKWMSC.js +0 -8
  214. package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +0 -9
  215. package/dist/cli-bundle/chunks/chunk-WYIDX67P.js +0 -31
  216. package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +0 -2
  217. package/dist/cli-bundle/chunks/register-list-query-DU4W7VJU.js +0 -11
  218. package/dist/cli-bundle/chunks/register-mutation-IC2C53QK.js +0 -20
  219. package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +0 -26
  220. package/dist/cli-bundle/focused-chunks/chunk-4PW5XWVI.js +0 -2
  221. package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +0 -2
  222. package/dist/cli-bundle/focused-chunks/chunk-AI2PYNFI.js +0 -2
  223. package/dist/cli-bundle/focused-chunks/chunk-CWFNQQZE.js +0 -3
  224. package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +0 -2
  225. package/dist/cli-bundle/focused-chunks/chunk-GFF6BITP.js +0 -2
  226. package/dist/cli-bundle/focused-chunks/chunk-IIBWXNW3.js +0 -3
  227. package/dist/cli-bundle/focused-chunks/chunk-J5N42SKC.js +0 -3
  228. package/dist/cli-bundle/focused-chunks/chunk-KL33JMPC.js +0 -2
  229. package/dist/cli-bundle/focused-chunks/chunk-LH4C7BLB.js +0 -2
  230. package/dist/cli-bundle/focused-chunks/chunk-LTQEYE2L.js +0 -81
  231. package/dist/cli-bundle/focused-chunks/chunk-MESFDQ3H.js +0 -26
  232. package/dist/cli-bundle/focused-chunks/chunk-MWTBAI3V.js +0 -2
  233. package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +0 -2
  234. package/dist/cli-bundle/focused-chunks/chunk-XAC6NP7U.js +0 -2
  235. package/dist/cli-bundle/focused-chunks/chunk-XG3TBYQK.js +0 -23
  236. package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +0 -91
  237. package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +0 -2
  238. package/dist/cli-bundle/focused-chunks/item-transaction-GUGAUY77.js +0 -2
  239. package/dist/cli-bundle/focused-chunks/mutation-admission-54FI37AA.js +0 -2
  240. package/dist/cli-bundle/focused-chunks/stage-OHDJ43T2.js +0 -2
  241. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +0 -472
@@ -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]="896ebde0-4ca1-50ed-bb8e-2a8c2d978d94")}catch{}})();import{RESERVED_EXTENSION_HOST_FLAG_NAMES}from"./reserved-host-flags.js";const EXTENSION_LONG_FLAG_PATTERN=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function parseExtensionLongFlagToken(value){if(typeof value!="string")return null;const matched=EXTENSION_LONG_FLAG_PATTERN.exec(value.trim());if(!matched)return null;const placeholder=matched[2];return{name:matched[1],valueName:placeholder?placeholder.slice(1,-1):null,optional:placeholder?.startsWith("[")??!1}}function resolveExtensionLongFlagName(value){const parsed=parseExtensionLongFlagToken(value);return parsed?parsed.name:typeof value=="string"&&value.trim()||null}function validateExtensionLongFlagToken(value){if(typeof value!="string")return null;const token=value.trim(),hostToken=token.split(/[ =]/,1)[0];return RESERVED_EXTENSION_HOST_FLAG_NAMES.has(hostToken)?"host_owned_flag_collision":EXTENSION_LONG_FLAG_PATTERN.test(token)?null:"malformed_long_flag"}function findExtensionFlagTokenFailure(long,short){const reserved=[long,short].find(token2=>typeof token2=="string"&&RESERVED_EXTENSION_HOST_FLAG_NAMES.has(token2.trim().split(/[ =]/,1)[0]));if(typeof reserved=="string")return{token:reserved.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof long!="string")return null;const token=long.trim(),failure=validateExtensionLongFlagToken(token);return failure===null?null:{token,failure}}function describeExtensionLongFlagFailure(token,failure){return failure==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${token}"; read it from context.global instead`:`long flag "${token}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}export{EXTENSION_LONG_FLAG_PATTERN,describeExtensionLongFlagFailure,findExtensionFlagTokenFailure,parseExtensionLongFlagToken,resolveExtensionLongFlagName,validateExtensionLongFlagToken};
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]="81054684-60df-57c9-af9d-0996874c1024")}catch{}})();import{RESERVED_EXTENSION_HOST_FLAG_NAMES}from"./reserved-host-flags.js";const EXTENSION_LONG_FLAG_PATTERN=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function parseExtensionLongFlagToken(value){if(typeof value!="string")return null;const matched=EXTENSION_LONG_FLAG_PATTERN.exec(value.trim());if(!matched)return null;const placeholder=matched[2];return{name:matched[1],valueName:placeholder?placeholder.slice(1,-1):null,optional:placeholder?.startsWith("[")??!1}}function resolveExtensionLongFlagName(value){const parsed=parseExtensionLongFlagToken(value);return parsed?parsed.name:typeof value=="string"&&value.trim()||null}function validateExtensionLongFlagToken(value){if(typeof value!="string")return null;const token=value.trim(),hostToken=token.split(/[ =]/,1)[0];return RESERVED_EXTENSION_HOST_FLAG_NAMES.has(hostToken)||RESERVED_EXTENSION_HOST_FLAG_NAMES.has(`--${hostToken.slice(2).replaceAll("_","-")}`)?"host_owned_flag_collision":EXTENSION_LONG_FLAG_PATTERN.test(token)?null:"malformed_long_flag"}function findExtensionFlagTokenFailure(long,short){const reserved=[long,short].find(token2=>typeof token2=="string"&&RESERVED_EXTENSION_HOST_FLAG_NAMES.has(token2.trim().split(/[ =]/,1)[0]));if(typeof reserved=="string")return{token:reserved.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof long!="string")return null;const token=long.trim(),failure=validateExtensionLongFlagToken(token);return failure===null?null:{token,failure}}function describeExtensionLongFlagFailure(token,failure){return failure==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${token}"; read it from context.global instead`:`long flag "${token}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}export{EXTENSION_LONG_FLAG_PATTERN,describeExtensionLongFlagFailure,findExtensionFlagTokenFailure,parseExtensionLongFlagToken,resolveExtensionLongFlagName,validateExtensionLongFlagToken};
2
2
  //# sourceMappingURL=flag-definition-validation.js.map
@@ -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]="32b0a81e-6a21-528a-8cf8-3e764f382044")}catch{}})();const RESERVED_EXTENSION_HOST_FLAGS=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),RESERVED_EXTENSION_HOST_FLAG_NAMES=new Set(RESERVED_EXTENSION_HOST_FLAGS.flatMap(definition=>[definition.flag,...definition.aliases??[]]));export{RESERVED_EXTENSION_HOST_FLAGS,RESERVED_EXTENSION_HOST_FLAG_NAMES};
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]="d4155698-c244-5623-b627-92dd25297125")}catch{}})();const RESERVED_EXTENSION_HOST_FLAGS=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields",extension_command_availability:"read_output"},{flag:"--output-limit",value_name:"count",extension_command_availability:"read_output"},{flag:"--output-budget",value_name:"tokens",extension_command_availability:"read_output"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state",extension_command_availability:"read_output"},{flag:"--output-cursor",value_name:"cursor",extension_command_availability:"read_output"},{flag:"--output-row-contract",extension_command_availability:"read_output"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"],discovery_value_name:"path"},{flag:"--no-extensions",extension_command_availability:"never"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),RESERVED_EXTENSION_HOST_FLAG_NAMES=new Set(RESERVED_EXTENSION_HOST_FLAGS.flatMap(definition=>[definition.flag,...definition.aliases??[]]));export{RESERVED_EXTENSION_HOST_FLAGS,RESERVED_EXTENSION_HOST_FLAG_NAMES};
2
2
  //# sourceMappingURL=reserved-host-flags.js.map
@@ -1,14 +1,24 @@
1
1
  import type { PmSettings } from "../../types/index.js";
2
- interface HistoryStreamPolicyParams {
2
+ /** Inputs for applying the history stream policy to one item before a mutation writes its history. */
3
+ export interface HistoryStreamPolicyParams {
4
+ /** Tracker storage root that owns the item and its history stream. */
3
5
  pmRoot:string;
6
+ /** Resolved settings that carry the history stream policy. */
4
7
  settings:PmSettings;
8
+ /** Item whose history stream the policy inspects. */
5
9
  itemId:string;
10
+ /** Command name reported in policy warnings and auto-created stream notices. */
6
11
  commandLabel:string;
7
12
  }
8
- interface HistoryStreamPolicyManyParams {
13
+ /** Inputs for applying the history stream policy to several items in one mutation. */
14
+ export interface HistoryStreamPolicyManyParams {
15
+ /** Tracker storage root that owns the items and their history streams. */
9
16
  pmRoot:string;
17
+ /** Resolved settings that carry the history stream policy. */
10
18
  settings:PmSettings;
19
+ /** Items whose history streams the policy inspects. */
11
20
  itemIds:string[];
21
+ /** Command name reported in policy warnings and auto-created stream notices. */
12
22
  commandLabel:string;
13
23
  }
14
24
  /** Documents the history stream policy result payload exchanged by command, SDK, and package integrations. */
@@ -22,4 +32,3 @@ warnings:string[];
22
32
  export declare function enforceHistoryStreamPolicyForItem(params:HistoryStreamPolicyParams):Promise<HistoryStreamPolicyResult>;
23
33
  /** Implements enforce history stream policy for items for the public runtime surface of this module. */
24
34
  export declare function enforceHistoryStreamPolicyForItems(params:HistoryStreamPolicyManyParams):Promise<HistoryStreamPolicyResult>;
25
- export {};
@@ -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]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[];for(const itemId of ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(params.settings.history.missing_stream==="strict_error")throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
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]="fd3a41f0-4e82-59ab-bb8c-ed796c96a0d7")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[];for(const itemId of ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(params.settings.history.missing_stream==="strict_error")throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
2
2
  //# sourceMappingURL=history-stream-policy.js.map
@@ -16,11 +16,17 @@ errorSubject?:"history" | "restore";
16
16
  /** Allow a timestamp after the final entry to select that final entry. */
17
17
  allowFutureTimestamp?:boolean;
18
18
  }
19
- interface PatchFailureContext {
19
+ /** Locates the history patch operation that failed to apply during replay. */
20
+ export interface PatchFailureContext {
21
+ /** Zero-based index of the failing operation within the entry patch. */
20
22
  patchIndex?:number;
23
+ /** JSON Patch operation name, such as add, replace or move. */
21
24
  op?:string;
25
+ /** JSON Pointer the operation targets. */
22
26
  path?:string;
27
+ /** Source JSON Pointer for move and copy operations. */
23
28
  from?:string;
29
+ /** Why the operation could not be applied. */
24
30
  reason?:string;
25
31
  }
26
32
  /** Extract best-effort JSON Patch position details for replay diagnostics. */
@@ -36,4 +42,3 @@ export declare function applyHistoryPatch(current:ReplayDocument,patch:HistoryPa
36
42
  export declare function replayHistoryToTarget(history:readonly HistoryEntry[],targetIndex:number):ReplayDocument;
37
43
  /** Reject a version whose reconstructed state represents a deleted item. */
38
44
  export declare function ensureMaterializedHistoryTarget(replayDocument:ReplayDocument,target:ResolvedHistoryTarget):ReplayDocument;
39
- export {};
@@ -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]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok)throw new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
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]="02424d1c-c29f-5a13-b711-d50267170b9f")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok)throw new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
2
2
  //# sourceMappingURL=projection.js.map
@@ -1,4 +1,4 @@
1
- import type { ItemDocument,ItemMetadata,RuntimeSchemaSettings,ItemTestRunSummary,LinkedTest,PlanDecision,PlanDiscovery,PlanStep,PlanStepDoc,PlanStepFile,PlanStepLink,PlanValidationCheck } from "../../types/index.js";
1
+ import type { Comment,ItemDocument,ItemMetadata,RuntimeSchemaSettings,ItemTestRunSummary,LinkedTest,LogNote,PlanDecision,PlanDiscovery,PlanStep,PlanStepDoc,PlanStepFile,PlanStepLink,PlanValidationCheck } from "../../types/index.js";
2
2
  import type { ItemFormat } from "../../types/index.js";
3
3
  import { type RuntimeFieldRegistry,type RuntimeStatusRegistry } from "../schema/runtime-schema.js";
4
4
  declare function firstNonZeroComparison(comparisons:readonly number[]):number;
@@ -24,6 +24,10 @@ requireSupportedFormat?:boolean;
24
24
  }
25
25
  declare function runtimeFieldRequiredForType(definition:RuntimeFieldRegistry["definitions"][number],typeName:string):boolean;
26
26
  declare function buildKnownItemMetadataKeys(runtimeContext:RuntimeSchemaValidationContext):Set<string>;
27
+ /** Annotation collections the store keeps in {@link compareLogValues} order; any other collection keeps write order. */
28
+ export declare const CANONICALLY_ORDERED_LOG_COLLECTIONS:ReadonlySet<string>;
29
+ /** The canonical stored order of annotation entries: created_at, then text, then author (a stable sort keeps ties in write order). */
30
+ export declare function compareLogValues(a:Comment | LogNote,b:Comment | LogNote):number;
27
31
  declare function normalizeTestRunSummaries(values:ItemTestRunSummary[] | undefined):ItemTestRunSummary[] | undefined;
28
32
  declare function sortTests(values:LinkedTest[] | undefined):LinkedTest[] | undefined;
29
33
  /** Normalize one linked-test entry consistently for storage and metadata comparisons. */
@@ -1,9 +1,9 @@
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]="2789e87f-0706-52e8-8f4c-3855c65c618c")}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??"")})}function sortLogValues(values){if(!(!values||values.length===0))return[...values].sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byText=a.text.localeCompare(b.text);return byText!==0?byText:a.author.localeCompare(b.author)})}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};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]===`
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]="85cb46b1-e5c7-56ac-b9bd-61391bd686cc")}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"]);function compareLogValues(a,b){const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byText=a.text.localeCompare(b.text);return byText!==0?byText:a.author.localeCompare(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};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
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(`
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}
6
6
  `:`${serializedMetadata}
7
7
  `}const LONE_SURROGATE_PATTERN=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function findIllFormedItemText(value,path){return typeof value=="string"?illFormedText(value,path):value===null||typeof value!="object"?null:Array.isArray(value)?firstIllFormed(value.map((entry,position)=>()=>findIllFormedItemText(entry,`${path}[${position}]`))):firstIllFormed(Object.entries(value).map(([key,entry])=>()=>{const childPath=path?`${path}.${key}`:key;return illFormedText(key,`${childPath} (key)`)??findIllFormedItemText(entry,childPath)}))}function illFormedText(text,path){const index=text.search(LONE_SURROGATE_PATTERN);return index<0?null:{path,index}}function firstIllFormed(probes){for(const probe of probes){const found=probe();if(found!==null)return found}return null}function assertWellFormedItemText(payload){const found=findIllFormedItemText(payload,"");if(found!==null)throw new PmCliError(`Item field ${found.path} contains an unpaired surrogate code unit at index ${found.index}; persisted item text requires well-formed Unicode.`,EXIT_CODE.USAGE,{code:"text_unpaired_surrogate",field:found.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${found.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function serializeToonItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options),orderedMetadata=orderItemMetadata(normalizedMetadata),normalizedBody=normalizeBody(document.body??""),payload={...orderedMetadata,body:normalizedBody},encodablePayload=JSON.parse(JSON.stringify(payload));assertWellFormedItemText(encodablePayload);const serialized=encodeToon(encodablePayload);let decoded;try{decoded=decodeToonItemContent(serialized).value}catch(error){throw new PmCliError("Refusing to persist a TOON item document that the configured decoder cannot read back.",EXIT_CODE.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:error instanceof Error?error.message:String(error)})}if(!isDeepStrictEqual(decoded,encodablePayload)){const decodedRecord=typeof decoded=="object"&&decoded!==null&&!Array.isArray(decoded)?decoded:{},field=Object.keys(encodablePayload).find(key=>!isDeepStrictEqual(encodablePayload[key],decodedRecord[key]))??"document";throw new PmCliError(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${field}".`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${serialized}
8
- `}function parseItemDocument(content,options={}){const conflictMarker=findFirstMergeConflictMarker(content);if(conflictMarker)throw new PmCliError(`Merge conflict markers detected in item document at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});const format=options.format??"toon",runtimeContext=resolveRuntimeSchemaValidationContext(options);return format==="toon"?parseToonItemDocument(content,runtimeContext,options):parseJsonMarkdownItemDocument(content,runtimeContext,options)}function serializeItemDocument(document,options={}){return(options.format??"toon")==="toon"?serializeToonItemDocument(document,options):serializeJsonMarkdownItemDocument(document,options)}function canonicalDocument(document,options={}){return{metadata:normalizeItemMetadata(document.metadata,options),body:normalizeBody(document.body??"")}}const _testOnlyItemFormat={buildKnownItemMetadataKeys,firstNonZeroComparison,normalizeBody,normalizePlanDecisions,normalizePlanDiscoveries,normalizePlanStepDocs,normalizePlanStepFiles,normalizePlanStepLinks,normalizePlanSteps,normalizePlanStepTests,normalizePlanValidation,normalizeTestRunSummaries,normalizeTypeOptions,runtimeFieldRequiredForType,sortTests};export{_testOnlyItemFormat,canonicalDocument,normalizeItemMetadata,normalizeLinkedTest,parseItemDocument,serializeItemDocument,splitFrontMatter};
8
+ `}function parseItemDocument(content,options={}){const conflictMarker=findFirstMergeConflictMarker(content);if(conflictMarker)throw new PmCliError(`Merge conflict markers detected in item document at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});const format=options.format??"toon",runtimeContext=resolveRuntimeSchemaValidationContext(options);return format==="toon"?parseToonItemDocument(content,runtimeContext,options):parseJsonMarkdownItemDocument(content,runtimeContext,options)}function serializeItemDocument(document,options={}){return(options.format??"toon")==="toon"?serializeToonItemDocument(document,options):serializeJsonMarkdownItemDocument(document,options)}function canonicalDocument(document,options={}){return{metadata:normalizeItemMetadata(document.metadata,options),body:normalizeBody(document.body??"")}}const _testOnlyItemFormat={buildKnownItemMetadataKeys,firstNonZeroComparison,normalizeBody,normalizePlanDecisions,normalizePlanDiscoveries,normalizePlanStepDocs,normalizePlanStepFiles,normalizePlanStepLinks,normalizePlanSteps,normalizePlanStepTests,normalizePlanValidation,normalizeTestRunSummaries,normalizeTypeOptions,runtimeFieldRequiredForType,sortTests};export{CANONICALLY_ORDERED_LOG_COLLECTIONS,_testOnlyItemFormat,canonicalDocument,compareLogValues,normalizeItemMetadata,normalizeLinkedTest,parseItemDocument,serializeItemDocument,splitFrontMatter};
9
9
  //# sourceMappingURL=item-format.js.map
@@ -84,7 +84,7 @@ release:() => Promise<void>;
84
84
  fence:<T>(commit:() => Promise<T>) => Promise<T>;
85
85
  }
86
86
  /** Positional lock policy shared by acquireLock and acquireLockLease. */
87
- type AcquireLockOptions = {
87
+ export type AcquireLockOptions = {
88
88
  /** Allow lock acquisition to initialize missing lock directories. */
89
89
  createParentDirectories?:boolean;
90
90
  /** Ceiling on the effective retry budget, including PM_LOCK_WAIT_MS. */
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7f116073-a02b-568b-a408-17c0fcc8b4a4")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";import{LOCK_PATH_UNSAFE_CODE,assertLockEntryNotSymlink,inspectConfinedLockDirectory,verifyConfinedLockCreation}from"./lock-confinement.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,createParentDirectories){const existingDirectory=await inspectConfinedLockDirectory(pmRoot,lockPath,id);createParentDirectories&&existingDirectory===null&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let createdAt;try{const directory=await inspectConfinedLockDirectory(pmRoot,lockPath,id,!1),handle=await fs.open(lockPath,"wx");try{await verifyConfinedLockCreation({pmRoot,lockPath,id,handle,directory})}catch(error){throw await handle.close(),error}try{try{const payload=await buildLockPayload(id,owner,ttlSeconds,token);createdAt=payload.created_at,await handle.writeFile(`${JSON.stringify(payload,null,2)}
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54aee8ec-9ef4-54d4-92fa-f4104b3ec4cc")}catch{}})();import{isFileMissingError}from"../fs/fs-utils.js";import{constants as fsConstants}from"node:fs";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{runActiveOnReadHooks,runActiveOnWriteHooks,runActiveServiceOverride}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{toErrorMessage}from"../shared/primitives.js";import{getLockPath}from"../store/paths.js";import{nowIso}from"../shared/time.js";import{LOCK_PATH_UNSAFE_CODE,assertLockEntryNotSymlink,inspectConfinedLockDirectory,verifyConfinedLockCreation}from"./lock-confinement.js";import{captureProcessIdentity,captureLockOwnerIdentity,inspectLockOwner,isProcessIdentityAlive,parseLinuxProcessStartIdentity,readProcessStartIdentity}from"./lock-owner.js";import{captureProcessIdentity as captureProcessIdentity2,isProcessIdentityAlive as isProcessIdentityAlive2,readProcessStartIdentity as readProcessStartIdentity2}from"./lock-owner.js";function parseLockInfo(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return{info:null,warnings:["lock_info_invalid_shape"]};const candidate=parsed,id=candidate.id,pid=candidate.pid,owner=candidate.owner,token=candidate.token,createdAt=candidate.created_at,ttlSeconds=candidate.ttl_seconds;return typeof id!="string"||typeof pid!="number"||!Number.isFinite(pid)||typeof owner!="string"||token!==void 0&&(typeof token!="string"||token.trim().length===0)||typeof createdAt!="string"||typeof ttlSeconds!="number"||!Number.isFinite(ttlSeconds)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id,pid,owner,...typeof token=="string"?{token}:{},created_at:createdAt,ttl_seconds:ttlSeconds,host_identity:candidate.host_identity,process_start_identity:candidate.process_start_identity},warnings:[]}}async function readLockInfo(lockPath,emitReadHook=!0){try{const raw=await fs.readFile(lockPath,"utf8");return emitReadHook&&await runActiveOnReadHooks({path:lockPath,scope:"project"}),parseLockInfo(raw)}catch(error){return isFileMissingError(error)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function isErrno(error,code){return typeof error=="object"&&error!==null&&"code"in error&&error.code===code}async function isLockCreateContention(error,lockPath,platform=process.platform){if(isErrno(error,"EEXIST"))return!0;if(!isErrno(error,"EPERM")&&!isErrno(error,"EACCES")&&!isErrno(error,"EBUSY"))return!1;try{return await fs.lstat(lockPath),!0}catch(probeError){if(platform!=="win32"||!isFileMissingError(probeError)&&!isErrno(probeError,"EPERM")&&!isErrno(probeError,"EACCES")&&!isErrno(probeError,"EBUSY"))return!1}try{return await fs.access(path.dirname(lockPath),fsConstants.W_OK),!0}catch{return!1}}async function emitLockWriteHook(lockPath,op){await runActiveOnWriteHooks({path:lockPath,scope:"project",op})}async function buildLockPayload(id,owner,ttlSeconds,token=randomUUID()){return{...await captureLockOwnerIdentity(),id,pid:process.pid,owner,token,created_at:nowIso(),ttl_seconds:ttlSeconds}}async function createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,createParentDirectories){const existingDirectory=await inspectConfinedLockDirectory(pmRoot,lockPath,id);createParentDirectories&&existingDirectory===null&&await fs.mkdir(path.dirname(lockPath),{recursive:!0});const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null)throw await fs.access(path.dirname(lockPath)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let createdAt;try{const directory=await inspectConfinedLockDirectory(pmRoot,lockPath,id,!1),handle=await fs.open(lockPath,"wx");try{await verifyConfinedLockCreation({pmRoot,lockPath,id,handle,directory})}catch(error){throw await handle.close(),error}try{try{const payload=await buildLockPayload(id,owner,ttlSeconds,token);createdAt=payload.created_at,await handle.writeFile(`${JSON.stringify(payload,null,2)}
2
2
  `,"utf8")}finally{await handle.close()}}catch(error){throw await unlinkLockWithHook(lockPath,"lock:release"),error}}finally{await releaseCleanupGate()}return await emitLockWriteHook(lockPath,"lock:create"),createdAt}async function unlinkLockWithHook(lockPath,op){try{return await fs.unlink(lockPath),await emitLockWriteHook(lockPath,op),!0}catch{return!1}}async function releaseOwnedLock(lockPath,id,owner,token){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null){try{const current2=await readLockInfo(lockPath,!1);isOwnedLock(current2.info,id,owner,token)&&await unlinkLockWithHook(lockPath,"lock:release")}finally{await releaseCleanupGate()}return}const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,owner,token))return;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}function isOwnedLock(info,id,owner,token){return info?.id===id&&info.pid===process.pid&&info.owner===owner&&info.token===token}function isStaleLock(info,ttlSeconds){const createdAtMs=info?.created_at?Date.parse(info.created_at):Number.NaN;return(Number.isFinite(createdAtMs)?Date.now()-createdAtMs:Number.POSITIVE_INFINITY)>ttlSeconds*1e3}async function isConfirmedDeadLock(info){return info!==null&&Number.isFinite(Date.parse(info.created_at))&&await inspectLockOwner(info)==="dead"}async function isReclaimableLock(info,ttlSeconds){return isStaleLock(info,ttlSeconds)||await isConfirmedDeadLock(info)}async function hasUnexpiredLockOwner(pmRoot,id,ownerPrefix){const{info}=await readLockInfo(getLockPath(pmRoot,id),!1);return info!==null&&info.owner.startsWith(ownerPrefix)&&!await isReclaimableLock(info,info.ttl_seconds)}function lockOwnerSuffix(info){return info?.owner?` (owner ${info.owner})`:""}const LOCK_WAIT_INITIAL_DELAY_MS=25,LOCK_WAIT_MAX_DELAY_MS=200,LOCK_CONFLICT_RETRY_HINT_MS=250,LOCK_PROGRESS_MAX_WAIT_MS=12e4,MAX_STALE_LOCK_REMOVALS=3,STALE_CLEANUP_GATE_SUFFIX=".stale-cleanup",STALE_CLEANUP_GATE_OWNER_FILE="owner.json",STALE_CLEANUP_GATE_STALE_MS=1e4,LOCK_RELEASE_GATE_WAIT_MS=STALE_CLEANUP_GATE_STALE_MS+LOCK_WAIT_MAX_DELAY_MS;function parseNonNegativeIntegerWaitMs(value){if(typeof value=="string"){const trimmed=value.trim();if(!/^\d+$/.test(trimmed))return;const parsed=Number(trimmed);return Number.isSafeInteger(parsed)?parsed:void 0}if(typeof value=="number"&&Number.isFinite(value)&&value>=0)return Math.trunc(value)}function resolveLockWaitMs(waitMs){const envRaw=process.env.PM_LOCK_WAIT_MS,envParsed=parseNonNegativeIntegerWaitMs(envRaw);if(envParsed!==void 0)return envParsed;const callerParsed=parseNonNegativeIntegerWaitMs(waitMs);return callerParsed!==void 0?callerParsed:0}function cappedLockWaitMs(waitMs,maxWaitMs){return Math.min(resolveLockWaitMs(waitMs),maxWaitMs??1/0)}function sleepWithJitter(baseDelayMs){const jitteredMs=Math.max(1,Math.round(baseDelayMs*(.5+Math.random())));return new Promise(resolve=>setTimeout(resolve,jitteredMs))}async function buildLockConflictError(id,info,waitedMs,ownerHandoffs=0){waitedMs=Math.floor(waitedMs);const ownerState=await inspectLockOwner(info),handoffSuffix=ownerHandoffs>0?` across ${ownerHandoffs} owner handoff(s)`:"",waitedSuffix=waitedMs>0?` after waiting ${waitedMs}ms${handoffSuffix}`:"";return new PmCliError(`Item ${id} is locked${lockOwnerSuffix(info)} (owner process ${ownerState})${waitedSuffix}`,EXIT_CODE.CONFLICT,{code:"lock_conflict",item_id:id,reason:`lock_owner_${ownerState}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS,...waitedMs>0?{waited_ms:waitedMs,owner_handoffs:ownerHandoffs}:{}}})}function createLockWaitTracker(waitBudgetMs,totalCeilingMs){const startedAtMs=performance.now();let stallStartedAtMs=startedAtMs,observedGeneration,ownerHandoffs=0;return{startedAtMs,observe(info){const nowMs=performance.now(),generation=lockGenerationKey(info);observedGeneration!==void 0&&generation!==observedGeneration&&(ownerHandoffs+=1,stallStartedAtMs=nowMs),observedGeneration=generation;const elapsedMs=nowMs-startedAtMs,stalledMs=nowMs-stallStartedAtMs;return{exhausted:waitBudgetMs===0||stalledMs>=waitBudgetMs||elapsedMs>=totalCeilingMs,elapsedMs,remainingMs:Math.min(waitBudgetMs-stalledMs,totalCeilingMs-elapsedMs),ownerHandoffs}}}}function resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,waitPolicy){return waitPolicy!=="progress"||maxWaitMs!==void 0?waitBudgetMs:Math.max(waitBudgetMs,LOCK_PROGRESS_MAX_WAIT_MS)}function lockGenerationKey(info){return info===null?"released":info.token??`${info.pid}:${info.owner}:${info.created_at}`}function describeLease(lease){const expiresAtMs=Date.parse(lease.acquiredAt)+lease.ttlSeconds*1e3;return{owner:lease.owner,acquired_at:lease.acquiredAt,ttl_seconds:lease.ttlSeconds,expires_at:new Date(expiresAtMs).toISOString()}}function describeLockLoss(id,lease,current,reason){const leaseLabel=`the lease acquired at ${lease.acquiredAt} (ttl ${lease.ttlSeconds}s)`;if(reason==="fence_gate_unavailable")return{summary:`Lock for ${id} could not be verified before commit: ${leaseLabel} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};const holder=current===null?"the lock no longer exists":`it is now held by ${current.owner} since ${current.created_at}`;return{summary:`Lock for ${id} was lost before commit: ${leaseLabel} is no longer owned by this writer, and ${holder}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function buildLockLostError(id,lease,current,reason){const{summary,required}=describeLockLoss(id,lease,current,reason);return new PmCliError(`${summary} Nothing was written.`,EXIT_CODE.CONFLICT,{code:"lock_lost",item_id:id,reason,lease:describeLease(lease),current_owner:current===null?null:{owner:current.owner,pid:current.pid,created_at:current.created_at,ttl_seconds:current.ttl_seconds},required,recovery:{retry_after_ms:LOCK_CONFLICT_RETRY_HINT_MS}})}async function waitForStaleCleanupGate(lockPath,id){const startedAtMs=performance.now();let backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;for(;;){const releaseCleanupGate=await acquireStaleCleanupGate(lockPath,id);if(releaseCleanupGate!==null)return releaseCleanupGate;const elapsedMs=performance.now()-startedAtMs;if(elapsedMs>=LOCK_RELEASE_GATE_WAIT_MS)return null;await sleepWithJitter(Math.min(backoffMs,LOCK_RELEASE_GATE_WAIT_MS-elapsedMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}async function fenceOwnedLock(lockPath,id,lease,commit){const releaseCleanupGate=await waitForStaleCleanupGate(lockPath,id);if(releaseCleanupGate===null){const current=await readLockInfo(lockPath,!1);throw buildLockLostError(id,lease,current.info,"fence_gate_unavailable")}try{const current=await readLockInfo(lockPath,!1);if(!isOwnedLock(current.info,id,lease.owner,lease.token))throw buildLockLostError(id,lease,current.info,current.info===null?"lease_released":"lease_taken_over");return await commit()}finally{await releaseCleanupGate()}}function resolveLockOverrideRelease(result){if(typeof result=="function")return result;if(typeof result=="object"&&result!==null&&"release"in result){const release=result.release;return typeof release=="function"?release:null}return null}function throwIfStaleLockNeedsForce(id,lockInfo,force,forceRequired){if(!force&&forceRequired){const warningSuffix=lockInfo.warnings.length>0?` (${lockInfo.warnings.join(",")})`:"";throw new PmCliError(`Item ${id} lock is stale${warningSuffix}; rerun with --force when supported for this command`,EXIT_CODE.CONFLICT)}}function parseStaleCleanupGateOwner(raw){let parsed;try{parsed=JSON.parse(raw)}catch{return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))return null;const candidate=parsed,pid=candidate.pid,token=candidate.token,processStartIdentity=candidate.process_start_identity;return typeof pid!="number"||!Number.isInteger(pid)||pid<=0||typeof token!="string"||token.length===0||processStartIdentity!==void 0&&(typeof processStartIdentity!="string"||!/^\d+$/u.test(processStartIdentity))?null:{pid,token,host_identity:candidate.host_identity,...typeof processStartIdentity=="string"?{process_start_identity:processStartIdentity}:{}}}async function readStaleCleanupGateOwner(gatePath){try{return parseStaleCleanupGateOwner(await fs.readFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),"utf8"))}catch(error){return isFileMissingError(error)?null:void 0}}async function removeStaleCleanupGateDirectory(gatePath){try{return await fs.rm(gatePath,{recursive:!0,force:!0}),!0}catch{return!1}}async function releaseStaleCleanupGate(gatePath,token){let owner=await readStaleCleanupGateOwner(gatePath);for(let attempt=0;owner===void 0&&attempt<3;attempt+=1)await sleepWithJitter(LOCK_WAIT_INITIAL_DELAY_MS),owner=await readStaleCleanupGateOwner(gatePath);!owner||owner.token!==token||await removeStaleCleanupGateDirectory(gatePath)}async function tryCreateStaleCleanupGate(gatePath){try{await fs.mkdir(gatePath)}catch(error){return isErrno(error,"EEXIST"),null}const owner={...await captureProcessIdentity(),host_identity:(await captureLockOwnerIdentity()).host_identity,token:randomUUID()};try{await fs.writeFile(path.join(gatePath,STALE_CLEANUP_GATE_OWNER_FILE),`${JSON.stringify(owner)}
3
3
  `,"utf8")}catch{return await removeStaleCleanupGateDirectory(gatePath),null}return owner}async function retireCleanupGateGeneration(gatePath,token){const recoveries=path.join(path.dirname(gatePath),"recoveries"),generation=createHash("sha256").update(token).digest("hex");try{return await fs.mkdir(recoveries,{recursive:!0}),(await readStaleCleanupGateOwner(gatePath))?.token!==token?!1:(await fs.rename(gatePath,path.join(recoveries,`gate-${generation}`)),!0)}catch{return!1}}async function removeExpiredStaleCleanupGate(gatePath){let gateAgeMs;try{const stats=await fs.stat(gatePath);gateAgeMs=Date.now()-stats.mtimeMs}catch(error){return isFileMissingError(error)}const owner=await readStaleCleanupGateOwner(gatePath);if(owner===void 0)return!1;if(owner!==null){if(await inspectLockOwner(owner)==="dead")return retireCleanupGateGeneration(gatePath,owner.token);if(owner.host_identity!==void 0)return!1}return gateAgeMs<=STALE_CLEANUP_GATE_STALE_MS||owner!==null&&await isProcessIdentityAlive(owner,gateAgeMs,Number.POSITIVE_INFINITY)?!1:owner!==null?retireCleanupGateGeneration(gatePath,owner.token):removeStaleCleanupGateDirectory(gatePath)}async function acquireStaleCleanupGate(lockPath,_id){const gatePath=`${lockPath}${STALE_CLEANUP_GATE_SUFFIX}`,owner=await tryCreateStaleCleanupGate(gatePath);if(owner!==null)return async()=>releaseStaleCleanupGate(gatePath,owner.token);if(!await removeExpiredStaleCleanupGate(gatePath))return null;const recoveredOwner=await tryCreateStaleCleanupGate(gatePath);return recoveredOwner===null?null:async()=>releaseStaleCleanupGate(gatePath,recoveredOwner.token)}async function recordDeadLockRecovery(lockPath,raw){const directory=path.join(path.dirname(lockPath),"recoveries");await fs.mkdir(directory,{recursive:!0}),await fs.writeFile(path.join(directory,`${randomUUID()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:nowIso(),lock:JSON.parse(raw)})}
4
4
  `,{encoding:"utf8",flag:"wx",mode:384})}async function removeConfirmedStaleLock(params){const releaseCleanupGate=await acquireStaleCleanupGate(params.lockPath,params.id);if(releaseCleanupGate===null)return{lockInfo:params.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{const currentLockInfo=await readLockInfo(params.lockPath);if(currentLockInfo.info===null&&currentLockInfo.warnings.length===0)return{lockInfo:currentLockInfo,shouldRetryCreate:!0,staleRemovalCounted:!1};const ownerDead=await isConfirmedDeadLock(currentLockInfo.info);if(!isStaleLock(currentLockInfo.info,params.ttlSeconds)&&!ownerDead)return{lockInfo:currentLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};if(throwIfStaleLockNeedsForce(params.id,currentLockInfo,params.force||ownerDead,params.forceRequiredForStaleLock),params.staleRemovals>=MAX_STALE_LOCK_REMOVALS)throw await buildLockConflictError(params.id,currentLockInfo.info,performance.now()-params.startedAtMs);return ownerDead&&await recordDeadLockRecovery(params.lockPath,JSON.stringify(currentLockInfo.info)),{lockInfo:currentLockInfo,shouldRetryCreate:await unlinkLockWithHook(params.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await releaseCleanupGate()}}async function assertLockCreateContention(error,pmRoot,lockPath,id){if(error instanceof PmCliError&&error.code===LOCK_PATH_UNSAFE_CODE)throw error;if(!await isLockCreateContention(error,lockPath))throw new PmCliError(`Failed to acquire lock for ${id}: ${toErrorMessage(error)}`,EXIT_CODE.GENERIC_FAILURE);await assertLockEntryNotSymlink(pmRoot,lockPath,id)}const _testOnly={parseLockInfo,readLockInfo,isErrno,isLockCreateContention,buildLockPayload,isStaleLock,lockOwnerSuffix,resolveLockWaitMs,lockGenerationKey,parseLinuxProcessStartIdentity,readProcessStartIdentity,acquireStaleCleanupGate,removeConfirmedStaleLock};async function acquireLock(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){return(await acquireLockLease(pmRoot,id,ttlSeconds,owner,force,forceRequiredForStaleLock,waitMs,options)).release}async function acquireLockLease(pmRoot,id,ttlSeconds,owner,force=!1,forceRequiredForStaleLock=!0,waitMs,options={}){const maxWaitMs=parseNonNegativeIntegerWaitMs(options.maxWaitMs),lockOverride=await runActiveServiceOverride("lock_acquire",{pm_root:pmRoot,id,ttl_seconds:ttlSeconds,owner,force,force_required_for_stale_lock:forceRequiredForStaleLock,...maxWaitMs===void 0?{}:{max_wait_ms:maxWaitMs}});if(lockOverride.handled){const release=resolveLockOverrideRelease(lockOverride.result);if(release)return{release:async()=>{await Promise.resolve(release()),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>commit()}}const lockPath=getLockPath(pmRoot,id),waitBudgetMs=cappedLockWaitMs(waitMs,maxWaitMs),totalCeilingMs=resolveLockWaitCeilingMs(waitBudgetMs,maxWaitMs,options.waitPolicy),waitTracker=createLockWaitTracker(waitBudgetMs,totalCeilingMs),startedAtMs=waitTracker.startedAtMs;let staleRemovals=0,backoffMs=LOCK_WAIT_INITIAL_DELAY_MS;const token=randomUUID();for(;;)try{const acquiredAt=await createLockFile(pmRoot,lockPath,id,owner,ttlSeconds,token,options.createParentDirectories!==!1),lease={owner,token,acquiredAt,ttlSeconds};return{release:async()=>{await releaseOwnedLock(lockPath,id,owner,token),await runActiveServiceOverride("lock_release",{pm_root:pmRoot,id,owner})},fence:commit=>fenceOwnedLock(lockPath,id,lease,commit)}}catch(error){await assertLockCreateContention(error,pmRoot,lockPath,id);let lockInfo=await readLockInfo(lockPath);if(await isReclaimableLock(lockInfo.info,ttlSeconds)){const staleRemoval=await removeConfirmedStaleLock({lockPath,id,ttlSeconds,force,forceRequiredForStaleLock,staleRemovals,waitBudgetMs,startedAtMs,fallbackLockInfo:lockInfo});if(lockInfo=staleRemoval.lockInfo,staleRemoval.staleRemovalCounted&&(staleRemovals+=1),staleRemoval.shouldRetryCreate)continue}const observation=waitTracker.observe(lockInfo.info);if(observation.exhausted)throw await buildLockConflictError(id,lockInfo.info,waitBudgetMs===0?0:observation.elapsedMs,observation.ownerHandoffs);await sleepWithJitter(Math.min(backoffMs,observation.remainingMs)),backoffMs=Math.min(backoffMs*2,LOCK_WAIT_MAX_DELAY_MS)}}export{_testOnly,acquireLock,acquireLockLease,acquireStaleCleanupGate,captureProcessIdentity2 as captureProcessIdentity,hasUnexpiredLockOwner,isProcessIdentityAlive2 as isProcessIdentityAlive,readProcessStartIdentity2 as readProcessStartIdentity,recordDeadLockRecovery,waitForStaleCleanupGate};
@@ -57,7 +57,16 @@ declare function renderToonValue(value:unknown,depth:number):string;
57
57
  * extension overrides. SDK budget accounting uses this exact representation
58
58
  * so reported token cost describes the bytes the host emits by default.
59
59
  */
60
- export declare function formatBuiltInOutput(result:unknown,format:"json" | "toon",lean?:boolean):string;
60
+ export declare function formatBuiltInOutput(result:unknown,format:"json" | "toon",lean?:boolean,toon?:BuiltInToonOptions):string;
61
+ /** TOON presentation choices that depend on how the caller selected the result. */
62
+ export interface BuiltInToonOptions {
63
+ /**
64
+ * The result is an explicit `get --fields` selection: every collection its
65
+ * item carries was requested, so an empty one renders as `key: []` instead
66
+ * of being dropped by the sparse policy (pm-sj66lm).
67
+ */
68
+ preserveEmptyItemCollections?:boolean;
69
+ }
61
70
  /** Resolve command ownership and suppression before projecting and rendering the result. */
62
71
  export declare function formatOutput(result:unknown,options:OutputOptions):string;
63
72
  /** Apply declared exit codes and mutation projection before writing a nonquiet result. */
@@ -1,20 +1,20 @@
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]="d47af602-51bb-592c-8dce-3de5c8a96636")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadOutputBudgetExceeded,resolveReadOutputEncoding}from"../../sdk/read-output-contracts.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
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]="d32618bf-cced-5ea6-8741-ca596a643789")}catch{}})();import{getActiveCommandContext,runActiveCommandOverride,runActiveRendererOverride,runActiveServiceOverrideSync,setActiveCommandResult}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{isHostOutputSuppressed}from"./output-control.js";import{projectMutationResult}from"./mutation-projection.js";import{attachReadOutputContracts}from"../../sdk/context-intent-contracts.js";import{attachOutputTokenAccounting}from"../../sdk/output-token-accounting.js";import{propagateContextUsageServingReceipt}from"../../sdk/context-usage.js";import{isReadResultOmittedForBudget,resolveReadOutputEncoding}from"../../sdk/read-output-contracts.js";import{withDeliveredOutputRenderer}from"../../sdk/read-output-budget.js";import{encode as encodeToon}from"@toon-format/toon";import{encodePmTableRows}from"../../sdk/output/table-rows.js";import{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope}from"../../sdk/output/list-envelope.js";import{prepareWellFormedOutputText}from"../shared/output-unicode.js";const DECLARED_PROCESS_EXIT_CODES=new Set(Object.values(EXIT_CODE)),COLLECTION_COUNT_ALIASES=new Map([["notes_count","notes"],["tests_count","tests"]]),NATIVE_OUTPUT_MARKER="__pm_native_output";let streamErrorHandlersInstalled=!1;function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function setActiveCommandResultOmitted(source){const omitted={read_output:{result_omitted:!0}};propagateContextUsageServingReceipt(source,omitted),setActiveCommandResult(omitted)}function setActiveCommandDeliveryResult(result,receiptSource,structuredDeliveryPreserved){if(structuredDeliveryPreserved){setActiveCommandResult(result);return}setActiveCommandResultOmitted(receiptSource)}function stripNativeOutputMarker(result){if(!isPlainObject(result)||result[NATIVE_OUTPUT_MARKER]!==!0)return result;const{[NATIVE_OUTPUT_MARKER]:_marker,...rest}=result;return rest}function isBrokenPipeError(error){return typeof error=="object"&&error!==null&&error.code==="EPIPE"}function markStdoutBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.SUCCESS)}function markStderrBrokenPipeExitCode(){(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=EXIT_CODE.GENERIC_FAILURE)}function markBrokenPipeExitCode(target){if(target==="stdout"){markStdoutBrokenPipeExitCode();return}markStderrBrokenPipeExitCode()}function handleUnhandledStreamError(error){const unhandled=error instanceof Error?error:new Error(String(error));setImmediate(()=>{throw unhandled})}function installStreamErrorHandlers(){streamErrorHandlersInstalled||(streamErrorHandlersInstalled=!0,process.stdout.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stdout");return}handleUnhandledStreamError(error)}),process.stderr.on("error",error=>{if(isBrokenPipeError(error)){markBrokenPipeExitCode("stderr");return}handleUnhandledStreamError(error)}))}function writeToStream(target,text){installStreamErrorHandlers();try{return target==="stdout"?process.stdout.write(text):process.stderr.write(text),!0}catch(error){if(isBrokenPipeError(error))return markBrokenPipeExitCode(target),!1;throw error}}function writeStdout(text){return writeToStream("stdout",text)}function writeStderr(text){return writeToStream("stderr",text)}function renderScalar(value){return typeof value=="string"?JSON.stringify(value):typeof value=="number"||typeof value=="boolean"?String(value):value===null?"null":JSON.stringify(value)}function indentToon(encoded,depth){const indent=" ".repeat(depth);return encoded.split(`
2
2
  `).map(line=>`${indent}${line}`).join(`
3
- `)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
3
+ `)}function isNestedTableCandidateBounded(rows){const columns=new Set;let presentCells=0;for(const row of rows){const keys=Object.keys(row);presentCells+=keys.length;for(const key of keys)columns.add(key)}return rows.length*columns.size<=presentCells*2}function renderToonObjectEntry(key,entry,depth,allowNestedTable){const indent=" ".repeat(depth);if(!isPlainObject(entry)&&!Array.isArray(entry))return`${indent}${key}: ${renderScalar(entry)}`;if(key==="omission_receipt"&&isCompleteOmissionReceipt(entry))return`${indent}${key}: complete`;if(Array.isArray(entry)){if(entry.length===0)return`${indent}${key}: []`;const expanded=indentToon(encodeToon({[key]:entry}),depth);return allowNestedTable&&entry.length>=1&&entry.every(isPlainObject)&&isNestedTableCandidateBounded(entry)?[!1,!0].map(compact=>{const table=encodePmTableRows(entry,{compact});return indentToon(encodeToon({[key]:table.rows,[`${key}_encoding`]:table.encoding}),depth)}).reduce((smallest,candidate)=>Buffer.byteLength(candidate)<Buffer.byteLength(smallest)?candidate:smallest,expanded):expanded}return isPlainObject(entry)&&Object.keys(entry).length===0?`${indent}${key}: {}`:`${indent}${key}:
4
4
  ${renderToonValue(entry,depth+1)}`}function compactToonArray(values,policy,preserveEmpty){const compactedEntries=values.map(entry=>compactToonValue(entry,policy,preserveEmpty||policy.preserveRowFacts&&isPlainObject(entry))).filter(entry=>entry!==void 0);return compactedEntries.length>0||preserveEmpty?compactedEntries:void 0}function compactToonValue(value,policy={omitDuplicateCountAliases:!0,preserveRowFacts:!0},preserveEmpty=!1){if(value===null)return preserveEmpty?null:void 0;if(Array.isArray(value))return compactToonArray(value,policy,preserveEmpty);if(isPlainObject(value)){const compacted=[],entries=Object.entries(value).filter(([key,entry])=>{const canonicalCount=COLLECTION_COUNT_ALIASES.get(key);return!policy.omitDuplicateCountAliases||canonicalCount===void 0||!isPlainObject(value.collection_counts)||entry!==value.collection_counts[canonicalCount]});for(const[key,entry]of entries){if(key==="omitted_field_groups"&&Array.isArray(entry)&&entry.length===0){compacted.push([key,[]]);continue}const compactedEntry=compactToonValue(entry,policy,preserveEmpty);compactedEntry!==void 0&&compacted.push([key,compactedEntry])}return compacted.length>0||preserveEmpty?Object.fromEntries(compacted):void 0}return value}function renderToonValue(value,depth){const indent=" ".repeat(depth);if(Array.isArray(value))return value.length===0?"[]":indentToon(encodeToon(value),depth);if(isPlainObject(value)){const entries=Object.entries(value);return entries.length===0?"{}":entries.map(([key,entry])=>renderToonObjectEntry(key,entry,depth,!Object.hasOwn(value,`${key}_encoding`)&&!(key==="checks"&&isPlainObject(value.verdict)&&value.verdict.authority==="ok"))).join(`
5
5
  `)}return`${indent}${renderScalar(value)}`}function renderDefaultMarkdownResult(value){if(!isPlainObject(value)||value.output_default!=="markdown"||typeof value.view!="string"||!Array.isArray(value.events)||!Array.isArray(value.days))return null;const lines=[`# pm calendar (${value.view})`,""],summary=isPlainObject(value.summary)?value.summary:{};if(lines.push(`- events: ${String(summary.events??0)}`),lines.push(""),value.events.length===0)return lines.push("No calendar events matched the selected filters."),`${lines.join(`
6
6
  `)}
7
7
  `;for(const event of value.events){if(!isPlainObject(event))continue;const kind=typeof event.kind=="string"?event.kind:"event",title=typeof event.item_title=="string"?event.item_title:"",itemId=typeof event.item_id=="string"?event.item_id:"",reminderText=typeof event.reminder_text=="string"&&event.reminder_text.length>0?` ${event.reminder_text}`:"";lines.push(`- [${kind}] ${itemId} ${title}${reminderText}`.trim())}return`${lines.join(`
8
8
  `)}
9
- `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
10
- `}const compactedToon=compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return compactedToon===void 0?`{}
9
+ `}const LEAN_READ_ENVELOPE_ECHO_KEYS=new Set(["filters","now","projection","sorting"]);function projectLeanJsonValue(value){const compacted=compactToonValue(value,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!isPlainObject(compacted)||!Array.isArray(compacted.items))return compacted??null;const projected=Object.fromEntries(Object.entries(compacted).filter(([key])=>!LEAN_READ_ENVELOPE_ECHO_KEYS.has(key)));return projected.has_more!==!0&&delete projected.next_cursor,projected}function projectLinkedTestEvidence(value,lean){if(!isPlainObject(value)||!Array.isArray(value.run_results)||!value.run_results.every(isPlainObject))return value;const rows=value.run_results,sharedContext=resolveSharedExecutionContext(rows),runResults=rows.map(row=>{const{execution_context:_executionContext,stdout,stderr,...rest}=row;return sharedContext===void 0?row:!lean||row.status!=="passed"?{...rest,stdout,stderr}:rest});return lean&&isQuietLinkedTestSuccess(value,sharedContext,rows)?projectQuietLinkedTestSuccess(value,sharedContext,runResults):{...value,...sharedContext===void 0?{}:{execution_context:sharedContext},run_results:runResults}}function resolveSharedExecutionContext(rows){const contexts=rows.map(row=>row.execution_context).filter(context=>context!==void 0);if(contexts.length!==rows.length||contexts.length===0)return;const first=JSON.stringify(contexts[0]);return contexts.every(context=>JSON.stringify(context)===first)?contexts[0]:void 0}function isQuietLinkedTestSuccess(value,sharedContext,rows){if(value.ok!==!0||!isPlainObject(sharedContext)||sharedContext.mismatch_detected!==!1||!rows.every(row=>row.status==="passed"))return!1;const categories=value.failure_categories;return!(isPlainObject(categories)&&Object.values(categories).some(count=>count!==0))}function projectQuietLinkedTestSuccess(value,context,runResults){const{failure_categories:_zeroCategories,...rest}=value,trust=isPlainObject(context.trust)?context.trust:{};return{...rest,execution_context:{pm_context_mode:context.pm_context_mode,workspace_context_mode:context.workspace_context_mode,mismatch_detected:!1,...typeof trust.trusted=="boolean"?{trusted:trust.trusted}:{},...trust.reason===void 0?{}:{trust_reason:trust.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:runResults}}function projectEmptyCheckDetails(value){return!isPlainObject(value)||value.ok!==!0||!isPlainObject(value.verdict)||value.verdict.authority!=="ok"||!Array.isArray(value.checks)?value:{...value,checks:value.checks.map(omitEmptySuccessfulCheckDetails)}}function omitEmptySuccessfulCheckDetails(check){if(!isPlainObject(check)||check.ok!==!0||!isPlainObject(check.details)||Object.keys(check.details).length!==0)return check;const{details:_details,...rest}=check;return rest}function formatBuiltInOutput(result,format,lean=!1,toon={}){if(result=prepareWellFormedOutputText(result),format==="json"){const value=lean?projectLeanJsonValue(result):result,briefList=isPlainObject(result)&&isPlainObject(result.projection)&&result.projection.mode==="brief"&&Array.isArray(result.items);return`${JSON.stringify(value,null,briefList?void 0:2)}
10
+ `}const compactedToon=restoreRequestedEmptyItemCollections(result,compactToonValue(projectEmptyCheckDetails(projectPmBriefSearchEnvelope(projectPmBriefListEnvelope(result))),{omitDuplicateCountAliases:!0,preserveRowFacts:!0}),toon.preserveEmptyItemCollections===!0);return compactedToon===void 0?`{}
11
11
  `:`${renderToonValue(compactedToon,0)}
12
- `}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
12
+ `}function restoreRequestedEmptyItemCollections(source,compacted,preserve){if(!preserve||!isPlainObject(source)||!isPlainObject(source.item))return compacted;const base=isPlainObject(compacted)?compacted:{},compactedItem=isPlainObject(base.item)?base.item:{},item=Object.fromEntries(Object.entries(source.item).flatMap(([key,value])=>Object.hasOwn(compactedItem,key)?[[key,compactedItem[key]]]:Array.isArray(value)&&value.length===0?[[key,[]]]:isPlainObject(value)&&Object.keys(value).length===0?[[key,{}]]:[]));return Object.hasOwn(base,"item")?{...base,item}:{item,...base}}const COMPLETE_OMISSION_RECEIPT=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function isCompleteOmissionReceipt(value){const entries=Object.entries(Object(value)).sort(([left],[right])=>left.localeCompare(right));return JSON.stringify(Object.fromEntries(entries))===COMPLETE_OMISSION_RECEIPT}function resolveOutputService(effectiveResult,nativeOutput,options,format){const serviceOverride=nativeOutput?{handled:!1,result:effectiveResult,warnings:[]}:runActiveServiceOverrideSync("output_format",{command:options.command,args:options.commandArgs,command_options:options.commandOptions,global:{...options},pm_root:options.pmRoot,format,options:{...options},result:effectiveResult}),legacyPayloadEchoWarning=serviceOverride.warnings.find(warning=>warning.startsWith("extension_output_format_payload_echo_deprecated:"));return legacyPayloadEchoWarning!==void 0&&writeStderr(`Warning: ${legacyPayloadEchoWarning}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
13
13
  `),serviceOverride.handled&&typeof serviceOverride.result=="string"?{result:serviceOverride.result,rendered:serviceOverride.result.endsWith(`
14
14
  `)?serviceOverride.result:`${serviceOverride.result}
15
- `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format);if(service.rendered!==null)return setActiveCommandResultOmitted(effectiveResult),service.rendered;const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=command==="test"?projectLinkedTestEvidence(outputResult,options.lean===!0):outputResult,intentOutputResult=attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult);isReadOutputBudgetExceeded(intentOutputResult)&&(process.exitCode||=EXIT_CODE.USAGE);let{structuredDeliveryPreserved}=service;const renderResolvedOutput=value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return markdownDefault}const rendererOverride=nativeOutput?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?(structuredDeliveryPreserved=!1,rendererOverride.rendered.endsWith(`
15
+ `,structuredDeliveryPreserved:!1}:{result:serviceOverride.handled?serviceOverride.result:effectiveResult,rendered:null,structuredDeliveryPreserved:!serviceOverride.handled||isPlainObject(serviceOverride.result)}}function formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat){const activeCommandContext=getActiveCommandContext(),command=options.command??activeCommandContext?.command,commandOptions={...activeCommandContext?.options,...options.commandOptions,...Object.fromEntries([["outputInclude",options.outputInclude],["outputLimit",options.outputLimit],["outputBudget",options.outputBudget],["outputFormat",options.outputFormat],["outputSession",options.outputSession],["outputCursor",options.outputCursor],["outputRowContract",options.outputRowContract]].filter(entry=>entry[1]!==void 0))},format=resolveReadOutputEncoding(command??"",commandOptions)??defaultFormat,resolvedCommandOptions={...commandOptions,resolvedOutputFormat:format},effectiveOptions={...options,command,commandOptions:resolvedCommandOptions},service=resolveOutputService(effectiveResult,nativeOutput,effectiveOptions,format),renderNative=nativeRenderer(format,command,resolvedCommandOptions,options.lean===!0);if(service.rendered!==null)return deliverServiceRendering(service.rendered,{format,renderNative,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,effectiveResult),effectiveResult,quiet:options.quiet===!0});const outputResult=service.result;propagateContextUsageServingReceipt(effectiveResult,outputResult);const projectedOutputResult=command==="test"?projectLinkedTestEvidence(outputResult,options.lean===!0):outputResult;let nativeFallback=!1;return deliverContractedRead({format,contract:()=>attachReadOutputContracts(command,resolvedCommandOptions,projectedOutputResult),renderDelivered:value=>{if(format==="toon"){const markdownDefault=renderDefaultMarkdownResult(value);if(markdownDefault!==null)return{text:markdownDefault,custom:!1}}const rendererOverride=nativeOutput||nativeFallback||isReadResultOmittedForBudget(value)?{rendered:null}:runActiveRendererOverride(format,value);return rendererOverride.rendered!==null?{text:rendererOverride.rendered.endsWith(`
16
16
  `)?rendererOverride.rendered:`${rendererOverride.rendered}
17
- `):format==="json"?formatBuiltInOutput(value,"json",options.lean===!0):formatBuiltInOutput(value,"toon")},accountedOutputResult=options.tokenAccounting===!0?attachOutputTokenAccounting(intentOutputResult,renderResolvedOutput):intentOutputResult,rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,effectiveResult,options.quiet!==!0&&structuredDeliveryPreserved),rendered}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);if(setActiveCommandResult(effectiveResult),suppressedOutput)return setActiveCommandResultOmitted(effectiveResult),"";const defaultFormat=options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon";return formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat)}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const projected=options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0}),rendered=formatOutput(projected,options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
17
+ `,custom:!0}:{text:renderNative(value),custom:!1}},renderNative,useNativeRendering:()=>{nativeFallback=!0},structuredDeliveryPreserved:service.structuredDeliveryPreserved,tokenAccounting:options.tokenAccounting===!0,quiet:options.quiet===!0,effectiveResult})}function nativeRenderer(format,command,commandOptions,lean){if(format==="json")return value=>formatBuiltInOutput(value,"json",lean);const selectedFields=commandOptions.fields,preserveEmptyItemCollections=command==="get"&&typeof selectedFields=="string"&&selectedFields.trim().length>0;return value=>formatBuiltInOutput(value,"toon",!1,{preserveEmptyItemCollections})}function deliverServiceRendering(serviceRendered,delivery){const audited=withDeliveredOutputRenderer(delivery.format,value=>isReadResultOmittedForBudget(value)?delivery.renderNative(value):serviceRendered,delivery.contract);return isReadResultOmittedForBudget(audited)?(process.exitCode||=EXIT_CODE.USAGE,setActiveCommandDeliveryResult(audited,delivery.effectiveResult,!delivery.quiet),delivery.renderNative(audited)):(setActiveCommandResultOmitted(delivery.effectiveResult),serviceRendered)}function deliverContractedRead(delivery){let contracted=withDeliveredOutputRenderer(delivery.format,value=>delivery.renderDelivered(value).text,delivery.contract),unaccounted=delivery.renderDelivered(contracted);unaccounted.custom&&receiptsUnderstateDelivery(contracted,unaccounted.text)&&(delivery.useNativeRendering(),contracted=withDeliveredOutputRenderer(delivery.format,delivery.renderNative,delivery.contract),unaccounted={text:delivery.renderNative(contracted),custom:!1}),isReadResultOmittedForBudget(contracted)&&(process.exitCode||=EXIT_CODE.USAGE);let structuredDeliveryPreserved=delivery.structuredDeliveryPreserved&&!unaccounted.custom;if(!delivery.tokenAccounting)return setActiveCommandDeliveryResult(contracted,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),unaccounted.text;const renderResolvedOutput=value=>{const delivered=delivery.renderDelivered(value);return delivered.custom&&(structuredDeliveryPreserved=!1),delivered.text},accountedOutputResult=attachOutputTokenAccounting(contracted,renderResolvedOutput),rendered=renderResolvedOutput(accountedOutputResult);return setActiveCommandDeliveryResult(accountedOutputResult,delivery.effectiveResult,!delivery.quiet&&structuredDeliveryPreserved),rendered}const DELIVERED_TOKEN_RECEIPTS=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function receiptsUnderstateDelivery(value,text){const deliveredTokens=Math.ceil(Buffer.byteLength(text,"utf8")/4),record=Object(value);return DELIVERED_TOKEN_RECEIPTS.some(([receipt,field])=>{const section=record[receipt],estimate=isPlainObject(section)?section[field]:void 0;return typeof estimate=="number"&&estimate<deliveredTokens})}function formatOutput(result,options){const commandOverride=runActiveCommandOverride(result),suppressedOutput=isHostOutputSuppressed(commandOverride.result)?commandOverride.result:null,nativeResult=commandOverride.result,nativeOutput=isPlainObject(nativeResult)&&nativeResult[NATIVE_OUTPUT_MARKER]===!0,effectiveResult=suppressedOutput?suppressedOutput.result:stripNativeOutputMarker(commandOverride.result);if(setActiveCommandResult(effectiveResult),suppressedOutput)return setActiveCommandResultOmitted(effectiveResult),"";const defaultFormat=options.json===!0||options.json===void 0&&options.defaultOutputFormat==="json"?"json":"toon";return formatEffectiveOutput(effectiveResult,nativeOutput,options,defaultFormat)}function printResult(result,options){isPlainObject(result)&&Number.isInteger(result.exit_code)&&DECLARED_PROCESS_EXIT_CODES.has(Number(result.exit_code))&&(process.exitCode===void 0||process.exitCode===EXIT_CODE.SUCCESS)&&(process.exitCode=Number(result.exit_code));const projected=options.idOnly?projectMutationResult(result,{idOnly:!0}):options.fullChangedFields?result:options.noChangedFields?projectMutationResult(result,{changedFields:"compact"}):projectMutationResult(result,{compactEnvelope:!0}),rendered=formatOutput(projected,options);options.quiet||writeStdout(rendered)}function printError(message){const override=runActiveServiceOverrideSync("error_format",{message}),rendered=override.handled&&typeof override.result=="string"?override.result:message;writeStderr(rendered.endsWith(`
18
18
  `)?rendered:`${rendered}
19
19
  `)}const outputTestOnly={compactToonValue,renderToonValue};export{formatBuiltInOutput,formatOutput,outputTestOnly,printError,printResult,writeStderr,writeStdout};
20
20
  //# sourceMappingURL=output.js.map