@unbrained/pm-cli 2026.9.7 → 2026.9.9

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 (746) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +12 -4
  2. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +19 -10
  3. package/.agents/skills/pm-extensions/SKILL.md +6 -0
  4. package/.agents/skills/pm-sdk/SKILL.md +11 -2
  5. package/.agents/skills/pm-user/SKILL.md +7 -2
  6. package/.agents/skills/pm-user/references/ECOSYSTEM_PLANNING.md +95 -0
  7. package/.claude-plugin/marketplace.json +2 -2
  8. package/CHANGELOG.md +231 -182
  9. package/dist/cli/after-command-context-usage.js +1 -48
  10. package/dist/cli/argv-utils.js +1 -40
  11. package/dist/cli/bootstrap-args.js +1 -9
  12. package/dist/cli/bundle-integrity.js +2 -110
  13. package/dist/cli/commander-usage.js +11 -771
  14. package/dist/cli/commands/activity.js +1 -9
  15. package/dist/cli/commands/aggregate.js +1 -5
  16. package/dist/cli/commands/append.js +1 -5
  17. package/dist/cli/commands/claim.js +1 -5
  18. package/dist/cli/commands/close-many.js +1 -5
  19. package/dist/cli/commands/close.js +1 -9
  20. package/dist/cli/commands/comments.js +1 -5
  21. package/dist/cli/commands/config.js +1 -9
  22. package/dist/cli/commands/context.js +1 -9
  23. package/dist/cli/commands/contracts.js +1 -5
  24. package/dist/cli/commands/copy.js +1 -9
  25. package/dist/cli/commands/create.js +1 -9
  26. package/dist/cli/commands/delete.js +1 -9
  27. package/dist/cli/commands/deps.js +1 -9
  28. package/dist/cli/commands/docs.js +1 -9
  29. package/dist/cli/commands/duplicates.js +1 -9
  30. package/dist/cli/commands/eval.js +1 -9
  31. package/dist/cli/commands/extension/describe.js +1 -5
  32. package/dist/cli/commands/extension/scaffold.js +1 -5
  33. package/dist/cli/commands/extension/shared.js +1 -5
  34. package/dist/cli/commands/extension.js +1 -9
  35. package/dist/cli/commands/files.js +1 -9
  36. package/dist/cli/commands/focus.js +1 -9
  37. package/dist/cli/commands/gc.js +1 -9
  38. package/dist/cli/commands/get.js +1 -9
  39. package/dist/cli/commands/graph.js +1 -10
  40. package/dist/cli/commands/health.js +1 -9
  41. package/dist/cli/commands/history-compact.js +1 -10
  42. package/dist/cli/commands/history-redact.js +1 -11
  43. package/dist/cli/commands/history-repair.js +1 -10
  44. package/dist/cli/commands/history.js +1 -5
  45. package/dist/cli/commands/index.js +1 -58
  46. package/dist/cli/commands/init-agent-guidance.js +1 -9
  47. package/dist/cli/commands/init.js +1 -9
  48. package/dist/cli/commands/learnings.js +1 -5
  49. package/dist/cli/commands/lifecycle-transitions.js +1 -5
  50. package/dist/cli/commands/list.js +1 -9
  51. package/dist/cli/commands/merge.js +1 -11
  52. package/dist/cli/commands/next.js +1 -9
  53. package/dist/cli/commands/notes.js +1 -5
  54. package/dist/cli/commands/plan.js +1 -9
  55. package/dist/cli/commands/profile.js +1 -9
  56. package/dist/cli/commands/restore.js +1 -9
  57. package/dist/cli/commands/scheduling-shortcuts.js +1 -9
  58. package/dist/cli/commands/schema.js +1 -10
  59. package/dist/cli/commands/search.js +1 -9
  60. package/dist/cli/commands/stats.js +1 -9
  61. package/dist/cli/commands/telemetry.js +1 -9
  62. package/dist/cli/commands/test-all.js +1 -9
  63. package/dist/cli/commands/test-runs.js +1 -9
  64. package/dist/cli/commands/test.js +1 -9
  65. package/dist/cli/commands/update-many.js +1 -5
  66. package/dist/cli/commands/update.js +1 -9
  67. package/dist/cli/commands/upgrade.js +1 -5
  68. package/dist/cli/commands/validate.js +1 -15
  69. package/dist/cli/context-intent-invocation.js +1 -20
  70. package/dist/cli/description-stdin.js +1 -17
  71. package/dist/cli/error-guidance.js +1 -1353
  72. package/dist/cli/extension-command-help.js +5 -636
  73. package/dist/cli/extension-command-options.js +1 -427
  74. package/dist/cli/extension-recovery.js +1 -126
  75. package/dist/cli/help-content.js +2 -1001
  76. package/dist/cli/help-json-payload.js +4 -570
  77. package/dist/cli/main.d.ts +4 -0
  78. package/dist/cli/main.js +5 -2573
  79. package/dist/cli/migration-gates.js +1 -289
  80. package/dist/cli/public.js +1 -20
  81. package/dist/cli/register-annotations.js +1 -270
  82. package/dist/cli/register-assurance.js +1 -62
  83. package/dist/cli/register-files-lookup.js +1 -56
  84. package/dist/cli/register-history-activity.d.ts +8 -0
  85. package/dist/cli/register-history-activity.js +2 -0
  86. package/dist/cli/register-history-author.js +1 -38
  87. package/dist/cli/register-history-maintenance.d.ts +9 -0
  88. package/dist/cli/register-history-maintenance.js +2 -0
  89. package/dist/cli/register-list-query.js +10 -943
  90. package/dist/cli/register-mutation-options.js +1 -9
  91. package/dist/cli/register-mutation.d.ts +0 -5
  92. package/dist/cli/register-mutation.js +19 -1893
  93. package/dist/cli/register-operations.js +1 -920
  94. package/dist/cli/register-setup.js +1 -716
  95. package/dist/cli/register-structured-mutation.js +1 -196
  96. package/dist/cli/registration-helpers.js +1 -5
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -42
  98. package/dist/cli/schema-registration-helpers.js +1 -73
  99. package/dist/cli/search-refresh.js +1 -13
  100. package/dist/cli/stats-analytics-json.js +1 -68
  101. package/dist/cli/telemetry-flush.js +1 -10
  102. package/dist/cli-bundle/bundle-manifest.json +164 -156
  103. package/dist/cli-bundle/chunks/{chunk-NPN5I67J.js → chunk-3IPRM75M.js} +3 -3
  104. package/dist/cli-bundle/chunks/chunk-4VL5P22L.js +2 -0
  105. package/dist/cli-bundle/chunks/chunk-AAFBV3U3.js +29 -0
  106. package/dist/cli-bundle/chunks/chunk-D3YVILJJ.js +20 -0
  107. package/dist/cli-bundle/chunks/{chunk-WYRZZ5ZE.js → chunk-DEZPZOQ7.js} +2 -2
  108. package/dist/cli-bundle/chunks/chunk-ECBLPN7B.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-J6ERHBV2.js +235 -0
  110. package/dist/cli-bundle/chunks/chunk-JUNJ5EKI.js +2 -0
  111. package/dist/cli-bundle/chunks/chunk-L5RCDKQ2.js +2 -0
  112. package/dist/cli-bundle/chunks/chunk-NSAPNEYH.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-OHNLSGGV.js +79 -0
  114. package/dist/cli-bundle/chunks/chunk-WQKMSFBV.js +5 -0
  115. package/dist/cli-bundle/chunks/{chunk-BAX2BYUW.js → chunk-XZ6T7YPP.js} +256 -150
  116. package/dist/cli-bundle/chunks/{chunk-JT6XF6GE.js → chunk-Z3XVXUVF.js} +4 -4
  117. package/dist/cli-bundle/chunks/register-list-query-UIHRCS6D.js +11 -0
  118. package/dist/cli-bundle/chunks/register-mutation-WHWMGRVX.js +20 -0
  119. package/dist/cli-bundle/chunks/register-operations-64YZYTC5.js +2 -0
  120. package/dist/cli-bundle/chunks/register-setup-PERI45EM.js +2 -0
  121. package/dist/cli-bundle/focused-chunks/chunk-2W4XIYOB.js +2 -0
  122. package/dist/cli-bundle/focused-chunks/chunk-2WSBXIGF.js +12 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-5FHTCOHS.js +3 -0
  124. package/dist/cli-bundle/focused-chunks/chunk-7N6DOREF.js +26 -0
  125. package/dist/cli-bundle/focused-chunks/{chunk-3BZEOXLT.js → chunk-7PC4R5QB.js} +2 -2
  126. package/dist/cli-bundle/focused-chunks/chunk-BUCJUZVG.js +6 -0
  127. package/dist/cli-bundle/focused-chunks/chunk-FE3BABLJ.js +2 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-IWITF53W.js +2 -0
  129. package/dist/cli-bundle/focused-chunks/chunk-OQUGRHKV.js +10 -0
  130. package/dist/cli-bundle/focused-chunks/{chunk-M6PBRFSH.js → chunk-PNKIANFZ.js} +2 -2
  131. package/dist/cli-bundle/focused-chunks/{chunk-LIJIA4TY.js → chunk-QQQ4SAUO.js} +3 -3
  132. package/dist/cli-bundle/focused-chunks/chunk-TTYXF5YD.js +177 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-XNR3DM6J.js +2 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-XSS3APUF.js +9 -0
  135. package/dist/cli-bundle/focused-chunks/chunk-YCDQ2N23.js +8 -0
  136. package/dist/cli-bundle/focused-chunks/chunk-YJUXGS57.js +20 -0
  137. package/dist/cli-bundle/focused-chunks/chunk-ZTCE4UO6.js +58 -0
  138. package/dist/cli-bundle/main.js +20 -20
  139. package/dist/cli-bundle/sdk-authoring.js +1 -1
  140. package/dist/cli-bundle/sdk-contracts.js +2 -2
  141. package/dist/cli-bundle/sdk-core.js +37 -37
  142. package/dist/cli-bundle/sdk-governance.js +1 -1
  143. package/dist/cli-bundle/sdk-graph.js +1 -1
  144. package/dist/cli-bundle/sdk-merge.js +42 -42
  145. package/dist/cli-bundle/sdk-query.js +1 -1
  146. package/dist/cli-bundle/sdk-runtime.js +1 -1
  147. package/dist/cli-bundle/sdk-testing.js +1 -1
  148. package/dist/cli-bundle/sdk.js +11 -11
  149. package/dist/cli.js +1 -104
  150. package/dist/core/checkpoint/checkpoint-gc.js +1 -169
  151. package/dist/core/checkpoint/mutation-checkpoint.js +2 -133
  152. package/dist/core/config/nested-settings.js +1 -534
  153. package/dist/core/config/positional-value.js +1 -109
  154. package/dist/core/diagnostics/remediation.js +1 -506
  155. package/dist/core/extensions/activation-summary-markdown.js +2 -145
  156. package/dist/core/extensions/activation-summary.js +1 -92
  157. package/dist/core/extensions/activation-transaction.js +1 -46
  158. package/dist/core/extensions/capability-usage.js +1 -173
  159. package/dist/core/extensions/command-hook-context.js +1 -13
  160. package/dist/core/extensions/command-metadata-contract.js +1 -22
  161. package/dist/core/extensions/command-visibility-tier.js +1 -29
  162. package/dist/core/extensions/contribution-inventory.js +1 -173
  163. package/dist/core/extensions/exporter-output-contract.js +1 -66
  164. package/dist/core/extensions/extension-candidate.js +1 -18
  165. package/dist/core/extensions/extension-capability-aliases.js +1 -158
  166. package/dist/core/extensions/extension-hook-runtime.js +1 -699
  167. package/dist/core/extensions/extension-policy.js +1 -599
  168. package/dist/core/extensions/extension-registries.js +1 -62
  169. package/dist/core/extensions/extension-runtime-helpers.js +1 -33
  170. package/dist/core/extensions/extension-types.js +1 -102
  171. package/dist/core/extensions/flag-definition-validation.js +1 -52
  172. package/dist/core/extensions/flag-value-types.js +1 -64
  173. package/dist/core/extensions/index.js +1 -526
  174. package/dist/core/extensions/item-field-types.js +1 -39
  175. package/dist/core/extensions/item-fields.js +1 -261
  176. package/dist/core/extensions/loader.js +1 -2223
  177. package/dist/core/extensions/manifest-schema.js +1 -69
  178. package/dist/core/extensions/module-graph-snapshot.js +1 -33
  179. package/dist/core/extensions/preflight-ownership.js +1 -41
  180. package/dist/core/extensions/registration-validation.js +1 -82
  181. package/dist/core/extensions/registration-values.js +1 -209
  182. package/dist/core/extensions/reserved-host-flags.js +1 -36
  183. package/dist/core/extensions/runtime-registrations.js +1 -67
  184. package/dist/core/extensions/service-ownership.js +1 -19
  185. package/dist/core/extensions/version-compat.js +1 -216
  186. package/dist/core/fs/fs-utils.js +2 -158
  187. package/dist/core/fs/host-environment-errors.js +1 -141
  188. package/dist/core/fs/index.js +1 -9
  189. package/dist/core/fs/path-utils.js +1 -17
  190. package/dist/core/governance/content-fields.js +1 -160
  191. package/dist/core/governance/issue-codes.js +1 -151
  192. package/dist/core/governance/metadata-coverage.js +1 -358
  193. package/dist/core/history/drift-cache.js +3 -72
  194. package/dist/core/history/drift-scan.js +1 -342
  195. package/dist/core/history/event-classification.js +1 -109
  196. package/dist/core/history/event-index.js +8 -784
  197. package/dist/core/history/history-compact-bulk.js +1 -104
  198. package/dist/core/history/history-diff.js +1 -158
  199. package/dist/core/history/history-rewrite.d.ts +6 -1
  200. package/dist/core/history/history-rewrite.js +1 -107
  201. package/dist/core/history/history-storage-stats.js +1 -102
  202. package/dist/core/history/history-stream-policy.js +1 -62
  203. package/dist/core/history/history.js +2 -617
  204. package/dist/core/history/identity.js +1 -30
  205. package/dist/core/history/index.js +1 -9
  206. package/dist/core/history/projection.js +1 -196
  207. package/dist/core/history/read.d.ts +9 -0
  208. package/dist/core/history/read.js +1 -57
  209. package/dist/core/history/replay.js +2 -439
  210. package/dist/core/history/version-address.js +1 -32
  211. package/dist/core/history/workspace-history.js +2 -433
  212. package/dist/core/io/body-file.js +1 -62
  213. package/dist/core/io/bulk-ids-input.js +1 -112
  214. package/dist/core/item/actionability.js +1 -327
  215. package/dist/core/item/dependency-reference.js +1 -20
  216. package/dist/core/item/id.js +1 -112
  217. package/dist/core/item/index.js +1 -12
  218. package/dist/core/item/item-format-version.js +1 -78
  219. package/dist/core/item/item-format.js +5 -1473
  220. package/dist/core/item/item-record.js +1 -23
  221. package/dist/core/item/item-type-definition.js +1 -133
  222. package/dist/core/item/parent-reference-policy.js +1 -57
  223. package/dist/core/item/parse.js +2 -603
  224. package/dist/core/item/plan-lifecycle.js +1 -19
  225. package/dist/core/item/priority.js +1 -61
  226. package/dist/core/item/sprint-release-format.js +1 -38
  227. package/dist/core/item/status-filter.js +1 -115
  228. package/dist/core/item/status.js +1 -43
  229. package/dist/core/item/toon-decode.js +1 -29
  230. package/dist/core/item/type-registry.js +1 -715
  231. package/dist/core/item/type-synonyms.js +1 -38
  232. package/dist/core/lock/index.js +1 -9
  233. package/dist/core/lock/lock-gc.js +1 -240
  234. package/dist/core/lock/lock.js +3 -590
  235. package/dist/core/output/mutation-projection.js +1 -217
  236. package/dist/core/output/output-control.js +1 -25
  237. package/dist/core/output/output.js +11 -494
  238. package/dist/core/output/query-summary.js +1 -58
  239. package/dist/core/output/tabular.js +1 -77
  240. package/dist/core/packages/manifest.js +1 -244
  241. package/dist/core/packages/root.js +1 -84
  242. package/dist/core/policy/workflow-policy-schema.d.ts +312 -0
  243. package/dist/core/policy/workflow-policy-schema.js +2 -0
  244. package/dist/core/policy/workflow-policy-store.d.ts +24 -0
  245. package/dist/core/policy/workflow-policy-store.js +2 -0
  246. package/dist/core/policy/workflow-policy.d.ts +139 -0
  247. package/dist/core/policy/workflow-policy.js +2 -0
  248. package/dist/core/profile/profile-describe.js +1 -83
  249. package/dist/core/profile/profile-lint.js +1 -415
  250. package/dist/core/profile/profile-plan.js +0 -0
  251. package/dist/core/profile/profile-presets.js +1 -370
  252. package/dist/core/reproducibility/context.js +1 -82
  253. package/dist/core/schema/fields-file.js +2 -288
  254. package/dist/core/schema/item-types-file.js +2 -296
  255. package/dist/core/schema/runtime-field-filters.js +1 -49
  256. package/dist/core/schema/runtime-field-values.js +1 -313
  257. package/dist/core/schema/runtime-schema.js +2 -826
  258. package/dist/core/schema/status-defs-file.js +2 -227
  259. package/dist/core/schema/status-token.js +1 -31
  260. package/dist/core/schema/type-inference.js +1 -95
  261. package/dist/core/schema/type-presets.js +1 -87
  262. package/dist/core/schema/type-workflows.js +1 -104
  263. package/dist/core/search/background-refresh.js +2 -286
  264. package/dist/core/search/bm25.js +1 -146
  265. package/dist/core/search/cache.js +2 -534
  266. package/dist/core/search/corpus.js +1 -311
  267. package/dist/core/search/embedding-batches.js +1 -163
  268. package/dist/core/search/eval.js +1 -225
  269. package/dist/core/search/http-client.js +1 -75
  270. package/dist/core/search/providers.js +1 -242
  271. package/dist/core/search/relevance.js +1 -244
  272. package/dist/core/search/semantic-defaults.js +1 -199
  273. package/dist/core/search/staleness.js +1 -30
  274. package/dist/core/search/vector-stores.js +2 -664
  275. package/dist/core/search/vectorization-metadata.js +1 -81
  276. package/dist/core/sentry/helpers.js +1 -272
  277. package/dist/core/sentry/instrument.js +1 -387
  278. package/dist/core/session/session-state.js +1 -260
  279. package/dist/core/shared/agent-session-context.js +1 -133
  280. package/dist/core/shared/author.js +1 -1172
  281. package/dist/core/shared/command-types.js +1 -4
  282. package/dist/core/shared/conflict-markers.js +1 -31
  283. package/dist/core/shared/constants.js +1 -405
  284. package/dist/core/shared/errors.js +1 -20
  285. package/dist/core/shared/html-entity-decode.js +1 -131
  286. package/dist/core/shared/index.js +1 -12
  287. package/dist/core/shared/item-metadata-contract.js +1 -89
  288. package/dist/core/shared/lazy-module.js +1 -16
  289. package/dist/core/shared/levenshtein.js +1 -61
  290. package/dist/core/shared/memo.js +1 -19
  291. package/dist/core/shared/numeric-parsers.js +1 -20
  292. package/dist/core/shared/option-alias-visibility.js +1 -67
  293. package/dist/core/shared/primitives.js +1 -127
  294. package/dist/core/shared/serial-queue.js +1 -79
  295. package/dist/core/shared/serialization.js +1 -210
  296. package/dist/core/shared/split-comma-list.js +1 -30
  297. package/dist/core/shared/text-normalization.js +1 -38
  298. package/dist/core/shared/time.js +1 -306
  299. package/dist/core/store/index.js +1 -12
  300. package/dist/core/store/item-format-migration.js +1 -125
  301. package/dist/core/store/item-metadata-cache.js +1 -1116
  302. package/dist/core/store/item-metadata-query-index.js +9 -394
  303. package/dist/core/store/item-metadata-read-work.js +1 -43
  304. package/dist/core/store/item-store.js +1 -693
  305. package/dist/core/store/paths.d.ts +1 -1
  306. package/dist/core/store/paths.js +1 -214
  307. package/dist/core/store/settings-read-cache.js +1 -85
  308. package/dist/core/store/settings-validator.d.ts +1 -0
  309. package/dist/core/store/settings-validator.js +1 -421
  310. package/dist/core/store/settings.js +3 -1309
  311. package/dist/core/store/tracker-preflight.js +1 -141
  312. package/dist/core/telemetry/consent.js +5 -108
  313. package/dist/core/telemetry/observability.js +1 -246
  314. package/dist/core/telemetry/runtime.js +4 -1988
  315. package/dist/core/test/background-runs.js +4 -945
  316. package/dist/core/test/item-test-run-tracking.js +1 -63
  317. package/dist/core/test/run-selectors.js +1 -120
  318. package/dist/core/validate/estimate-defaults.js +1 -89
  319. package/dist/core/validate/fix-planning.js +1 -189
  320. package/dist/core/validate/linked-artifact-reference.js +1 -36
  321. package/dist/core/validate/missing-by-type.js +1 -34
  322. package/dist/core/validate/missing-link-owners.js +1 -95
  323. package/dist/core/validate/stale-file-classification.js +1 -82
  324. package/dist/mcp/http-server.js +5 -448
  325. package/dist/mcp/legacy-adapter.js +1 -77
  326. package/dist/mcp/runtime-capabilities.js +1 -200
  327. package/dist/mcp/server.js +4 -1233
  328. package/dist/mcp/tool-definitions.js +1 -804
  329. package/dist/sdk/actionability.js +1 -13
  330. package/dist/sdk/agent/closed-domain-contracts.js +1 -161
  331. package/dist/sdk/agent/command-recovery.js +1 -59
  332. package/dist/sdk/agent/command-suggestions.js +1 -66
  333. package/dist/sdk/agent/create-option-policy.js +1 -31
  334. package/dist/sdk/agent/identity-config.js +1 -106
  335. package/dist/sdk/agent/item-addressing.js +1 -207
  336. package/dist/sdk/agent/refusal-closure-census.js +1 -151
  337. package/dist/sdk/agent/refusal-closure.js +1 -133
  338. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -193
  339. package/dist/sdk/agent/refusal-reachability.js +1 -593
  340. package/dist/sdk/agent/subcommand-recovery.js +1 -83
  341. package/dist/sdk/agent/task-transcript-contracts.js +1 -197
  342. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -126
  343. package/dist/sdk/agent-capability-contracts.js +1 -428
  344. package/dist/sdk/agent-session-context.js +1 -9
  345. package/dist/sdk/annotations.js +1 -448
  346. package/dist/sdk/author-attribution.js +1 -468
  347. package/dist/sdk/authoring.js +1 -20
  348. package/dist/sdk/cli-bootstrap.js +1 -838
  349. package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +1 -1
  350. package/dist/sdk/cli-contracts/agent-output-contracts.js +4 -476
  351. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -79
  352. package/dist/sdk/cli-contracts/command-aliases.d.ts +4 -0
  353. package/dist/sdk/cli-contracts/command-aliases.js +1 -107
  354. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -151
  355. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1081
  356. package/dist/sdk/cli-contracts/commander-types.js +1 -159
  357. package/dist/sdk/cli-contracts/completeness.js +1 -393
  358. package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
  359. package/dist/sdk/cli-contracts/enum-contracts.js +1 -222
  360. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1947
  361. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -347
  362. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -986
  363. package/dist/sdk/cli-contracts/registration-helpers.js +7 -990
  364. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +5 -0
  365. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -2090
  366. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -324
  367. package/dist/sdk/cli-contracts/string-lists.js +1 -16
  368. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -461
  369. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -2167
  370. package/dist/sdk/cli-contracts/tool-schema.d.ts +3 -1
  371. package/dist/sdk/cli-contracts/tool-schema.js +1 -1664
  372. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -4
  373. package/dist/sdk/cli-contracts.d.ts +1 -1
  374. package/dist/sdk/cli-contracts.js +1 -17
  375. package/dist/sdk/cli-program.js +1 -49
  376. package/dist/sdk/command-line.d.ts +2 -5
  377. package/dist/sdk/command-line.js +1 -78
  378. package/dist/sdk/comments.js +1 -133
  379. package/dist/sdk/compile-cache.js +1 -73
  380. package/dist/sdk/completion.js +174 -839
  381. package/dist/sdk/compose.js +1 -1090
  382. package/dist/sdk/config.js +1 -1204
  383. package/dist/sdk/context/recency.js +1 -33
  384. package/dist/sdk/context/semantic-session-attribution.js +1 -82
  385. package/dist/sdk/context/usage-egress.js +1 -29
  386. package/dist/sdk/context/usage-ledger.js +3 -185
  387. package/dist/sdk/context-intent-contracts.js +1 -709
  388. package/dist/sdk/context-intent-runtime.js +1 -115
  389. package/dist/sdk/context-packing.js +1 -218
  390. package/dist/sdk/context-relevance.js +1 -503
  391. package/dist/sdk/context-signal-store.js +2 -426
  392. package/dist/sdk/context-usage.js +1 -367
  393. package/dist/sdk/contracts.js +1 -23
  394. package/dist/sdk/core-governance.js +1 -14
  395. package/dist/sdk/core.js +1 -14
  396. package/dist/sdk/corpus-shape.js +1 -401
  397. package/dist/sdk/define.js +1 -220
  398. package/dist/sdk/dependencies.js +1 -718
  399. package/dist/sdk/dependency-flag-validation.js +1 -156
  400. package/dist/sdk/dependency-provenance.js +1 -135
  401. package/dist/sdk/docs.js +1 -14
  402. package/dist/sdk/duplicates.js +1 -40
  403. package/dist/sdk/environment/agent-environment.js +1 -466
  404. package/dist/sdk/environment/host-environment-errors.js +1 -8
  405. package/dist/sdk/environment/project-runtime-compatibility.js +1 -481
  406. package/dist/sdk/environment/source-context.js +1 -28
  407. package/dist/sdk/environment/tracker-preflight.js +1 -9
  408. package/dist/sdk/error-code-catalog.js +1 -153
  409. package/dist/sdk/error-runtime.js +1 -58
  410. package/dist/sdk/errors.js +1 -58
  411. package/dist/sdk/eval.js +1 -190
  412. package/dist/sdk/extension/author-manifest.js +1 -92
  413. package/dist/sdk/extension/bundled-catalog.js +1 -332
  414. package/dist/sdk/extension/concurrency.js +1 -25
  415. package/dist/sdk/extension/copy-scope.d.ts +2 -0
  416. package/dist/sdk/extension/copy-scope.js +2 -0
  417. package/dist/sdk/extension/custom-field-collisions.js +1 -30
  418. package/dist/sdk/extension/describe.js +3 -189
  419. package/dist/sdk/extension/doctor.js +1 -606
  420. package/dist/sdk/extension/install-plan.d.ts +69 -0
  421. package/dist/sdk/extension/install-plan.js +2 -0
  422. package/dist/sdk/extension/install-receipts.d.ts +7 -0
  423. package/dist/sdk/extension/install-receipts.js +2 -0
  424. package/dist/sdk/extension/install-runtime.js +3 -313
  425. package/dist/sdk/extension/install-snapshot.js +1 -66
  426. package/dist/sdk/extension/install-sources.js +5 -1057
  427. package/dist/sdk/extension/managed-state.js +2 -252
  428. package/dist/sdk/extension/migrations.js +2 -174
  429. package/dist/sdk/extension/output-ownership.js +1 -25
  430. package/dist/sdk/extension/runtime-summary.js +1 -18
  431. package/dist/sdk/extension/scaffold.js +4 -2308
  432. package/dist/sdk/extension/shared.js +1 -147
  433. package/dist/sdk/extension/source-resolution.js +1 -65
  434. package/dist/sdk/extension/update-check.js +1 -67
  435. package/dist/sdk/extension-command-context.js +1 -44
  436. package/dist/sdk/extension-contracts.js +1 -73
  437. package/dist/sdk/extension.d.ts +7 -2
  438. package/dist/sdk/extension.js +1 -2196
  439. package/dist/sdk/files.js +1 -535
  440. package/dist/sdk/flag-invocation-contracts.d.ts +0 -5
  441. package/dist/sdk/flag-invocation-contracts.js +1 -344
  442. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -2224
  443. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -2236
  444. package/dist/sdk/generated-error-code-catalog.js +1 -16
  445. package/dist/sdk/governance/assurance-action-contracts.js +1 -4
  446. package/dist/sdk/governance/assurance-action.js +1 -411
  447. package/dist/sdk/governance/assurance-limits.js +1 -10
  448. package/dist/sdk/governance/assurance-mutation-error.js +1 -81
  449. package/dist/sdk/governance/assurance-presets.js +1 -135
  450. package/dist/sdk/governance/assurance-runtime.js +1 -238
  451. package/dist/sdk/governance/assurance.js +4 -1182
  452. package/dist/sdk/governance/boundary-fixtures.js +1 -200
  453. package/dist/sdk/governance/coverage-assurance.js +1 -60
  454. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -188
  455. package/dist/sdk/governance/defect-recurrence-graph.js +1 -120
  456. package/dist/sdk/governance/defect-recurrence-signals.js +1 -24
  457. package/dist/sdk/governance/defect-recurrence.js +1 -623
  458. package/dist/sdk/governance/extension-host-version.js +1 -115
  459. package/dist/sdk/governance/gc.js +1 -368
  460. package/dist/sdk/governance/health.js +1 -2367
  461. package/dist/sdk/governance/hierarchy-validation.js +1 -108
  462. package/dist/sdk/governance/linked-file-report.js +1 -71
  463. package/dist/sdk/governance/merge-receipt-history.js +1 -206
  464. package/dist/sdk/governance/provenance-health.js +1 -282
  465. package/dist/sdk/governance/reindex.js +4 -761
  466. package/dist/sdk/governance/stale-work.js +1 -82
  467. package/dist/sdk/governance/status-role-diagnostics.js +1 -35
  468. package/dist/sdk/governance/storage-integrity.js +1 -280
  469. package/dist/sdk/governance/tracked-runtime-cache.js +1 -106
  470. package/dist/sdk/governance/upgrade.js +2 -327
  471. package/dist/sdk/governance/validate-history-drift.js +1 -81
  472. package/dist/sdk/governance/validate-item-reader.js +1 -17
  473. package/dist/sdk/governance/validate-normalization.js +1 -36
  474. package/dist/sdk/governance/validate.d.ts +3 -1
  475. package/dist/sdk/governance/validate.js +1 -2261
  476. package/dist/sdk/governance/workflow-completeness.d.ts +32 -0
  477. package/dist/sdk/governance/workflow-completeness.js +2 -0
  478. package/dist/sdk/governance/workflow-policy.d.ts +47 -0
  479. package/dist/sdk/governance/workflow-policy.js +4 -0
  480. package/dist/sdk/governance/workspace-position.js +1 -163
  481. package/dist/sdk/governance.d.ts +2 -0
  482. package/dist/sdk/governance.js +1 -31
  483. package/dist/sdk/graph/adapter.js +1 -181
  484. package/dist/sdk/graph/analytics.js +1 -474
  485. package/dist/sdk/graph/assembly.js +1 -377
  486. package/dist/sdk/graph/cache.js +1 -160
  487. package/dist/sdk/graph/centrality.js +1 -258
  488. package/dist/sdk/graph/conformance.js +1 -130
  489. package/dist/sdk/graph/deadline-scheduling.d.ts +90 -0
  490. package/dist/sdk/graph/deadline-scheduling.js +2 -0
  491. package/dist/sdk/graph/durable-cache.d.ts +1 -1
  492. package/dist/sdk/graph/durable-cache.js +1 -361
  493. package/dist/sdk/graph/governance-contracts.js +1 -34
  494. package/dist/sdk/graph/governance.d.ts +13 -1
  495. package/dist/sdk/graph/governance.js +1 -735
  496. package/dist/sdk/graph/hierarchy-integrity.js +1 -310
  497. package/dist/sdk/graph/index.d.ts +3 -2
  498. package/dist/sdk/graph/index.js +1 -26
  499. package/dist/sdk/graph/lifecycle-coverage.d.ts +32 -0
  500. package/dist/sdk/graph/lifecycle-coverage.js +2 -0
  501. package/dist/sdk/graph/mutation-advisory.js +1 -176
  502. package/dist/sdk/graph/remediation.js +1 -197
  503. package/dist/sdk/graph/run.d.ts +15 -1
  504. package/dist/sdk/graph/run.js +1 -768
  505. package/dist/sdk/graph/scheduling.js +1 -124
  506. package/dist/sdk/graph/traversal.js +1 -284
  507. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -27
  508. package/dist/sdk/graph.js +1 -15
  509. package/dist/sdk/guide-topics.js +1 -707
  510. package/dist/sdk/guide.js +1 -279
  511. package/dist/sdk/history/maintenance.d.ts +71 -0
  512. package/dist/sdk/history/maintenance.js +2 -0
  513. package/dist/sdk/history/salvage.js +2 -247
  514. package/dist/sdk/history/subject.d.ts +19 -0
  515. package/dist/sdk/history/subject.js +2 -0
  516. package/dist/sdk/history-analytics.js +1 -282
  517. package/dist/sdk/history-compact.js +1 -527
  518. package/dist/sdk/history-mcp.js +1 -68
  519. package/dist/sdk/history-provenance.js +1 -182
  520. package/dist/sdk/history-read.js +1 -96
  521. package/dist/sdk/history-redact.d.ts +1 -14
  522. package/dist/sdk/history-redact.js +1 -643
  523. package/dist/sdk/history-repair.d.ts +5 -0
  524. package/dist/sdk/history-repair.js +1 -657
  525. package/dist/sdk/improvement-ledger-validation.js +1 -62
  526. package/dist/sdk/improvement-ledger.js +2 -257
  527. package/dist/sdk/index.d.ts +4 -1
  528. package/dist/sdk/index.js +1 -183
  529. package/dist/sdk/init-agent-guidance.js +2 -496
  530. package/dist/sdk/init.js +2 -820
  531. package/dist/sdk/invocation-author.js +1 -39
  532. package/dist/sdk/item-children.js +1 -90
  533. package/dist/sdk/item-metadata-index.js +1 -15
  534. package/dist/sdk/item-schedule.js +1 -27
  535. package/dist/sdk/item-transaction.js +1 -396
  536. package/dist/sdk/learnings.js +1 -29
  537. package/dist/sdk/lifecycle/append.js +2 -53
  538. package/dist/sdk/lifecycle/claim.d.ts +2 -0
  539. package/dist/sdk/lifecycle/claim.js +1 -242
  540. package/dist/sdk/lifecycle/close-many.js +1 -438
  541. package/dist/sdk/lifecycle/close.js +1 -468
  542. package/dist/sdk/lifecycle/copy.js +1 -212
  543. package/dist/sdk/lifecycle/create.js +1 -1949
  544. package/dist/sdk/lifecycle/delete.js +1 -45
  545. package/dist/sdk/lifecycle/event-validation-messages.js +1 -91
  546. package/dist/sdk/lifecycle/focus.js +1 -91
  547. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -24
  548. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -149
  549. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -40
  550. package/dist/sdk/lifecycle/mcp-actions.d.ts +2 -0
  551. package/dist/sdk/lifecycle/mcp-actions.js +1 -51
  552. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -46
  553. package/dist/sdk/lifecycle/mutation-command-options.js +1 -9
  554. package/dist/sdk/lifecycle/plan.js +1 -1606
  555. package/dist/sdk/lifecycle/recurrence-parsers.d.ts +1 -1
  556. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -147
  557. package/dist/sdk/lifecycle/reopen.js +1 -68
  558. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +1 -143
  559. package/dist/sdk/lifecycle/restore.d.ts +1 -0
  560. package/dist/sdk/lifecycle/restore.js +1 -330
  561. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -295
  562. package/dist/sdk/lifecycle/update-many.js +1 -861
  563. package/dist/sdk/lifecycle/update.js +1 -2136
  564. package/dist/sdk/lifecycle-completion.js +1 -92
  565. package/dist/sdk/lifecycle-policy.js +1 -120
  566. package/dist/sdk/linked-artifacts.js +1 -530
  567. package/dist/sdk/mcp/apps.js +4 -133
  568. package/dist/sdk/mcp/authorization.js +1 -404
  569. package/dist/sdk/mcp/discovery.js +1 -494
  570. package/dist/sdk/mcp/interactions.js +1 -336
  571. package/dist/sdk/mcp/protocol.d.ts +7 -0
  572. package/dist/sdk/mcp/protocol.js +1 -184
  573. package/dist/sdk/mcp/skills.js +1 -389
  574. package/dist/sdk/mcp/subscriptions.js +1 -211
  575. package/dist/sdk/mcp/tasks.js +2 -430
  576. package/dist/sdk/mcp/transport.js +1 -260
  577. package/dist/sdk/merge/abandoned-receipts.js +1 -46
  578. package/dist/sdk/merge/driver.js +1 -212
  579. package/dist/sdk/merge/index.js +1 -16
  580. package/dist/sdk/merge/install.js +3 -561
  581. package/dist/sdk/merge/receipt-file-boundary.js +1 -46
  582. package/dist/sdk/merge/receipt-operation.js +1 -96
  583. package/dist/sdk/merge/receipt-schema.js +1 -397
  584. package/dist/sdk/merge/receipts.js +4 -525
  585. package/dist/sdk/merge/reconcile.js +1 -352
  586. package/dist/sdk/merge/three-way.js +3 -775
  587. package/dist/sdk/merge.js +1 -10
  588. package/dist/sdk/mutation-events.js +1 -292
  589. package/dist/sdk/mutation-guard.js +1 -216
  590. package/dist/sdk/notes.js +1 -139
  591. package/dist/sdk/output-contracts.js +1 -172
  592. package/dist/sdk/output-projection.js +1 -430
  593. package/dist/sdk/output-token-accounting.js +1 -140
  594. package/dist/sdk/output.js +1 -64
  595. package/dist/sdk/ownership-source.js +1 -21
  596. package/dist/sdk/package-import-adapters.js +1 -442
  597. package/dist/sdk/package-migrations.js +1 -20
  598. package/dist/sdk/package-runtime-options.js +1 -80
  599. package/dist/sdk/pagination.js +1 -162
  600. package/dist/sdk/profile.js +1 -454
  601. package/dist/sdk/provenance.js +1 -258
  602. package/dist/sdk/public-surface.json +1 -1
  603. package/dist/sdk/query/activity.js +1 -401
  604. package/dist/sdk/query/aggregate.d.ts +16 -0
  605. package/dist/sdk/query/aggregate.js +1 -390
  606. package/dist/sdk/query/calendar.js +1 -964
  607. package/dist/sdk/query/complete-list.js +1 -215
  608. package/dist/sdk/query/context.js +1 -1702
  609. package/dist/sdk/query/duplicate-candidates.js +1 -70
  610. package/dist/sdk/query/get.js +1 -450
  611. package/dist/sdk/query/history.js +1 -186
  612. package/dist/sdk/query/item-filter-options.js +1 -9
  613. package/dist/sdk/query/light-metadata.js +1 -18
  614. package/dist/sdk/query/list-filter-shared.js +1 -81
  615. package/dist/sdk/query/list.js +1 -1304
  616. package/dist/sdk/query/multi-value-filters.js +1 -78
  617. package/dist/sdk/query/next.js +1 -513
  618. package/dist/sdk/query/parsers.js +1 -44
  619. package/dist/sdk/query/projection-contracts.js +1 -184
  620. package/dist/sdk/query/search-contracts.d.ts +27 -0
  621. package/dist/sdk/query/search-contracts.js +1 -230
  622. package/dist/sdk/query/search-pagination.js +1 -35
  623. package/dist/sdk/query/search-rendering.js +1 -105
  624. package/dist/sdk/query/search.d.ts +6 -4
  625. package/dist/sdk/query/search.js +2 -1987
  626. package/dist/sdk/query.js +1 -35
  627. package/dist/sdk/read-output/continuation.js +1 -194
  628. package/dist/sdk/read-output-budget.js +1 -135
  629. package/dist/sdk/read-output-contracts.d.ts +1 -1
  630. package/dist/sdk/read-output-contracts.js +1 -1225
  631. package/dist/sdk/read-output-rows.js +1 -186
  632. package/dist/sdk/read-output-session.js +1 -208
  633. package/dist/sdk/relationship-analytics.js +1 -410
  634. package/dist/sdk/relationship-context.js +1 -284
  635. package/dist/sdk/relationship-history.js +4 -519
  636. package/dist/sdk/relationship-kinds/contract.js +1 -22
  637. package/dist/sdk/relationship-migration.js +1 -77
  638. package/dist/sdk/relationships.js +1 -579
  639. package/dist/sdk/reproducibility/process.js +1 -87
  640. package/dist/sdk/runtime-action-aliases.js +1 -59
  641. package/dist/sdk/runtime-extended-actions.js +1 -177
  642. package/dist/sdk/runtime-input.js +1 -614
  643. package/dist/sdk/runtime-primitives.js +1 -84
  644. package/dist/sdk/runtime-public-contracts.d.ts +2 -1
  645. package/dist/sdk/runtime-public-contracts.js +1 -4
  646. package/dist/sdk/runtime-stats-options.js +1 -38
  647. package/dist/sdk/runtime.d.ts +4 -0
  648. package/dist/sdk/runtime.js +1 -1928
  649. package/dist/sdk/scheduling-shortcuts.js +1 -63
  650. package/dist/sdk/schema-migration.js +3 -856
  651. package/dist/sdk/schema.d.ts +2 -1
  652. package/dist/sdk/schema.js +1 -1376
  653. package/dist/sdk/search-refresh-worker.js +1 -18
  654. package/dist/sdk/similarity-scoring.js +1 -53
  655. package/dist/sdk/similarity.js +1 -326
  656. package/dist/sdk/start-task-status.js +1 -14
  657. package/dist/sdk/stats.js +1 -270
  658. package/dist/sdk/structured-mutations.js +1 -580
  659. package/dist/sdk/telemetry-flush.js +1 -13
  660. package/dist/sdk/telemetry.js +1 -405
  661. package/dist/sdk/templates.js +2 -292
  662. package/dist/sdk/test/batch.js +2 -509
  663. package/dist/sdk/test/entry.js +1 -70
  664. package/dist/sdk/test/execution.js +6 -2211
  665. package/dist/sdk/test/linked-command-detection.js +1 -546
  666. package/dist/sdk/test/measurements.js +1 -91
  667. package/dist/sdk/test/parsers.js +1 -545
  668. package/dist/sdk/test/runs.js +1 -193
  669. package/dist/sdk/test/trust.js +2 -206
  670. package/dist/sdk/testing.js +4 -1391
  671. package/dist/sdk/traceability/runtime-files-lookup.js +1 -32
  672. package/dist/sdk/traceability/source-traceability.js +1 -292
  673. package/dist/sdk/tracker-root-discovery.js +1 -9
  674. package/dist/sdk/workspace-contracts-cache.js +1 -28
  675. package/dist/sdk/workspace-contracts.js +1 -33
  676. package/dist/sdk/workspace-memory.js +2 -318
  677. package/dist/sdk/workspace-recipe.js +1 -71
  678. package/dist/sdk/workspace-snapshot.js +4 -613
  679. package/dist/sdk/workspace-transaction-gc.js +1 -149
  680. package/dist/sdk/workspace-transaction.js +2 -363
  681. package/dist/sdk/workspace.js +3 -127
  682. package/dist/types/index.js +1 -9
  683. package/dist/types.d.ts +4 -0
  684. package/dist/types.js +1 -245
  685. package/docs/AGENT_GUIDE.md +1 -1
  686. package/docs/COMMANDS.md +10 -0
  687. package/docs/CONFIGURATION.md +12 -1
  688. package/docs/CONTEXT_ALGORITHM_PORTFOLIO.md +167 -0
  689. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +9 -3
  690. package/docs/EXTENSIONS.md +1 -0
  691. package/docs/HISTORY_MAINTENANCE.md +125 -0
  692. package/docs/MCP_2026_07_28_CONFORMANCE.md +20 -10
  693. package/docs/PACKAGE_EVIDENCE.md +92 -0
  694. package/docs/PLANNING_MEASUREMENTS.md +183 -0
  695. package/docs/README.md +4 -0
  696. package/docs/READ_OUTPUT_CONTRACTS.md +5 -0
  697. package/docs/SCRIPTING.md +21 -0
  698. package/docs/TESTING.md +33 -0
  699. package/docs/WORKFLOW_POLICIES.md +129 -0
  700. package/docs/generated/FLAG_LEXICON_BUDGETS.md +7 -7
  701. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +11 -5
  702. package/marketplace.json +2 -2
  703. package/package.json +5 -5
  704. package/packages/pm-beads/package.json +1 -1
  705. package/packages/pm-calendar/package.json +1 -1
  706. package/packages/pm-command-kit/package.json +1 -1
  707. package/packages/pm-digital-twin/package.json +1 -1
  708. package/packages/pm-governance-audit/package.json +1 -1
  709. package/packages/pm-guide-shell/package.json +1 -1
  710. package/packages/pm-kanban/package.json +1 -1
  711. package/packages/pm-lifecycle-hooks/package.json +1 -1
  712. package/packages/pm-linked-test-adapters/package.json +1 -1
  713. package/packages/pm-search-advanced/package.json +1 -1
  714. package/packages/pm-templates/package.json +1 -1
  715. package/packages/pm-todos/package.json +1 -1
  716. package/packages/pm-vcs/package.json +1 -1
  717. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  718. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  719. package/scripts/finalize-build.mjs +45 -3
  720. package/dist/cli-bundle/chunks/chunk-AZDFJGH6.js +0 -9
  721. package/dist/cli-bundle/chunks/chunk-CKOL5U7J.js +0 -77
  722. package/dist/cli-bundle/chunks/chunk-JX4DH4WC.js +0 -3
  723. package/dist/cli-bundle/chunks/chunk-OF76PSDQ.js +0 -5
  724. package/dist/cli-bundle/chunks/chunk-QUWFABDM.js +0 -232
  725. package/dist/cli-bundle/chunks/chunk-QWRRFYK3.js +0 -2
  726. package/dist/cli-bundle/chunks/chunk-RWWBOWJ5.js +0 -2
  727. package/dist/cli-bundle/chunks/chunk-WGAOYSYH.js +0 -40
  728. package/dist/cli-bundle/chunks/chunk-WI2AYPA7.js +0 -2
  729. package/dist/cli-bundle/chunks/register-list-query-5JL52D33.js +0 -11
  730. package/dist/cli-bundle/chunks/register-mutation-ZPG7KMVP.js +0 -20
  731. package/dist/cli-bundle/chunks/register-operations-I5W3KMGB.js +0 -2
  732. package/dist/cli-bundle/chunks/register-setup-H4SVAVX7.js +0 -2
  733. package/dist/cli-bundle/focused-chunks/chunk-AL5ON6K6.js +0 -2
  734. package/dist/cli-bundle/focused-chunks/chunk-CHC2IDXA.js +0 -6
  735. package/dist/cli-bundle/focused-chunks/chunk-CK6QFAPZ.js +0 -20
  736. package/dist/cli-bundle/focused-chunks/chunk-EZR3GHFE.js +0 -2
  737. package/dist/cli-bundle/focused-chunks/chunk-H2WJWK7L.js +0 -56
  738. package/dist/cli-bundle/focused-chunks/chunk-NTPY5GSO.js +0 -3
  739. package/dist/cli-bundle/focused-chunks/chunk-P5O7MP5Y.js +0 -2
  740. package/dist/cli-bundle/focused-chunks/chunk-PDMW2E36.js +0 -177
  741. package/dist/cli-bundle/focused-chunks/chunk-PEFABF7E.js +0 -26
  742. package/dist/cli-bundle/focused-chunks/chunk-QTVCLMSZ.js +0 -6
  743. package/dist/cli-bundle/focused-chunks/chunk-QTZRBUYA.js +0 -8
  744. package/dist/cli-bundle/focused-chunks/chunk-SGQST3PQ.js +0 -12
  745. package/dist/cli-bundle/focused-chunks/chunk-UKHASMMP.js +0 -10
  746. package/dist/cli-bundle/focused-chunks/chunk-ZPEKQHOC.js +0 -2
