@unbrained/pm-cli 2026.11.21 → 2026.11.23

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 (943) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/dist/cli/after-command-context-usage.js +1 -1
  4. package/dist/cli/argv-utils.js +1 -1
  5. package/dist/cli/bootstrap-args.js +1 -1
  6. package/dist/cli/bundle-integrity.js +2 -2
  7. package/dist/cli/command-namespaces.js +1 -1
  8. package/dist/cli/commander-usage.js +11 -11
  9. package/dist/cli/commands/annotations/comments.js +1 -1
  10. package/dist/cli/commands/annotations/docs.js +1 -1
  11. package/dist/cli/commands/annotations/files.js +1 -1
  12. package/dist/cli/commands/annotations/learnings.js +1 -1
  13. package/dist/cli/commands/annotations/notes.js +1 -1
  14. package/dist/cli/commands/extension/describe.js +1 -1
  15. package/dist/cli/commands/extension/extension.js +1 -1
  16. package/dist/cli/commands/extension/scaffold.js +1 -1
  17. package/dist/cli/commands/extension/shared.js +1 -1
  18. package/dist/cli/commands/governance/gc.js +1 -1
  19. package/dist/cli/commands/governance/health.js +1 -1
  20. package/dist/cli/commands/governance/telemetry.js +1 -1
  21. package/dist/cli/commands/governance/validate.js +1 -1
  22. package/dist/cli/commands/history/activity.js +1 -1
  23. package/dist/cli/commands/history/history-compact.js +1 -1
  24. package/dist/cli/commands/history/history-redact.js +1 -1
  25. package/dist/cli/commands/history/history-repair.js +1 -1
  26. package/dist/cli/commands/history/history.js +1 -1
  27. package/dist/cli/commands/history/restore.js +1 -1
  28. package/dist/cli/commands/lifecycle/append.js +1 -1
  29. package/dist/cli/commands/lifecycle/claim.js +1 -1
  30. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  31. package/dist/cli/commands/lifecycle/close.js +1 -1
  32. package/dist/cli/commands/lifecycle/copy.js +1 -1
  33. package/dist/cli/commands/lifecycle/create.js +1 -1
  34. package/dist/cli/commands/lifecycle/delete.js +1 -1
  35. package/dist/cli/commands/lifecycle/focus.js +1 -1
  36. package/dist/cli/commands/lifecycle/plan.js +1 -1
  37. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  38. package/dist/cli/commands/lifecycle/update.js +1 -1
  39. package/dist/cli/commands/query/aggregate.js +1 -1
  40. package/dist/cli/commands/query/context.js +1 -1
  41. package/dist/cli/commands/query/deps.js +1 -1
  42. package/dist/cli/commands/query/duplicates.js +1 -1
  43. package/dist/cli/commands/query/eval.js +1 -1
  44. package/dist/cli/commands/query/get.js +1 -1
  45. package/dist/cli/commands/query/graph.js +1 -1
  46. package/dist/cli/commands/query/list.js +1 -1
  47. package/dist/cli/commands/query/next.js +1 -1
  48. package/dist/cli/commands/query/search.js +1 -1
  49. package/dist/cli/commands/query/stats.js +1 -1
  50. package/dist/cli/commands/test/test-all.js +1 -1
  51. package/dist/cli/commands/test/test-runs.js +1 -1
  52. package/dist/cli/commands/test/test.js +1 -1
  53. package/dist/cli/commands/workspace/config.js +1 -1
  54. package/dist/cli/commands/workspace/contracts.js +1 -1
  55. package/dist/cli/commands/workspace/init.js +1 -1
  56. package/dist/cli/commands/workspace/merge.js +1 -1
  57. package/dist/cli/commands/workspace/profile.js +1 -1
  58. package/dist/cli/commands/workspace/schema.js +1 -1
  59. package/dist/cli/commands/workspace/upgrade.js +1 -1
  60. package/dist/cli/context-intent-invocation.js +1 -1
  61. package/dist/cli/description-stdin.js +1 -1
  62. package/dist/cli/error-guidance.js +5 -5
  63. package/dist/cli/expected-revisions.js +1 -1
  64. package/dist/cli/extension-command-help.js +6 -6
  65. package/dist/cli/extension-recovery.js +1 -1
  66. package/dist/cli/help-content.js +5 -5
  67. package/dist/cli/help-json-payload.js +7 -7
  68. package/dist/cli/invocation-profile.js +2 -2
  69. package/dist/cli/main.js +5 -5
  70. package/dist/cli/migration-gates.js +1 -1
  71. package/dist/cli/option-values.js +1 -1
  72. package/dist/cli/preflight-warnings.js +3 -3
  73. package/dist/cli/public.js +1 -1
  74. package/dist/cli/register-annotations.js +1 -1
  75. package/dist/cli/register-assurance.js +1 -1
  76. package/dist/cli/register-files-lookup.js +1 -1
  77. package/dist/cli/register-history-activity.js +1 -1
  78. package/dist/cli/register-history-author.js +1 -1
  79. package/dist/cli/register-history-maintenance.js +2 -2
  80. package/dist/cli/register-list-query.js +10 -10
  81. package/dist/cli/register-mutation-options.js +0 -1
  82. package/dist/cli/register-mutation.js +6 -6
  83. package/dist/cli/register-operations.js +1 -1
  84. package/dist/cli/register-setup.js +1 -1
  85. package/dist/cli/register-structured-mutation.js +1 -1
  86. package/dist/cli/registration-helpers.js +1 -1
  87. package/dist/cli/runtime/activation.js +1 -1
  88. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  89. package/dist/cli/runtime/close-fields-retry.js +1 -1
  90. package/dist/cli/runtime/field-route-retry.js +1 -1
  91. package/dist/cli/runtime/invocation-options.js +1 -1
  92. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  93. package/dist/cli/runtime/projection-retry.js +1 -1
  94. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  95. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  96. package/dist/cli/runtime/selection.js +1 -1
  97. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  98. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  99. package/dist/cli/schema/registration.js +15 -15
  100. package/dist/cli/schema-registration-helpers.js +1 -1
  101. package/dist/cli/search-refresh.js +1 -1
  102. package/dist/cli/stats-analytics-json.js +1 -1
  103. package/dist/cli/telemetry-flush.js +1 -1
  104. package/dist/cli-bundle/bundle-manifest.json +1 -1
  105. package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  108. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  110. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AEOHUSUI.js +2289 -0
  112. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  113. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  114. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  115. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  116. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  117. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  120. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  122. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  123. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  124. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  125. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  126. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  129. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  130. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  132. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  133. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  135. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  136. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  137. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  138. package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-FMD4KWBB.js} +2 -2
  139. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  141. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  142. package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-L4IBU64P.js} +11 -11
  143. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  144. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  145. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  146. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  147. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  178. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  179. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  180. package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-YDACCDVY.js} +2 -2
  181. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  184. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  185. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  186. package/dist/cli-bundle/main.js +27 -27
  187. package/dist/cli-bundle/sdk-authoring.js +1 -1
  188. package/dist/cli-bundle/sdk-contracts.js +5 -5
  189. package/dist/cli-bundle/sdk-core.js +1 -1
  190. package/dist/cli-bundle/sdk-governance.js +1 -1
  191. package/dist/cli-bundle/sdk-graph.js +1 -1
  192. package/dist/cli-bundle/sdk-merge.js +72 -60
  193. package/dist/cli-bundle/sdk-query.js +1 -1
  194. package/dist/cli-bundle/sdk-runtime.js +1 -1
  195. package/dist/cli-bundle/sdk-testing.js +1 -1
  196. package/dist/cli-bundle/sdk.js +13 -13
  197. package/dist/cli.js +1 -1
  198. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  199. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  200. package/dist/core/checkpoint/mutation-context.js +1 -1
  201. package/dist/core/config/nested-settings.js +1 -1
  202. package/dist/core/config/positional-value.js +1 -1
  203. package/dist/core/diagnostics/remediation.js +1 -1
  204. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  205. package/dist/core/extensions/activation-summary.js +1 -1
  206. package/dist/core/extensions/activation-transaction.js +1 -1
  207. package/dist/core/extensions/capability-usage.js +1 -1
  208. package/dist/core/extensions/command-hook-context.js +1 -1
  209. package/dist/core/extensions/command-metadata-contract.js +1 -1
  210. package/dist/core/extensions/command-visibility-tier.js +1 -1
  211. package/dist/core/extensions/contribution-inventory.js +1 -1
  212. package/dist/core/extensions/exporter-output-contract.js +1 -1
  213. package/dist/core/extensions/extension-candidate.js +1 -1
  214. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  215. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  216. package/dist/core/extensions/extension-policy.js +1 -1
  217. package/dist/core/extensions/extension-registries.js +1 -1
  218. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  219. package/dist/core/extensions/extension-types.js +1 -1
  220. package/dist/core/extensions/flag-definition-validation.js +1 -1
  221. package/dist/core/extensions/flag-value-types.js +1 -1
  222. package/dist/core/extensions/index.js +1 -1
  223. package/dist/core/extensions/item-field-types.js +1 -1
  224. package/dist/core/extensions/item-fields.js +1 -1
  225. package/dist/core/extensions/loader.js +1 -1
  226. package/dist/core/extensions/manifest-parser.js +1 -1
  227. package/dist/core/extensions/manifest-schema.js +1 -1
  228. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  230. package/dist/core/extensions/mutation-actor.js +1 -1
  231. package/dist/core/extensions/preflight-ownership.js +1 -1
  232. package/dist/core/extensions/read-output-contract.js +1 -1
  233. package/dist/core/extensions/registration-contracts.js +1 -1
  234. package/dist/core/extensions/registration-validation.js +1 -1
  235. package/dist/core/extensions/registration-values.js +1 -1
  236. package/dist/core/extensions/reserved-host-flags.js +1 -1
  237. package/dist/core/extensions/runtime-registrations.js +1 -1
  238. package/dist/core/extensions/service-ownership.js +1 -1
  239. package/dist/core/extensions/version-compat.js +1 -1
  240. package/dist/core/extensions/version-diagnostics.js +1 -1
  241. package/dist/core/fs/atomic-create.js +1 -1
  242. package/dist/core/fs/file-glob.js +1 -1
  243. package/dist/core/fs/fs-utils.js +2 -2
  244. package/dist/core/fs/host-environment-errors.js +1 -1
  245. package/dist/core/fs/index.js +1 -1
  246. package/dist/core/fs/path-utils.js +1 -1
  247. package/dist/core/governance/content-fields.js +1 -1
  248. package/dist/core/governance/issue-codes.js +1 -1
  249. package/dist/core/governance/metadata-coverage.js +1 -1
  250. package/dist/core/history/bridge.js +2 -0
  251. package/dist/core/history/digest.js +1 -1
  252. package/dist/core/history/drift-cache.js +3 -3
  253. package/dist/core/history/drift-scan.js +1 -1
  254. package/dist/core/history/event-classification.js +1 -1
  255. package/dist/core/history/event-index.js +11 -11
  256. package/dist/core/history/history-compact-bulk.js +1 -1
  257. package/dist/core/history/history-diff.js +1 -1
  258. package/dist/core/history/history-rewrite.js +1 -1
  259. package/dist/core/history/history-storage-stats.js +1 -1
  260. package/dist/core/history/history-stream-policy.js +1 -1
  261. package/dist/core/history/history.d.ts +12 -0
  262. package/dist/core/history/history.js +2 -2
  263. package/dist/core/history/identity.js +1 -1
  264. package/dist/core/history/index.js +1 -1
  265. package/dist/core/history/operation-contract.js +1 -1
  266. package/dist/core/history/projection.js +1 -1
  267. package/dist/core/history/read.d.ts +9 -0
  268. package/dist/core/history/read.js +1 -1
  269. package/dist/core/history/replay.d.ts +46 -5
  270. package/dist/core/history/replay.js +2 -2
  271. package/dist/core/history/stream-summary.js +2 -2
  272. package/dist/core/history/tombstone.js +1 -1
  273. package/dist/core/history/version-address.js +1 -1
  274. package/dist/core/history/workspace-history.js +2 -2
  275. package/dist/core/io/body-file.js +1 -1
  276. package/dist/core/io/bulk-ids-input.js +2 -2
  277. package/dist/core/item/actionability.js +1 -1
  278. package/dist/core/item/deferred-fields.js +1 -1
  279. package/dist/core/item/dependency-reference.js +1 -1
  280. package/dist/core/item/id.js +1 -1
  281. package/dist/core/item/index.js +1 -1
  282. package/dist/core/item/item-format-version.js +1 -1
  283. package/dist/core/item/item-format.js +7 -7
  284. package/dist/core/item/item-record.js +1 -1
  285. package/dist/core/item/item-type-definition.js +1 -1
  286. package/dist/core/item/literal-mutation-input.js +1 -1
  287. package/dist/core/item/parent-reference-policy.js +1 -1
  288. package/dist/core/item/parse.js +8 -8
  289. package/dist/core/item/plan-lifecycle.js +1 -1
  290. package/dist/core/item/priority.js +1 -1
  291. package/dist/core/item/sprint-release-format.js +1 -1
  292. package/dist/core/item/status-filter.js +1 -1
  293. package/dist/core/item/status.js +1 -1
  294. package/dist/core/item/toon-decode.js +1 -1
  295. package/dist/core/item/type-registry.js +1 -1
  296. package/dist/core/item/type-synonyms.js +1 -1
  297. package/dist/core/lock/index.js +1 -1
  298. package/dist/core/lock/lock-confinement.js +1 -1
  299. package/dist/core/lock/lock-gc.js +1 -1
  300. package/dist/core/lock/lock-owner.js +1 -1
  301. package/dist/core/lock/lock.js +4 -4
  302. package/dist/core/output/linked-test-projection.js +5 -5
  303. package/dist/core/output/mutation-projection.js +1 -1
  304. package/dist/core/output/output-control.js +1 -1
  305. package/dist/core/output/output.js +19 -19
  306. package/dist/core/output/query-summary.js +1 -1
  307. package/dist/core/output/tabular.js +3 -3
  308. package/dist/core/packages/manifest.js +1 -1
  309. package/dist/core/packages/root.js +1 -1
  310. package/dist/core/policy/workflow-policy-schema.js +1 -1
  311. package/dist/core/policy/workflow-policy-store.js +1 -1
  312. package/dist/core/policy/workflow-policy.js +1 -1
  313. package/dist/core/profile/profile-describe.js +1 -1
  314. package/dist/core/profile/profile-lint.d.ts +1 -1
  315. package/dist/core/profile/profile-lint.js +1 -1
  316. package/dist/core/profile/profile-plan.js +1 -1
  317. package/dist/core/profile/profile-presets.js +4 -4
  318. package/dist/core/reproducibility/context.js +1 -1
  319. package/dist/core/schema/fields-file.js +2 -2
  320. package/dist/core/schema/item-types-file.js +2 -2
  321. package/dist/core/schema/runtime-field-filters.js +1 -1
  322. package/dist/core/schema/runtime-field-values.js +1 -1
  323. package/dist/core/schema/runtime-schema.js +2 -2
  324. package/dist/core/schema/status-defs-file.js +2 -2
  325. package/dist/core/schema/status-token.js +1 -1
  326. package/dist/core/schema/type-inference.js +1 -1
  327. package/dist/core/schema/type-presets.js +1 -1
  328. package/dist/core/schema/type-workflows.js +1 -1
  329. package/dist/core/search/background-refresh.js +2 -2
  330. package/dist/core/search/bm25.js +1 -1
  331. package/dist/core/search/cache.js +2 -2
  332. package/dist/core/search/corpus.js +1 -1
  333. package/dist/core/search/embedding-batches.js +1 -1
  334. package/dist/core/search/eval-thresholds.js +1 -1
  335. package/dist/core/search/eval.js +1 -1
  336. package/dist/core/search/http-client.js +1 -1
  337. package/dist/core/search/providers.js +1 -1
  338. package/dist/core/search/relevance.js +1 -1
  339. package/dist/core/search/semantic-defaults.js +1 -1
  340. package/dist/core/search/staleness.js +1 -1
  341. package/dist/core/search/vector-stores.js +2 -2
  342. package/dist/core/search/vectorization-metadata.js +1 -1
  343. package/dist/core/sentry/helpers.js +1 -1
  344. package/dist/core/sentry/instrument.js +1 -1
  345. package/dist/core/sentry/sensitive-assignments.js +1 -1
  346. package/dist/core/session/session-state.js +1 -1
  347. package/dist/core/shared/agent-session-context.js +1 -1
  348. package/dist/core/shared/author.js +5 -5
  349. package/dist/core/shared/command-line.js +1 -1
  350. package/dist/core/shared/command-types.js +0 -1
  351. package/dist/core/shared/conflict-markers.js +1 -1
  352. package/dist/core/shared/constants.js +1 -1
  353. package/dist/core/shared/error-details.js +1 -1
  354. package/dist/core/shared/errors.js +1 -1
  355. package/dist/core/shared/html-entity-decode.js +1 -1
  356. package/dist/core/shared/index.js +1 -1
  357. package/dist/core/shared/item-metadata-contract.js +1 -1
  358. package/dist/core/shared/lazy-module.js +1 -1
  359. package/dist/core/shared/levenshtein.js +1 -1
  360. package/dist/core/shared/memo.js +1 -1
  361. package/dist/core/shared/numeric-parsers.js +1 -1
  362. package/dist/core/shared/option-alias-visibility.js +1 -1
  363. package/dist/core/shared/output-unicode.js +1 -1
  364. package/dist/core/shared/primitives.js +1 -1
  365. package/dist/core/shared/process-tree.js +2 -2
  366. package/dist/core/shared/secret-rules.js +5 -5
  367. package/dist/core/shared/serial-queue.js +1 -1
  368. package/dist/core/shared/serialization.js +1 -1
  369. package/dist/core/shared/split-comma-list.js +1 -1
  370. package/dist/core/shared/text-normalization.js +1 -1
  371. package/dist/core/shared/time.js +2 -2
  372. package/dist/core/shared/url-credentials.js +1 -1
  373. package/dist/core/store/index.js +1 -1
  374. package/dist/core/store/item-format-migration.js +1 -1
  375. package/dist/core/store/item-metadata-cache.js +1 -1
  376. package/dist/core/store/item-metadata-query-index.js +11 -11
  377. package/dist/core/store/item-metadata-read-work.js +1 -1
  378. package/dist/core/store/item-mutation-precondition.js +1 -1
  379. package/dist/core/store/item-store.js +1 -1
  380. package/dist/core/store/paths.js +1 -1
  381. package/dist/core/store/settings-concurrency.js +1 -1
  382. package/dist/core/store/settings-read-cache.js +1 -1
  383. package/dist/core/store/settings-sections.js +2 -2
  384. package/dist/core/store/settings-validator.js +1 -1
  385. package/dist/core/store/settings.d.ts +3 -1
  386. package/dist/core/store/settings.js +6 -6
  387. package/dist/core/store/sqlite-runtime.js +1 -1
  388. package/dist/core/store/tracker-preflight.js +1 -1
  389. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  390. package/dist/core/telemetry/consent.js +3 -3
  391. package/dist/core/telemetry/observability.js +1 -1
  392. package/dist/core/telemetry/policy.js +1 -1
  393. package/dist/core/telemetry/read-sampling.js +2 -2
  394. package/dist/core/telemetry/runtime.js +9 -9
  395. package/dist/core/test/background-runs.js +4 -4
  396. package/dist/core/test/item-test-run-tracking.js +1 -1
  397. package/dist/core/test/run-selectors.js +1 -1
  398. package/dist/core/validate/estimate-defaults.js +1 -1
  399. package/dist/core/validate/fix-planning.js +1 -1
  400. package/dist/core/validate/linked-artifact-reference.js +1 -1
  401. package/dist/core/validate/missing-by-type.js +1 -1
  402. package/dist/core/validate/missing-link-owners.js +1 -1
  403. package/dist/core/validate/stale-file-classification.js +1 -1
  404. package/dist/mcp/http-server.js +5 -5
  405. package/dist/mcp/legacy-adapter.js +1 -1
  406. package/dist/mcp/runtime-capabilities.js +1 -1
  407. package/dist/mcp/server.js +4 -4
  408. package/dist/mcp/tool-definitions.js +1 -1
  409. package/dist/sdk/actionability.js +1 -1
  410. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  411. package/dist/sdk/agent/command-recovery.js +1 -1
  412. package/dist/sdk/agent/command-suggestions.js +1 -1
  413. package/dist/sdk/agent/create-option-policy.js +1 -1
  414. package/dist/sdk/agent/identity-config.js +1 -1
  415. package/dist/sdk/agent/item-addressing.js +1 -1
  416. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  417. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  418. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  419. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  420. package/dist/sdk/agent-capability-contracts.js +3 -3
  421. package/dist/sdk/agent-session-context.js +1 -1
  422. package/dist/sdk/annotations.js +1 -1
  423. package/dist/sdk/author-attribution.js +1 -1
  424. package/dist/sdk/cli-bootstrap.js +1 -1
  425. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  426. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  427. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  428. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  430. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  431. package/dist/sdk/cli-contracts/completeness.js +1 -1
  432. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  433. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  435. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  436. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  437. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  438. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  439. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  440. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  442. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  443. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  444. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  445. package/dist/sdk/cli-contracts.js +1 -1
  446. package/dist/sdk/cli-program.js +1 -1
  447. package/dist/sdk/command-line.js +1 -1
  448. package/dist/sdk/comments.js +1 -1
  449. package/dist/sdk/compile-cache.js +1 -1
  450. package/dist/sdk/completion/bash.js +2 -2
  451. package/dist/sdk/completion/fish.js +74 -73
  452. package/dist/sdk/completion/shared.js +1 -1
  453. package/dist/sdk/completion/zsh.js +77 -76
  454. package/dist/sdk/completion.js +1 -1
  455. package/dist/sdk/config.js +1 -1
  456. package/dist/sdk/context/recency.js +1 -1
  457. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  458. package/dist/sdk/context/usage-egress.js +1 -1
  459. package/dist/sdk/context/usage-ledger.js +6 -6
  460. package/dist/sdk/context-intent-contracts.js +1 -1
  461. package/dist/sdk/context-intent-runtime.js +1 -1
  462. package/dist/sdk/context-packing.js +1 -1
  463. package/dist/sdk/context-relevance.js +1 -1
  464. package/dist/sdk/context-signal-store.js +2 -2
  465. package/dist/sdk/context-usage.js +1 -1
  466. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  467. package/dist/sdk/dependencies.js +1 -1
  468. package/dist/sdk/dependency-flag-validation.js +1 -1
  469. package/dist/sdk/dependency-provenance.js +1 -1
  470. package/dist/sdk/docs.js +1 -1
  471. package/dist/sdk/duplicates.js +1 -1
  472. package/dist/sdk/environment/host-environment-errors.js +1 -1
  473. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  474. package/dist/sdk/environment/source-context.js +1 -1
  475. package/dist/sdk/environment/tracker-preflight.js +1 -1
  476. package/dist/sdk/error-code-catalog.js +1 -1
  477. package/dist/sdk/error-runtime.js +1 -1
  478. package/dist/sdk/errors.js +1 -1
  479. package/dist/sdk/eval.js +1 -1
  480. package/dist/sdk/extension/author-manifest.js +1 -1
  481. package/dist/sdk/extension/bundled-catalog.js +1 -1
  482. package/dist/sdk/extension/command-options.js +1 -1
  483. package/dist/sdk/extension/concurrency.js +1 -1
  484. package/dist/sdk/extension/copy-scope.js +1 -1
  485. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  486. package/dist/sdk/extension/describe.js +3 -3
  487. package/dist/sdk/extension/doctor.js +1 -1
  488. package/dist/sdk/extension/install-plan.js +1 -1
  489. package/dist/sdk/extension/install-receipts.js +1 -1
  490. package/dist/sdk/extension/install-runtime.js +3 -3
  491. package/dist/sdk/extension/install-snapshot.js +1 -1
  492. package/dist/sdk/extension/install-sources.js +5 -5
  493. package/dist/sdk/extension/managed-state.js +2 -2
  494. package/dist/sdk/extension/managed-update-status.js +1 -1
  495. package/dist/sdk/extension/migrations.js +2 -2
  496. package/dist/sdk/extension/native-command-options.js +1 -1
  497. package/dist/sdk/extension/output-ownership.js +1 -1
  498. package/dist/sdk/extension/runtime-summary.js +1 -1
  499. package/dist/sdk/extension/scaffold.js +11 -11
  500. package/dist/sdk/extension/shared.js +1 -1
  501. package/dist/sdk/extension/source-resolution.js +1 -1
  502. package/dist/sdk/extension/static-inventory.js +1 -1
  503. package/dist/sdk/extension/update-check.js +1 -1
  504. package/dist/sdk/extension-command-context.js +2 -2
  505. package/dist/sdk/extension-contracts.js +1 -1
  506. package/dist/sdk/extension.js +1 -1
  507. package/dist/sdk/files.js +1 -1
  508. package/dist/sdk/flag-invocation-contracts.js +1 -1
  509. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  510. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  511. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  512. package/dist/sdk/generated-error-code-catalog.js +1 -1
  513. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  514. package/dist/sdk/governance/assurance-action.js +1 -1
  515. package/dist/sdk/governance/assurance-limits.js +1 -1
  516. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  517. package/dist/sdk/governance/assurance-presets.js +1 -1
  518. package/dist/sdk/governance/assurance-runtime.js +1 -1
  519. package/dist/sdk/governance/assurance.js +4 -4
  520. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  521. package/dist/sdk/governance/closure-timestamps.js +1 -1
  522. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  523. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  524. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  525. package/dist/sdk/governance/defect-recurrence.js +2 -2
  526. package/dist/sdk/governance/extension-host-version.js +1 -1
  527. package/dist/sdk/governance/gc.js +1 -1
  528. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  529. package/dist/sdk/governance/health/projection.js +1 -1
  530. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  531. package/dist/sdk/governance/health.js +2 -2
  532. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  533. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  534. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  535. package/dist/sdk/governance/linked-file-report.js +1 -1
  536. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  537. package/dist/sdk/governance/provenance-health.js +4 -4
  538. package/dist/sdk/governance/reindex.js +5 -5
  539. package/dist/sdk/governance/stale-work.js +1 -1
  540. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  541. package/dist/sdk/governance/storage-integrity.js +1 -1
  542. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  543. package/dist/sdk/governance/upgrade.js +2 -2
  544. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  545. package/dist/sdk/governance/validate-history-drift.js +1 -1
  546. package/dist/sdk/governance/validate-item-reader.js +1 -1
  547. package/dist/sdk/governance/validate-normalization.js +1 -1
  548. package/dist/sdk/governance/validate.js +1 -1
  549. package/dist/sdk/governance/workflow-completeness.js +1 -1
  550. package/dist/sdk/governance/workflow-policy.js +3 -3
  551. package/dist/sdk/governance/workspace-position.js +2 -2
  552. package/dist/sdk/graph/analytics.js +1 -1
  553. package/dist/sdk/graph/assembly.js +1 -1
  554. package/dist/sdk/graph/cache.js +1 -1
  555. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  556. package/dist/sdk/graph/centrality.js +1 -1
  557. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  558. package/dist/sdk/graph/durable-cache.js +1 -1
  559. package/dist/sdk/graph/governance-contracts.js +1 -1
  560. package/dist/sdk/graph/governance.js +1 -1
  561. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  562. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  563. package/dist/sdk/graph/mutation-advisory.js +1 -1
  564. package/dist/sdk/graph/query-contracts.js +1 -1
  565. package/dist/sdk/graph/remediation.js +1 -1
  566. package/dist/sdk/graph/run.js +1 -1
  567. package/dist/sdk/graph/scheduling.js +1 -1
  568. package/dist/sdk/graph/traversal.js +1 -1
  569. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  570. package/dist/sdk/guide-topics.js +1 -1
  571. package/dist/sdk/guide.js +7 -7
  572. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  573. package/dist/sdk/history/append-only-repair.js +6 -0
  574. package/dist/sdk/history/attestation-command.js +2 -2
  575. package/dist/sdk/history/attestation-contract.js +1 -1
  576. package/dist/sdk/history/attestation-scan.js +1 -1
  577. package/dist/sdk/history/attestation.js +1 -1
  578. package/dist/sdk/history/maintenance.d.ts +8 -2
  579. package/dist/sdk/history/maintenance.js +1 -1
  580. package/dist/sdk/history/reanchor-refusal.js +2 -0
  581. package/dist/sdk/history/reseed.d.ts +15 -0
  582. package/dist/sdk/history/reseed.js +2 -0
  583. package/dist/sdk/history/salvage.d.ts +19 -8
  584. package/dist/sdk/history/salvage.js +5 -3
  585. package/dist/sdk/history/subject.js +1 -1
  586. package/dist/sdk/history-analytics.js +1 -1
  587. package/dist/sdk/history-compact.js +1 -1
  588. package/dist/sdk/history-mcp.js +1 -1
  589. package/dist/sdk/history-provenance.js +1 -1
  590. package/dist/sdk/history-read.js +1 -1
  591. package/dist/sdk/history-redact.js +1 -1
  592. package/dist/sdk/history-repair.d.ts +8 -2
  593. package/dist/sdk/history-repair.js +1 -1
  594. package/dist/sdk/improvement-ledger-validation.js +1 -1
  595. package/dist/sdk/improvement-ledger.js +2 -2
  596. package/dist/sdk/index.d.ts +1 -1
  597. package/dist/sdk/init-agent-guidance.js +10 -10
  598. package/dist/sdk/init.js +14 -14
  599. package/dist/sdk/invocation-author.js +1 -1
  600. package/dist/sdk/item-children.js +1 -1
  601. package/dist/sdk/item-metadata-index.js +1 -1
  602. package/dist/sdk/item-schedule.js +1 -1
  603. package/dist/sdk/item-transaction.d.ts +33 -1
  604. package/dist/sdk/item-transaction.js +1 -1
  605. package/dist/sdk/learnings.js +1 -1
  606. package/dist/sdk/lifecycle/append.js +3 -3
  607. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  608. package/dist/sdk/lifecycle/claim.js +1 -1
  609. package/dist/sdk/lifecycle/cli-input.js +1 -1
  610. package/dist/sdk/lifecycle/close-many.js +1 -1
  611. package/dist/sdk/lifecycle/close.js +1 -1
  612. package/dist/sdk/lifecycle/copy.js +1 -1
  613. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  614. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  615. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  616. package/dist/sdk/lifecycle/create.js +1 -1
  617. package/dist/sdk/lifecycle/delete.js +1 -1
  618. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  619. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  620. package/dist/sdk/lifecycle/focus.js +1 -1
  621. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  622. package/dist/sdk/lifecycle/item-revision.js +1 -1
  623. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  624. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  625. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  626. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  627. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  628. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  630. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  631. package/dist/sdk/lifecycle/plan.js +1 -1
  632. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  633. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  634. package/dist/sdk/lifecycle/reopen.js +1 -1
  635. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  636. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  637. package/dist/sdk/lifecycle/restore.js +1 -1
  638. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  639. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  640. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  641. package/dist/sdk/lifecycle/task-composition.js +1 -1
  642. package/dist/sdk/lifecycle/update-many.js +1 -1
  643. package/dist/sdk/lifecycle/update.js +2 -2
  644. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  645. package/dist/sdk/lifecycle-completion.js +1 -1
  646. package/dist/sdk/lifecycle-policy.js +1 -1
  647. package/dist/sdk/linked-artifacts.js +2 -2
  648. package/dist/sdk/mcp/apps.js +5 -5
  649. package/dist/sdk/mcp/authorization.js +1 -1
  650. package/dist/sdk/mcp/discovery.js +1 -1
  651. package/dist/sdk/mcp/executable.js +4 -4
  652. package/dist/sdk/mcp/interactions.js +1 -1
  653. package/dist/sdk/mcp/protocol.js +1 -1
  654. package/dist/sdk/mcp/skills.js +3 -3
  655. package/dist/sdk/mcp/subscriptions.js +1 -1
  656. package/dist/sdk/mcp/tasks.js +2 -2
  657. package/dist/sdk/mcp/transport.js +1 -1
  658. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  659. package/dist/sdk/merge/driver.js +7 -7
  660. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  661. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  662. package/dist/sdk/merge/index.js +1 -1
  663. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  664. package/dist/sdk/merge/install.js +6 -6
  665. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  666. package/dist/sdk/merge/receipt-operation.js +1 -1
  667. package/dist/sdk/merge/receipt-schema.js +1 -1
  668. package/dist/sdk/merge/receipts.js +4 -4
  669. package/dist/sdk/merge/reconcile.js +1 -1
  670. package/dist/sdk/merge/settlement-hook.js +4 -4
  671. package/dist/sdk/merge/stage.js +1 -1
  672. package/dist/sdk/merge/three-way.d.ts +22 -3
  673. package/dist/sdk/merge/three-way.js +9 -3
  674. package/dist/sdk/merge/worktree-config.js +2 -2
  675. package/dist/sdk/merge.js +1 -1
  676. package/dist/sdk/mutation-events.js +1 -1
  677. package/dist/sdk/mutation-guard.js +1 -1
  678. package/dist/sdk/notes.js +1 -1
  679. package/dist/sdk/output/fit-envelope.js +1 -1
  680. package/dist/sdk/output/list-envelope.js +1 -1
  681. package/dist/sdk/output/table-rows.js +1 -1
  682. package/dist/sdk/output-contracts.js +1 -1
  683. package/dist/sdk/output-projection.js +1 -1
  684. package/dist/sdk/output-token-accounting.js +1 -1
  685. package/dist/sdk/output.js +2 -2
  686. package/dist/sdk/ownership-source.js +1 -1
  687. package/dist/sdk/package-import-adapters.js +1 -1
  688. package/dist/sdk/package-migrations.js +1 -1
  689. package/dist/sdk/package-runtime-options.js +1 -1
  690. package/dist/sdk/pagination.js +1 -1
  691. package/dist/sdk/profile.js +5 -5
  692. package/dist/sdk/provenance.js +1 -1
  693. package/dist/sdk/public-surface.json +1 -1
  694. package/dist/sdk/query/activity.js +1 -1
  695. package/dist/sdk/query/aggregate.js +1 -1
  696. package/dist/sdk/query/calendar.js +4 -4
  697. package/dist/sdk/query/complete-list.js +1 -1
  698. package/dist/sdk/query/context.js +2 -2
  699. package/dist/sdk/query/declared-blockers.js +1 -1
  700. package/dist/sdk/query/duplicate-candidates.js +1 -1
  701. package/dist/sdk/query/get-facet-roots.js +1 -1
  702. package/dist/sdk/query/get.js +1 -1
  703. package/dist/sdk/query/history.js +1 -1
  704. package/dist/sdk/query/item-filter-options.js +0 -1
  705. package/dist/sdk/query/light-metadata.js +1 -1
  706. package/dist/sdk/query/list-filter-shared.js +1 -1
  707. package/dist/sdk/query/list.js +1 -1
  708. package/dist/sdk/query/multi-value-filters.js +1 -1
  709. package/dist/sdk/query/next-ranking-policy.js +1 -1
  710. package/dist/sdk/query/next-ready-budget.js +1 -1
  711. package/dist/sdk/query/next.js +2 -2
  712. package/dist/sdk/query/parsers.js +1 -1
  713. package/dist/sdk/query/projection-contracts.js +1 -1
  714. package/dist/sdk/query/search/corpus.js +2 -2
  715. package/dist/sdk/query/search/filters.js +1 -1
  716. package/dist/sdk/query/search/input.js +1 -1
  717. package/dist/sdk/query/search/lexical.js +1 -1
  718. package/dist/sdk/query/search/response.js +1 -1
  719. package/dist/sdk/query/search/semantic.js +3 -3
  720. package/dist/sdk/query/search/types.js +0 -1
  721. package/dist/sdk/query/search-contracts.js +1 -1
  722. package/dist/sdk/query/search-pagination.js +1 -1
  723. package/dist/sdk/query/search-rendering.js +1 -1
  724. package/dist/sdk/query/search.js +1 -1
  725. package/dist/sdk/query/window-pagination.js +1 -1
  726. package/dist/sdk/query/workspace-contracts.js +1 -1
  727. package/dist/sdk/read-output/continuation.js +1 -1
  728. package/dist/sdk/read-output/extension.js +1 -1
  729. package/dist/sdk/read-output/options.js +1 -1
  730. package/dist/sdk/read-output/positional-rows.js +1 -1
  731. package/dist/sdk/read-output/provenance.js +1 -1
  732. package/dist/sdk/read-output/session-result.js +0 -1
  733. package/dist/sdk/read-output/surfaces.js +1 -1
  734. package/dist/sdk/read-output/tail-retention.js +1 -1
  735. package/dist/sdk/read-output-budget.js +1 -1
  736. package/dist/sdk/read-output-contracts.js +1 -1
  737. package/dist/sdk/read-output-rows.js +1 -1
  738. package/dist/sdk/read-output-session.js +1 -1
  739. package/dist/sdk/relationship-analytics.js +1 -1
  740. package/dist/sdk/relationship-context.js +1 -1
  741. package/dist/sdk/relationship-history.js +6 -6
  742. package/dist/sdk/relationship-kinds/contract.js +1 -1
  743. package/dist/sdk/relationships.js +1 -1
  744. package/dist/sdk/reproducibility/process.js +1 -1
  745. package/dist/sdk/runtime/actions.js +1 -1
  746. package/dist/sdk/runtime/context.js +1 -1
  747. package/dist/sdk/runtime/mutation-admission.js +1 -1
  748. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  749. package/dist/sdk/runtime/schema-preview.js +1 -1
  750. package/dist/sdk/runtime/schema.js +1 -1
  751. package/dist/sdk/runtime-action-aliases.js +1 -1
  752. package/dist/sdk/runtime-extended-actions.js +1 -1
  753. package/dist/sdk/runtime-input.d.ts +8 -2
  754. package/dist/sdk/runtime-input.js +1 -1
  755. package/dist/sdk/runtime-primitives.d.ts +1 -1
  756. package/dist/sdk/runtime-primitives.js +1 -1
  757. package/dist/sdk/runtime-public-contracts.js +0 -1
  758. package/dist/sdk/runtime-stats-options.js +1 -1
  759. package/dist/sdk/runtime.d.ts +9 -0
  760. package/dist/sdk/runtime.js +1 -1
  761. package/dist/sdk/scheduling-shortcuts.js +1 -1
  762. package/dist/sdk/schema/field-option-collisions.js +2 -0
  763. package/dist/sdk/schema-migration.js +4 -4
  764. package/dist/sdk/schema.js +7 -7
  765. package/dist/sdk/search-refresh-worker.js +1 -1
  766. package/dist/sdk/similarity-scoring.js +1 -1
  767. package/dist/sdk/similarity.js +1 -1
  768. package/dist/sdk/start-task-status.js +1 -1
  769. package/dist/sdk/stats.js +1 -1
  770. package/dist/sdk/structured-mutations.d.ts +5 -5
  771. package/dist/sdk/structured-mutations.js +1 -1
  772. package/dist/sdk/telemetry-flush.js +1 -1
  773. package/dist/sdk/telemetry.js +4 -4
  774. package/dist/sdk/templates.js +3 -3
  775. package/dist/sdk/test/batch.js +2 -2
  776. package/dist/sdk/test/command-args.js +1 -1
  777. package/dist/sdk/test/command-resolution.js +2 -2
  778. package/dist/sdk/test/entry.js +2 -2
  779. package/dist/sdk/test/execution-receipts.js +2 -2
  780. package/dist/sdk/test/execution.js +5 -5
  781. package/dist/sdk/test/json-path.js +1 -1
  782. package/dist/sdk/test/linked-command-detection.js +1 -1
  783. package/dist/sdk/test/measurements.js +1 -1
  784. package/dist/sdk/test/parsers.js +1 -1
  785. package/dist/sdk/test/prerequisites.js +1 -1
  786. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  787. package/dist/sdk/test/run-phases.js +1 -1
  788. package/dist/sdk/test/runs.js +1 -1
  789. package/dist/sdk/test/trust.js +2 -2
  790. package/dist/sdk/test/update.js +1 -1
  791. package/dist/sdk/test/workspace-snapshot.js +1 -1
  792. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  793. package/dist/sdk/traceability/source-traceability.js +2 -2
  794. package/dist/sdk/tracker-root-discovery.js +1 -1
  795. package/dist/sdk/transactions/item-finalization.js +2 -0
  796. package/dist/sdk/workspace-contracts-cache.js +1 -1
  797. package/dist/sdk/workspace-contracts.js +1 -1
  798. package/dist/sdk/workspace-memory.js +2 -2
  799. package/dist/sdk/workspace-snapshot.js +5 -5
  800. package/dist/sdk/workspace-transaction-gc.js +1 -1
  801. package/dist/sdk/workspace-transaction.js +2 -2
  802. package/dist/sdk/workspace.js +6 -6
  803. package/dist/types/index.js +1 -1
  804. package/dist/types.d.ts +20 -0
  805. package/dist/types.js +1 -1
  806. package/docs/AGENT_GUIDE.md +1 -1
  807. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  808. package/docs/COMMANDS.md +7 -3
  809. package/docs/EXTENSIONS.md +1 -1
  810. package/docs/HISTORY_RECOVERY.md +229 -5
  811. package/docs/README.md +2 -2
  812. package/docs/SDK.md +174 -5
  813. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  814. package/marketplace.json +1 -1
  815. package/node_modules/tar/package.json +2 -3
  816. package/package.json +31 -2
  817. package/packages/pm-beads/package.json +1 -1
  818. package/packages/pm-calendar/package.json +1 -1
  819. package/packages/pm-command-kit/package.json +1 -1
  820. package/packages/pm-digital-twin/package.json +1 -1
  821. package/packages/pm-governance-audit/package.json +1 -1
  822. package/packages/pm-guide-shell/package.json +1 -1
  823. package/packages/pm-kanban/package.json +1 -1
  824. package/packages/pm-lifecycle-hooks/package.json +1 -1
  825. package/packages/pm-linked-test-adapters/package.json +1 -1
  826. package/packages/pm-search-advanced/package.json +1 -1
  827. package/packages/pm-templates/package.json +1 -1
  828. package/packages/pm-todos/package.json +1 -1
  829. package/packages/pm-vcs/package.json +1 -1
  830. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  831. package/plugins/pm-claude/package.json +1 -1
  832. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  833. package/plugins/pm-codex/package.json +1 -1
  834. package/plugins/pm-codex/plugin.json +1 -1
  835. package/runtime-dependencies.json +1 -1
  836. package/scripts/finalize-build.mjs +63 -24
  837. package/scripts/prepare-build-cache.mjs +28 -1
  838. package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
  839. package/dist/cli-bundle/chunks/chunk-5647LU3A.js +0 -2287
  840. package/dist/cli-bundle/chunks/chunk-6QLEXRUG.js +0 -9
  841. package/dist/cli-bundle/chunks/chunk-AHQB7W2H.js +0 -3
  842. package/dist/cli-bundle/chunks/chunk-BKSVHOWI.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-CASX6SFI.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-CIKGG34F.js +0 -2
  845. package/dist/cli-bundle/chunks/chunk-D6ILFXZY.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
  849. package/dist/cli-bundle/chunks/chunk-JVGRFU5H.js +0 -3
  850. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  851. package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
  852. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-NCFCBKIP.js +0 -2
  854. package/dist/cli-bundle/chunks/chunk-NT5AKFE5.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-PJXKA4QU.js +0 -125
  856. package/dist/cli-bundle/chunks/chunk-RMIRNYRG.js +0 -71
  857. package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
  858. package/dist/cli-bundle/chunks/chunk-S6HB3WL2.js +0 -2
  859. package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-SRVTCYAU.js +0 -2
  862. package/dist/cli-bundle/chunks/chunk-WELSVDPU.js +0 -2
  863. package/dist/cli-bundle/chunks/chunk-XHJ3H5PL.js +0 -3
  864. package/dist/cli-bundle/chunks/chunk-XWHJIRNV.js +0 -8
  865. package/dist/cli-bundle/chunks/chunk-YJEBK7HU.js +0 -8
  866. package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
  867. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  868. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  869. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  870. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  871. package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
  872. package/dist/cli-bundle/chunks/mutation-actor-3TG636XG.js +0 -2
  873. package/dist/cli-bundle/chunks/mutation-admission-LICSDNNO.js +0 -2
  874. package/dist/cli-bundle/chunks/register-mutation-WWVECKFQ.js +0 -21
  875. package/dist/cli-bundle/chunks/register-operations-L6HFJNWD.js +0 -2
  876. package/dist/cli-bundle/chunks/register-setup-K7UFG5TD.js +0 -2
  877. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  878. package/dist/cli-bundle/chunks/stage-57KH3KAC.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  880. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  881. package/dist/cli-bundle/focused-chunks/chunk-532WZV65.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-7A4QWNZX.js +0 -8
  883. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  884. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  885. package/dist/cli-bundle/focused-chunks/chunk-CU2BRAOX.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  888. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-IQK5NPMG.js +0 -13
  892. package/dist/cli-bundle/focused-chunks/chunk-J63D6QST.js +0 -6
  893. package/dist/cli-bundle/focused-chunks/chunk-JMQJBZQ5.js +0 -2
  894. package/dist/cli-bundle/focused-chunks/chunk-LNHUE4VV.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-MKM5NKD7.js +0 -8
  896. package/dist/cli-bundle/focused-chunks/chunk-NP72ZDXE.js +0 -2
  897. package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
  898. package/dist/cli-bundle/focused-chunks/chunk-QGKLRXP7.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
  900. package/dist/cli-bundle/focused-chunks/chunk-RPE6IX26.js +0 -2
  901. package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
  902. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  903. package/dist/cli-bundle/focused-chunks/chunk-UOC6257J.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
  905. package/dist/cli-bundle/focused-chunks/chunk-WXMI4AV5.js +0 -8
  906. package/dist/cli-bundle/focused-chunks/chunk-XCJSHNXK.js +0 -27
  907. package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
  908. package/dist/cli-bundle/focused-chunks/chunk-YOAYY3HE.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  911. package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
  912. package/dist/cli-bundle/focused-chunks/mutation-actor-62HKR5IO.js +0 -2
  913. package/dist/cli-bundle/focused-chunks/mutation-admission-X4PF2SG3.js +0 -2
  914. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  915. package/dist/cli-bundle/focused-chunks/stage-O7T7CXBB.js +0 -2
  916. package/dist/sdk/agent/refusal-closure.js +0 -2
  917. package/dist/sdk/agent/refusal-reachability.js +0 -4
  918. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  919. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  920. package/dist/sdk/authoring.js +0 -2
  921. package/dist/sdk/compose.js +0 -2
  922. package/dist/sdk/contracts.js +0 -2
  923. package/dist/sdk/core-governance.js +0 -2
  924. package/dist/sdk/core.js +0 -2
  925. package/dist/sdk/corpus-shape.js +0 -2
  926. package/dist/sdk/define.js +0 -2
  927. package/dist/sdk/environment/agent-environment.js +0 -2
  928. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  929. package/dist/sdk/governance/coverage-assurance.js +0 -2
  930. package/dist/sdk/governance/reliability.js +0 -2
  931. package/dist/sdk/governance.js +0 -2
  932. package/dist/sdk/graph/adapter.js +0 -2
  933. package/dist/sdk/graph/conformance.js +0 -2
  934. package/dist/sdk/graph/index.js +0 -2
  935. package/dist/sdk/graph.js +0 -2
  936. package/dist/sdk/index.js +0 -2
  937. package/dist/sdk/query.js +0 -2
  938. package/dist/sdk/relationship-migration.js +0 -2
  939. package/dist/sdk/testing.js +0 -8
  940. package/dist/sdk/workspace-recipe.js +0 -2
  941. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  942. package/docs/DEFECT_RECURRENCE.md +0 -257
  943. package/docs/PERFORMANCE.md +0 -204
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){return{metadata:{id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents},body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count))replay=tryApplyReplayPatch(replay,entry.patch).document;return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents=="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath),documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries)),matching=[],mismatched=[],missing=[],unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));if(raw=await readFileIfExists(resolved.absolutePath),raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry)return{entry:idempotentEntry,historyPath};const timestamp=nowIso(),beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument),recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before))throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at),entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,!1,!1,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return!1;const before=beforeRaw===null?null:JSON.parse(beforeRaw),after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{(beforeRaw!==null||params.recordCreation!==!1)&&await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,idempotencyKey:params.idempotencyKey,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}catch(error){throw beforeRaw===null?await fs.rm(params.filePath,{force:!0}):await writeFileAtomic(params.filePath,beforeRaw),error}return!0}async function mutateWorkspaceJsonWithHistory(params){const{documentPath}=resolveGovernedDocumentPath(params.pmRoot,params.filePath),release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);if(params.dryRun===!0||params.idempotencyKey!==void 0){const entries=await readHistoryEntries(getWorkspaceHistoryPath(params.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const recorded=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries))[documentPath];if(recorded!==void 0&&stableStringify(recorded)!==stableStringify(beforeRaw===null?null:JSON.parse(beforeRaw)))throw new PmCliError(`Workspace history state for "${documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict"});if(params.idempotencyKey!==void 0&&entries.some(entry=>entry.op===`${params.op}:${params.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}const mutation=await params.mutate(beforeRaw);return JSON.parse(mutation.raw),params.dryRun===!0?{changed:beforeRaw!==mutation.raw,result:mutation.result}:{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision)throw new TypeError("Workspace history reconciliation requires an authorization decision");const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath))throw new TypeError(`Workspace history does not govern document ${documentPath}`);const raw=await readFileIfExists(absolutePath);if(raw===null)throw new TypeError(`Workspace history document is missing: ${documentPath}`);const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current))return{changed:!1,historyPath};const timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});return await appendHistoryEntry(historyPath,entry),{changed:!0,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);if(verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors),!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length)throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`);const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0)throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`);const beforeRaw=await readFileIfExists(absolutePath),targetRaw=`${JSON.stringify(target,null,2)}
2
- `;if(beforeRaw===targetRaw)return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!1};const beforeDocument=replayWorkspaceEntries(entries),timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...workspaceDocuments(beforeDocument),[documentPath]:target},beforeDocument.metadata.created_at),message:options.message,context:{reason:"workspace_state_restore",document_path:documentPath,restored_from_version:options.targetVersion,replaced_out_of_band_state:!0}});await writeFileAtomic(absolutePath,targetRaw);try{await appendHistoryEntry(getWorkspaceHistoryPath(options.pmRoot),entry)}catch(error){throw beforeRaw===null?await fs.rm(absolutePath,{force:!0}):await writeFileAtomic(absolutePath,beforeRaw),error}return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!0}}finally{await release()}}export{WORKSPACE_HISTORY_ID,appendWorkspaceAuditEvent,appendWorkspaceHistoryChange,getWorkspaceHistoryPath,inspectWorkspaceHistoryState,mutateWorkspaceJsonWithHistory,reconcileWorkspaceJsonHistory,restoreWorkspaceJsonFromHistory,writeWorkspaceJsonWithHistory};
1
+ import $ from"node:fs/promises";import p from"node:path";import{readFileIfExists as W,writeFileAtomic as b}from"../fs/fs-utils.js";import{acquireLock as w}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT as P,EXIT_CODE as O}from"../shared/constants.js";import{PmCliError as C}from"../shared/errors.js";import{stableStringify as h}from"../shared/serialization.js";import{nowIso as R}from"../shared/time.js";import{appendHistoryEntry as x,createHistoryEntry as S}from"./history.js";import{readHistoryEntries as k}from"./read.js";import{cloneEmptyReplayDocument as A,replayToItemDocument as J,tryApplyReplayPatch as j,verifyHistoryChain as _}from"./replay.js";const f="_workspace";function y(t){return p.join(t,"history",`${f}.jsonl`)}function D(t,o){return{metadata:{id:f,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:o,updated_at:o,documents:t},body:""}}function m(t,o=t.length){let r=A();for(const e of t.slice(0,o))r=j(r,e.patch).document;return J(r)}function g(t){return"documents"in t.metadata&&typeof t.metadata.documents=="object"&&t.metadata.documents!==null&&!Array.isArray(t.metadata.documents)?t.metadata.documents:{}}function v(t){throw new C(`Workspace history verification failed: ${t.join(", ")}`,O.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...t],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function T(t,o){const r=p.resolve(o),e=p.relative(t,r).replaceAll("\\","/");if(e.length===0||e===".."||e.startsWith("../")||p.isAbsolute(e))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:e,absolutePath:r}}async function X(t){const o=await k(y(t),f),r=_(o);r.ok||v(r.errors);const e=g(o.length===0?P:m(o)),a=[],n=[],i=[],c=[];for(const s of Object.keys(e).sort()){let u;try{const l=T(t,p.resolve(t,s));if(u=await W(l.absolutePath),u===null){i.push(s);continue}const d=JSON.parse(u);(h(d)===h(e[s])?a:n).push(s)}catch{c.push(s)}}return{ok:n.length===0&&i.length===0&&c.length===0,document_count:Object.keys(e).length,matching_documents:a,mismatched_documents:n,missing_documents:i,unreadable_documents:c}}async function H(t){const o=y(t.pmRoot),r=await k(o,f),e=_(r);e.ok||v(e.errors);const a=t.idempotencyKey===void 0?void 0:r.find(d=>d.op===`${t.op}:${t.idempotencyKey}`);if(a)return{entry:a,historyPath:o};const n=R(),i=r.length===0?P:m(r),c=g(i),s=c[t.documentPath];if(s!==void 0&&h(s)!==h(t.before))throw new C(`Workspace history state for "${t.documentPath}" changed outside the audited mutation path.`,O.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});const u=D({...c,[t.documentPath]:t.after},r.length===0?n:i.metadata.created_at),l=S({nowIso:n,author:t.author,op:t.idempotencyKey===void 0?t.op:`${t.op}:${t.idempotencyKey}`,before:i,after:u,message:t.message});return await x(o,l),{entry:l,historyPath:o}}async function Q(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{return await H(t)}finally{await o()}}async function Z(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const r=y(t.pmRoot),e=await k(r,f),a=_(e);a.ok||v(a.errors);const n=e.length===0?P:m(e),i=S({nowIso:R(),author:t.author,op:t.op,before:n,after:n,message:t.message,context:t.context});return await x(r,i),{entry:i,historyPath:r}}finally{await o()}}async function N(t,o){if(o===t.raw)return!1;const r=o===null?null:JSON.parse(o),e=JSON.parse(t.raw);await b(t.filePath,t.raw);try{(o!==null||t.recordCreation!==!1)&&await H({pmRoot:t.pmRoot,documentPath:p.relative(t.pmRoot,t.filePath).replaceAll("\\","/"),before:r,after:e,op:t.op,idempotencyKey:t.idempotencyKey,author:t.author,lockTtlSeconds:t.lockTtlSeconds,lockWaitMs:t.lockWaitMs,message:t.message})}catch(a){throw o===null?await $.rm(t.filePath,{force:!0}):await b(t.filePath,o),a}return!0}async function tt(t){const{documentPath:o}=T(t.pmRoot,t.filePath),r=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const e=await W(t.filePath);if(t.dryRun===!0||t.idempotencyKey!==void 0){const n=await k(y(t.pmRoot),f),i=_(n);i.ok||v(i.errors);const c=g(n.length===0?P:m(n))[o];if(c!==void 0&&h(c)!==h(e===null?null:JSON.parse(e)))throw new C(`Workspace history state for "${o}" changed outside the audited mutation path.`,O.CONFLICT,{code:"workspace_history_state_conflict"});if(t.idempotencyKey!==void 0&&n.some(s=>s.op===`${t.op}:${t.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}const a=await t.mutate(e);return JSON.parse(a.raw),t.dryRun===!0?{changed:e!==a.raw,result:a.result}:{changed:await N({...t,raw:a.raw},e),result:a.result}}finally{await r()}}async function et(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{return await N(t,await W(t.filePath))}finally{await o()}}async function ot(t){const o=t.authorizationDecision.trim();if(!o)throw new TypeError("Workspace history reconciliation requires an authorization decision");const r=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const{documentPath:e,absolutePath:a}=T(t.pmRoot,t.filePath),n=y(t.pmRoot),i=await k(n,f),c=_(i);c.ok||v(c.errors);const s=m(i),u=g(s);if(!Object.hasOwn(u,e))throw new TypeError(`Workspace history does not govern document ${e}`);const l=await W(a);if(l===null)throw new TypeError(`Workspace history document is missing: ${e}`);const d=JSON.parse(l);if(h(u[e])===h(d))return{changed:!1,historyPath:n};const E=R(),I=S({nowIso:E,author:t.author,op:t.op,before:s,after:D({...u,[e]:d},s.metadata.created_at),message:t.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:e,authorization_decision:o}});return await x(n,I),{changed:!0,entry:I,historyPath:n}}finally{await r()}}async function rt(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const{documentPath:r,absolutePath:e}=T(t.pmRoot,t.filePath),a=await k(y(t.pmRoot),f),n=_(a);if(n.ok||v(n.errors),!Number.isInteger(t.targetVersion)||t.targetVersion<1||t.targetVersion>a.length)throw new TypeError(`Invalid workspace history target version: ${String(t.targetVersion)}`);const i=g(m(a,t.targetVersion))[r];if(i===void 0)throw new TypeError(`Workspace history version ${t.targetVersion} does not contain ${r}`);const c=await W(e),s=`${JSON.stringify(i,null,2)}
2
+ `;if(c===s)return{document_path:r,restored_from_version:t.targetVersion,changed:!1};const u=m(a),l=R(),d=S({nowIso:l,author:t.author,op:t.op,before:u,after:D({...g(u),[r]:i},u.metadata.created_at),message:t.message,context:{reason:"workspace_state_restore",document_path:r,restored_from_version:t.targetVersion,replaced_out_of_band_state:!0}});await b(e,s);try{await x(y(t.pmRoot),d)}catch(E){throw c===null?await $.rm(e,{force:!0}):await b(e,c),E}return{document_path:r,restored_from_version:t.targetVersion,changed:!0}}finally{await o()}}export{f as WORKSPACE_HISTORY_ID,Z as appendWorkspaceAuditEvent,Q as appendWorkspaceHistoryChange,y as getWorkspaceHistoryPath,X as inspectWorkspaceHistoryState,tt as mutateWorkspaceJsonWithHistory,ot as reconcileWorkspaceJsonHistory,rt as restoreWorkspaceJsonFromHistory,et as writeWorkspaceJsonWithHistory};
3
3
  //# sourceMappingURL=workspace-history.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]="80805c6b-9b9a-5dad-b94b-d7dbd365fe5e")}catch{}})();import{readFile}from"node:fs/promises";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{createStdinTokenResolver}from"../item/parse.js";const defaultBodyFileReader=path=>readFile(path,"utf8");async function resolveBodyFileContent(bodyFile,inlineBody,readFileImpl=defaultBodyFileReader){if(inlineBody!==void 0)throw new PmCliError("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",EXIT_CODE.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});const path=bodyFile.trim();if(path.length===0)throw new PmCliError("--body-file requires a file path.",EXIT_CODE.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});if(path==="-")return await createStdinTokenResolver().resolveValue("-","--body-file");try{return await readFileImpl(path)}catch(error){const errno=error?.code,isDirectory=errno==="EISDIR",detail=errno?` (${errno})`:"";throw new PmCliError(isDirectory?`--body-file "${path}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${path}"${detail}. Check that the file exists and is readable.`,EXIT_CODE.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${errno?` (underlying error: ${errno})`:""}.`,nextSteps:[`Verify the path: ls -l "${path}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}export{resolveBodyFileContent};