@@ -1,1475 +1,7 @@
1
- /**
2
- * @module core/item/item-format
3
- *
4
- * Defines item parsing, formatting, and lifecycle helpers for Item Format.
5
- */
1
+ !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="48df511d-df81-56f7-bb1d-f10230b43cfa")}catch(e2){}})();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,normalizeItemFormatVersion}from"./item-format-version.js";import{normalizeStatusInput}from"./status.js";import{decodeToonItemContent}from"./toon-decode.js";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";import{orderObject}from"../shared/serialization.js";import{compareTimestampStrings,isTimestampLiteral}from"../shared/time.js";import{coerceFiniteNumber}from"../shared/primitives.js";const LINKED_TEST_PM_CONTEXT_MODE_VALUES=new Set(["schema","tracker","auto"]);const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES=new Set(["source","isolated","snapshot"]);const LINKED_TEST_TRUST_REASON_VALUES=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]);const ITEM_TEST_RUN_STATUS_VALUES=new Set(["passed","failed","stopped","canceled"]);const 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)){if(value===void 0){delete record[key]}}}const REQUIRED_STRING_FIELDS=["id","title","description","created_at","updated_at"];const STATIC_ITEM_METADATA_FIELD_SET=new Set(ITEM_METADATA_KEY_ORDER);function resolveRuntimeSchemaValidationContext(options){if(!options?.schema){return void 0}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){if(!definition.required){return false}if(definition.required_types.length===0){return true}return definition.required_types.map(value=>value.toLowerCase()).includes(typeName.trim().toLowerCase())}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 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){if(!condition){validationError(message)}}function requireItemMetadataRecord(value,message){if(typeof value!=="object"||value===null||Array.isArray(value)){validationError(message)}return value}function assertTimestampField(record,fieldName){const rawValue=record[fieldName];assertItemMetadataCondition(typeof rawValue==="string",`${fieldName} must be a string`);const timestamp=rawValue;assertItemMetadataCondition(isTimestampLiteral(timestamp),`${fieldName} must be a valid ISO timestamp`)}function assertPositiveIntegerField(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}assertItemMetadataCondition(typeof value==="number"&&Number.isInteger(value)&&value>=1,`${messagePrefix} must be an integer >= 1`)}function assertOptionalTimestampString(record,fieldName,messagePrefix){const value=record[fieldName];if(value===void 0){return}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){return}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){return}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){return}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;if(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}`)}return 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;const normalizedStatus=normalizeStatusInput(status,statusRegistry);const 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){return}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();const isKnownTextConfidence=normalizedConfidence==="med"||CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);assertItemMetadataCondition(isKnownTextConfidence,`confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES,"med"].join(", ")}`);return}assertItemMetadataCondition(false,"confidence must be a number or string")}function assertSeverityItemMetadataField(record){const severity=record.severity;if(severity===void 0){return}if(typeof severity!=="string"){validationError("severity must be a string")}const normalizedSeverity=severity.trim().toLowerCase();const isKnownSeverity=normalizedSeverity==="med"||ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);assertItemMetadataCondition(isKnownSeverity,`severity value must be one of: ${[...ISSUE_SEVERITY_VALUES,"med"].join(", ")}`)}function assertRegressionItemMetadataField(record){if(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){return}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"]){if(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){if(eventRecord.recurrence===void 0){return}assertValidRecurrenceRule(eventRecord.recurrence);if(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");if(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);if(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){return}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];if(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");const optionText=optionValue;assertItemMetadataCondition(optionText.trim().length>0,"type_options values must be non-empty strings")}}function coerceRuntimeItemMetadataFields(record,itemType,runtimeContext){if(!runtimeContext?.fieldRegistry){return}for(const definition of runtimeContext.fieldRegistry.definitions){const fieldValue=record[definition.metadata_key];if(fieldValue===void 0){if(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}"`)}catch(error){validationError(String(error?.message).replace(/^Invalid\s+/u,""))}}}function assertRuntimeUnknownItemMetadataFields(record,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length===0){return}if(runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}else{runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function assertValidItemMetadata(itemMetadata,runtimeContext){const record=requireItemMetadataRecord(itemMetadata,"item metadata must be an object");const itemType=assertRequiredItemMetadataFields(record);assertStatusItemMetadataField(record,runtimeContext);assertPriorityAndTags(record);assertConfidenceItemMetadataField(record);assertSeverityItemMetadataField(record);assertRegressionItemMetadataField(record);assertTimestampField(record,"created_at");assertTimestampField(record,"updated_at");if(record.deadline!==void 0){assertTimestampField(record,"deadline")}assertReminderEntries(record);assertCalendarEvents(record);assertOptionalTimestampString(record,"closed_at","closed_at");assertOptionalTimestampString(record,"completed_at","completed_at");assertOptionalStringFields(record);assertTypeOptionsField(record);coerceRuntimeItemMetadataFields(record,itemType,runtimeContext);assertRuntimeUnknownItemMetadataFields(record,runtimeContext)}function sortDependencies(values){if(!values||values.length===0)return void 0;return[...values].map(value=>({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);if(byKind!==0)return byKind;return(a.source_kind??"").localeCompare(b.source_kind??"")})}function sortLogValues(values){if(!values||values.length===0)return void 0;return[...values].sort((a,b)=>{const byCreated=compareTimestampStrings(a.created_at,b.created_at);if(byCreated!==0)return byCreated;const byText=a.text.localeCompare(b.text);if(byText!==0)return byText;return a.author.localeCompare(b.author)})}function sortReminders(values){if(!values||values.length===0)return void 0;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);if(byAt!==0)return byAt;return a.text.localeCompare(b.text)});return normalized.length===0?void 0:normalized}function normalizeRecurrenceRule(value){if(!value){return void 0}const normalizedFrequency=value.freq.trim().toLowerCase();if(!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency)){return void 0}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));const 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);const exdates=Array.from(new Set((value.exdates??[]).map(timestamp=>timestamp.trim()).filter(timestamp=>isTimestampLiteral(timestamp)))).sort((a,b)=>compareTimestampStrings(a,b));const 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)){if(fieldValue===void 0){delete normalized[key]}}return normalized}function sortEvents(values){if(!Array.isArray(values)||values.length===0){return void 0}const normalized=[...values].map(normalizeCalendarEvent).sort(compareCalendarEvents);return normalized}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)};deleteUndefinedFields(event);return 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??""),Number(Boolean(a.all_day))-Number(Boolean(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 void 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 void 0;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 void 0;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:void 0,threshold:typeof measurement.threshold==="number"&&Number.isFinite(measurement.threshold)?measurement.threshold:void 0,recorded_at:measurement.recorded_at.trim()}));const 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 void 0;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():"";const kind=value.kind==="test"||value.kind==="test-all"?value.kind:"test";const status=ITEM_TEST_RUN_STATUS_VALUES.has(value.status)?value.status:"failed";const 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===true?true:void 0,measurements:normalizeTestRunMeasurements(value.measurements),executions:normalizeTestRunExecutions(value.executions)};deleteUndefinedFields(summary);return summary}function sortTests(values){if(!Array.isArray(values)||values.length===0)return void 0;return values.map(normalizeLinkedTest)}function normalizeTrimmedStringList(value){if(!Array.isArray(value)){return void 0}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 false}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 void 0}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 void 0}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 void 0}return normalized}function normalizeLinkedTestWorkspaceContextMode(value){const normalized=value?.trim().toLowerCase();if(!normalized||!LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)){return void 0}return normalized}function normalizeLinkedTestProvenance(value,invalid){if(invalid===true){return{provenance_invalid:true}}if(value===void 0){return{}}if(!isPlainObjectRecord(value)){return{provenance_invalid:true}}const author=trimStringOrUndefined(value.author);const createdAt=trimStringOrUndefined(value.created_at);const sourceKind=value.source_kind;if(!author||!createdAt||!isTimestampLiteral(createdAt)||sourceKind!=="local_mutation"&&sourceKind!=="merge_union"){return{provenance_invalid:true}}return{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),env_set:normalizeStringRecord(value.env_set),env_clear:normalizeTrimmedStringList(value.env_clear),shared_host_safe:value.shared_host_safe===true?true: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};deleteUndefinedFields(test);return test}function sortDocs(values){if(!values||values.length===0)return void 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);if(byPath!==0)return byPath;return(a.note??"").localeCompare(b.note??"")})}function trimStringOrUndefined(value){if(typeof value!=="string")return void 0;const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}function normalizePlanStepLinks(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const id=trimStringOrUndefined(record.id);const kind=trimStringOrUndefined(record.kind);if(!id||!kind)continue;const link={id,kind};const note=trimStringOrUndefined(record.note);if(note)link.note=note;if(record.required_before_step===true)link.required_before_step=true;out.push(link)}return out.length>0?out:void 0}function normalizePlanStepFiles(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const file={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")file.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)file.note=note;out.push(file)}return out.length>0?out:void 0}function normalizePlanStepTests(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const command=trimStringOrUndefined(record.command);const path=trimStringOrUndefined(record.path);if(!command&&!path)continue;const test={};if(command)test.command=command;if(path)test.path=normalizePathValue(path);const note=trimStringOrUndefined(record.note);if(note)test.note=note;out.push(test)}return out.length>0?out:void 0}function normalizePlanStepDocs(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const path=trimStringOrUndefined(record.path);if(!path)continue;const doc={path:normalizePathValue(path)};if(record.scope==="project"||record.scope==="global")doc.scope=record.scope;const note=trimStringOrUndefined(record.note);if(note)doc.note=note;out.push(doc)}return out.length>0?out:void 0}function normalizePlanStepEntry(entry){if(entry===null||typeof entry!=="object"){return void 0}const record=entry;const id=trimStringOrUndefined(record.id);const title=trimStringOrUndefined(record.title);const statusRaw=trimStringOrUndefined(record.status);const status=statusRaw&&PLAN_STEP_STATUS_SET.has(statusRaw)?statusRaw:void 0;const order=coerceFiniteNumber(record.order)??Number.NaN;const created_at=typeof record.created_at==="string"?record.created_at:"";const updated_at=typeof record.updated_at==="string"?record.updated_at:"";if(!id||!title||!status||!Number.isFinite(order)||!created_at||!updated_at){return void 0}const step={id,order,title,status,created_at,updated_at};applyPlanStepOptionalFields(step,record);return 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]);if(value){step[target]=value}}const completedAt=typeof record.completed_at==="string"?record.completed_at:void 0;if(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]);if(value){step[target]=value}}}function normalizePlanSteps(value){if(!Array.isArray(value))return void 0;const out=value.flatMap(entry=>{const step=normalizePlanStepEntry(entry);return step?[step]:[]});out.sort((left,right)=>left.order-right.order);return out.length>0?out:void 0}function normalizePlanDecisions(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const decision=trimStringOrUndefined(record.decision);if(!ts||!author||!decision)continue;const item={ts,author,decision};const rationale=trimStringOrUndefined(record.rationale);if(rationale)item.rationale=rationale;const evidence=trimStringOrUndefined(record.evidence);if(evidence)item.evidence=evidence;const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanDiscoveries(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const ts=typeof record.ts==="string"?record.ts:"";const author=typeof record.author==="string"?record.author:"";const text=trimStringOrUndefined(record.text);if(!ts||!author||!text)continue;const item={ts,author,text};const stepId=trimStringOrUndefined(record.step_id);if(stepId)item.step_id=stepId;out.push(item)}return out.length>0?out:void 0}function normalizePlanValidation(value){if(!Array.isArray(value))return void 0;const out=[];for(const entry of value){if(entry===null||typeof entry!=="object")continue;const record=entry;const text=trimStringOrUndefined(record.text);if(!text)continue;const item={text};const command=trimStringOrUndefined(record.command);if(command)item.command=command;const expected=trimStringOrUndefined(record.expected);if(expected)item.expected=expected;out.push(item)}return out.length>0?out:void 0}function normalizeTypeOptions(values){if(!values){return void 0}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 void 0}return Object.fromEntries(normalizedEntries)}function normalizeBody(body){let start=0;while(start<body.length&&body[start]==="\n"){start+=1}return body.slice(start).trimEnd()}function normalizeConfidenceValue(value){if(value===void 0){return void 0}if(typeof value==="number"){return value}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(CONFIDENCE_TEXT_VALUES.includes(normalized)){return normalized}return void 0}function normalizeSeverityValue(value){if(value===void 0){return void 0}const normalized=value.trim().toLowerCase();if(normalized==="med"){return"medium"}if(ISSUE_SEVERITY_VALUES.includes(normalized)){return normalized}return void 0}function emptyStringToUndefined(value){return value||void 0}function copyExtensionItemMetadataFields(normalized,source){const targetRecord=normalized;const sourceRecord=source;for(const[key,value]of Object.entries(sourceRecord)){if(isUnsafeObjectKey(key)||Object.prototype.hasOwnProperty.call(targetRecord,key)||value===void 0){continue}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];if(currentValue===void 0){continue}record[definition.metadata_key]=coerceRuntimeFieldValue(definition,currentValue,`metadata field "${definition.metadata_key}"`)}}function assertNormalizedUnknownFields(normalized,runtimeContext){if(!runtimeContext||runtimeContext.unknownFieldPolicy==="allow"){return}const knownKeys=buildKnownItemMetadataKeys(runtimeContext);const record=normalized;const unknownKeys=Object.keys(record).filter(key=>!knownKeys.has(key)).sort((left,right)=>left.localeCompare(right));if(unknownKeys.length>0&&runtimeContext.unknownFieldPolicy==="reject"){validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`)}if(unknownKeys.length>0){runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`)}}function normalizeItemMetadata(itemMetadata,options={}){const runtimeContext=resolveRuntimeSchemaValidationContext(options);const normalizedStatus=normalizeStatusInput(itemMetadata.status,runtimeContext?.statusRegistry)??itemMetadata.status;const 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));const normalized={id:itemMetadata.id,title:itemMetadata.title,description:itemMetadata.description,type:itemMetadata.type,pm_format_version:normalizeItemFormatVersion(itemMetadata.pm_format_version),source_type:trimStringOrUndefined(itemMetadata.source_type),type_options:normalizeTypeOptions(itemMetadata.type_options),status:normalizedStatus,priority:itemMetadata.priority,tags,created_at:itemMetadata.created_at,updated_at:itemMetadata.updated_at,dependencies:sortDependencies(itemMetadata.dependencies),comments:sortLogValues(itemMetadata.comments),notes:sortLogValues(itemMetadata.notes),learnings:sortLogValues(itemMetadata.learnings),files:normalizeFiles(itemMetadata.files),tests:sortTests(itemMetadata.tests),test_runs:normalizeTestRunSummaries(itemMetadata.test_runs),docs:sortDocs(itemMetadata.docs),deadline:emptyStringToUndefined(itemMetadata.deadline),reminders:sortReminders(itemMetadata.reminders),events:sortEvents(itemMetadata.events),closed_at:emptyStringToUndefined(itemMetadata.closed_at),completed_at:emptyStringToUndefined(itemMetadata.completed_at),assignee:trimStringOrUndefined(itemMetadata.assignee),claim_principal:trimStringOrUndefined(itemMetadata.claim_principal),source_owner:trimStringOrUndefined(itemMetadata.source_owner),author:emptyStringToUndefined(itemMetadata.author),estimated_minutes:itemMetadata.estimated_minutes,acceptance_criteria:itemMetadata.acceptance_criteria??void 0,design:itemMetadata.design??void 0,external_ref:itemMetadata.external_ref??void 0,definition_of_ready:trimStringOrUndefined(itemMetadata.definition_of_ready),order:itemMetadata.order,goal:trimStringOrUndefined(itemMetadata.goal),objective:trimStringOrUndefined(itemMetadata.objective),value:trimStringOrUndefined(itemMetadata.value),impact:trimStringOrUndefined(itemMetadata.impact),outcome:trimStringOrUndefined(itemMetadata.outcome),why_now:trimStringOrUndefined(itemMetadata.why_now),parent:trimStringOrUndefined(itemMetadata.parent),reviewer:trimStringOrUndefined(itemMetadata.reviewer),risk:itemMetadata.risk??void 0,confidence:normalizeConfidenceValue(itemMetadata.confidence),sprint:trimStringOrUndefined(itemMetadata.sprint),release:trimStringOrUndefined(itemMetadata.release),blocked_by:trimStringOrUndefined(itemMetadata.blocked_by),blocked_reason:trimStringOrUndefined(itemMetadata.blocked_reason),unblock_note:trimStringOrUndefined(itemMetadata.unblock_note),reporter:trimStringOrUndefined(itemMetadata.reporter),severity:normalizeSeverityValue(itemMetadata.severity),environment:trimStringOrUndefined(itemMetadata.environment),repro_steps:trimStringOrUndefined(itemMetadata.repro_steps),resolution:trimStringOrUndefined(itemMetadata.resolution),expected_result:trimStringOrUndefined(itemMetadata.expected_result),actual_result:trimStringOrUndefined(itemMetadata.actual_result),affected_version:trimStringOrUndefined(itemMetadata.affected_version),fixed_version:trimStringOrUndefined(itemMetadata.fixed_version),component:trimStringOrUndefined(itemMetadata.component),regression:itemMetadata.regression,customer_impact:trimStringOrUndefined(itemMetadata.customer_impact),close_reason:emptyStringToUndefined(itemMetadata.close_reason),plan_mode:trimStringOrUndefined(itemMetadata.plan_mode),plan_scope:trimStringOrUndefined(itemMetadata.plan_scope),plan_harness:trimStringOrUndefined(itemMetadata.plan_harness),plan_resume_context:trimStringOrUndefined(itemMetadata.plan_resume_context),plan_steps:normalizePlanSteps(itemMetadata.plan_steps),plan_decisions:normalizePlanDecisions(itemMetadata.plan_decisions),plan_discoveries:normalizePlanDiscoveries(itemMetadata.plan_discoveries),plan_validation:normalizePlanValidation(itemMetadata.plan_validation)};copyExtensionItemMetadataFields(normalized,itemMetadata);coerceNormalizedRuntimeFields(normalized,runtimeContext);assertNormalizedUnknownFields(normalized,runtimeContext);deleteUndefinedFields(normalized);return normalized}function orderItemMetadata(itemMetadata){return orderObject(itemMetadata,ITEM_METADATA_KEY_ORDER)}function findJsonObjectEnd(content){let depth=0;let inString=false;let escaped=false;for(let i=0;i<content.length;i+=1){const char=content[i];if(inString){if(escaped){escaped=false;continue}if(char==="\\"){escaped=true;continue}if(char==='"'){inString=false}continue}if(char==='"'){inString=true;continue}if(char==="{"){depth+=1;continue}if(char==="}"){depth-=1;if(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);const body=content.slice(end+1).replace(/^\r?\n+/,"");return{frontMatter,body}}function stripLeadingYamlDocument(content){const normalizedContent=content.charCodeAt(0)===65279?content.slice(1):content;const opener=normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!opener){return{content:normalizedContent,stripped:false}}let cursor=opener[0].length;while(cursor<normalizedContent.length){const nextNewline=normalizedContent.indexOf("\n",cursor);const lineEnd=nextNewline===-1?normalizedContent.length:nextNewline;const line=normalizedContent.slice(cursor,lineEnd).replace(/\r$/,"");const afterLine=nextNewline===-1?lineEnd:lineEnd+1;if(line.trim()==="---"){return{content:normalizedContent.slice(afterLine).replace(/^\s+/,""),stripped:true}}cursor=afterLine}return{content:normalizedContent,stripped:false}}function normalizeParsedItemMetadata(itemMetadata,options){return normalizeItemMetadata(itemMetadata,{...options,onWarning:void 0})}function parseJsonMarkdownItemDocument(content,runtimeContext,options={}){const normalized=stripLeadingYamlDocument(content);if(normalized.stripped){options.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored")}const{frontMatter,body}=splitFrontMatter(normalized.content);if(!frontMatter){const trimmed=content.trimStart();if(trimmed.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")}assertValidItemMetadata(parsed,runtimeContext);return{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(!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")}if(Object.prototype.hasOwnProperty.call(record,"front_matter")){assertValidItemMetadata(record.front_matter,runtimeContext);assertItemMetadataCondition(record.body===void 0||typeof record.body==="string","TOON item document body must be a string");return{metadata:normalizeParsedItemMetadata(record.front_matter,options),body:normalizeBody(typeof record.body==="string"?record.body:"")}}const{body,...itemMetadataRecord}=record;assertItemMetadataCondition(body===void 0||typeof body==="string","TOON item document body must be a string");assertValidItemMetadata(itemMetadataRecord,runtimeContext);return{metadata:normalizeParsedItemMetadata(itemMetadataRecord,options),body:normalizeBody(typeof body==="string"?body:"")}}function serializeJsonMarkdownItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options);const orderedMetadata=orderItemMetadata(normalizedMetadata);const serializedMetadata=JSON.stringify(orderedMetadata,null,2);const normalizedBody=normalizeBody(document.body??"");if(!normalizedBody){return`${serializedMetadata}
2
+ `}return`${serializedMetadata}
6
3
 
7
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="051655a4-8ba7-5118-9758-d9ca377fa7e4")}catch(e){}}();
8
- import { encode as encodeToon } from "@toon-format/toon";
9
- import { isDeepStrictEqual } from "node:util";
10
- import { CONFIDENCE_TEXT_VALUES, ISSUE_SEVERITY_VALUES, PLAN_STEP_STATUS_VALUES, RECURRENCE_FREQUENCY_VALUES, RECURRENCE_WEEKDAY_VALUES, STATUS_VALUES, weekdayOrderIndex, } from "../../types/index.js";
11
- import { coerceRuntimeFieldValue } from "../schema/runtime-field-values.js";
12
- import { resolveRuntimeFieldRegistry, resolveRuntimeStatusRegistry, } from "../schema/runtime-schema.js";
13
- import { BASELINE_ITEM_FORMAT_VERSION, normalizeItemFormatVersion, } from "./item-format-version.js";
14
- import { normalizeStatusInput } from "./status.js";
15
- import { decodeToonItemContent } from "./toon-decode.js";
16
- import { EXIT_CODE, ITEM_METADATA_KEY_ORDER } from "../shared/constants.js";
17
- import { findFirstMergeConflictMarker } from "../shared/conflict-markers.js";
18
- import { PmCliError } from "../shared/errors.js";
19
- import { orderObject } from "../shared/serialization.js";
20
- import { compareTimestampStrings, isTimestampLiteral } from "../shared/time.js";
21
- import { coerceFiniteNumber } from "../shared/primitives.js";
22
- const LINKED_TEST_PM_CONTEXT_MODE_VALUES = new Set([
23
- "schema",
24
- "tracker",
25
- "auto",
26
- ]);
27
- const LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES = new Set([
28
- "source",
29
- "isolated",
30
- "snapshot",
31
- ]);
32
- const LINKED_TEST_TRUST_REASON_VALUES = new Set([
33
- "legacy",
34
- "local_mutation",
35
- "local_source_ref",
36
- "acknowledged",
37
- "invalid_provenance",
38
- "foreign_source_ref",
39
- ]);
40
- const ITEM_TEST_RUN_STATUS_VALUES = new Set([
41
- "passed",
42
- "failed",
43
- "stopped",
44
- "canceled",
45
- ]);
46
- const PLAN_STEP_STATUS_SET = new Set(PLAN_STEP_STATUS_VALUES);
47
- function normalizePathValue(value) {
48
- return value.replaceAll("\\", "/");
49
- }
50
- function firstNonZeroComparison(comparisons) {
51
- for (const comparison of comparisons) {
52
- if (comparison !== 0) {
53
- return comparison;
54
- }
55
- }
56
- return 0;
57
- }
58
- function deleteUndefinedFields(record) {
59
- for (const [key, value] of Object.entries(record)) {
60
- if (value === undefined) {
61
- delete record[key];
62
- }
63
- }
64
- }
65
- const REQUIRED_STRING_FIELDS = [
66
- "id",
67
- "title",
68
- "description",
69
- "created_at",
70
- "updated_at",
71
- ];
72
- const STATIC_ITEM_METADATA_FIELD_SET = new Set(ITEM_METADATA_KEY_ORDER);
73
- function resolveRuntimeSchemaValidationContext(options) {
74
- if (!options?.schema) {
75
- return undefined;
76
- }
77
- return {
78
- statusRegistry: resolveRuntimeStatusRegistry(options.schema),
79
- fieldRegistry: resolveRuntimeFieldRegistry(options.schema),
80
- unknownFieldPolicy: options.schema.unknown_field_policy ?? "allow",
81
- extensionFieldNames: new Set(options.extensionFieldNames ?? []),
82
- onWarning: options.onWarning,
83
- };
84
- }
85
- function runtimeFieldRequiredForType(definition, typeName) {
86
- if (!definition.required) {
87
- return false;
88
- }
89
- if (definition.required_types.length === 0) {
90
- return true;
91
- }
92
- return definition.required_types
93
- .map((value) => value.toLowerCase())
94
- .includes(typeName.trim().toLowerCase());
95
- }
96
- function validationError(message) {
97
- const field = message.match(/^([a-z_][\w.]*)\s/u)?.[1];
98
- throw new PmCliError(`Invalid item metadata: ${message}`, EXIT_CODE.GENERIC_FAILURE, {
99
- code: "item_document_invalid",
100
- reason: message.includes("required")
101
- ? "missing_required_field"
102
- : "schema_validation_error",
103
- ...(field ? { field } : {}),
104
- required: "Provide an item document whose metadata satisfies the active runtime schema.",
105
- why: message,
106
- });
107
- }
108
- function documentSyntaxError(format, message) {
109
- throw new PmCliError(message, EXIT_CODE.GENERIC_FAILURE, {
110
- code: "item_document_invalid",
111
- reason: "syntax_error",
112
- format,
113
- required: `Provide a syntactically valid ${format === "toon" ? "TOON" : "JSON Markdown"} item document.`,
114
- why: "The document could not be decoded far enough to validate item metadata.",
115
- });
116
- }
117
- function buildKnownItemMetadataKeys(runtimeContext) {
118
- const knownKeys = new Set(STATIC_ITEM_METADATA_FIELD_SET);
119
- for (const definition of runtimeContext.fieldRegistry?.definitions ?? []) {
120
- knownKeys.add(definition.metadata_key);
121
- }
122
- for (const fieldName of runtimeContext.extensionFieldNames) {
123
- knownKeys.add(fieldName);
124
- }
125
- return knownKeys;
126
- }
127
- function assertItemMetadataCondition(condition, message) {
128
- if (!condition) {
129
- validationError(message);
130
- }
131
- }
132
- function requireItemMetadataRecord(value, message) {
133
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
134
- validationError(message);
135
- }
136
- return value;
137
- }
138
- function assertTimestampField(record, fieldName) {
139
- const rawValue = record[fieldName];
140
- assertItemMetadataCondition(typeof rawValue === "string", `${fieldName} must be a string`);
141
- const timestamp = rawValue;
142
- assertItemMetadataCondition(isTimestampLiteral(timestamp), `${fieldName} must be a valid ISO timestamp`);
143
- }
144
- function assertPositiveIntegerField(record, fieldName, messagePrefix) {
145
- const value = record[fieldName];
146
- if (value === undefined) {
147
- return;
148
- }
149
- assertItemMetadataCondition(typeof value === "number" && Number.isInteger(value) && value >= 1, `${messagePrefix} must be an integer >= 1`);
150
- }
151
- function assertOptionalTimestampString(record, fieldName, messagePrefix) {
152
- const value = record[fieldName];
153
- if (value === undefined) {
154
- return;
155
- }
156
- assertItemMetadataCondition(typeof value === "string", `${messagePrefix} must be a string`);
157
- assertItemMetadataCondition(isTimestampLiteral(value), `${messagePrefix} must be a valid ISO timestamp`);
158
- }
159
- function assertRecurrenceWeekdays(value) {
160
- if (value === undefined) {
161
- return;
162
- }
163
- assertItemMetadataCondition(Array.isArray(value), "event.recurrence.by_weekday must be an array");
164
- for (const weekday of value) {
165
- assertItemMetadataCondition(typeof weekday === "string", "event.recurrence.by_weekday entries must be strings");
166
- const normalizedWeekday = weekday.trim().toLowerCase();
167
- assertItemMetadataCondition(RECURRENCE_WEEKDAY_VALUES.includes(normalizedWeekday), `event.recurrence.by_weekday entries must be one of: ${RECURRENCE_WEEKDAY_VALUES.join(", ")}`);
168
- }
169
- }
170
- function assertRecurrenceMonthDays(value) {
171
- if (value === undefined) {
172
- return;
173
- }
174
- assertItemMetadataCondition(Array.isArray(value), "event.recurrence.by_month_day must be an array");
175
- for (const day of value) {
176
- assertItemMetadataCondition(typeof day === "number" && Number.isInteger(day) && day >= 1 && day <= 31, "event.recurrence.by_month_day entries must be integers 1..31");
177
- }
178
- }
179
- function assertRecurrenceExdates(value) {
180
- if (value === undefined) {
181
- return;
182
- }
183
- assertItemMetadataCondition(Array.isArray(value), "event.recurrence.exdates must be an array");
184
- for (const exdate of value) {
185
- assertItemMetadataCondition(typeof exdate === "string", "event.recurrence.exdates entries must be strings");
186
- assertItemMetadataCondition(isTimestampLiteral(exdate), "event.recurrence.exdates entries must be valid ISO timestamps");
187
- }
188
- }
189
- function assertValidRecurrenceRule(recurrence) {
190
- const recurrenceRecord = requireItemMetadataRecord(recurrence, "event.recurrence must be an object");
191
- assertItemMetadataCondition(typeof recurrenceRecord.freq === "string", "event.recurrence.freq must be a string");
192
- const frequency = recurrenceRecord.freq.trim().toLowerCase();
193
- assertItemMetadataCondition(RECURRENCE_FREQUENCY_VALUES.includes(frequency), `event.recurrence.freq must be one of: ${RECURRENCE_FREQUENCY_VALUES.join(", ")}`);
194
- assertPositiveIntegerField(recurrenceRecord, "interval", "event.recurrence.interval");
195
- assertPositiveIntegerField(recurrenceRecord, "count", "event.recurrence.count");
196
- assertOptionalTimestampString(recurrenceRecord, "until", "event.recurrence.until");
197
- assertRecurrenceWeekdays(recurrenceRecord.by_weekday);
198
- assertRecurrenceMonthDays(recurrenceRecord.by_month_day);
199
- assertRecurrenceExdates(recurrenceRecord.exdates);
200
- }
201
- function assertRequiredItemMetadataFields(record) {
202
- for (const fieldName of REQUIRED_STRING_FIELDS) {
203
- assertItemMetadataCondition(typeof record[fieldName] === "string", `${fieldName} is required and must be a string`);
204
- }
205
- const itemType = record.type;
206
- assertItemMetadataCondition(typeof itemType === "string" && itemType.trim().length > 0, "type must be a non-empty string");
207
- const formatVersion = record.pm_format_version;
208
- if (formatVersion !== undefined) {
209
- assertItemMetadataCondition(typeof formatVersion === "number" &&
210
- Number.isInteger(formatVersion) &&
211
- formatVersion >= BASELINE_ITEM_FORMAT_VERSION, `pm_format_version must be an integer >= ${BASELINE_ITEM_FORMAT_VERSION}`);
212
- }
213
- return itemType;
214
- }
215
- function assertStatusItemMetadataField(record, runtimeContext) {
216
- const status = record.status;
217
- assertItemMetadataCondition(typeof status === "string" && status.trim().length > 0, "status must be a non-empty string");
218
- const statusRegistry = runtimeContext?.statusRegistry;
219
- const normalizedStatus = normalizeStatusInput(status, statusRegistry);
220
- const statusDomain = statusRegistry
221
- ? statusRegistry.definitions.map((definition) => definition.id)
222
- : [...STATUS_VALUES];
223
- assertItemMetadataCondition(normalizedStatus !== undefined, `status must be one of: ${statusDomain.join(", ")}`);
224
- }
225
- function assertPriorityAndTags(record) {
226
- const priority = record.priority;
227
- assertItemMetadataCondition(typeof priority === "number" &&
228
- Number.isInteger(priority) &&
229
- [0, 1, 2, 3, 4].includes(priority), "priority must be an integer 0..4");
230
- const tags = record.tags;
231
- assertItemMetadataCondition(Array.isArray(tags), "tags must be an array");
232
- for (const tag of tags) {
233
- assertItemMetadataCondition(typeof tag === "string", "tags entries must be strings");
234
- }
235
- }
236
- function assertConfidenceItemMetadataField(record) {
237
- const confidence = record.confidence;
238
- if (confidence === undefined) {
239
- return;
240
- }
241
- if (typeof confidence === "number") {
242
- assertItemMetadataCondition(Number.isInteger(confidence) && confidence >= 0 && confidence <= 100, "confidence number value must be an integer 0..100");
243
- return;
244
- }
245
- if (typeof confidence === "string") {
246
- const normalizedConfidence = confidence.trim().toLowerCase();
247
- const isKnownTextConfidence = normalizedConfidence === "med" ||
248
- CONFIDENCE_TEXT_VALUES.includes(normalizedConfidence);
249
- assertItemMetadataCondition(isKnownTextConfidence, `confidence string value must be one of: ${[...CONFIDENCE_TEXT_VALUES, "med"].join(", ")}`);
250
- return;
251
- }
252
- assertItemMetadataCondition(false, "confidence must be a number or string");
253
- }
254
- function assertSeverityItemMetadataField(record) {
255
- const severity = record.severity;
256
- if (severity === undefined) {
257
- return;
258
- }
259
- if (typeof severity !== "string") {
260
- validationError("severity must be a string");
261
- }
262
- const normalizedSeverity = severity.trim().toLowerCase();
263
- const isKnownSeverity = normalizedSeverity === "med" ||
264
- ISSUE_SEVERITY_VALUES.includes(normalizedSeverity);
265
- assertItemMetadataCondition(isKnownSeverity, `severity value must be one of: ${[...ISSUE_SEVERITY_VALUES, "med"].join(", ")}`);
266
- }
267
- function assertRegressionItemMetadataField(record) {
268
- if (record.regression !== undefined &&
269
- typeof record.regression !== "boolean") {
270
- validationError("regression must be a boolean");
271
- }
272
- }
273
- function assertReminderEntries(record) {
274
- const reminders = record.reminders;
275
- if (reminders === undefined) {
276
- return;
277
- }
278
- assertItemMetadataCondition(Array.isArray(reminders), "reminders must be an array");
279
- for (const reminder of reminders) {
280
- const reminderRecord = requireItemMetadataRecord(reminder, "reminders entries must be objects");
281
- assertItemMetadataCondition(typeof reminderRecord.at === "string", "reminder.at must be a string");
282
- assertItemMetadataCondition(isTimestampLiteral(reminderRecord.at), "reminder.at must be a valid ISO timestamp");
283
- assertItemMetadataCondition(typeof reminderRecord.text === "string", "reminder.text must be a string");
284
- assertItemMetadataCondition(reminderRecord.text.trim().length > 0, "reminder.text must not be empty");
285
- }
286
- }
287
- function assertEventStringFields(eventRecord) {
288
- for (const stringField of [
289
- "title",
290
- "description",
291
- "location",
292
- "timezone",
293
- ]) {
294
- if (eventRecord[stringField] !== undefined) {
295
- assertItemMetadataCondition(typeof eventRecord[stringField] === "string", `event.${stringField} must be a string`);
296
- assertItemMetadataCondition(eventRecord[stringField].trim().length > 0, `event.${stringField} must not be empty`);
297
- }
298
- }
299
- }
300
- function assertEventRecurrence(eventRecord) {
301
- if (eventRecord.recurrence === undefined) {
302
- return;
303
- }
304
- assertValidRecurrenceRule(eventRecord.recurrence);
305
- if (eventRecord.recurrence.until !== undefined) {
306
- assertItemMetadataCondition(compareTimestampStrings(eventRecord.recurrence.until, eventRecord.start_at) >= 0, "event.recurrence.until must be at or after event.start_at");
307
- }
308
- }
309
- function assertCalendarEventEntry(event) {
310
- const eventRecord = requireItemMetadataRecord(event, "events entries must be objects");
311
- assertItemMetadataCondition(typeof eventRecord.start_at === "string", "event.start_at must be a string");
312
- assertItemMetadataCondition(isTimestampLiteral(eventRecord.start_at), "event.start_at must be a valid ISO timestamp");
313
- if (eventRecord.end_at !== undefined) {
314
- assertItemMetadataCondition(typeof eventRecord.end_at === "string", "event.end_at must be a string");
315
- assertItemMetadataCondition(isTimestampLiteral(eventRecord.end_at), "event.end_at must be a valid ISO timestamp");
316
- assertItemMetadataCondition(compareTimestampStrings(eventRecord.end_at, eventRecord.start_at) > 0, "event.end_at must be after event.start_at");
317
- }
318
- assertEventStringFields(eventRecord);
319
- if (eventRecord.all_day !== undefined) {
320
- assertItemMetadataCondition(typeof eventRecord.all_day === "boolean", "event.all_day must be a boolean");
321
- }
322
- assertEventRecurrence(eventRecord);
323
- }
324
- function assertCalendarEvents(record) {
325
- const events = record.events;
326
- if (events === undefined) {
327
- return;
328
- }
329
- assertItemMetadataCondition(Array.isArray(events), "events must be an array");
330
- for (const event of events) {
331
- assertCalendarEventEntry(event);
332
- }
333
- }
334
- function assertOptionalStringFields(record) {
335
- for (const fieldName of [
336
- "source_type",
337
- "source_owner",
338
- "design",
339
- "external_ref",
340
- ]) {
341
- const value = record[fieldName];
342
- if (value !== undefined) {
343
- assertItemMetadataCondition(typeof value === "string", `${fieldName} must be a string`);
344
- }
345
- }
346
- }
347
- function assertTypeOptionsField(record) {
348
- const typeOptions = record.type_options;
349
- if (typeOptions === undefined) {
350
- return;
351
- }
352
- const typeOptionsRecord = requireItemMetadataRecord(typeOptions, "type_options must be an object");
353
- for (const [optionKey, optionValue] of Object.entries(typeOptionsRecord)) {
354
- assertItemMetadataCondition(optionKey.trim().length > 0, "type_options keys must be non-empty");
355
- assertItemMetadataCondition(typeof optionValue === "string", "type_options values must be strings");
356
- const optionText = optionValue;
357
- assertItemMetadataCondition(optionText.trim().length > 0, "type_options values must be non-empty strings");
358
- }
359
- }
360
- function coerceRuntimeItemMetadataFields(record, itemType, runtimeContext) {
361
- if (!runtimeContext?.fieldRegistry) {
362
- return;
363
- }
364
- for (const definition of runtimeContext.fieldRegistry.definitions) {
365
- const fieldValue = record[definition.metadata_key];
366
- if (fieldValue === undefined) {
367
- if (runtimeFieldRequiredForType(definition, itemType)) {
368
- validationError(`missing required schema field: ${definition.metadata_key}`);
369
- }
370
- continue;
371
- }
372
- try {
373
- record[definition.metadata_key] = coerceRuntimeFieldValue(definition, fieldValue, `metadata field "${definition.metadata_key}"`);
374
- }
375
- catch (error) {
376
- validationError(String(error?.message).replace(/^Invalid\s+/u, ""));
377
- }
378
- }
379
- }
380
- function assertRuntimeUnknownItemMetadataFields(record, runtimeContext) {
381
- if (!runtimeContext || runtimeContext.unknownFieldPolicy === "allow") {
382
- return;
383
- }
384
- const knownKeys = buildKnownItemMetadataKeys(runtimeContext);
385
- const unknownKeys = Object.keys(record)
386
- .filter((key) => !knownKeys.has(key))
387
- .sort((left, right) => left.localeCompare(right));
388
- if (unknownKeys.length === 0) {
389
- return;
390
- }
391
- if (runtimeContext.unknownFieldPolicy === "reject") {
392
- validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`);
393
- }
394
- else {
395
- runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`);
396
- }
397
- }
398
- function assertValidItemMetadata(itemMetadata, runtimeContext) {
399
- const record = requireItemMetadataRecord(itemMetadata, "item metadata must be an object");
400
- const itemType = assertRequiredItemMetadataFields(record);
401
- assertStatusItemMetadataField(record, runtimeContext);
402
- assertPriorityAndTags(record);
403
- assertConfidenceItemMetadataField(record);
404
- assertSeverityItemMetadataField(record);
405
- assertRegressionItemMetadataField(record);
406
- assertTimestampField(record, "created_at");
407
- assertTimestampField(record, "updated_at");
408
- if (record.deadline !== undefined) {
409
- assertTimestampField(record, "deadline");
410
- }
411
- assertReminderEntries(record);
412
- assertCalendarEvents(record);
413
- assertOptionalTimestampString(record, "closed_at", "closed_at");
414
- assertOptionalTimestampString(record, "completed_at", "completed_at");
415
- assertOptionalStringFields(record);
416
- assertTypeOptionsField(record);
417
- coerceRuntimeItemMetadataFields(record, itemType, runtimeContext);
418
- assertRuntimeUnknownItemMetadataFields(record, runtimeContext);
419
- }
420
- function sortDependencies(values) {
421
- if (!values || values.length === 0)
422
- return undefined;
423
- return [...values]
424
- .map((value) => ({
425
- id: value.id.trim(),
426
- kind: value.kind,
427
- created_at: value.created_at,
428
- author: value.author?.trim() || undefined,
429
- source_kind: value.source_kind?.trim() || undefined,
430
- author_source: value.author_source,
431
- }))
432
- .sort((a, b) => {
433
- const byCreated = compareTimestampStrings(a.created_at, b.created_at);
434
- if (byCreated !== 0)
435
- return byCreated;
436
- const byId = a.id.localeCompare(b.id);
437
- if (byId !== 0)
438
- return byId;
439
- const byKind = a.kind.localeCompare(b.kind);
440
- if (byKind !== 0)
441
- return byKind;
442
- return (a.source_kind ?? "").localeCompare(b.source_kind ?? "");
443
- });
444
- }
445
- function sortLogValues(values) {
446
- if (!values || values.length === 0)
447
- return undefined;
448
- return [...values].sort((a, b) => {
449
- const byCreated = compareTimestampStrings(a.created_at, b.created_at);
450
- if (byCreated !== 0)
451
- return byCreated;
452
- const byText = a.text.localeCompare(b.text);
453
- if (byText !== 0)
454
- return byText;
455
- return a.author.localeCompare(b.author);
456
- });
457
- }
458
- function sortReminders(values) {
459
- if (!values || values.length === 0)
460
- return undefined;
461
- const normalized = [...values]
462
- .map((value) => ({
463
- at: value.at,
464
- text: value.text.trim(),
465
- }))
466
- .filter((value) => value.text.length > 0)
467
- .sort((a, b) => {
468
- const byAt = compareTimestampStrings(a.at, b.at);
469
- if (byAt !== 0)
470
- return byAt;
471
- return a.text.localeCompare(b.text);
472
- });
473
- return normalized.length === 0 ? undefined : normalized;
474
- }
475
- function normalizeRecurrenceRule(value) {
476
- if (!value) {
477
- return undefined;
478
- }
479
- const normalizedFrequency = value.freq.trim().toLowerCase();
480
- if (!RECURRENCE_FREQUENCY_VALUES.includes(normalizedFrequency)) {
481
- return undefined;
482
- }
483
- const byWeekday = Array.from(new Set((value.by_weekday ?? [])
484
- .map((weekday) => weekday.trim().toLowerCase())
485
- .filter((weekday) => RECURRENCE_WEEKDAY_VALUES.includes(weekday)))).sort((a, b) => weekdayOrderIndex(a) -
486
- weekdayOrderIndex(b));
487
- const byMonthDay = Array.from(new Set((value.by_month_day ?? [])
488
- .filter((day) => Number.isInteger(day) && day >= 1 && day <= 31)
489
- .map((day) => day))).sort((a, b) => a - b);
490
- const exdates = Array.from(new Set((value.exdates ?? [])
491
- .map((timestamp) => timestamp.trim())
492
- .filter((timestamp) => isTimestampLiteral(timestamp)))).sort((a, b) => compareTimestampStrings(a, b));
493
- const normalized = {
494
- freq: normalizedFrequency,
495
- interval: value.interval !== undefined && value.interval > 1
496
- ? value.interval
497
- : undefined,
498
- count: value.count,
499
- until: value.until?.trim() || undefined,
500
- by_weekday: byWeekday.length > 0
501
- ? byWeekday
502
- : undefined,
503
- by_month_day: byMonthDay.length > 0 ? byMonthDay : undefined,
504
- exdates: exdates.length > 0 ? exdates : undefined,
505
- };
506
- for (const [key, fieldValue] of Object.entries(normalized)) {
507
- if (fieldValue === undefined) {
508
- delete normalized[key];
509
- }
510
- }
511
- return normalized;
512
- }
513
- function sortEvents(values) {
514
- if (!Array.isArray(values) || values.length === 0) {
515
- return undefined;
516
- }
517
- const normalized = [...values]
518
- .map(normalizeCalendarEvent)
519
- .sort(compareCalendarEvents);
520
- return normalized;
521
- }
522
- function normalizeCalendarEvent(value) {
523
- const event = {
524
- start_at: value.start_at,
525
- end_at: value.end_at || undefined,
526
- title: value.title?.trim() || undefined,
527
- description: value.description?.trim() || undefined,
528
- location: value.location?.trim() || undefined,
529
- all_day: value.all_day,
530
- timezone: value.timezone?.trim() || undefined,
531
- recurrence: normalizeRecurrenceRule(value.recurrence),
532
- };
533
- deleteUndefinedFields(event);
534
- return event;
535
- }
536
- function compareCalendarEvents(a, b) {
537
- return firstNonZeroComparison([
538
- compareTimestampStrings(a.start_at, b.start_at),
539
- (a.end_at ?? "").localeCompare(b.end_at ?? ""),
540
- (a.title ?? "").localeCompare(b.title ?? ""),
541
- Number(Boolean(a.all_day)) - Number(Boolean(b.all_day)),
542
- (a.timezone ?? "").localeCompare(b.timezone ?? ""),
543
- (a.location ?? "").localeCompare(b.location ?? ""),
544
- (a.description ?? "").localeCompare(b.description ?? ""),
545
- JSON.stringify(a.recurrence ?? {}).localeCompare(JSON.stringify(b.recurrence ?? {})),
546
- ]);
547
- }
548
- function normalizeFiles(values) {
549
- if (!values || values.length === 0)
550
- return undefined;
551
- return values.map((value) => ({
552
- path: normalizePathValue(value.path),
553
- scope: value.scope,
554
- note: value.note?.trim() || undefined,
555
- }));
556
- }
557
- function normalizeTestRunSummaries(values) {
558
- if (!values || values.length === 0)
559
- return undefined;
560
- const normalized = values
561
- .map(normalizeTestRunSummary)
562
- .filter((value) => value.run_id.length > 0 &&
563
- value.started_at.length > 0 &&
564
- value.finished_at.length > 0 &&
565
- value.recorded_at.length > 0)
566
- .sort((a, b) => firstNonZeroComparison([
567
- compareTimestampStrings(a.recorded_at, b.recorded_at),
568
- a.run_id.localeCompare(b.run_id),
569
- a.kind.localeCompare(b.kind),
570
- ]));
571
- return normalized.length > 0 ? normalized : undefined;
572
- }
573
- function normalizeNonNegativeInteger(value) {
574
- return typeof value === "number" && Number.isFinite(value) && value >= 0
575
- ? Math.floor(value)
576
- : undefined;
577
- }
578
- function normalizePositiveInteger(value) {
579
- return typeof value === "number" && Number.isFinite(value) && value >= 1
580
- ? Math.floor(value)
581
- : undefined;
582
- }
583
- function stringOrEmpty(value) {
584
- return typeof value === "string" ? value : "";
585
- }
586
- function normalizeTestRunMeasurements(value) {
587
- if (!Array.isArray(value))
588
- return undefined;
589
- const normalized = value
590
- .filter((measurement) => measurement !== null &&
591
- typeof measurement === "object" &&
592
- typeof measurement.name === "string" &&
593
- measurement.name.trim().length > 0 &&
594
- typeof measurement.value === "number" &&
595
- Number.isFinite(measurement.value) &&
596
- typeof measurement.recorded_at === "string" &&
597
- measurement.recorded_at.trim().length > 0)
598
- .map((measurement) => ({
599
- name: measurement.name.trim(),
600
- value: measurement.value,
601
- unit: typeof measurement.unit === "string"
602
- ? measurement.unit.trim() || undefined
603
- : undefined,
604
- threshold: typeof measurement.threshold === "number" &&
605
- Number.isFinite(measurement.threshold)
606
- ? measurement.threshold
607
- : undefined,
608
- recorded_at: measurement.recorded_at.trim(),
609
- }));
610
- const deduplicated = [
611
- ...new Map(normalized.map((measurement) => [measurement.name, measurement])).values(),
612
- ]
613
- .sort((left, right) => left.name.localeCompare(right.name))
614
- .slice(0, 32);
615
- return deduplicated.length > 0 ? deduplicated : undefined;
616
- }
617
- /** Normalize and bound command/context provenance retained for a test run. */
618
- function normalizeTestRunEnum(value, allowedValues) {
619
- return typeof value === "string" && allowedValues.has(value)
620
- ? value
621
- : undefined;
622
- }
623
- /** Normalize and bound command/context provenance retained for a test run. */
624
- function normalizeTestRunExecutions(values) {
625
- if (!Array.isArray(values))
626
- return undefined;
627
- const executions = values
628
- .filter((execution) => execution &&
629
- typeof execution.command === "string" &&
630
- execution.command.trim().length > 0)
631
- .slice(0, 32)
632
- .map((execution) => ({
633
- command: execution.command.trim(),
634
- requested_pm_context_mode: normalizeTestRunEnum(execution.requested_pm_context_mode, LINKED_TEST_PM_CONTEXT_MODE_VALUES),
635
- pm_context_mode: normalizeTestRunEnum(execution.pm_context_mode, LINKED_TEST_PM_CONTEXT_MODE_VALUES),
636
- workspace_context_mode: normalizeTestRunEnum(execution.workspace_context_mode, LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES),
637
- trust_reason: normalizeTestRunEnum(execution.trust_reason, LINKED_TEST_TRUST_REASON_VALUES),
638
- }));
639
- return executions.length > 0 ? executions : undefined;
640
- }
641
- function normalizeTestRunSummary(value) {
642
- const runId = typeof value.run_id === "string" ? value.run_id.trim() : "";
643
- const kind = value.kind === "test" || value.kind === "test-all" ? value.kind : "test";
644
- const status = ITEM_TEST_RUN_STATUS_VALUES.has(value.status)
645
- ? value.status
646
- : "failed";
647
- const summary = {
648
- run_id: runId,
649
- kind,
650
- status,
651
- started_at: stringOrEmpty(value.started_at),
652
- finished_at: stringOrEmpty(value.finished_at),
653
- recorded_at: stringOrEmpty(value.recorded_at),
654
- attempt: normalizePositiveInteger(value.attempt),
655
- resumed_from: value.resumed_from?.trim() || undefined,
656
- passed: normalizeNonNegativeInteger(value.passed) ?? 0,
657
- failed: normalizeNonNegativeInteger(value.failed) ?? 0,
658
- skipped: normalizeNonNegativeInteger(value.skipped) ?? 0,
659
- items: normalizeNonNegativeInteger(value.items),
660
- linked_tests: normalizeNonNegativeInteger(value.linked_tests),
661
- fail_on_skipped_triggered: value.fail_on_skipped_triggered === true ? true : undefined,
662
- measurements: normalizeTestRunMeasurements(value.measurements),
663
- executions: normalizeTestRunExecutions(value.executions),
664
- };
665
- deleteUndefinedFields(summary);
666
- return summary;
667
- }
668
- function sortTests(values) {
669
- if (!Array.isArray(values) || values.length === 0)
670
- return undefined;
671
- return values.map(normalizeLinkedTest);
672
- }
673
- function normalizeTrimmedStringList(value) {
674
- if (!Array.isArray(value)) {
675
- return undefined;
676
- }
677
- const normalized = [
678
- ...new Set(value
679
- .filter((entry) => typeof entry === "string")
680
- .map((entry) => entry.trim())
681
- .filter((entry) => entry.length > 0)),
682
- ].sort((a, b) => a.localeCompare(b));
683
- return normalized.length > 0 ? normalized : undefined;
684
- }
685
- function isPlainObjectRecord(value) {
686
- if (!value || typeof value !== "object" || Array.isArray(value)) {
687
- return false;
688
- }
689
- const prototype = Object.getPrototypeOf(value);
690
- return prototype === Object.prototype || prototype === null;
691
- }
692
- function isUnsafeObjectKey(key) {
693
- return key === "__proto__" || key === "constructor" || key === "prototype";
694
- }
695
- function normalizeStringRecord(value) {
696
- if (!isPlainObjectRecord(value)) {
697
- return undefined;
698
- }
699
- const entries = Object.entries(value)
700
- .map(([key, recordValue]) => [key.trim(), String(recordValue).trim()])
701
- .filter(([key, recordValue]) => key.length > 0 && !isUnsafeObjectKey(key) && recordValue.length > 0)
702
- .sort(([left], [right]) => left.localeCompare(right));
703
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
704
- }
705
- function normalizeNumericRecord(value) {
706
- if (!isPlainObjectRecord(value)) {
707
- return undefined;
708
- }
709
- const entries = Object.entries(value)
710
- .map(([key, recordValue]) => [key.trim(), Number(recordValue)])
711
- .filter(([key, recordValue]) => key.length > 0 &&
712
- !isUnsafeObjectKey(key) &&
713
- Number.isFinite(recordValue))
714
- .sort(([left], [right]) => left.localeCompare(right));
715
- return entries.length > 0 ? Object.fromEntries(entries) : undefined;
716
- }
717
- function normalizeLinkedTestContextMode(value) {
718
- const normalized = value?.trim().toLowerCase();
719
- if (!normalized || !LINKED_TEST_PM_CONTEXT_MODE_VALUES.has(normalized)) {
720
- return undefined;
721
- }
722
- return normalized;
723
- }
724
- function normalizeLinkedTestWorkspaceContextMode(value) {
725
- const normalized = value?.trim().toLowerCase();
726
- if (!normalized ||
727
- !LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES.has(normalized)) {
728
- return undefined;
729
- }
730
- return normalized;
731
- }
732
- function normalizeLinkedTestProvenance(value, invalid) {
733
- if (invalid === true) {
734
- return { provenance_invalid: true };
735
- }
736
- if (value === undefined) {
737
- return {};
738
- }
739
- if (!isPlainObjectRecord(value)) {
740
- return { provenance_invalid: true };
741
- }
742
- const author = trimStringOrUndefined(value.author);
743
- const createdAt = trimStringOrUndefined(value.created_at);
744
- const sourceKind = value.source_kind;
745
- if (!author ||
746
- !createdAt ||
747
- !isTimestampLiteral(createdAt) ||
748
- (sourceKind !== "local_mutation" && sourceKind !== "merge_union")) {
749
- // Preserve malformed provenance as an explicit runtime sentinel. Dropping
750
- // it would make a tampered entry indistinguishable from a trusted legacy
751
- // command in the clone-local trust resolver.
752
- return { provenance_invalid: true };
753
- }
754
- return {
755
- provenance: {
756
- author,
757
- created_at: createdAt,
758
- source_kind: sourceKind,
759
- source_ref: trimStringOrUndefined(value.source_ref),
760
- },
761
- };
762
- }
763
- function normalizeLinkedTest(value) {
764
- const test = {
765
- command: value.command?.trim() || undefined,
766
- path: value.path ? normalizePathValue(value.path) : undefined,
767
- scope: value.scope,
768
- timeout_seconds: typeof value.timeout_seconds === "number" &&
769
- Number.isFinite(value.timeout_seconds) &&
770
- value.timeout_seconds > 0
771
- ? value.timeout_seconds
772
- : undefined,
773
- pm_context_mode: normalizeLinkedTestContextMode(value.pm_context_mode),
774
- workspace_context_mode: normalizeLinkedTestWorkspaceContextMode(value.workspace_context_mode),
775
- ...normalizeLinkedTestProvenance(value.provenance, value.provenance_invalid),
776
- env_set: normalizeStringRecord(value.env_set),
777
- env_clear: normalizeTrimmedStringList(value.env_clear),
778
- shared_host_safe: value.shared_host_safe === true ? true : undefined,
779
- assert_stdout_contains: normalizeTrimmedStringList(value.assert_stdout_contains),
780
- assert_stdout_regex: normalizeTrimmedStringList(value.assert_stdout_regex),
781
- assert_stderr_contains: normalizeTrimmedStringList(value.assert_stderr_contains),
782
- assert_stderr_regex: normalizeTrimmedStringList(value.assert_stderr_regex),
783
- assert_stdout_min_lines: normalizeNonNegativeInteger(value.assert_stdout_min_lines),
784
- assert_json_field_equals: normalizeStringRecord(value.assert_json_field_equals),
785
- assert_json_field_gte: normalizeNumericRecord(value.assert_json_field_gte),
786
- note: value.note?.trim() || undefined,
787
- };
788
- deleteUndefinedFields(test);
789
- return test;
790
- }
791
- function sortDocs(values) {
792
- if (!values || values.length === 0)
793
- return undefined;
794
- return [...values]
795
- .map((value) => ({
796
- path: normalizePathValue(value.path),
797
- scope: value.scope,
798
- note: value.note?.trim() || undefined,
799
- }))
800
- .sort((a, b) => {
801
- const byScope = a.scope.localeCompare(b.scope);
802
- if (byScope !== 0)
803
- return byScope;
804
- const byPath = a.path.localeCompare(b.path);
805
- if (byPath !== 0)
806
- return byPath;
807
- return (a.note ?? "").localeCompare(b.note ?? "");
808
- });
809
- }
810
- function trimStringOrUndefined(value) {
811
- if (typeof value !== "string")
812
- return undefined;
813
- const trimmed = value.trim();
814
- return trimmed.length > 0 ? trimmed : undefined;
815
- }
816
- function normalizePlanStepLinks(value) {
817
- if (!Array.isArray(value))
818
- return undefined;
819
- const out = [];
820
- for (const entry of value) {
821
- if (entry === null || typeof entry !== "object")
822
- continue;
823
- const record = entry;
824
- const id = trimStringOrUndefined(record.id);
825
- const kind = trimStringOrUndefined(record.kind);
826
- if (!id || !kind)
827
- continue;
828
- const link = { id, kind: kind };
829
- const note = trimStringOrUndefined(record.note);
830
- if (note)
831
- link.note = note;
832
- if (record.required_before_step === true)
833
- link.required_before_step = true;
834
- out.push(link);
835
- }
836
- return out.length > 0 ? out : undefined;
837
- }
838
- function normalizePlanStepFiles(value) {
839
- if (!Array.isArray(value))
840
- return undefined;
841
- const out = [];
842
- for (const entry of value) {
843
- if (entry === null || typeof entry !== "object")
844
- continue;
845
- const record = entry;
846
- const path = trimStringOrUndefined(record.path);
847
- if (!path)
848
- continue;
849
- const file = { path: normalizePathValue(path) };
850
- if (record.scope === "project" || record.scope === "global")
851
- file.scope = record.scope;
852
- const note = trimStringOrUndefined(record.note);
853
- if (note)
854
- file.note = note;
855
- out.push(file);
856
- }
857
- return out.length > 0 ? out : undefined;
858
- }
859
- function normalizePlanStepTests(value) {
860
- if (!Array.isArray(value))
861
- return undefined;
862
- const out = [];
863
- for (const entry of value) {
864
- if (entry === null || typeof entry !== "object")
865
- continue;
866
- const record = entry;
867
- const command = trimStringOrUndefined(record.command);
868
- const path = trimStringOrUndefined(record.path);
869
- if (!command && !path)
870
- continue;
871
- const test = {};
872
- if (command)
873
- test.command = command;
874
- if (path)
875
- test.path = normalizePathValue(path);
876
- const note = trimStringOrUndefined(record.note);
877
- if (note)
878
- test.note = note;
879
- out.push(test);
880
- }
881
- return out.length > 0 ? out : undefined;
882
- }
883
- function normalizePlanStepDocs(value) {
884
- if (!Array.isArray(value))
885
- return undefined;
886
- const out = [];
887
- for (const entry of value) {
888
- if (entry === null || typeof entry !== "object")
889
- continue;
890
- const record = entry;
891
- const path = trimStringOrUndefined(record.path);
892
- if (!path)
893
- continue;
894
- const doc = { path: normalizePathValue(path) };
895
- if (record.scope === "project" || record.scope === "global")
896
- doc.scope = record.scope;
897
- const note = trimStringOrUndefined(record.note);
898
- if (note)
899
- doc.note = note;
900
- out.push(doc);
901
- }
902
- return out.length > 0 ? out : undefined;
903
- }
904
- function normalizePlanStepEntry(entry) {
905
- if (entry === null || typeof entry !== "object") {
906
- return undefined;
907
- }
908
- const record = entry;
909
- const id = trimStringOrUndefined(record.id);
910
- const title = trimStringOrUndefined(record.title);
911
- const statusRaw = trimStringOrUndefined(record.status);
912
- const status = statusRaw && PLAN_STEP_STATUS_SET.has(statusRaw)
913
- ? statusRaw
914
- : undefined;
915
- const order = coerceFiniteNumber(record.order) ?? Number.NaN;
916
- const created_at = typeof record.created_at === "string" ? record.created_at : "";
917
- const updated_at = typeof record.updated_at === "string" ? record.updated_at : "";
918
- if (!id ||
919
- !title ||
920
- !status ||
921
- !Number.isFinite(order) ||
922
- !created_at ||
923
- !updated_at) {
924
- return undefined;
925
- }
926
- const step = {
927
- id,
928
- order,
929
- title,
930
- status,
931
- created_at,
932
- updated_at,
933
- };
934
- applyPlanStepOptionalFields(step, record);
935
- return step;
936
- }
937
- function applyPlanStepOptionalFields(step, record) {
938
- const stringFields = [
939
- ["body", "body"],
940
- ["owner", "owner"],
941
- ["evidence", "evidence"],
942
- ["blocked_reason", "blocked_reason"],
943
- ["superseded_by", "superseded_by"],
944
- ];
945
- for (const [target, source] of stringFields) {
946
- const value = trimStringOrUndefined(record[source]);
947
- if (value) {
948
- step[target] = value;
949
- }
950
- }
951
- const completedAt = typeof record.completed_at === "string" ? record.completed_at : undefined;
952
- if (completedAt && completedAt.length > 0) {
953
- step.completed_at = completedAt;
954
- }
955
- const collectionFields = [
956
- ["linked_items", "linked_items", normalizePlanStepLinks],
957
- ["files", "files", normalizePlanStepFiles],
958
- ["tests", "tests", normalizePlanStepTests],
959
- ["docs", "docs", normalizePlanStepDocs],
960
- ];
961
- for (const [target, source, normalize] of collectionFields) {
962
- const value = normalize(record[source]);
963
- if (value) {
964
- step[target] = value;
965
- }
966
- }
967
- }
968
- function normalizePlanSteps(value) {
969
- if (!Array.isArray(value))
970
- return undefined;
971
- const out = value.flatMap((entry) => {
972
- const step = normalizePlanStepEntry(entry);
973
- return step ? [step] : [];
974
- });
975
- out.sort((left, right) => left.order - right.order);
976
- return out.length > 0 ? out : undefined;
977
- }
978
- function normalizePlanDecisions(value) {
979
- if (!Array.isArray(value))
980
- return undefined;
981
- const out = [];
982
- for (const entry of value) {
983
- if (entry === null || typeof entry !== "object")
984
- continue;
985
- const record = entry;
986
- const ts = typeof record.ts === "string" ? record.ts : "";
987
- const author = typeof record.author === "string" ? record.author : "";
988
- const decision = trimStringOrUndefined(record.decision);
989
- if (!ts || !author || !decision)
990
- continue;
991
- const item = { ts, author, decision };
992
- const rationale = trimStringOrUndefined(record.rationale);
993
- if (rationale)
994
- item.rationale = rationale;
995
- const evidence = trimStringOrUndefined(record.evidence);
996
- if (evidence)
997
- item.evidence = evidence;
998
- const stepId = trimStringOrUndefined(record.step_id);
999
- if (stepId)
1000
- item.step_id = stepId;
1001
- out.push(item);
1002
- }
1003
- return out.length > 0 ? out : undefined;
1004
- }
1005
- function normalizePlanDiscoveries(value) {
1006
- if (!Array.isArray(value))
1007
- return undefined;
1008
- const out = [];
1009
- for (const entry of value) {
1010
- if (entry === null || typeof entry !== "object")
1011
- continue;
1012
- const record = entry;
1013
- const ts = typeof record.ts === "string" ? record.ts : "";
1014
- const author = typeof record.author === "string" ? record.author : "";
1015
- const text = trimStringOrUndefined(record.text);
1016
- if (!ts || !author || !text)
1017
- continue;
1018
- const item = { ts, author, text };
1019
- const stepId = trimStringOrUndefined(record.step_id);
1020
- if (stepId)
1021
- item.step_id = stepId;
1022
- out.push(item);
1023
- }
1024
- return out.length > 0 ? out : undefined;
1025
- }
1026
- function normalizePlanValidation(value) {
1027
- if (!Array.isArray(value))
1028
- return undefined;
1029
- const out = [];
1030
- for (const entry of value) {
1031
- if (entry === null || typeof entry !== "object")
1032
- continue;
1033
- const record = entry;
1034
- const text = trimStringOrUndefined(record.text);
1035
- if (!text)
1036
- continue;
1037
- const item = { text };
1038
- const command = trimStringOrUndefined(record.command);
1039
- if (command)
1040
- item.command = command;
1041
- const expected = trimStringOrUndefined(record.expected);
1042
- if (expected)
1043
- item.expected = expected;
1044
- out.push(item);
1045
- }
1046
- return out.length > 0 ? out : undefined;
1047
- }
1048
- function normalizeTypeOptions(values) {
1049
- if (!values) {
1050
- return undefined;
1051
- }
1052
- const normalizedEntries = Object.entries(values)
1053
- .map(([key, value]) => [key.trim(), value.trim()])
1054
- .filter(([key, value]) => key.length > 0 && value.length > 0)
1055
- .sort((left, right) => left[0].localeCompare(right[0]));
1056
- if (normalizedEntries.length === 0) {
1057
- return undefined;
1058
- }
1059
- return Object.fromEntries(normalizedEntries);
1060
- }
1061
- function normalizeBody(body) {
1062
- let start = 0;
1063
- while (start < body.length && body[start] === "\n") {
1064
- start += 1;
1065
- }
1066
- return body.slice(start).trimEnd();
1067
- }
1068
- function normalizeConfidenceValue(value) {
1069
- if (value === undefined) {
1070
- return undefined;
1071
- }
1072
- if (typeof value === "number") {
1073
- return value;
1074
- }
1075
- const normalized = value.trim().toLowerCase();
1076
- if (normalized === "med") {
1077
- return "medium";
1078
- }
1079
- if (CONFIDENCE_TEXT_VALUES.includes(normalized)) {
1080
- return normalized;
1081
- }
1082
- return undefined;
1083
- }
1084
- function normalizeSeverityValue(value) {
1085
- if (value === undefined) {
1086
- return undefined;
1087
- }
1088
- const normalized = value.trim().toLowerCase();
1089
- if (normalized === "med") {
1090
- return "medium";
1091
- }
1092
- if (ISSUE_SEVERITY_VALUES.includes(normalized)) {
1093
- return normalized;
1094
- }
1095
- return undefined;
1096
- }
1097
- function emptyStringToUndefined(value) {
1098
- return value || undefined;
1099
- }
1100
- function copyExtensionItemMetadataFields(normalized, source) {
1101
- const targetRecord = normalized;
1102
- const sourceRecord = source;
1103
- for (const [key, value] of Object.entries(sourceRecord)) {
1104
- if (isUnsafeObjectKey(key) ||
1105
- Object.prototype.hasOwnProperty.call(targetRecord, key) ||
1106
- value === undefined) {
1107
- continue;
1108
- }
1109
- targetRecord[key] = value;
1110
- }
1111
- }
1112
- function coerceNormalizedRuntimeFields(normalized, runtimeContext) {
1113
- if (!runtimeContext?.fieldRegistry) {
1114
- return;
1115
- }
1116
- const record = normalized;
1117
- for (const definition of runtimeContext.fieldRegistry.definitions) {
1118
- const currentValue = record[definition.metadata_key];
1119
- if (currentValue === undefined) {
1120
- continue;
1121
- }
1122
- record[definition.metadata_key] = coerceRuntimeFieldValue(definition, currentValue, `metadata field "${definition.metadata_key}"`);
1123
- }
1124
- }
1125
- function assertNormalizedUnknownFields(normalized, runtimeContext) {
1126
- if (!runtimeContext || runtimeContext.unknownFieldPolicy === "allow") {
1127
- return;
1128
- }
1129
- const knownKeys = buildKnownItemMetadataKeys(runtimeContext);
1130
- const record = normalized;
1131
- const unknownKeys = Object.keys(record)
1132
- .filter((key) => !knownKeys.has(key))
1133
- .sort((left, right) => left.localeCompare(right));
1134
- if (unknownKeys.length > 0 &&
1135
- runtimeContext.unknownFieldPolicy === "reject") {
1136
- validationError(`unknown schema fields are not allowed: ${unknownKeys.join(", ")}`);
1137
- }
1138
- if (unknownKeys.length > 0) {
1139
- runtimeContext.onWarning?.(`item_unknown_schema_fields:${unknownKeys.join(",")}`);
1140
- }
1141
- }
1142
- /** Implements normalize item metadata for the public runtime surface of this module. */
1143
- export function normalizeItemMetadata(itemMetadata, options = {}) {
1144
- const runtimeContext = resolveRuntimeSchemaValidationContext(options);
1145
- const normalizedStatus = normalizeStatusInput(itemMetadata.status, runtimeContext?.statusRegistry) ??
1146
- itemMetadata.status;
1147
- const tags = Array.from(new Set((Array.isArray(itemMetadata.tags) ? itemMetadata.tags : [])
1148
- .filter((tag) => typeof tag === "string")
1149
- .map((tag) => tag.trim().toLowerCase())
1150
- .filter(Boolean))).sort((a, b) => a.localeCompare(b));
1151
- const normalized = {
1152
- id: itemMetadata.id,
1153
- title: itemMetadata.title,
1154
- description: itemMetadata.description,
1155
- type: itemMetadata.type,
1156
- pm_format_version: normalizeItemFormatVersion(itemMetadata.pm_format_version),
1157
- source_type: trimStringOrUndefined(itemMetadata.source_type),
1158
- type_options: normalizeTypeOptions(itemMetadata.type_options),
1159
- status: normalizedStatus,
1160
- priority: itemMetadata.priority,
1161
- tags,
1162
- created_at: itemMetadata.created_at,
1163
- updated_at: itemMetadata.updated_at,
1164
- dependencies: sortDependencies(itemMetadata.dependencies),
1165
- comments: sortLogValues(itemMetadata.comments),
1166
- notes: sortLogValues(itemMetadata.notes),
1167
- learnings: sortLogValues(itemMetadata.learnings),
1168
- files: normalizeFiles(itemMetadata.files),
1169
- tests: sortTests(itemMetadata.tests),
1170
- test_runs: normalizeTestRunSummaries(itemMetadata.test_runs),
1171
- docs: sortDocs(itemMetadata.docs),
1172
- deadline: emptyStringToUndefined(itemMetadata.deadline),
1173
- reminders: sortReminders(itemMetadata.reminders),
1174
- events: sortEvents(itemMetadata.events),
1175
- closed_at: emptyStringToUndefined(itemMetadata.closed_at),
1176
- completed_at: emptyStringToUndefined(itemMetadata.completed_at),
1177
- assignee: trimStringOrUndefined(itemMetadata.assignee),
1178
- claim_principal: trimStringOrUndefined(itemMetadata.claim_principal),
1179
- source_owner: trimStringOrUndefined(itemMetadata.source_owner),
1180
- author: emptyStringToUndefined(itemMetadata.author),
1181
- estimated_minutes: itemMetadata.estimated_minutes,
1182
- acceptance_criteria: itemMetadata.acceptance_criteria ?? undefined,
1183
- design: itemMetadata.design ?? undefined,
1184
- external_ref: itemMetadata.external_ref ?? undefined,
1185
- definition_of_ready: trimStringOrUndefined(itemMetadata.definition_of_ready),
1186
- order: itemMetadata.order,
1187
- goal: trimStringOrUndefined(itemMetadata.goal),
1188
- objective: trimStringOrUndefined(itemMetadata.objective),
1189
- value: trimStringOrUndefined(itemMetadata.value),
1190
- impact: trimStringOrUndefined(itemMetadata.impact),
1191
- outcome: trimStringOrUndefined(itemMetadata.outcome),
1192
- why_now: trimStringOrUndefined(itemMetadata.why_now),
1193
- parent: trimStringOrUndefined(itemMetadata.parent),
1194
- reviewer: trimStringOrUndefined(itemMetadata.reviewer),
1195
- risk: itemMetadata.risk ?? undefined,
1196
- confidence: normalizeConfidenceValue(itemMetadata.confidence),
1197
- sprint: trimStringOrUndefined(itemMetadata.sprint),
1198
- release: trimStringOrUndefined(itemMetadata.release),
1199
- blocked_by: trimStringOrUndefined(itemMetadata.blocked_by),
1200
- blocked_reason: trimStringOrUndefined(itemMetadata.blocked_reason),
1201
- unblock_note: trimStringOrUndefined(itemMetadata.unblock_note),
1202
- reporter: trimStringOrUndefined(itemMetadata.reporter),
1203
- severity: normalizeSeverityValue(itemMetadata.severity),
1204
- environment: trimStringOrUndefined(itemMetadata.environment),
1205
- repro_steps: trimStringOrUndefined(itemMetadata.repro_steps),
1206
- resolution: trimStringOrUndefined(itemMetadata.resolution),
1207
- expected_result: trimStringOrUndefined(itemMetadata.expected_result),
1208
- actual_result: trimStringOrUndefined(itemMetadata.actual_result),
1209
- affected_version: trimStringOrUndefined(itemMetadata.affected_version),
1210
- fixed_version: trimStringOrUndefined(itemMetadata.fixed_version),
1211
- component: trimStringOrUndefined(itemMetadata.component),
1212
- regression: itemMetadata.regression,
1213
- customer_impact: trimStringOrUndefined(itemMetadata.customer_impact),
1214
- close_reason: emptyStringToUndefined(itemMetadata.close_reason),
1215
- plan_mode: trimStringOrUndefined(itemMetadata.plan_mode),
1216
- plan_scope: trimStringOrUndefined(itemMetadata.plan_scope),
1217
- plan_harness: trimStringOrUndefined(itemMetadata.plan_harness),
1218
- plan_resume_context: trimStringOrUndefined(itemMetadata.plan_resume_context),
1219
- plan_steps: normalizePlanSteps(itemMetadata.plan_steps),
1220
- plan_decisions: normalizePlanDecisions(itemMetadata.plan_decisions),
1221
- plan_discoveries: normalizePlanDiscoveries(itemMetadata.plan_discoveries),
1222
- plan_validation: normalizePlanValidation(itemMetadata.plan_validation),
1223
- };
1224
- copyExtensionItemMetadataFields(normalized, itemMetadata);
1225
- coerceNormalizedRuntimeFields(normalized, runtimeContext);
1226
- assertNormalizedUnknownFields(normalized, runtimeContext);
1227
- deleteUndefinedFields(normalized);
1228
- return normalized;
1229
- }
1230
- function orderItemMetadata(itemMetadata) {
1231
- return orderObject(itemMetadata, ITEM_METADATA_KEY_ORDER);
1232
- }
1233
- function findJsonObjectEnd(content) {
1234
- let depth = 0;
1235
- let inString = false;
1236
- let escaped = false;
1237
- for (let i = 0; i < content.length; i += 1) {
1238
- const char = content[i];
1239
- if (inString) {
1240
- if (escaped) {
1241
- escaped = false;
1242
- continue;
1243
- }
1244
- if (char === "\\") {
1245
- escaped = true;
1246
- continue;
1247
- }
1248
- if (char === '"') {
1249
- inString = false;
1250
- }
1251
- continue;
1252
- }
1253
- if (char === '"') {
1254
- inString = true;
1255
- continue;
1256
- }
1257
- if (char === "{") {
1258
- depth += 1;
1259
- continue;
1260
- }
1261
- if (char === "}") {
1262
- depth -= 1;
1263
- if (depth === 0) {
1264
- return i;
1265
- }
1266
- }
1267
- }
1268
- return -1;
1269
- }
1270
- /** Implements split front matter for the public runtime surface of this module. */
1271
- export function splitFrontMatter(content) {
1272
- if (!content.startsWith("{")) {
1273
- return { frontMatter: "", body: content };
1274
- }
1275
- const end = findJsonObjectEnd(content);
1276
- if (end < 0) {
1277
- return { frontMatter: "", body: content };
1278
- }
1279
- const frontMatter = content.slice(0, end + 1);
1280
- const body = content.slice(end + 1).replace(/^\r?\n+/, "");
1281
- return { frontMatter, body };
1282
- }
1283
- function stripLeadingYamlDocument(content) {
1284
- const normalizedContent = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
1285
- const opener = normalizedContent.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);
1286
- if (!opener) {
1287
- return { content: normalizedContent, stripped: false };
1288
- }
1289
- let cursor = opener[0].length;
1290
- while (cursor < normalizedContent.length) {
1291
- const nextNewline = normalizedContent.indexOf("\n", cursor);
1292
- const lineEnd = nextNewline === -1 ? normalizedContent.length : nextNewline;
1293
- const line = normalizedContent.slice(cursor, lineEnd).replace(/\r$/, "");
1294
- const afterLine = nextNewline === -1 ? lineEnd : lineEnd + 1;
1295
- if (line.trim() === "---") {
1296
- return {
1297
- content: normalizedContent.slice(afterLine).replace(/^\s+/, ""),
1298
- stripped: true,
1299
- };
1300
- }
1301
- cursor = afterLine;
1302
- }
1303
- return { content: normalizedContent, stripped: false };
1304
- }
1305
- function normalizeParsedItemMetadata(itemMetadata, options) {
1306
- return normalizeItemMetadata(itemMetadata, {
1307
- ...options,
1308
- onWarning: undefined,
1309
- });
1310
- }
1311
- function parseJsonMarkdownItemDocument(content, runtimeContext, options = {}) {
1312
- const normalized = stripLeadingYamlDocument(content);
1313
- if (normalized.stripped) {
1314
- options.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");
1315
- }
1316
- const { frontMatter, body } = splitFrontMatter(normalized.content);
1317
- if (!frontMatter) {
1318
- const trimmed = content.trimStart();
1319
- if (trimmed.startsWith("{")) {
1320
- documentSyntaxError("json_markdown", "JSON front matter is not valid JSON");
1321
- }
1322
- documentSyntaxError("json_markdown", "JSON Markdown item document is missing JSON front matter");
1323
- }
1324
- let parsed;
1325
- try {
1326
- parsed = JSON.parse(frontMatter);
1327
- }
1328
- catch {
1329
- documentSyntaxError("json_markdown", "JSON front matter is not valid JSON");
1330
- }
1331
- assertValidItemMetadata(parsed, runtimeContext);
1332
- return {
1333
- metadata: normalizeParsedItemMetadata(parsed, options),
1334
- body: normalizeBody(body),
1335
- };
1336
- }
1337
- function parseToonItemDocument(content, runtimeContext, options = {}) {
1338
- let parsed;
1339
- try {
1340
- // decodeToonItemContent transparently recovers documents that the upstream
1341
- // strict decoder rejects (bracketed-token-then-colon inside a quoted value;
1342
- // see toon-decode.ts). The recovery is lossless, so it stays silent rather
1343
- // than emitting a per-read warning that would perpetually flip pm health
1344
- // red for legacy files. The behavior is pinned by toon-decode.spec.ts.
1345
- parsed = decodeToonItemContent(content).value;
1346
- }
1347
- catch {
1348
- documentSyntaxError("toon", "TOON item document is not valid TOON");
1349
- }
1350
- assertItemMetadataCondition(typeof parsed === "object" && parsed !== null && !Array.isArray(parsed), "TOON item document must be an object");
1351
- const record = parsed;
1352
- if (!REQUIRED_STRING_FIELDS.some((fieldName) => Object.prototype.hasOwnProperty.call(record, fieldName)) &&
1353
- !Object.prototype.hasOwnProperty.call(record, "front_matter")) {
1354
- documentSyntaxError("toon", "TOON input does not have the shape of an item document");
1355
- }
1356
- if (Object.prototype.hasOwnProperty.call(record, "front_matter")) {
1357
- assertValidItemMetadata(record.front_matter, runtimeContext);
1358
- assertItemMetadataCondition(record.body === undefined || typeof record.body === "string", "TOON item document body must be a string");
1359
- return {
1360
- metadata: normalizeParsedItemMetadata(record.front_matter, options),
1361
- body: normalizeBody(typeof record.body === "string" ? record.body : ""),
1362
- };
1363
- }
1364
- const { body, ...itemMetadataRecord } = record;
1365
- assertItemMetadataCondition(body === undefined || typeof body === "string", "TOON item document body must be a string");
1366
- assertValidItemMetadata(itemMetadataRecord, runtimeContext);
1367
- return {
1368
- metadata: normalizeParsedItemMetadata(itemMetadataRecord, options),
1369
- body: normalizeBody(typeof body === "string" ? body : ""),
1370
- };
1371
- }
1372
- function serializeJsonMarkdownItemDocument(document, options = {}) {
1373
- const normalizedMetadata = normalizeItemMetadata(document.metadata, options);
1374
- const orderedMetadata = orderItemMetadata(normalizedMetadata);
1375
- const serializedMetadata = JSON.stringify(orderedMetadata, null, 2);
1376
- const normalizedBody = normalizeBody(document.body ?? "");
1377
- if (!normalizedBody) {
1378
- return `${serializedMetadata}\n`;
1379
- }
1380
- return `${serializedMetadata}\n\n${normalizedBody}\n`;
1381
- }
1382
- function serializeToonItemDocument(document, options = {}) {
1383
- const normalizedMetadata = normalizeItemMetadata(document.metadata, options);
1384
- const orderedMetadata = orderItemMetadata(normalizedMetadata);
1385
- const normalizedBody = normalizeBody(document.body ?? "");
1386
- const payload = {
1387
- ...orderedMetadata,
1388
- body: normalizedBody,
1389
- };
1390
- const encodablePayload = JSON.parse(JSON.stringify(payload));
1391
- const serialized = encodeToon(encodablePayload);
1392
- let decoded;
1393
- try {
1394
- decoded = decodeToonItemContent(serialized).value;
1395
- }
1396
- catch (error) {
1397
- throw new PmCliError("Refusing to persist a TOON item document that the configured decoder cannot read back.", EXIT_CODE.GENERIC_FAILURE, {
1398
- code: "item_document_roundtrip_failed",
1399
- reason: "encode_decode_error",
1400
- format: "toon",
1401
- required: "Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",
1402
- why: error instanceof Error ? error.message : String(error),
1403
- });
1404
- }
1405
- if (!isDeepStrictEqual(decoded, encodablePayload)) {
1406
- const decodedRecord = typeof decoded === "object" && decoded !== null && !Array.isArray(decoded)
1407
- ? decoded
1408
- : {};
1409
- const field = Object.keys(encodablePayload).find((key) => !isDeepStrictEqual(encodablePayload[key], decodedRecord[key])) ?? "document";
1410
- throw new PmCliError(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${field}".`, EXIT_CODE.GENERIC_FAILURE, {
1411
- code: "item_document_roundtrip_failed",
1412
- reason: "encode_decode_mismatch",
1413
- format: "toon",
1414
- field,
1415
- required: "Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",
1416
- why: "The encoded document decoded to a value different from the canonical item payload.",
1417
- });
1418
- }
1419
- return `${serialized}\n`;
1420
- }
1421
- /** Implements parse item document for the public runtime surface of this module. */
1422
- export function parseItemDocument(content, options = {}) {
1423
- const conflictMarker = findFirstMergeConflictMarker(content);
1424
- if (conflictMarker) {
1425
- throw new PmCliError(`Merge conflict markers detected in item document at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`, EXIT_CODE.GENERIC_FAILURE, {
1426
- code: "merge_conflict_markers_detected",
1427
- reason: "merge_conflict",
1428
- required: "Resolve merge-conflict markers in the item file before parsing or mutation commands.",
1429
- why: "Partially merged documents can corrupt item metadata and history integrity.",
1430
- examples: ["git status", "git add <resolved-file> && git commit"],
1431
- nextSteps: [
1432
- "Resolve conflicts, save the file, then rerun the pm command.",
1433
- ],
1434
- });
1435
- }
1436
- const format = options.format ?? "toon";
1437
- const runtimeContext = resolveRuntimeSchemaValidationContext(options);
1438
- return format === "toon"
1439
- ? parseToonItemDocument(content, runtimeContext, options)
1440
- : parseJsonMarkdownItemDocument(content, runtimeContext, options);
1441
- }
1442
- /** Implements serialize item document for the public runtime surface of this module. */
1443
- export function serializeItemDocument(document, options = {}) {
1444
- const format = options.format ?? "toon";
1445
- return format === "toon"
1446
- ? serializeToonItemDocument(document, options)
1447
- : serializeJsonMarkdownItemDocument(document, options);
1448
- }
1449
- /** Implements canonical document for the public runtime surface of this module. */
1450
- export function canonicalDocument(document, options = {}) {
1451
- return {
1452
- metadata: normalizeItemMetadata(document.metadata, options),
1453
- body: normalizeBody(document.body ?? ""),
1454
- };
1455
- }
1456
- /** Public contract for test only item format, shared by SDK and presentation-layer consumers. */
1457
- export const _testOnlyItemFormat = {
1458
- buildKnownItemMetadataKeys,
1459
- firstNonZeroComparison,
1460
- normalizeBody,
1461
- normalizePlanDecisions,
1462
- normalizePlanDiscoveries,
1463
- normalizePlanStepDocs,
1464
- normalizePlanStepFiles,
1465
- normalizePlanStepLinks,
1466
- normalizePlanSteps,
1467
- normalizePlanStepTests,
1468
- normalizePlanValidation,
1469
- normalizeTestRunSummaries,
1470
- normalizeTypeOptions,
1471
- runtimeFieldRequiredForType,
1472
- sortTests,
1473
- };
4
+ ${normalizedBody}
5
+ `}function serializeToonItemDocument(document,options={}){const normalizedMetadata=normalizeItemMetadata(document.metadata,options);const orderedMetadata=orderItemMetadata(normalizedMetadata);const normalizedBody=normalizeBody(document.body??"");const payload={...orderedMetadata,body:normalizedBody};const encodablePayload=JSON.parse(JSON.stringify(payload));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:{};const 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}
6
+ `}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";const runtimeContext=resolveRuntimeSchemaValidationContext(options);return format==="toon"?parseToonItemDocument(content,runtimeContext,options):parseJsonMarkdownItemDocument(content,runtimeContext,options)}function serializeItemDocument(document,options={}){const format=options.format??"toon";return format==="toon"?serializeToonItemDocument(document,options):serializeJsonMarkdownItemDocument(document,options)}function canonicalDocument(document,options={}){return{metadata:normalizeItemMetadata(document.metadata,options),body:normalizeBody(document.body??"")}}const _testOnlyItemFormat={buildKnownItemMetadataKeys,firstNonZeroComparison,normalizeBody,normalizePlanDecisions,normalizePlanDiscoveries,normalizePlanStepDocs,normalizePlanStepFiles,normalizePlanStepLinks,normalizePlanSteps,normalizePlanStepTests,normalizePlanValidation,normalizeTestRunSummaries,normalizeTypeOptions,runtimeFieldRequiredForType,sortTests};export{_testOnlyItemFormat,canonicalDocument,normalizeItemMetadata,parseItemDocument,serializeItemDocument,splitFrontMatter};
1474
7
  //# sourceMappingURL=item-format.js.map
1475
- //# debugId=051655a4-8ba7-5118-9758-d9ca377fa7e4