1
+ import{readFile as f}from"node:fs/promises";import{EXIT_CODE as i}from"../shared/constants.js";import{PmCliError as r}from"../shared/errors.js";import{createStdinTokenResolver as h}from"../item/parse.js";const b=t=>f(t,"utf8");async function m(t,d,a=b){if(d!==void 0)throw new r("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",i.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});const e=t.trim();if(e.length===0)throw new r("--body-file requires a file path.",i.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});if(e==="-")return await h().resolveValue("-","--body-file");try{return await a(e)}catch(l){const o=l?.code,n=o==="EISDIR",y=o?` (${o})`:"";throw new r(n?`--body-file "${e}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${e}"${y}. Check that the file exists and is readable.`,i.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${o?` (underlying error: ${o})`:""}.`,nextSteps:[`Verify the path: ls -l "${e}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}export{m as resolveBodyFileContent};
2
2
  //# sourceMappingURL=body-file.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4441095d-0acd-5780-8758-7df94396cb8e")}catch{}})();import{readFile}from"node:fs/promises";import{createStdinTokenResolver}from"../item/parse.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const defaultFileReader=path=>readFile(path,"utf8"),defaultStdinReader=async optionName=>await createStdinTokenResolver().resolveValue("-",optionName);function parseBulkIdsText(raw){return[...new Set(raw.split(/[,\r\n]+/).map(entry=>entry.trim()).filter(entry=>entry.length>0))]}function normalizeBulkIdsArray(value){const entries=[];for(const entry of value)if(typeof entry=="string")entries.push(entry);else if(typeof entry=="number"&&Number.isFinite(entry))entries.push(String(entry));else return"";const ids=parseBulkIdsText(entries.join(`
2
- `));return ids.length>0?ids.join(","):""}function normalizeBulkIdsValue(value){if(value===void 0)return;if(typeof value=="number")return Number.isFinite(value)?String(value):"";if(Array.isArray(value))return normalizeBulkIdsArray(value);if(typeof value!="string")return"";const ids=parseBulkIdsText(value);return ids.length>0?ids.join(","):""}async function resolveCliBulkIdsInput(value,optionName="--ids",readers={}){if(value===void 0)return;const trimmed=value.trim();let raw=value;try{if(trimmed==="-")raw=await(readers.readStdin??defaultStdinReader)(optionName);else if(trimmed.startsWith("@")){const path=trimmed.slice(1).trim();if(path.length===0)throw new PmCliError(`${optionName} @path requires a non-empty file path.`,EXIT_CODE.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${optionName} @<path>, ${optionName} -, or inline IDs.`});raw=await(readers.readFile??defaultFileReader)(path)}}catch(error){if(error instanceof PmCliError)throw error;const detail=error instanceof Error?error.message:String(error);throw new PmCliError(`${optionName} could not read ${trimmed==="-"?"stdin":`"${trimmed.slice(1).trim()}"`}: ${detail}`,EXIT_CODE.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${optionName} -, ${optionName} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${optionName} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${optionName} - --dry-run`]})}const normalized=normalizeBulkIdsValue(raw);if(normalized!=="")return normalized;throw new PmCliError(`${optionName} requires at least one non-empty item ID.`,EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @path."})}export{normalizeBulkIdsValue,parseBulkIdsText,resolveCliBulkIdsInput};
1
+ import{readFile as f}from"node:fs/promises";import{createStdinTokenResolver as m}from"../item/parse.js";import{EXIT_CODE as d}from"../shared/constants.js";import{PmCliError as s}from"../shared/errors.js";const c=r=>f(r,"utf8"),p=async r=>await m().resolveValue("-",r);function l(r){return[...new Set(r.split(/[,\r\n]+/).map(e=>e.trim()).filter(e=>e.length>0))]}function h(r){const e=[];for(const t of r)if(typeof t=="string")e.push(t);else if(typeof t=="number"&&Number.isFinite(t))e.push(String(t));else return"";const n=l(e.join(`
2
+ `));return n.length>0?n.join(","):""}function y(r){if(r===void 0)return;if(typeof r=="number")return Number.isFinite(r)?String(r):"";if(Array.isArray(r))return h(r);if(typeof r!="string")return"";const e=l(r);return e.length>0?e.join(","):""}async function $(r,e="--ids",n={}){if(r===void 0)return;const t=r.trim();let o=r;try{if(t==="-")o=await(n.readStdin??p)(e);else if(t.startsWith("@")){const i=t.slice(1).trim();if(i.length===0)throw new s(`${e} @path requires a non-empty file path.`,d.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${e} @<path>, ${e} -, or inline IDs.`});o=await(n.readFile??c)(i)}}catch(i){if(i instanceof s)throw i;const a=i instanceof Error?i.message:String(i);throw new s(`${e} could not read ${t==="-"?"stdin":`"${t.slice(1).trim()}"`}: ${a}`,d.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${e} -, ${e} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${e} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${e} - --dry-run`]})}const u=y(o);if(u!=="")return u;throw new s(`${e} requires at least one non-empty item ID.`,d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @path."})}export{y as normalizeBulkIdsValue,l as parseBulkIdsText,$ as resolveCliBulkIdsInput};
3
3
  //# sourceMappingURL=bulk-ids-input.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]="a319e7d9-e248-573b-bf1f-35217ce49fd0")}catch{}})();import{isTerminalStatus,normalizeStatusForRegistry}from"./status.js";import{BUILTIN_ITEM_EXECUTION_ROLES,resolveTypeDefinition}from"./type-registry.js";import{resolveCanonicalRelationshipKind}from"../../sdk/relationships.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"./dependency-reference.js";function resolveItemExecutionRole(type,registry){return(registry===void 0?void 0:resolveTypeDefinition(type,registry))?.execution_role??BUILTIN_ITEM_EXECUTION_ROLES[type.trim().toLowerCase()]??"agent"}const BLOCKED_BY_DEPENDENCY_KIND="blocked_by",BLOCKS_DEPENDENCY_KIND="blocks",ACTIONABILITY_ORDERING_KINDS=Object.freeze([BLOCKED_BY_DEPENDENCY_KIND,BLOCKS_DEPENDENCY_KIND]),NO_ACTIVE_BLOCKER_SENTINEL="no-active-blocker";function normalizeItemId(id){return id.trim().toLowerCase()}function blockerReferenceKey(id,external){return external?`external:${id}`:`local:${normalizeItemId(id)}`}function collectBlockedByIds(item){const ids=new Map,scalar=typeof item.blocked_by=="string"?item.blocked_by.trim():"";if(scalar.length>0&&normalizeItemId(scalar)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(scalar);ids.set(blockerReferenceKey(scalar,external),external?scalar:normalizeItemId(scalar))}for(const dependency of item.dependencies??[]){const dependencyId=typeof dependency.id=="string"?dependency.id.trim():"";if(resolveCanonicalRelationshipKind(dependency.kind)===BLOCKED_BY_DEPENDENCY_KIND&&dependencyId.length>0&&normalizeItemId(dependencyId)!==NO_ACTIVE_BLOCKER_SENTINEL){const external=isExternalDependencyReference(dependencyId)||isExternalDependencySourceKind(dependency.source_kind);ids.set(blockerReferenceKey(dependencyId,external),external?dependencyId:normalizeItemId(dependencyId))}}return[...ids.values()].sort((left,right)=>left.localeCompare(right))}function indexBlockedByIds(corpus){const idsByItem=new Map;for(const item of corpus){const itemId=normalizeItemId(item.id);itemId.length!==0&&idsByItem.set(itemId,new Set(collectBlockedByIds(item)))}for(const candidate of corpus){const candidateId=normalizeItemId(candidate.id);if(candidateId.length!==0)for(const dependency of candidate.dependencies??[]){const targetId=resolveCanonicalRelationshipKind(dependency.kind)===BLOCKS_DEPENDENCY_KIND&&typeof dependency.id=="string"?normalizeItemId(dependency.id):"";if(targetId.length===0||targetId===NO_ACTIVE_BLOCKER_SENTINEL)continue;const blockerIds=idsByItem.get(targetId)??new Set;blockerIds.add(candidateId),idsByItem.set(targetId,blockerIds)}}return new Map([...idsByItem].map(([itemId,blockerIds])=>[itemId,[...blockerIds].sort((left,right)=>left.localeCompare(right))]))}function collectBlockedByIdsFromCorpus(item,corpus){const itemId=normalizeItemId(item.id);return itemId.length>0?indexBlockedByIds(corpus).get(itemId)??collectBlockedByIds(item):collectBlockedByIds(item)}function resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem){const itemWithId=item,blockerIds=typeof itemWithId.id=="string"?blockerIdsByItem?.get(normalizeItemId(itemWithId.id))??collectBlockedByIdsFromCorpus(itemWithId,[...itemsById.values()]):collectBlockedByIds(item),structuredExternalBlockerIds=new Set((item.dependencies??[]).filter(dependency=>resolveCanonicalRelationshipKind(dependency.kind)===BLOCKED_BY_DEPENDENCY_KIND&&isExternalDependencySourceKind(dependency.source_kind)&&typeof dependency.id=="string"&&dependency.id.trim().length>0).map(dependency=>blockerReferenceKey(dependency.id.trim(),!0)));return blockerIds.map(id=>{if(isExternalDependencyReference(id)||structuredExternalBlockerIds.has(blockerReferenceKey(id,!0)))return{id,title:null,status:null,resolved:!1,external:!0,...typeof item.updated_at=="string"?{blocked_since:item.updated_at}:{},resolver:null};const blocker=itemsById.get(normalizeItemId(id));return blocker?{id,title:blocker.title,status:blocker.status,resolved:isTerminalStatus(blocker.status,statusRegistry)}:{id,title:null,status:null,resolved:!1}})}function resolveItemBlockers(item,itemsById,statusRegistry){return resolveItemBlockersWithIndex(item,itemsById,statusRegistry)}function collectDependencyBlockedIds(corpus,statusRegistry){const itemsById=new Map(corpus.map(item=>[normalizeItemId(item.id),item])),blockerIdsByItem=indexBlockedByIds(corpus),candidateStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),blocked=new Set;for(const item of corpus){const normalizedStatus=normalizeStatusForRegistry(item.status,statusRegistry);candidateStatuses.has(normalizedStatus)&&(statusRegistry.blocked_statuses.has(normalizedStatus)||resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).some(blocker=>!blocker.resolved))&&blocked.add(normalizeItemId(item.id))}return blocked}function selectActionableEntries(report,statusRegistry,options={},typeRegistry){const candidates=[...report.ready,...report.decisions,...report.gates];options.includeContainers===!0&&candidates.push(...report.containers.filter(entry=>entry.open_blockers.length===0&&!statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(entry.item.status,statusRegistry))));const selected={ready:[],decisions:[],gates:[]};for(const entry of candidates){const role=resolveItemExecutionRole(entry.item.type,typeRegistry);role==="human"&&options.includeDecisions!==!0?selected.decisions.push(entry):role==="gate"&&options.includeGates!==!0?selected.gates.push(entry):selected.ready.push(entry)}return selected}function resolveActiveStatusSet(statusRegistry){return statusRegistry.active_statuses.size>0?statusRegistry.active_statuses:new Set([statusRegistry.open_status])}function hasOpenDescendant(rootId,childrenByParent,statusRegistry){const stack=[normalizeItemId(rootId)],visited=new Set;for(;stack.length>0;){const current=stack.pop();if(!visited.has(current)){visited.add(current);for(const child of childrenByParent.get(current)??[]){if(!isTerminalStatus(child.status,statusRegistry))return!0;stack.push(normalizeItemId(child.id))}}}return!1}function indexCorpus(corpus){const itemsById=new Map,childrenByParent=new Map,blockedByReverse=new Map,blockerIdsByItem=indexBlockedByIds(corpus);for(const item of corpus){itemsById.set(normalizeItemId(item.id),item);const parent=typeof item.parent=="string"?item.parent.trim():"";if(parent.length>0){const parentKey=normalizeItemId(parent),siblings=childrenByParent.get(parentKey)??[];siblings.push(item),childrenByParent.set(parentKey,siblings)}for(const blockerId of blockerIdsByItem.get(normalizeItemId(item.id))){const blockerKey=normalizeItemId(blockerId),dependents=blockedByReverse.get(blockerKey)??[];dependents.push(item.id),blockedByReverse.set(blockerKey,dependents)}}return{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}}function computeActionabilityReport(candidates,corpus,statusRegistry,typeRegistry){const{itemsById,childrenByParent,blockedByReverse,blockerIdsByItem}=indexCorpus(corpus),activeStatuses=new Set([...resolveActiveStatusSet(statusRegistry),...statusRegistry.blocked_statuses]),nonTerminalIds=new Set(corpus.filter(entry=>!isTerminalStatus(entry.status,statusRegistry)).map(entry=>normalizeItemId(entry.id))),ready=[],blocked=[],containers=[],decisions=[],gates=[];let activeCount=0;for(const item of candidates){if(!activeStatuses.has(normalizeStatusForRegistry(item.status,statusRegistry)))continue;activeCount+=1;const openBlockers=resolveItemBlockersWithIndex(item,itemsById,statusRegistry,blockerIdsByItem).filter(blocker=>!blocker.resolved),unblocks=(blockedByReverse.get(normalizeItemId(item.id))??[]).filter(dependentId=>nonTerminalIds.has(normalizeItemId(dependentId))).sort((left,right)=>left.localeCompare(right)),entry={item,open_blockers:openBlockers,unblocks};if(hasOpenDescendant(item.id,childrenByParent,statusRegistry)){containers.push(entry);continue}const lifecycleBlocked=statusRegistry.blocked_statuses.has(normalizeStatusForRegistry(item.status,statusRegistry));if(openBlockers.length===0&&!lifecycleBlocked){const role=resolveItemExecutionRole(item.type,typeRegistry);role==="human"?decisions.push(entry):role==="gate"?gates.push(entry):ready.push(entry)}else blocked.push(entry)}return{ready,blocked,containers,decisions,gates,active_count:activeCount,container_count:containers.length}}export{ACTIONABILITY_ORDERING_KINDS,collectBlockedByIds,collectBlockedByIdsFromCorpus,collectDependencyBlockedIds,computeActionabilityReport,indexBlockedByIds,resolveItemBlockers,resolveItemExecutionRole,selectActionableEntries};
1
+ import{isTerminalStatus as b,normalizeStatusForRegistry as k}from"./status.js";import{BUILTIN_ITEM_EXECUTION_ROLES as P,resolveTypeDefinition as Y}from"./type-registry.js";import{resolveCanonicalRelationshipKind as _}from"../../sdk/relationships.js";import{isExternalDependencyReference as B,isExternalDependencySourceKind as K}from"./dependency-reference.js";function O(e,n){return(n===void 0?void 0:Y(e,n))?.execution_role??P[e.trim().toLowerCase()]??"agent"}const y="blocked_by",T="blocks",X=Object.freeze([y,T]),v="no-active-blocker";function l(e){return e.trim().toLowerCase()}function m(e,n){return n?`external:${e}`:`local:${l(e)}`}function I(e){const n=new Map,t=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(t.length>0&&l(t)!==v){const o=B(t);n.set(m(t,o),o?t:l(t))}for(const o of e.dependencies??[]){const c=typeof o.id=="string"?o.id.trim():"";if(_(o.kind)===y&&c.length>0&&l(c)!==v){const s=B(c)||K(o.source_kind);n.set(m(c,s),s?c:l(c))}}return[...n.values()].sort((o,c)=>o.localeCompare(c))}function g(e){const n=new Map;for(const t of e){const o=l(t.id);o.length!==0&&n.set(o,new Set(I(t)))}for(const t of e){const o=l(t.id);if(o.length!==0)for(const c of t.dependencies??[]){const s=_(c.kind)===T&&typeof c.id=="string"?l(c.id):"";if(s.length===0||s===v)continue;const i=n.get(s)??new Set;i.add(o),n.set(s,i)}}return new Map([...n].map(([t,o])=>[t,[...o].sort((c,s)=>c.localeCompare(s))]))}function F(e,n){const t=l(e.id);return t.length>0?g(n).get(t)??I(e):I(e)}function x(e,n,t,o){const c=e,s=typeof c.id=="string"?o?.get(l(c.id))??F(c,[...n.values()]):I(e),i=new Set((e.dependencies??[]).filter(r=>_(r.kind)===y&&K(r.source_kind)&&typeof r.id=="string"&&r.id.trim().length>0).map(r=>m(r.id.trim(),!0)));return s.map(r=>{if(B(r)||i.has(m(r,!0)))return{id:r,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};const d=n.get(l(r));return d?{id:r,title:d.title,status:d.status,resolved:b(d.status,t)}:{id:r,title:null,status:null,resolved:!1}})}function q(e,n,t){return x(e,n,t)}function H(e,n){const t=new Map(e.map(i=>[l(i.id),i])),o=g(e),c=new Set([...L(n),...n.blocked_statuses]),s=new Set;for(const i of e){const r=k(i.status,n);if(!c.has(r))continue;(n.blocked_statuses.has(r)||x(i,t,n,o).some(f=>!f.resolved))&&s.add(l(i.id))}return s}function J(e,n,t={},o){const c=[...e.ready,...e.decisions,...e.gates];t.includeContainers===!0&&c.push(...e.containers.filter(i=>i.open_blockers.length===0&&!n.blocked_statuses.has(k(i.item.status,n))));const s={ready:[],decisions:[],gates:[]};for(const i of c){const r=O(i.item.type,o);r==="human"&&t.includeDecisions!==!0?s.decisions.push(i):r==="gate"&&t.includeGates!==!0?s.gates.push(i):s.ready.push(i)}return s}function L(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function G(e,n,t){const o=[l(e)],c=new Set;for(;o.length>0;){const s=o.pop();if(!c.has(s)){c.add(s);for(const i of n.get(s)??[]){if(!b(i.status,t))return!0;o.push(l(i.id))}}}return!1}function U(e){const n=new Map,t=new Map,o=new Map,c=g(e);for(const s of e){n.set(l(s.id),s);const i=typeof s.parent=="string"?s.parent.trim():"";if(i.length>0){const r=l(i),d=t.get(r)??[];d.push(s),t.set(r,d)}for(const r of c.get(l(s.id))){const d=l(r),f=o.get(d)??[];f.push(s.id),o.set(d,f)}}return{itemsById:n,childrenByParent:t,blockedByReverse:o,blockerIdsByItem:c}}function Q(e,n,t,o){const{itemsById:c,childrenByParent:s,blockedByReverse:i,blockerIdsByItem:r}=U(n),d=new Set([...L(t),...t.blocked_statuses]),f=new Set(n.filter(a=>!b(a.status,t)).map(a=>l(a.id))),E=[],S=[],h=[],w=[],C=[];let D=0;for(const a of e){if(!d.has(k(a.status,t)))continue;D+=1;const N=x(a,c,t,r).filter(u=>!u.resolved),M=(i.get(l(a.id))??[]).filter(u=>f.has(l(u))).sort((u,z)=>u.localeCompare(z)),p={item:a,open_blockers:N,unblocks:M};if(G(a.id,s,t)){h.push(p);continue}const A=t.blocked_statuses.has(k(a.status,t));if(N.length===0&&!A){const u=O(a.type,o);u==="human"?w.push(p):u==="gate"?C.push(p):E.push(p)}else S.push(p)}return{ready:E,blocked:S,containers:h,decisions:w,gates:C,active_count:D,container_count:h.length}}export{X as ACTIONABILITY_ORDERING_KINDS,I as collectBlockedByIds,F as collectBlockedByIdsFromCorpus,H as collectDependencyBlockedIds,Q as computeActionabilityReport,g as indexBlockedByIds,q as resolveItemBlockers,O as resolveItemExecutionRole,J as selectActionableEntries};
2
2
  //# sourceMappingURL=actionability.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]="b24a4ce2-c356-56ee-8a34-f48a78507ac4")}catch{}})();const DEFERRABLE_ITEM_FIELDS=[{field:"acceptance_criteria",option:"acceptanceCriteria",flag:"--acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","acceptancecriteria","ac"]},{field:"assignee",option:"assignee",flag:"--assignee",aliases:["assignee"]},{field:"deadline",option:"deadline",flag:"--deadline",aliases:["deadline"]},{field:"estimated_minutes",option:"estimatedMinutes",flag:"--estimate",aliases:["estimated_minutes","estimated-minutes","estimatedminutes","estimate"]}],DEFERRABLE_BY_FIELD=new Map(DEFERRABLE_ITEM_FIELDS.map(entry=>[entry.field,entry])),DEFERRABLE_BY_ALIAS=new Map(DEFERRABLE_ITEM_FIELDS.flatMap(entry=>entry.aliases.map(alias=>[alias,entry])));function resolveDeferrableItemField(input){return DEFERRABLE_BY_ALIAS.get(input.trim().toLowerCase())}function deferrableItemFieldByKey(field){return DEFERRABLE_BY_FIELD.get(field)}function hasConcreteItemFieldValue(metadata,field){const value=metadata[field];return typeof value=="string"?value.trim().length>0:typeof value=="number"?Number.isFinite(value):value!=null}function outstandingDeferredFields(metadata){return(metadata.deferred_fields??[]).filter(entry=>!hasConcreteItemFieldValue(metadata,entry.field))}function pruneResolvedDeferredFields(metadata){const entries=metadata.deferred_fields;if(entries===void 0||entries.length===0)return!1;const outstanding=outstandingDeferredFields(metadata);return outstanding.length===entries.length?!1:(outstanding.length===0?delete metadata.deferred_fields:metadata.deferred_fields=outstanding,!0)}function describeInvalidDeferredFields(value){if(value===void 0)return;if(!Array.isArray(value))return"deferred_fields must be an array";const seen=new Set;for(const[index,entry]of value.entries()){if(typeof entry!="object"||entry===null||Array.isArray(entry))return`deferred_fields[${index}] must be an object`;const{field,reason}=entry;if(typeof field!="string"||!DEFERRABLE_BY_FIELD.has(field))return`deferred_fields[${index}].field must be one of ${DEFERRABLE_ITEM_FIELDS.map(item=>item.field).join(", ")}`;if(typeof reason!="string"||reason.trim().length===0)return`deferred_fields[${index}].reason must be a non-empty string`;if(seen.has(field))return`deferred_fields lists ${field} more than once`;seen.add(field)}}function normalizeDeferredFields(values){if(!(values===void 0||values.length===0))return values.map(entry=>({field:entry.field,reason:entry.reason.trim()})).sort((left,right)=>left.field.localeCompare(right.field))}export{DEFERRABLE_ITEM_FIELDS,deferrableItemFieldByKey,describeInvalidDeferredFields,hasConcreteItemFieldValue,normalizeDeferredFields,outstandingDeferredFields,pruneResolvedDeferredFields,resolveDeferrableItemField};
1
+ const d=[{field:"acceptance_criteria",option:"acceptanceCriteria",flag:"--acceptance-criteria",aliases:["acceptance_criteria","acceptance-criteria","acceptancecriteria","ac"]},{field:"assignee",option:"assignee",flag:"--assignee",aliases:["assignee"]},{field:"deadline",option:"deadline",flag:"--deadline",aliases:["deadline"]},{field:"estimated_minutes",option:"estimatedMinutes",flag:"--estimate",aliases:["estimated_minutes","estimated-minutes","estimatedminutes","estimate"]}],f=new Map(d.map(e=>[e.field,e])),l=new Map(d.flatMap(e=>e.aliases.map(r=>[r,e])));function c(e){return l.get(e.trim().toLowerCase())}function p(e){return f.get(e)}function o(e,r){const i=e[r];return typeof i=="string"?i.trim().length>0:typeof i=="number"?Number.isFinite(i):i!=null}function u(e){return(e.deferred_fields??[]).filter(r=>!o(e,r.field))}function m(e){const r=e.deferred_fields;if(r===void 0||r.length===0)return!1;const i=u(e);return i.length===r.length?!1:(i.length===0?delete e.deferred_fields:e.deferred_fields=i,!0)}function g(e){if(e===void 0)return;if(!Array.isArray(e))return"deferred_fields must be an array";const r=new Set;for(const[i,t]of e.entries()){if(typeof t!="object"||t===null||Array.isArray(t))return`deferred_fields[${i}] must be an object`;const{field:n,reason:s}=t;if(typeof n!="string"||!f.has(n))return`deferred_fields[${i}].field must be one of ${d.map(a=>a.field).join(", ")}`;if(typeof s!="string"||s.trim().length===0)return`deferred_fields[${i}].reason must be a non-empty string`;if(r.has(n))return`deferred_fields lists ${n} more than once`;r.add(n)}}function _(e){if(!(e===void 0||e.length===0))return e.map(r=>({field:r.field,reason:r.reason.trim()})).sort((r,i)=>r.field.localeCompare(i.field))}export{d as DEFERRABLE_ITEM_FIELDS,p as deferrableItemFieldByKey,g as describeInvalidDeferredFields,o as hasConcreteItemFieldValue,_ as normalizeDeferredFields,u as outstandingDeferredFields,m as pruneResolvedDeferredFields,c as resolveDeferrableItemField};
2
2
  //# sourceMappingURL=deferred-fields.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]="e216fd39-09ee-5a04-b0b5-44f518db4f93")}catch{}})();function isExternalDependencyReference(target){const normalized=target?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(normalized)||/^(?:github|gitlab|jira|linear):/iu.test(normalized)}function isExternalDependencySourceKind(sourceKind){const normalized=sourceKind?.trim().toLowerCase();return normalized==="global"||normalized==="external"}export{isExternalDependencyReference,isExternalDependencySourceKind};
1
+ function t(n){const e=n?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:github|gitlab|jira|linear):/iu.test(e)}function r(n){const e=n?.trim().toLowerCase();return e==="global"||e==="external"}export{t as isExternalDependencyReference,r as isExternalDependencySourceKind};
2
2
  //# sourceMappingURL=dependency-reference.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]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();import crypto from"node:crypto";import path from"node:path";import{TYPE_TO_FOLDER}from"../shared/constants.js";import{pathExists}from"../fs/fs-utils.js";import{nextReproducibleToken}from"../reproducibility/context.js";function normalizePrefix(input){const normalized=[];let separatorPending=!1;for(const character of(input??"").toLowerCase()){const codePoint=character.charCodeAt(0),isAsciiDigit=codePoint>=48&&codePoint<=57,isAsciiLetter=codePoint>=97&&codePoint<=122;if(!isAsciiDigit&&!isAsciiLetter){separatorPending=normalized.length>0;continue}separatorPending&&(normalized.push("-"),separatorPending=!1),normalized.push(character)}return normalized.length===0?"pm-":`${normalized.join("")}-`}function normalizeRawItemId(input){let normalized=input.trim().toLowerCase();return normalized.startsWith("#")&&(normalized=normalized.slice(1)),normalized}function normalizeItemId(input,prefix){const canonicalPrefix=normalizePrefix(prefix),normalized=normalizeRawItemId(input);return normalized.startsWith(canonicalPrefix)?normalized:`${canonicalPrefix}${normalized}`}function randomToken(length){const reproducibleToken=nextReproducibleToken(length);if(reproducibleToken!==void 0)return reproducibleToken;let token="";for(let index=0;index<length;index+=1)token+=crypto.randomInt(0,36).toString(36);return token}async function idExists(pmRoot,id,typeToFolder){const checks=[...new Set(Object.values(typeToFolder))].flatMap(folder=>[path.join(pmRoot,folder,`${id}.md`),path.join(pmRoot,folder,`${id}.toon`)]);return checks.push(path.join(pmRoot,"history",`${id}.jsonl`)),(await Promise.all(checks.map(target=>pathExists(target)))).some(Boolean)}const ID_TOKEN_LENGTH_MIN=4,ID_TOKEN_LENGTH_MAX=12;function clampIdTokenLength(value){return typeof value!="number"||!Number.isFinite(value)?ID_TOKEN_LENGTH_MIN:Math.min(ID_TOKEN_LENGTH_MAX,Math.max(ID_TOKEN_LENGTH_MIN,Math.trunc(value)))}async function generateItemId(pmRoot,prefix,options={}){let tokenLength=clampIdTokenLength(options.tokenLength);const maxTokenLength=Math.min(tokenLength+6,ID_TOKEN_LENGTH_MAX);let attempts=0;for(;tokenLength<=maxTokenLength;){for(let i=0;i<32;i+=1){const id=`${normalizePrefix(prefix)}${randomToken(tokenLength)}`;if(!await(options.probeExisting===!1?pathExists(path.join(pmRoot,"history",`${id}.jsonl`)):idExists(pmRoot,id,options.typeToFolder??TYPE_TO_FOLDER)))return id;attempts+=1}tokenLength+=1}throw new Error(`Unable to generate unique id after ${attempts} attempts`)}export{ID_TOKEN_LENGTH_MAX,ID_TOKEN_LENGTH_MIN,clampIdTokenLength,generateItemId,normalizeItemId,normalizePrefix,normalizeRawItemId};
1
+ import p from"node:crypto";import s from"node:path";import{TYPE_TO_FOLDER as h}from"../shared/constants.js";import{pathExists as m}from"../fs/fs-utils.js";import{nextReproducibleToken as d}from"../reproducibility/context.js";function f(e){const t=[];let o=!1;for(const n of(e??"").toLowerCase()){const r=n.charCodeAt(0),i=r>=48&&r<=57,a=r>=97&&r<=122;if(!i&&!a){o=t.length>0;continue}o&&(t.push("-"),o=!1),t.push(n)}return t.length===0?"pm-":`${t.join("")}-`}function x(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function _(e,t){const o=f(t),n=x(e);return n.startsWith(o)?n:`${o}${n}`}function T(e){const t=d(e);if(t!==void 0)return t;let o="";for(let n=0;n<e;n+=1)o+=p.randomInt(0,36).toString(36);return o}async function g(e,t,o){const n=[...new Set(Object.values(o))].flatMap(r=>[s.join(e,r,`${t}.md`),s.join(e,r,`${t}.toon`)]);return n.push(s.join(e,"history",`${t}.jsonl`)),(await Promise.all(n.map(r=>m(r)))).some(Boolean)}const u=4,l=12;function I(e){return typeof e!="number"||!Number.isFinite(e)?u:Math.min(l,Math.max(u,Math.trunc(e)))}async function b(e,t,o={}){let n=I(o.tokenLength);const r=Math.min(n+6,l);let i=0;for(;n<=r;){for(let a=0;a<32;a+=1){const c=`${f(t)}${T(n)}`;if(!await(o.probeExisting===!1?m(s.join(e,"history",`${c}.jsonl`)):g(e,c,o.typeToFolder??h)))return c;i+=1}n+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}export{l as ID_TOKEN_LENGTH_MAX,u as ID_TOKEN_LENGTH_MIN,I as clampIdTokenLength,b as generateItemId,_ as normalizeItemId,f as normalizePrefix,x as normalizeRawItemId};
2
2
  //# sourceMappingURL=id.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]="af340813-f1da-5d0d-9ad6-f4be63a6c96f")}catch{}})();export*from"./id.js";export*from"./item-format.js";export*from"./parse.js";export*from"./type-registry.js";
1
+ export*from"./id.js";export*from"./item-format.js";export*from"./parse.js";export*from"./type-registry.js";
2
2
  //# sourceMappingURL=index.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]="ec8ac553-25db-5fb1-bf2f-555815d7b283")}catch{}})();const BASELINE_ITEM_FORMAT_VERSION=1,CURRENT_ITEM_FORMAT_VERSION=4;function requiredItemFormatVersion(metadata){const tests=metadata.tests??[],linkedTestFormat=tests.some(test=>test.phase==="setup")?3:tests.some(test=>test.updated_by!==void 0||test.updated_at!==void 0)?2:1,deferralFormat=(metadata.deferred_fields?.length??0)>0?4:1;return Math.max(effectiveItemFormatVersion(metadata),linkedTestFormat,deferralFormat)}function effectiveItemFormatVersion(metadata){const raw=metadata.pm_format_version;return typeof raw=="number"&&Number.isInteger(raw)&&raw>=1?raw:1}function normalizeItemFormatVersion(value){if(!(typeof value!="number"||!Number.isInteger(value)||value<=1))return value}function classifyItemFormatVersion(version,current=4,minimum=current){return version<minimum?"outdated":version>current?"ahead":"current"}function scanItemFormatVersions(entries,current=4,minimum=current){const outdated=[],ahead=[];for(const entry of entries){const status=classifyItemFormatVersion(entry.version,current,minimum);status==="outdated"?outdated.push(entry.ref):status==="ahead"&&ahead.push(entry.ref)}return{outdated:outdated.sort((left,right)=>left.localeCompare(right)),ahead:ahead.sort((left,right)=>left.localeCompare(right))}}export{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,classifyItemFormatVersion,effectiveItemFormatVersion,normalizeItemFormatVersion,requiredItemFormatVersion,scanItemFormatVersions};
1
+ const i=1,u=4;function a(e){const t=e.tests??[],s=t.some(r=>r.phase==="setup")?3:t.some(r=>r.updated_by!==void 0||r.updated_at!==void 0)?2:1,E=(e.deferred_fields?.length??0)>0?4:1;return Math.max(_(e),s,E)}function _(e){const t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function f(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function I(e,t=4,s=t){return e<s?"outdated":e>t?"ahead":"current"}function d(e,t=4,s=t){const E=[],r=[];for(const o of e){const n=I(o.version,t,s);n==="outdated"?E.push(o.ref):n==="ahead"&&r.push(o.ref)}return{outdated:E.sort((o,n)=>o.localeCompare(n)),ahead:r.sort((o,n)=>o.localeCompare(n))}}export{i as BASELINE_ITEM_FORMAT_VERSION,u as CURRENT_ITEM_FORMAT_VERSION,I as classifyItemFormatVersion,_ as effectiveItemFormatVersion,f as normalizeItemFormatVersion,a as requiredItemFormatVersion,d as scanItemFormatVersions};
2
2
  //# sourceMappingURL=item-format-version.js.map
@@ -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]="5eaa8bf7-ef0a-51a2-a206-274e9d4c5f82")}catch{}})();import{encode as encodeToon}from"@toon-format/toon";import{isDeepStrictEqual}from"node:util";import{CONFIDENCE_TEXT_VALUES,ISSUE_SEVERITY_VALUES,PLAN_STEP_STATUS_VALUES,RECURRENCE_FREQUENCY_VALUES,RECURRENCE_WEEKDAY_VALUES,STATUS_VALUES,weekdayOrderIndex}from"../../types/index.js";import{coerceRuntimeFieldValue}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION,CURRENT_ITEM_FORMAT_VERSION,effectiveItemFormatVersion,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{describeInvalidDeferredFields,normalizeDeferredFields}from"./deferred-fields.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isRfc3339DateTime,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto","none"]),LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]),LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]),PLAN_STEP_STATUS_SET=new Set(PLAN_STEP_STATUS_VALUES);function normalizePathValue(value){return value.replaceAll("\\","/")}function firstNonZeroComparison(comparisons){for(const comparison of comparisons)if(comparison!==0)return comparison;return 0}function deleteUndefinedFields(record){for(const[key,value]of Object.entries(record))value===void 0&&delete record[key]}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"],STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(options?.schema)return{statusRegistry:resolveRuntimeStatusRegistry(options.schema),fieldRegistry:resolveRuntimeFieldRegistry(options.schema),unknownFieldPolicy:options.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(options.extensionFieldNames??[]),onWarning:options.onWarning}}function runtimeFieldRequiredForType(definition,typeName){return definition.required?definition.required_types.length===0?!0:definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase()):!1}function validationError(message){const field=message.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new PmCliError(`Invalid item metadata: ${message}`,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:message.includes("required")?"missing_required_field":"schema_validation_error",...field?{field}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:message})}function documentSyntaxError(format,message){throw new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format,required:`Provide a syntactically valid ${format==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function assertSupportedItemFormat(metadata,required){if(!required||typeof metadata!="object"||metadata===null)return;const formatVersion=effectiveItemFormatVersion(metadata);if(!(formatVersion<=CURRENT_ITEM_FORMAT_VERSION))throw new PmCliError(`Stored item uses format version ${formatVersion}; this runtime supports up to ${CURRENT_ITEM_FORMAT_VERSION}. Upgrade pm before reading or changing this item.`,EXIT_CODE.CONFLICT,{code:"item_format_version_unsupported",format_version:formatVersion,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function buildKnownItemMetadataKeys(runtimeContext){const knownKeys=new Set(STATIC_ITEM_METADATA_FIELD_SET);for(const definition of runtimeContext.fieldRegistry?.definitions??[])knownKeys.add(definition.metadata_key);for(const fieldName of runtimeContext.extensionFieldNames)knownKeys.add(fieldName);return knownKeys}function assertItemMetadataCondition(condition,message){condition||validationError(message)}function requireItemMetadataRecord(value,message){return(typeof value!="object"||value===null||Array.isArray(value))&&validationError(message),value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue=="string",`${fieldName} must be a string`),assertItemMetadataCondition(isTimestampLiteral(rawValue),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];value!==void 0&&(assertItemMetadataCondition(typeof value=="string",`${messagePrefix} must be a string`),assertItemMetadataCondition(isTimestampLiteral(value),`${messagePrefix} must be a valid ISO timestamp`))}function assertRecurrenceWeekdays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_weekday must be an array");for(const weekday of value){assertItemMetadataCondition(typeof weekday=="string","event.recurrence.by_weekday entries must be strings");const normalizedWeekday=weekday.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday),`event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`)}}}function assertRecurrenceMonthDays(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.by_month_day must be an array");for(const day of value)assertItemMetadataCondition(typeof day=="number"&&Number.isInteger(day)&&day>=1&&day<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function assertRecurrenceExdates(value){if(value!==void 0){assertItemMetadataCondition(Array.isArray(value),"event.recurrence.exdates must be an array");for(const exdate of value)assertItemMetadataCondition(typeof exdate=="string","event.recurrence.exdates entries must be strings"),assertItemMetadataCondition(isTimestampLiteral(exdate),"event.recurrence.exdates entries must be valid ISO timestamps")}}function assertValidRecurrenceRule(recurrence){const recurrenceRecord=requireItemMetadataRecord(recurrence,"event.recurrence must be an object");assertItemMetadataCondition(typeof recurrenceRecord.freq=="string","event.recurrence.freq must be a string");const frequency=recurrenceRecord.freq.trim().toLowerCase();assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency),`event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`),assertPositiveIntegerField(recurrenceRecord,"interval","event.recurrence.interval"),assertPositiveIntegerField(recurrenceRecord,"count","event.recurrence.count"),assertOptionalTimestampString(recurrenceRecord,"until","event.recurrence.until"),assertRecurrenceWeekdays(recurrenceRecord.by_weekday),assertRecurrenceMonthDays(recurrenceRecord.by_month_day),assertRecurrenceExdates(recurrenceRecord.exdates)}function assertRequiredItemMetadataFields(record){for(const fieldName of REQUIRED_STRING_FIELDS)assertItemMetadataCondition(typeof record[fieldName]=="string",`${fieldName} is required and must be a string`);const itemType=record.type;assertItemMetadataCondition(typeof itemType=="string"&&itemType.trim().length>0,"type must be a non-empty string");const formatVersion=record.pm_format_version;return formatVersion!==void 0&&assertItemMetadataCondition(typeof formatVersion=="number"&&Number.isInteger(formatVersion)&&formatVersion>=BASELINE_ITEM_FORMAT_VERSION,`pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`),itemType}function assertStatusItemMetadataField(record,runtimeContext){const status=record.status;assertItemMetadataCondition(typeof status=="string"&&status.trim().length>0,"status must be a non-empty string");const statusRegistry=runtimeContext?.statusRegistry,normalizedStatus=normalizeStatusInput(status,statusRegistry),statusDomain=statusRegistry?statusRegistry.definitions.map(definition=>definition.id):[...STATUS_VALUES];assertItemMetadataCondition(normalizedStatus!==void 0,`status must be one of: ${statusDomain.join(", ")}`)}function assertPriorityAndTags(record){const priority=record.priority;assertItemMetadataCondition(typeof priority=="number"&&Number.isInteger(priority)&&[0,1,2,3,4].includes(priority),"priority must be an integer 0..4");const tags=record.tags;assertItemMetadataCondition(Array.isArray(tags),"tags must be an array");for(const tag of tags)assertItemMetadataCondition(typeof tag=="string","tags entries must be strings")}function assertConfidenceItemMetadataField(record){const confidence=record.confidence;if(confidence!==void 0){if(typeof confidence=="number"){assertItemMetadataCondition(Number.isInteger(confidence)&&confidence>=0&&confidence<=100,"confidence number value must be an integer 0..100");return}if(typeof confidence=="string"){const normalizedConfidence=confidence.trim().toLowerCase(),isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(!1,"confidence must be a number or string")}}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0)return;typeof severity!="string"&&validationError("severity must be a string");const normalizedSeverity=severity.trim().toLowerCase(),isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){record.regression!==void 0&&typeof record.regression!="boolean"&&validationError("regression must be a boolean")}function assertReminderEntries(record){const reminders=record.reminders;if(reminders!==void 0){assertItemMetadataCondition(Array.isArray(reminders),"reminders must be an array");for(const reminder of reminders){const reminderRecord=requireItemMetadataRecord(reminder,"reminders entries must be objects");assertItemMetadataCondition(typeof reminderRecord.at=="string","reminder.at must be a string"),assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at),"reminder.at must be a valid ISO timestamp"),assertItemMetadataCondition(typeof reminderRecord.text=="string","reminder.text must be a string"),assertItemMetadataCondition(reminderRecord.text.trim().length>0,"reminder.text must not be empty")}}}function assertEventStringFields(eventRecord){for(const stringField of["title","description","location","timezone"])eventRecord[stringField]!==void 0&&(assertItemMetadataCondition(typeof eventRecord[stringField]=="string",`event.${stringField} must be a string`),assertItemMetadataCondition(eventRecord[stringField].trim().length>0,`event.${stringField} must not be empty`))}function assertEventRecurrence(eventRecord){eventRecord.recurrence!==void 0&&(assertValidRecurrenceRule(eventRecord.recurrence),eventRecord.recurrence.until!==void 0&&assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until,eventRecord.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function assertCalendarEventEntry(event){const eventRecord=requireItemMetadataRecord(event,"events entries must be objects");assertItemMetadataCondition(typeof eventRecord.start_at=="string","event.start_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at),"event.start_at must be a valid ISO timestamp"),eventRecord.end_at!==void 0&&(assertItemMetadataCondition(typeof eventRecord.end_at=="string","event.end_at must be a string"),assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at),"event.end_at must be a valid ISO timestamp"),assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at,eventRecord.start_at)>0,"event.end_at must be after event.start_at")),assertEventStringFields(eventRecord),eventRecord.all_day!==void 0&&assertItemMetadataCondition(typeof eventRecord.all_day=="boolean","event.all_day must be a boolean"),assertEventRecurrence(eventRecord)}function assertCalendarEvents(record){const events=record.events;if(events!==void 0){assertItemMetadataCondition(Array.isArray(events),"events must be an array");for(const event of events)assertCalendarEventEntry(event)}}function assertOptionalStringFields(record){for(const fieldName of["source_type","source_owner","design","external_ref"]){const value=record[fieldName];value!==void 0&&assertItemMetadataCondition(typeof value=="string",`${fieldName} must be a string`)}}function assertTypeOptionsField(record){const typeOptions=record.type_options;if(typeOptions===void 0)return;const typeOptionsRecord=requireItemMetadataRecord(typeOptions,"type_options must be an object");for(const[optionKey,optionValue]of Object.entries(typeOptionsRecord))assertItemMetadataCondition(optionKey.trim().length>0,"type_options keys must be non-empty"),assertItemMetadataCondition(typeof optionValue=="string","type_options values must be strings"),assertItemMetadataCondition(optionValue.trim().length>0,"type_options values must be non-empty strings")}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(runtimeContext?.fieldRegistry)for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){runtimeFieldRequiredForType(definition,itemType)&&validationError(`missing required schema field: ${definition.metadata_key}`);continue}try{record[definition.metadata_key]=coerceRuntimeFieldValue(definition,fieldValue,`metadata field "${definition.metadata_key}"`,"metadata")}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length!==0&&(runtimeContext.unknownFieldPolicy==="reject"?validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`):runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`))}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object"),itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext),assertPriorityAndTags(record),assertConfidenceItemMetadataField(record),assertSeverityItemMetadataField(record),assertRegressionItemMetadataField(record),assertTimestampField(record,"created_at"),assertTimestampField(record,"updated_at"),record.deadline!==void 0&&assertTimestampField(record,"deadline"),assertReminderEntries(record),assertCalendarEvents(record),assertOptionalTimestampString(record,"closed_at","closed_at"),assertOptionalTimestampString(record,"completed_at","completed_at"),assertOptionalStringFields(record),assertTypeOptionsField(record);const invalidDeferral=describeInvalidDeferredFields(record.deferred_fields);assertItemMetadataCondition(invalidDeferral===void 0,invalidDeferral??""),coerceRuntimeItemMetadataFields(record,itemType,runtimeContext),assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!(!values||values.length===0))return[...values].map((value,index)=>(assertItemMetadataCondition(value.created_at===void 0||typeof value.created_at=="string"&&isRfc3339DateTime(value.created_at),`dependencies.${index}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:value.id.trim(),kind:value.kind,created_at:value.created_at,author:value.author?.trim()||void 0,source_kind:value.source_kind?.trim()||void 0,author_source:value.author_source})).sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at??"",b.created_at??"");if(byCreated!==0)return byCreated;const byId=a.id.localeCompare(b.id);if(byId!==0)return byId;const byKind=a.kind.localeCompare(b.kind);return byKind!==0?byKind:(a.source_kind??"").localeCompare(b.source_kind??"")})}const CANONICALLY_ORDERED_LOG_COLLECTIONS=new Set(["comments","notes","learnings"]),UNCONVERTIBLE_LOG_SORT_KEY="[unconvertible]";function logSortField(entry,key){try{return String(entry?.[key])}catch{return UNCONVERTIBLE_LOG_SORT_KEY}}function compareLogValues(a,b){const byCreated=compareTimestampStrings(logSortField(a,"created_at"),logSortField(b,"created_at"));if(byCreated!==0)return byCreated;const byText=logSortField(a,"text").localeCompare(logSortField(b,"text"));return byText!==0?byText:logSortField(a,"author").localeCompare(logSortField(b,"author"))}function sortLogValues(values){if(!(!values||values.length===0))return[...values].sort(compareLogValues)}function sortReminders(values){if(!values||values.length===0)return;const normalized=[...values].map(value=>({at:value.at,text:value.text.trim()})).filter(value=>value.text.length>0).sort((a,b)=>{const byAt=compareTimestampStrings(a.at,b.at);return byAt!==0?byAt:a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value)return;const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency))return;const byWeekday=Array.from(new Set((value.by_weekday??[]).map(weekday=>weekday.trim().toLowerCase()).filter(weekday=>RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a,b)=>weekdayOrderIndex(a)-weekdayOrderIndex(b)),byMonthDay=Array.from(new Set((value.by_month_day??[]).filter(day=>Number.isInteger(day)&&day>=1&&day<=31).map(day=>day))).sort((a,b)=>a-b),exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b)),normalized={freq:normalizedFrequency,interval:value.interval!==void 0&&value.interval>1?value.interval:void 0,count:value.count,until:value.until?.trim()||void 0,by_weekday:byWeekday.length>0?byWeekday:void 0,by_month_day:byMonthDay.length>0?byMonthDay:void 0,exdates:exdates.length>0?exdates:void 0};for(const[key,fieldValue]of Object.entries(normalized))fieldValue===void 0&&delete normalized[key];return normalized}function sortEvents(values){return!Array.isArray(values)||values.length===0?void 0:[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents)}function normalizeCalendarEvent(value){const event={start_at:value.start_at,end_at:value.end_at||void 0,title:value.title?.trim()||void 0,description:value.description?.trim()||void 0,location:value.location?.trim()||void 0,all_day:value.all_day,timezone:value.timezone?.trim()||void 0,recurrence:normalizeRecurrenceRule(value.recurrence)};return deleteUndefinedFields(event),event}function compareCalendarEvents(a,b){return firstNonZeroComparison([compareTimestampStrings(a.start_at,b.start_at),(a.end_at??"").localeCompare(b.end_at??""),(a.title??"").localeCompare(b.title??""),+!!a.all_day-+!!b.all_day,(a.timezone??"").localeCompare(b.timezone??""),(a.location??"").localeCompare(b.location??""),(a.description??"").localeCompare(b.description??""),JSON.stringify(a.recurrence??{}).localeCompare(JSON.stringify(b.recurrence??{}))])}function normalizeFiles(values){if(!(!values||values.length===0))return values.map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0}))}function normalizeTestRunSummaries(values){if(!values||values.length===0)return;const normalized=values.map(normalizeTestRunSummary).filter(value=>value.run_id.length>0&&value.started_at.length>0&&value.finished_at.length>0&&value.recorded_at.length>0).sort((a,b)=>firstNonZeroComparison([compareTimestampStrings(a.recorded_at,b.recorded_at),a.run_id.localeCompare(b.run_id),a.kind.localeCompare(b.kind)]));return normalized.length>0?normalized:void 0}function normalizeNonNegativeInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0?Math.floor(value):void 0}function normalizePositiveInteger(value){return typeof value=="number"&&Number.isFinite(value)&&value>=1?Math.floor(value):void 0}function stringOrEmpty(value){return typeof value=="string"?value:""}function normalizeTestRunMeasurements(value){if(!Array.isArray(value))return;const normalized=value.filter(measurement=>measurement!==null&&typeof measurement=="object"&&typeof measurement.name=="string"&&measurement.name.trim().length>0&&typeof measurement.value=="number"&&Number.isFinite(measurement.value)&&typeof measurement.recorded_at=="string"&&measurement.recorded_at.trim().length>0).map(measurement=>({name:measurement.name.trim(),value:measurement.value,unit:typeof measurement.unit=="string"&&measurement.unit.trim()||void 0,threshold:typeof measurement.threshold=="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()})),deduplicated=[...new Map(normalized.map(measurement=>[measurement.name,measurement])).values()].sort((left,right)=>left.name.localeCompare(right.name)).slice(0,32);return deduplicated.length>0?deduplicated:void 0}function normalizeTestRunEnum(value,allowedValues){return typeof value=="string"&&allowedValues.has(value)?value:void 0}function normalizeTestRunExecutions(values){if(!Array.isArray(values))return;const executions=values.filter(execution=>execution&&typeof execution.command=="string"&&execution.command.trim().length>0).slice(0,32).map(execution=>({command:execution.command.trim(),requested_pm_context_mode:normalizeTestRunEnum(execution.requested_pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),pm_context_mode:normalizeTestRunEnum(execution.pm_context_mode,LINKED_TEST_PM_CONTEXT_MODE_VALUES),workspace_context_mode:normalizeTestRunEnum(execution.workspace_context_mode,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),trust_reason:normalizeTestRunEnum(execution.trust_reason,LINKED_TEST_TRUST_REASON_VALUES)}));return executions.length>0?executions:void 0}function normalizeTestRunSummary(value){const runId=typeof value.run_id=="string"?value.run_id.trim():"",kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test",status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed",summary={run_id:runId,kind,status,started_at:stringOrEmpty(value.started_at),finished_at:stringOrEmpty(value.finished_at),recorded_at:stringOrEmpty(value.recorded_at),attempt:normalizePositiveInteger(value.attempt),resumed_from:value.resumed_from?.trim()||void 0,passed:normalizeNonNegativeInteger(value.passed)??0,failed:normalizeNonNegativeInteger(value.failed)??0,skipped:normalizeNonNegativeInteger(value.skipped)??0,items:normalizeNonNegativeInteger(value.items),linked_tests:normalizeNonNegativeInteger(value.linked_tests),fail_on_skipped_triggered:value.fail_on_skipped_triggered===!0?!0:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};return deleteUndefinedFields(summary),summary}function sortTests(values){if(!(!Array.isArray(values)||values.length===0))return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value))return;const normalized=[...new Set(value.filter(entry=>typeof entry=="string").map(entry=>entry.trim()).filter(entry=>entry.length>0))].sort((a,b)=>a.localeCompare(b));return normalized.length>0?normalized:void 0}function isPlainObjectRecord(value){if(!value||typeof value!="object"||Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===Object.prototype||prototype===null}function isUnsafeObjectKey(key){return key==="__proto__"||key==="constructor"||key==="prototype"}function normalizeStringRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),String(recordValue).trim()]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&recordValue.length>0).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeNumericRecord(value){if(!isPlainObjectRecord(value))return;const entries=Object.entries(value).map(([key,recordValue])=>[key.trim(),Number(recordValue)]).filter(([key,recordValue])=>key.length>0&&!isUnsafeObjectKey(key)&&Number.isFinite(recordValue)).sort(([left],[right])=>left.localeCompare(right));return entries.length>0?Object.fromEntries(entries):void 0}function normalizeLinkedTestContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)))return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===!0)return{provenance_invalid:!0};if(value===void 0)return{};if(!isPlainObjectRecord(value))return{provenance_invalid:!0};const author=trimStringOrUndefined(value.author),createdAt=trimStringOrUndefined(value.created_at),sourceKind=value.source_kind;return!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"?{provenance_invalid:!0}:{provenance:{author,created_at:createdAt,source_kind:sourceKind,source_ref:trimStringOrUndefined(value.source_ref)}}}function normalizeLinkedTest(value){const test={command:value.command?.trim()||void 0,path:value.path?normalizePathValue(value.path):void 0,scope:value.scope,timeout_seconds:typeof value.timeout_seconds=="number"&&Number.isFinite(value.timeout_seconds)&&value.timeout_seconds>0?value.timeout_seconds:void 0,pm_context_mode:normalizeLinkedTestContextMode(value.pm_context_mode),workspace_context_mode:normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),...normalizeLinkedTestProvenance(value.provenance,value.provenance_invalid),updated_by:trimStringOrUndefined(value.updated_by),updated_at:trimStringOrUndefined(value.updated_at),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===!0?!0:void 0,assert_stdout_contains:normalizeTrimmedStringList(value.assert_stdout_contains),assert_stdout_regex:normalizeTrimmedStringList(value.assert_stdout_regex),assert_stderr_contains:normalizeTrimmedStringList(value.assert_stderr_contains),assert_stderr_regex:normalizeTrimmedStringList(value.assert_stderr_regex),assert_stdout_min_lines:normalizeNonNegativeInteger(value.assert_stdout_min_lines),assert_json_field_equals:normalizeStringRecord(value.assert_json_field_equals),assert_json_field_gte:normalizeNumericRecord(value.assert_json_field_gte),note:value.note?.trim()||void 0,phase:value.phase==="setup"?"setup":void 0};return deleteUndefinedFields(test),test}function sortDocs(values){if(!(!values||values.length===0))return[...values].map(value=>({path:normalizePathValue(value.path),scope:value.scope,note:value.note?.trim()||void 0})).sort((a,b)=>{const byScope=a.scope.localeCompare(b.scope);if(byScope!==0)return byScope;const byPath=a.path.localeCompare(b.path);return byPath!==0?byPath:(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!="string")return;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,id=trimStringOrUndefined(record.id),kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind},note=trimStringOrUndefined(record.note);note&&(link.note=note),record.required_before_step===!0&&(link.required_before_step=!0),out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(file.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(file.note=note),out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,command=trimStringOrUndefined(record.command),path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};command&&(test.command=command),path&&(test.path=normalizePathValue(path));const note=trimStringOrUndefined(record.note);note&&(test.note=note),out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};(record.scope==="project"||record.scope==="global")&&(doc.scope=record.scope);const note=trimStringOrUndefined(record.note);note&&(doc.note=note),out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!="object")return;const record=entry,id=trimStringOrUndefined(record.id),title=trimStringOrUndefined(record.title),statusRaw=trimStringOrUndefined(record.status),status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0,order=coerceFiniteNumber(record.order)??Number.NaN,created_at=typeof record.created_at=="string"?record.created_at:"",updated_at=typeof record.updated_at=="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at)return;const step={id,order,title,status,created_at,updated_at};return applyPlanStepOptionalFields(step,record),step}function applyPlanStepOptionalFields(step,record){const stringFields=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[target,source]of stringFields){const value=trimStringOrUndefined(record[source]);value&&(step[target]=value)}const completedAt=typeof record.completed_at=="string"?record.completed_at:void 0;completedAt&&completedAt.length>0&&(step.completed_at=completedAt);const collectionFields=[["linked_items","linked_items",normalizePlanStepLinks],["files","files",normalizePlanStepFiles],["tests","tests",normalizePlanStepTests],["docs","docs",normalizePlanStepDocs]];for(const[target,source,normalize]of collectionFields){const value=normalize(record[source]);value&&(step[target]=value)}}function normalizePlanSteps(value){if(!Array.isArray(value))return;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});return out.sort((left,right)=>left.order-right.order),out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision},rationale=trimStringOrUndefined(record.rationale);rationale&&(item.rationale=rationale);const evidence=trimStringOrUndefined(record.evidence);evidence&&(item.evidence=evidence);const stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,ts=typeof record.ts=="string"?record.ts:"",author=typeof record.author=="string"?record.author:"",text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text},stepId=trimStringOrUndefined(record.step_id);stepId&&(item.step_id=stepId),out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return;const out=[];for(const entry of value){if(entry===null||typeof entry!="object")continue;const record=entry,text=trimStringOrUndefined(record.text);if(!text)continue;const item={text},command=trimStringOrUndefined(record.command);command&&(item.command=command);const expected=trimStringOrUndefined(record.expected);expected&&(item.expected=expected),out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values)return;const normalizedEntries=Object.entries(values).map(([key,value])=>[key.trim(),value.trim()]).filter(([key,value])=>key.length>0&&value.length>0).sort((left,right)=>left[0].localeCompare(right[0]));if(normalizedEntries.length!==0)return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;for(;start<body.length&&body[start]===`
2
- `;)start+=1;return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0)return;if(typeof value=="number")return value;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(CONFIDENCE_TEXT_VALUES.includes(normalized))return normalized}function normalizeSeverityValue(value){if(value===void 0)return;const normalized=value.trim().toLowerCase();if(normalized==="med")return"medium";if(ISSUE_SEVERITY_VALUES.includes(normalized))return normalized}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized,sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord))isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0||(targetRecord[key]=value)}function coerceNormalizedRuntimeFields(normalized,runtimeContext){if(!runtimeContext?.fieldRegistry)return;const record=normalized;for(const definition of runtimeContext.fieldRegistry.definitions){const currentValue=record[definition.metadata_key];currentValue!==void 0&&(record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`,"metadata"))}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow")return;const knownKeys=buildKnownItemMetadataKeys(runtimeContext),unknownKeys=Object.keys(normalized).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"&&validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`),unknownKeys.length>0&&runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options),normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status,tags=Array.from(new Set((Array.isArray(itemMetadata.tags)?itemMetadata.tags:[]).filter(tag=>typeof tag=="string").map(tag=>tag.trim().toLowerCase()).filter(Boolean))).sort((a,b)=>a.localeCompare(b)),normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,deferred_fields:normalizeDeferredFields(itemMetadata.deferred_fields),design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};return copyExtensionItemMetadataFields(normalized,itemMetadata),coerceNormalizedRuntimeFields(normalized,runtimeContext),assertNormalizedUnknownFields(normalized,runtimeContext),deleteUndefinedFields(normalized),normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0,inString=!1,escaped=!1;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=!1;continue}if(char==="\\"){escaped=!0;continue}char==='"'&&(inString=!1);continue}if(char==='"'){inString=!0;continue}if(char==="{"){depth+=1;continue}if(char==="}"&&(depth-=1,depth===0))return i}return-1}function splitFrontMatter(content){if(!content.startsWith("{"))return{frontMatter:"",body:content};const end=findJsonObjectEnd(content);if(end<0)return{frontMatter:"",body:content};const frontMatter=content.slice(0,end+1),body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content,opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener)return{content:normalizedContent,stripped:!1};let cursor=opener[0].length;for(;cursor<normalizedContent.length;){const nextNewline=normalizedContent.indexOf(`
3
- `,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}
1
+ import{encode as Ee}from"@toon-format/toon";import{isDeepStrictEqual as G}from"node:util";import{CONFIDENCE_TEXT_VALUES as I,ISSUE_SEVERITY_VALUES as F,PLAN_STEP_STATUS_VALUES as Oe,RECURRENCE_FREQUENCY_VALUES as x,RECURRENCE_WEEKDAY_VALUES as z,STATUS_VALUES as ke,weekdayOrderIndex as Y}from"../../types/index.js";import{coerceRuntimeFieldValue as X}from"../schema/runtime-field-values.js";import{resolveRuntimeFieldRegistry as Te,resolveRuntimeStatusRegistry as Ae}from"../schema/runtime-schema.js";import{BASELINE_ITEM_FORMAT_VERSION as Q,CURRENT_ITEM_FORMAT_VERSION as Z,effectiveItemFormatVersion as Re,normalizeItemFormatVersion as Ne}from"./item-format-version.js";import{normalizeStatusInput as H}from"./status.js";import{describeInvalidDeferredFields as Ie,normalizeDeferredFields as Fe}from"./deferred-fields.js";import{decodeToonItemContent as M}from"./toon-decode.js";import{EXIT_CODE as _,ITEM_METADATA_KEY_ORDER as ee}from"../shared/constants.js";import{findFirstMergeConflictMarker as xe}from"../shared/conflict-markers.js";import{PmCliError as y}from"../shared/errors.js";import{orderObject as ze}from"../shared/serialization.js";import{compareTimestampStrings as m,isRfc3339DateTime as Ce,isTimestampLiteral as l}from"../shared/time.js";import{coerceFiniteNumber as je}from"../shared/primitives.js";const C=new Set(["schema","tracker","auto","none"]),te=new Set(["source","isolated","snapshot"]),Le=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),De=new Set(["passed","failed","stopped","canceled"]),Pe=new Set(Oe);function h(e){return e.replaceAll("\\","/")}function j(e){for(const t of e)if(t!==0)return t;return 0}function A(e){for(const[t,n]of Object.entries(e))n===void 0&&delete e[t]}const ne=["id","title","description","created_at","updated_at"],$e=new Set(ee);function re(e){if(e?.schema)return{statusRegistry:Ae(e.schema),fieldRegistry:Te(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function oe(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function p(e){const t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new y(`Invalid item metadata: ${e}`,_.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function E(e,t){throw new y(t,_.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function ie(e,t){if(!t||typeof e!="object"||e===null)return;const n=Re(e);if(!(n<=Z))throw new y(`Stored item uses format version ${n}; this runtime supports up to ${Z}. Upgrade pm before reading or changing this item.`,_.CONFLICT,{code:"item_format_version_unsupported",format_version:n,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 L(e){const t=new Set($e);for(const n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(const n of e.extensionFieldNames)t.add(n);return t}function c(e,t){e||p(t)}function O(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&p(t),e}function D(e,t){const n=e[t];c(typeof n=="string",`${t} must be a string`),c(l(n),`${t} must be a valid ISO timestamp`)}function se(e,t,n){const r=e[t];r!==void 0&&c(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function P(e,t,n){const r=e[t];r!==void 0&&(c(typeof r=="string",`${n} must be a string`),c(l(r),`${n} must be a valid ISO timestamp`))}function Ue(e){if(e!==void 0){c(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(const t of e){c(typeof t=="string","event.recurrence.by_weekday entries must be strings");const n=t.trim().toLowerCase();c(z.includes(n),`event.recurrence.by_weekday entries must be one of: ${z.join(", ")}`)}}}function qe(e){if(e!==void 0){c(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(const t of e)c(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Ve(e){if(e!==void 0){c(Array.isArray(e),"event.recurrence.exdates must be an array");for(const t of e)c(typeof t=="string","event.recurrence.exdates entries must be strings"),c(l(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Ke(e){const t=O(e,"event.recurrence must be an object");c(typeof t.freq=="string","event.recurrence.freq must be a string");const n=t.freq.trim().toLowerCase();c(x.includes(n),`event.recurrence.freq must be one of: ${x.join(", ")}`),se(t,"interval","event.recurrence.interval"),se(t,"count","event.recurrence.count"),P(t,"until","event.recurrence.until"),Ue(t.by_weekday),qe(t.by_month_day),Ve(t.exdates)}function Je(e){for(const r of ne)c(typeof e[r]=="string",`${r} is required and must be a string`);const t=e.type;c(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");const n=e.pm_format_version;return n!==void 0&&c(typeof n=="number"&&Number.isInteger(n)&&n>=Q,`pm_format_version must be an integer >= ${Q}`),t}function ve(e,t){const n=e.status;c(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");const r=t?.statusRegistry,o=H(n,r),i=r?r.definitions.map(s=>s.id):[...ke];c(o!==void 0,`status must be one of: ${i.join(", ")}`)}function We(e){const t=e.priority;c(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");const n=e.tags;c(Array.isArray(n),"tags must be an array");for(const r of n)c(typeof r=="string","tags entries must be strings")}function Be(e){const t=e.confidence;if(t!==void 0){if(typeof t=="number"){c(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){const n=t.trim().toLowerCase(),r=n==="med"||I.includes(n);c(r,`confidence string value must be one of: ${[...I,"med"].join(", ")}`);return}c(!1,"confidence must be a number or string")}}function Ge(e){const t=e.severity;if(t===void 0)return;typeof t!="string"&&p("severity must be a string");const n=t.trim().toLowerCase(),r=n==="med"||F.includes(n);c(r,`severity value must be one of: ${[...F,"med"].join(", ")}`)}function Ye(e){e.regression!==void 0&&typeof e.regression!="boolean"&&p("regression must be a boolean")}function Xe(e){const t=e.reminders;if(t!==void 0){c(Array.isArray(t),"reminders must be an array");for(const n of t){const r=O(n,"reminders entries must be objects");c(typeof r.at=="string","reminder.at must be a string"),c(l(r.at),"reminder.at must be a valid ISO timestamp"),c(typeof r.text=="string","reminder.text must be a string"),c(r.text.trim().length>0,"reminder.text must not be empty")}}}function Qe(e){for(const t of["title","description","location","timezone"])e[t]!==void 0&&(c(typeof e[t]=="string",`event.${t} must be a string`),c(e[t].trim().length>0,`event.${t} must not be empty`))}function Ze(e){e.recurrence!==void 0&&(Ke(e.recurrence),e.recurrence.until!==void 0&&c(m(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function He(e){const t=O(e,"events entries must be objects");c(typeof t.start_at=="string","event.start_at must be a string"),c(l(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(c(typeof t.end_at=="string","event.end_at must be a string"),c(l(t.end_at),"event.end_at must be a valid ISO timestamp"),c(m(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Qe(t),t.all_day!==void 0&&c(typeof t.all_day=="boolean","event.all_day must be a boolean"),Ze(t)}function Me(e){const t=e.events;if(t!==void 0){c(Array.isArray(t),"events must be an array");for(const n of t)He(n)}}function et(e){for(const t of["source_type","source_owner","design","external_ref"]){const n=e[t];n!==void 0&&c(typeof n=="string",`${t} must be a string`)}}function tt(e){const t=e.type_options;if(t===void 0)return;const n=O(t,"type_options must be an object");for(const[r,o]of Object.entries(n))c(r.trim().length>0,"type_options keys must be non-empty"),c(typeof o=="string","type_options values must be strings"),c(o.trim().length>0,"type_options values must be non-empty strings")}function nt(e,t,n){if(n?.fieldRegistry)for(const r of n.fieldRegistry.definitions){const o=e[r.metadata_key];if(o===void 0){oe(r,t)&&p(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=X(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){p(String(i?.message).replace(/^Invalid\s+/u,""))}}}function rt(e,t){if(!t||t.unknownFieldPolicy==="allow")return;const n=L(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?p(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function $(e,t){const n=O(e,"item metadata must be an object"),r=Je(n);ve(n,t),We(n),Be(n),Ge(n),Ye(n),D(n,"created_at"),D(n,"updated_at"),n.deadline!==void 0&&D(n,"deadline"),Xe(n),Me(n),P(n,"closed_at","closed_at"),P(n,"completed_at","completed_at"),et(n),tt(n);const o=Ie(n.deferred_fields);c(o===void 0,o??""),nt(n,r,t),rt(n,t)}function ot(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(c(t.created_at===void 0||typeof t.created_at=="string"&&Ce(t.created_at),`dependencies.${n}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{const r=m(t.created_at??"",n.created_at??"");if(r!==0)return r;const o=t.id.localeCompare(n.id);if(o!==0)return o;const i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}const Mt=new Set(["comments","notes","learnings"]),it="[unconvertible]";function b(e,t){try{return String(e?.[t])}catch{return it}}function st(e,t){const n=m(b(e,"created_at"),b(t,"created_at"));if(n!==0)return n;const r=b(e,"text").localeCompare(b(t,"text"));return r!==0?r:b(e,"author").localeCompare(b(t,"author"))}function U(e){if(!(!e||e.length===0))return[...e].sort(st)}function dt(e){if(!e||e.length===0)return;const t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{const o=m(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function ct(e){if(!e)return;const t=e.freq.trim().toLowerCase();if(!x.includes(t))return;const n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>z.includes(s)))).sort((s,a)=>Y(s)-Y(a)),r=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>l(s)))).sort((s,a)=>m(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:n.length>0?n:void 0,by_month_day:r.length>0?r:void 0,exdates:o.length>0?o:void 0};for(const[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function at(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(ft).sort(ut)}function ft(e){const t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:ct(e.recurrence)};return A(t),t}function ut(e,t){return j([m(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function mt(e){if(!(!e||e.length===0))return e.map(t=>({path:h(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function de(e){if(!e||e.length===0)return;const t=e.map(yt).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>j([m(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function w(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function lt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function q(e){return typeof e=="string"?e:""}function pt(e){if(!Array.isArray(e))return;const t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function R(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function _t(e){if(!Array.isArray(e))return;const t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:R(n.requested_pm_context_mode,C),pm_context_mode:R(n.pm_context_mode,C),workspace_context_mode:R(n.workspace_context_mode,te),trust_reason:R(n.trust_reason,Le)}));return t.length>0?t:void 0}function yt(e){const t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=De.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:q(e.started_at),finished_at:q(e.finished_at),recorded_at:q(e.recorded_at),attempt:lt(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:w(e.passed)??0,failed:w(e.failed)??0,skipped:w(e.skipped)??0,items:w(e.items),linked_tests:w(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:pt(e.measurements),executions:_t(e.executions)};return A(o),o}function ce(e){if(!(!Array.isArray(e)||e.length===0))return e.map(St)}function k(e){if(!Array.isArray(e))return;const t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function V(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function K(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function ae(e){if(!V(e))return;const t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!K(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function gt(e){if(!V(e))return;const t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!K(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function ht(e){const t=e?.trim().toLowerCase();if(!(!t||!C.has(t)))return t}function bt(e){const t=e?.trim().toLowerCase();if(!(!t||!te.has(t)))return t}function wt(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!V(e))return{provenance_invalid:!0};const n=d(e.author),r=d(e.created_at),o=e.source_kind;return!n||!r||!l(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:d(e.source_ref)}}}function St(e){const t={command:e.command?.trim()||void 0,path:e.path?h(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:ht(e.pm_context_mode),workspace_context_mode:bt(e.workspace_context_mode),...wt(e.provenance,e.provenance_invalid),updated_by:d(e.updated_by),updated_at:d(e.updated_at),env_set:ae(e.env_set),env_clear:k(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:k(e.assert_stdout_contains),assert_stdout_regex:k(e.assert_stdout_regex),assert_stderr_contains:k(e.assert_stderr_contains),assert_stderr_regex:k(e.assert_stderr_regex),assert_stdout_min_lines:w(e.assert_stdout_min_lines),assert_json_field_equals:ae(e.assert_json_field_equals),assert_json_field_gte:gt(e.assert_json_field_gte),note:e.note?.trim()||void 0,phase:e.phase==="setup"?"setup":void 0};return A(t),t}function Et(e){if(!(!e||e.length===0))return[...e].map(t=>({path:h(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{const r=t.scope.localeCompare(n.scope);if(r!==0)return r;const o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function d(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function fe(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=d(r.id),i=d(r.kind);if(!o||!i)continue;const s={id:o,kind:i},a=d(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function ue(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=d(r.path);if(!o)continue;const i={path:h(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);const s=d(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function me(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=d(r.command),i=d(r.path);if(!o&&!i)continue;const s={};o&&(s.command=o),i&&(s.path=h(i));const a=d(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function le(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=d(r.path);if(!o)continue;const i={path:h(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);const s=d(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Ot(e){if(e===null||typeof e!="object")return;const t=e,n=d(t.id),r=d(t.title),o=d(t.status),i=o&&Pe.has(o)?o:void 0,s=je(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",f=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!f)return;const u={id:n,order:s,title:r,status:i,created_at:a,updated_at:f};return kt(u,t),u}function kt(e,t){const n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(const[i,s]of n){const a=d(t[s]);a&&(e[i]=a)}const r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);const o=[["linked_items","linked_items",fe],["files","files",ue],["tests","tests",me],["docs","docs",le]];for(const[i,s,a]of o){const f=a(t[s]);f&&(e[i]=f)}}function pe(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Ot(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function _e(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=d(r.decision);if(!o||!i||!s)continue;const a={ts:o,author:i,decision:s},f=d(r.rationale);f&&(a.rationale=f);const u=d(r.evidence);u&&(a.evidence=u);const S=d(r.step_id);S&&(a.step_id=S),t.push(a)}return t.length>0?t:void 0}function ye(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=d(r.text);if(!o||!i||!s)continue;const a={ts:o,author:i,text:s},f=d(r.step_id);f&&(a.step_id=f),t.push(a)}return t.length>0?t:void 0}function ge(e){if(!Array.isArray(e))return;const t=[];for(const n of e){if(n===null||typeof n!="object")continue;const r=n,o=d(r.text);if(!o)continue;const i={text:o},s=d(r.command);s&&(i.command=s);const a=d(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function he(e){if(!e)return;const t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function g(e){let t=0;for(;t<e.length&&e[t]===`
2
+ `;)t+=1;return e.slice(t).trimEnd()}function Tt(e){if(e===void 0)return;if(typeof e=="number")return e;const t=e.trim().toLowerCase();if(t==="med")return"medium";if(I.includes(t))return t}function At(e){if(e===void 0)return;const t=e.trim().toLowerCase();if(t==="med")return"medium";if(F.includes(t))return t}function T(e){return e||void 0}function Rt(e,t){const n=e,r=t;for(const[o,i]of Object.entries(r))K(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function Nt(e,t){if(!t?.fieldRegistry)return;const n=e;for(const r of t.fieldRegistry.definitions){const o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=X(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function It(e,t){if(!t||t.unknownFieldPolicy==="allow")return;const n=L(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&p(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function N(e,t={}){const n=re(t),r=H(e.status,n?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:Ne(e.pm_format_version),source_type:d(e.source_type),type_options:he(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:ot(e.dependencies),comments:U(e.comments),notes:U(e.notes),learnings:U(e.learnings),files:mt(e.files),tests:ce(e.tests),test_runs:de(e.test_runs),docs:Et(e.docs),deadline:T(e.deadline),reminders:dt(e.reminders),events:at(e.events),closed_at:T(e.closed_at),completed_at:T(e.completed_at),assignee:d(e.assignee),claim_principal:d(e.claim_principal),source_owner:d(e.source_owner),author:T(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,deferred_fields:Fe(e.deferred_fields),design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:d(e.definition_of_ready),order:e.order,goal:d(e.goal),objective:d(e.objective),value:d(e.value),impact:d(e.impact),outcome:d(e.outcome),why_now:d(e.why_now),parent:d(e.parent),reviewer:d(e.reviewer),risk:e.risk??void 0,confidence:Tt(e.confidence),sprint:d(e.sprint),release:d(e.release),blocked_by:d(e.blocked_by),blocked_reason:d(e.blocked_reason),unblock_note:d(e.unblock_note),reporter:d(e.reporter),severity:At(e.severity),environment:d(e.environment),repro_steps:d(e.repro_steps),resolution:d(e.resolution),expected_result:d(e.expected_result),actual_result:d(e.actual_result),affected_version:d(e.affected_version),fixed_version:d(e.fixed_version),component:d(e.component),regression:e.regression,customer_impact:d(e.customer_impact),close_reason:T(e.close_reason),plan_mode:d(e.plan_mode),plan_scope:d(e.plan_scope),plan_harness:d(e.plan_harness),plan_resume_context:d(e.plan_resume_context),plan_steps:pe(e.plan_steps),plan_decisions:_e(e.plan_decisions),plan_discoveries:ye(e.plan_discoveries),plan_validation:ge(e.plan_validation)};return Rt(i,e),Nt(i,n),It(i,n),A(i),i}function be(e){return ze(e,ee)}function Ft(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){const i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function xt(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};const t=Ft(e);if(t<0)return{frontMatter:"",body:e};const n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function zt(e){const t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){const o=t.indexOf(`
3
+ `,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function J(e,t){return N(e,{...t,onWarning:void 0})}function Ct(e,t,n={}){const r=zt(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");const{frontMatter:o,body:i}=xt(r.content);o||(e.trimStart().startsWith("{")&&E("json_markdown","JSON front matter is not valid JSON"),E("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{E("json_markdown","JSON front matter is not valid JSON")}return ie(s,n.requireSupportedFormat),$(s,t),{metadata:J(s,n),body:g(i)}}function jt(e,t,n={}){let r;try{r=M(e).value}catch{E("toon","TOON item document is not valid TOON")}c(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");const o=r;if(ie(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!ne.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&E("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return $(o.front_matter,t),c(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:J(o.front_matter,n),body:g(typeof o.body=="string"?o.body:"")};const{body:i,...s}=o;return c(i===void 0||typeof i=="string","TOON item document body must be a string"),$(s,t),{metadata:J(s,n),body:g(typeof i=="string"?i:"")}}function Lt(e,t={}){const n=N(e.metadata,t),r=be(n),o=g(e.body??"");W(JSON.parse(JSON.stringify(r))),W({body:o});const i=JSON.stringify(r,null,2);return o?`${i}
4
4
 
5
- ${normalizedBody}
6
- `:`${serializedMetadata}
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{CANONICALLY_ORDERED_LOG_COLLECTIONS,_testOnlyItemFormat,canonicalDocument,compareLogValues,normalizeItemMetadata,normalizeLinkedTest,parseItemDocument,serializeItemDocument,splitFrontMatter};
5
+ ${o}
6
+ `:`${i}
7
+ `}const Dt=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function v(e,t){return typeof e=="string"?we(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Se(e.map((n,r)=>()=>v(n,`${t}[${r}]`))):Se(Object.entries(e).map(([n,r])=>()=>{const o=t?`${t}.${n}`:n;return we(n,`${o} (key)`)??v(r,o)}))}function we(e,t){const n=e.search(Dt);return n<0?null:{path:t,index:n}}function Se(e){for(const t of e){const n=t();if(n!==null)return n}return null}function W(e){const t=v(e,"");if(t!==null)throw new y(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,_.USAGE,{code:"text_unpaired_surrogate",field:t.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 ${t.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 Pt(e,t={}){const n=N(e.metadata,t),r=be(n),o=g(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));W(s);const a=Ee(s);let f;try{f=M(a).value}catch(u){throw new y("Refusing to persist a TOON item document that the configured decoder cannot read back.",_.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:u instanceof Error?u.message:String(u)})}if(!G(f,s)){const u=typeof f=="object"&&f!==null&&!Array.isArray(f)?f:{},S=Object.keys(s).find(B=>!G(s[B],u[B]))??"document";throw new y(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${S}".`,_.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:S,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`${a}
8
+ `}function en(e,t={}){const n=xe(e);if(n)throw new y(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,_.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 r=t.format??"toon",o=re(t);return r==="toon"?jt(e,o,t):Ct(e,o,t)}function tn(e,t={}){return(t.format??"toon")==="toon"?Pt(e,t):Lt(e,t)}function nn(e,t={}){return{metadata:N(e.metadata,t),body:g(e.body??"")}}const rn={buildKnownItemMetadataKeys:L,firstNonZeroComparison:j,normalizeBody:g,normalizePlanDecisions:_e,normalizePlanDiscoveries:ye,normalizePlanStepDocs:le,normalizePlanStepFiles:ue,normalizePlanStepLinks:fe,normalizePlanSteps:pe,normalizePlanStepTests:me,normalizePlanValidation:ge,normalizeTestRunSummaries:de,normalizeTypeOptions:he,runtimeFieldRequiredForType:oe,sortTests:ce};export{Mt as CANONICALLY_ORDERED_LOG_COLLECTIONS,rn as _testOnlyItemFormat,nn as canonicalDocument,st as compareLogValues,N as normalizeItemMetadata,St as normalizeLinkedTest,en as parseItemDocument,tn as serializeItemDocument,xt as splitFrontMatter};
9
9
  //# sourceMappingURL=item-format.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]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();function toItemRecord(item){return item}export{toItemRecord};
1
+ function e(t){return t}export{e as toItemRecord};
2
2
  //# sourceMappingURL=item-record.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]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function normalizeItemTypeStringList(values){return[...new Set((values??[]).map(value=>value.trim()).filter(value=>value.length>0))].sort((left,right)=>left.localeCompare(right))}function normalizeItemTypeOption(option){const key=option.key.trim();if(key.length===0)return null;const aliases=normalizeItemTypeStringList(option.aliases),description=option.description?.trim();return{key,values:normalizeItemTypeStringList(option.values),required:option.required===!0?!0:void 0,aliases:aliases.length>0?aliases:void 0,description:description&&description.length>0?description:void 0}}const keepPolicyCommand=command=>command,strictPolicyCommand=command=>{const normalized=command.trim().toLowerCase();return normalized==="create"||normalized==="update"?normalized:null};function normalizeItemTypeCommandOptionPolicy(policy,resolvePolicyCommand){const command=resolvePolicyCommand(policy.command);if(command===null)return null;const option=policy.option.trim();return option.length===0?null:{command,option,required:policy.required,visible:policy.visible,enabled:policy.enabled}}function normalizeItemTypeCommandOptionPolicies(policies,resolvePolicyCommand){const dedupedByKey=new Map;for(const policy of policies??[]){const normalized=normalizeItemTypeCommandOptionPolicy(policy,resolvePolicyCommand);normalized&&dedupedByKey.set(`${normalized.command}:${normalized.option.toLowerCase()}`,normalized)}return[...dedupedByKey.values()].sort((left,right)=>left.command===right.command?left.option.localeCompare(right.option):left.command.localeCompare(right.command))}function normalizeOptionalStringList(values,preservePresence){return preservePresence?normalizeItemTypeStringList(values):void 0}function optionalNonEmptyString(value){const normalized=value?.trim();return normalized&&normalized.length>0?normalized:void 0}function parseItemExecutionRole(value){if(value===void 0||value==="agent"||value==="human"||value==="gate")return value;throw new Error("Item type execution_role must be agent, human, or gate.")}function normalizeItemTypeDefinition(definition,options={}){const resolvePolicyCommand=options.resolvePolicyCommand??keepPolicyCommand,name=definition.name.trim();if(name.length===0)return null;const hasRequiredCreateFields=definition.required_create_fields!==void 0,hasRequiredCreateRepeatables=definition.required_create_repeatables!==void 0,hasOptions=definition.options!==void 0,hasCommandOptionPolicies=definition.command_option_policies!==void 0,aliases=normalizeItemTypeStringList(definition.aliases),normalizedOptions=(definition.options??[]).map(option=>normalizeItemTypeOption(option)).filter(option=>option!==null).sort((left,right)=>left.key.localeCompare(right.key)),commandOptionPolicies=normalizeItemTypeCommandOptionPolicies(definition.command_option_policies,resolvePolicyCommand);return{name,description:optionalNonEmptyString(definition.description),default_status:optionalNonEmptyString(definition.default_status),...definition.execution_role===void 0?{}:{execution_role:parseItemExecutionRole(definition.execution_role)},folder:optionalNonEmptyString(definition.folder),aliases:aliases.length>0?aliases:void 0,required_create_fields:normalizeOptionalStringList(definition.required_create_fields,hasRequiredCreateFields),required_create_repeatables:normalizeOptionalStringList(definition.required_create_repeatables,hasRequiredCreateRepeatables),options:hasOptions?normalizedOptions:void 0,command_option_policies:hasCommandOptionPolicies?commandOptionPolicies:void 0}}export{keepPolicyCommand,normalizeItemTypeCommandOptionPolicies,normalizeItemTypeCommandOptionPolicy,normalizeItemTypeDefinition,normalizeItemTypeOption,normalizeItemTypeStringList,parseItemExecutionRole,strictPolicyCommand};
1
+ function i(e){return[...new Set((e??[]).map(n=>n.trim()).filter(n=>n.length>0))].sort((n,o)=>n.localeCompare(o))}function y(e){const n=e.key.trim();if(n.length===0)return null;const o=i(e.aliases),t=e.description?.trim();return{key:n,values:i(e.values),required:e.required===!0?!0:void 0,aliases:o.length>0?o:void 0,description:t&&t.length>0?t:void 0}}const C=e=>e,q=e=>{const n=e.trim().toLowerCase();return n==="create"||n==="update"?n:null};function g(e,n){const o=n(e.command);if(o===null)return null;const t=e.option.trim();return t.length===0?null:{command:o,option:t,required:e.required,visible:e.visible,enabled:e.enabled}}function h(e,n){const o=new Map;for(const t of e??[]){const r=g(t,n);r&&o.set(`${r.command}:${r.option.toLowerCase()}`,r)}return[...o.values()].sort((t,r)=>t.command===r.command?t.option.localeCompare(r.option):t.command.localeCompare(r.command))}function m(e,n){return n?i(e):void 0}function s(e){const n=e?.trim();return n&&n.length>0?n:void 0}function x(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function z(e,n={}){const o=n.resolvePolicyCommand??C,t=e.name.trim();if(t.length===0)return null;const r=e.required_create_fields!==void 0,c=e.required_create_repeatables!==void 0,u=e.options!==void 0,d=e.command_option_policies!==void 0,l=i(e.aliases),p=(e.options??[]).map(a=>y(a)).filter(a=>a!==null).sort((a,_)=>a.key.localeCompare(_.key)),f=h(e.command_option_policies,o);return{name:t,description:s(e.description),default_status:s(e.default_status),...e.execution_role===void 0?{}:{execution_role:x(e.execution_role)},folder:s(e.folder),aliases:l.length>0?l:void 0,required_create_fields:m(e.required_create_fields,r),required_create_repeatables:m(e.required_create_repeatables,c),options:u?p:void 0,command_option_policies:d?f:void 0}}export{C as keepPolicyCommand,h as normalizeItemTypeCommandOptionPolicies,g as normalizeItemTypeCommandOptionPolicy,z as normalizeItemTypeDefinition,y as normalizeItemTypeOption,i as normalizeItemTypeStringList,x as parseItemExecutionRole,q as strictPolicyCommand};
2
2
  //# sourceMappingURL=item-type-definition.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]="8dd367eb-617e-5645-8f8a-57862f8385f7")}catch{}})();const literalInputs=new WeakSet,literalFields=new WeakMap,cliInputs=new WeakSet;function markCliMutationInput(input){return cliInputs.add(input),input}function isCliMutationInput(input){return cliInputs.has(input)}function preserveLiteralMutationInput(input){literalInputs.add(input);for(const[key,value]of Object.entries(input)){if(!Array.isArray(value))continue;const owned=[...value];Reflect.set(input,key,owned),literalInputs.add(owned)}return input}function isLiteralMutationInput(input,field){return literalInputs.has(input)||field!==void 0&&literalFields.get(input)?.has(field)===!0}function preserveLiteralMutationInputFields(input,fields){const selected=new Set(fields);literalFields.set(input,selected);for(const field of selected){const value=Reflect.get(input,field);if(!Array.isArray(value))continue;const owned=[...value];Reflect.set(input,field,owned),literalInputs.add(owned)}return input}function transferLiteralMutationInput(source,target){if(isCliMutationInput(source)&&markCliMutationInput(target),isLiteralMutationInput(source))return preserveLiteralMutationInput(target);const fields=literalFields.get(source);return fields?preserveLiteralMutationInputFields(target,fields):target}function mutationInputAudience(input){return isLiteralMutationInput(input)?"sdk":"cli"}function mutationOptionLabel(audience,flag){return audience==="cli"?`--${flag}`:flag.replace(/-([a-z])/gu,(_match,letter)=>letter.toUpperCase())}function sdkClearRemedy(unsetToken){return`Pass unset: ["${unsetToken}"] to clear it`}function emptyMutationOptionMessage(audience,flag,cliRemedy=""){return audience==="cli"?`--${flag} must not be empty${cliRemedy}`:`${mutationOptionLabel("sdk",flag)} must not be empty. ${sdkClearRemedy(flag)}, or omit ${mutationOptionLabel("sdk",flag)}.`}export{emptyMutationOptionMessage,isCliMutationInput,isLiteralMutationInput,markCliMutationInput,mutationInputAudience,mutationOptionLabel,preserveLiteralMutationInput,preserveLiteralMutationInputFields,sdkClearRemedy,transferLiteralMutationInput};
1
+ const o=new WeakSet,i=new WeakMap,a=new WeakSet;function d(t){return a.add(t),t}function p(t){return a.has(t)}function f(t){o.add(t);for(const[e,n]of Object.entries(t)){if(!Array.isArray(n))continue;const r=[...n];Reflect.set(t,e,r),o.add(r)}return t}function c(t,e){return o.has(t)||e!==void 0&&i.get(t)?.has(e)===!0}function m(t,e){const n=new Set(e);i.set(t,n);for(const r of n){const s=Reflect.get(t,r);if(!Array.isArray(s))continue;const u=[...s];Reflect.set(t,r,u),o.add(u)}return t}function k(t,e){if(p(t)&&d(e),c(t))return f(e);const n=i.get(t);return n?m(e,n):e}function y(t){return c(t)?"sdk":"cli"}function l(t,e){return t==="cli"?`--${e}`:e.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function x(t){return`Pass unset: ["${t}"] to clear it`}function I(t,e,n=""){return t==="cli"?`--${e} must not be empty${n}`:`${l("sdk",e)} must not be empty. ${x(e)}, or omit ${l("sdk",e)}.`}export{I as emptyMutationOptionMessage,p as isCliMutationInput,c as isLiteralMutationInput,d as markCliMutationInput,y as mutationInputAudience,l as mutationOptionLabel,f as preserveLiteralMutationInput,m as preserveLiteralMutationInputFields,x as sdkClearRemedy,k as transferLiteralMutationInput};
2
2
  //# sourceMappingURL=literal-mutation-input.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]="0394e0c1-ff68-5553-b022-1e8b6fff04f0")}catch{}})();import{normalizeItemId}from"./id.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{emptyMutationOptionMessage,sdkClearRemedy}from"./literal-mutation-input.js";const PLACEHOLDER_REFERENCE_TOKENS=new Set(["none","null","undefined"]);function normalizeParentReferencePolicy(value){const normalized=value?.trim().toLowerCase().replaceAll("-","_");if(normalized==="warn"||normalized==="strict_error")return normalized;if(normalized==="strict")return"strict_error";throw new PmCliError("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",EXIT_CODE.USAGE)}function normalizeParentReferenceValue(rawValue,audience="cli"){const sdk=audience==="sdk";if(typeof rawValue!="string")throw new PmCliError(sdk?`parent must be a string. ${sdkClearRemedy("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",EXIT_CODE.USAGE);const value=rawValue.trim();if(value.length===0)throw new PmCliError(emptyMutationOptionMessage(audience,"parent",". Use --parent none to unset."),EXIT_CODE.USAGE);if(isPlaceholderReferenceToken(value))throw new PmCliError(sdk?`parent must not be the placeholder "${value}". ${sdkClearRemedy("parent")}, or omit parent.`:`--parent must not use placeholder token "${value}". Use --unset parent to clear this field.`,EXIT_CODE.USAGE);return value}function isPlaceholderReferenceToken(value){return PLACEHOLDER_REFERENCE_TOKENS.has(value.trim().toLowerCase())}function validateMissingParentReference(parentId,policy,audience="cli"){if(policy==="strict_error")throw new PmCliError(`Parent item "${parentId}" was not found. Create it first or ${audience==="sdk"?"omit parent":"use --parent none"}.`,EXIT_CODE.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${parentId}`]}}function assertParentReferenceIsNotSelf(itemId,parentId,prefix,audience="cli"){const normalizedItemId=normalizeItemId(itemId,prefix),normalizedParentId=normalizeItemId(parentId,prefix);if(normalizedItemId!==normalizedParentId)return;const normalizationDetail=parentId!==normalizedParentId||itemId!==normalizedItemId?` (normalized from parent "${parentId}" and item "${itemId}")`:"";throw new PmCliError(`Parent item "${normalizedParentId}" cannot be the same as item "${normalizedItemId}"${normalizationDetail}. ${audience==="sdk"?`${sdkClearRemedy("parent")}.`:"Use --unset parent to clear this field."}`,EXIT_CODE.USAGE)}export{assertParentReferenceIsNotSelf,isPlaceholderReferenceToken,normalizeParentReferencePolicy,normalizeParentReferenceValue,validateMissingParentReference};
1
+ import{normalizeItemId as c}from"./id.js";import{EXIT_CODE as o}from"../shared/constants.js";import{PmCliError as i}from"../shared/errors.js";import{emptyMutationOptionMessage as f,sdkClearRemedy as l}from"./literal-mutation-input.js";const p=new Set(["none","null","undefined"]);function $(e){const t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new i("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",o.USAGE)}function P(e,t="cli"){const r=t==="sdk";if(typeof e!="string")throw new i(r?`parent must be a string. ${l("parent")}.`:"--parent must be a string. Use --unset parent to clear this field.",o.USAGE);const n=e.trim();if(n.length===0)throw new i(f(t,"parent",". Use --parent none to unset."),o.USAGE);if(u(n))throw new i(r?`parent must not be the placeholder "${n}". ${l("parent")}, or omit parent.`:`--parent must not use placeholder token "${n}". Use --unset parent to clear this field.`,o.USAGE);return n}function u(e){return p.has(e.trim().toLowerCase())}function _(e,t,r="cli"){if(t==="strict_error")throw new i(`Parent item "${e}" was not found. Create it first or ${r==="sdk"?"omit parent":"use --parent none"}.`,o.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function g(e,t,r,n="cli"){const a=c(e,r),s=c(t,r);if(a!==s)return;const m=t!==s||e!==a?` (normalized from parent "${t}" and item "${e}")`:"";throw new i(`Parent item "${s}" cannot be the same as item "${a}"${m}. ${n==="sdk"?`${l("parent")}.`:"Use --unset parent to clear this field."}`,o.USAGE)}export{g as assertParentReferenceIsNotSelf,u as isPlaceholderReferenceToken,$ as normalizeParentReferencePolicy,P as normalizeParentReferenceValue,_ as validateMissingParentReference};
2
2
  //# sourceMappingURL=parent-reference-policy.js.map