@unbrained/pm-cli 2026.11.22 → 2026.11.24

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 (912) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-23K6DQQY.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-37UDIJ2K.js +3 -0
  106. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
  109. package/dist/cli-bundle/chunks/chunk-7VRFEURZ.js +33 -0
  110. package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
  111. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  112. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
  115. package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
  116. package/dist/cli-bundle/chunks/chunk-HNKK2UG6.js +8 -0
  117. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
  119. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-MXUSC5RS.js +31 -0
  121. package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
  122. package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
  123. package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
  124. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  125. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  126. package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
  128. package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
  129. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-TVIJ2VCU.js} +93 -93
  130. package/dist/cli-bundle/chunks/chunk-VJSGUXGU.js +3 -0
  131. package/dist/cli-bundle/chunks/chunk-WWTPNIC2.js +6 -0
  132. package/dist/cli-bundle/chunks/chunk-XFADNMGD.js +2 -0
  133. package/dist/cli-bundle/chunks/chunk-YOPTAIBD.js +125 -0
  134. package/dist/cli-bundle/chunks/chunk-YW2HBHRO.js +70 -0
  135. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  136. package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
  137. package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
  138. package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
  139. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  140. package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
  141. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  142. package/dist/cli-bundle/{focused-chunks/item-revision-2O6MLPEX.js → chunks/item-revision-D3LSBNIR.js} +2 -2
  143. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
  144. package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
  145. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
  146. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-3LBV6CS2.js} +11 -11
  147. package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
  148. package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
  149. package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
  150. package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
  151. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  152. package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-3GT4A3ZN.js +44 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-3OCDKITJ.js +3 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-5LDBS6MS.js +91 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-B6BNHKUW.js +78 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-FDZPRJXJ.js +27 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Q2HY44LV.js +13 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
  177. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  178. package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
  179. package/dist/cli-bundle/focused-chunks/chunk-RLO2HCZT.js +2 -0
  180. package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
  181. package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/chunk-XDBHD4CY.js +8 -0
  184. package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
  185. package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
  186. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  187. package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
  188. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  189. package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
  190. package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
  191. package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
  192. package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
  193. package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
  194. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  195. package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
  196. package/dist/cli-bundle/main.js +27 -27
  197. package/dist/cli-bundle/sdk-authoring.js +1 -1
  198. package/dist/cli-bundle/sdk-contracts.js +5 -5
  199. package/dist/cli-bundle/sdk-core.js +1 -1
  200. package/dist/cli-bundle/sdk-governance.js +1 -1
  201. package/dist/cli-bundle/sdk-graph.js +1 -1
  202. package/dist/cli-bundle/sdk-merge.js +66 -66
  203. package/dist/cli-bundle/sdk-query.js +1 -1
  204. package/dist/cli-bundle/sdk-runtime.js +1 -1
  205. package/dist/cli-bundle/sdk-testing.js +1 -1
  206. package/dist/cli-bundle/sdk.js +13 -13
  207. package/dist/cli.js +1 -1
  208. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  209. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  210. package/dist/core/checkpoint/mutation-context.js +1 -1
  211. package/dist/core/config/nested-settings.js +1 -1
  212. package/dist/core/config/positional-value.js +1 -1
  213. package/dist/core/diagnostics/remediation.js +1 -1
  214. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  215. package/dist/core/extensions/activation-summary.js +1 -1
  216. package/dist/core/extensions/activation-transaction.js +1 -1
  217. package/dist/core/extensions/capability-usage.js +1 -1
  218. package/dist/core/extensions/command-hook-context.js +1 -1
  219. package/dist/core/extensions/command-metadata-contract.js +1 -1
  220. package/dist/core/extensions/command-visibility-tier.js +1 -1
  221. package/dist/core/extensions/contribution-inventory.js +1 -1
  222. package/dist/core/extensions/exporter-output-contract.js +1 -1
  223. package/dist/core/extensions/extension-candidate.js +1 -1
  224. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  225. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  226. package/dist/core/extensions/extension-policy.js +1 -1
  227. package/dist/core/extensions/extension-registries.js +1 -1
  228. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  229. package/dist/core/extensions/extension-types.js +1 -1
  230. package/dist/core/extensions/flag-definition-validation.js +1 -1
  231. package/dist/core/extensions/flag-value-types.js +1 -1
  232. package/dist/core/extensions/index.js +1 -1
  233. package/dist/core/extensions/item-field-types.js +1 -1
  234. package/dist/core/extensions/item-fields.js +1 -1
  235. package/dist/core/extensions/loader.js +1 -1
  236. package/dist/core/extensions/manifest-parser.js +1 -1
  237. package/dist/core/extensions/manifest-schema.js +1 -1
  238. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  239. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  240. package/dist/core/extensions/mutation-actor.js +1 -1
  241. package/dist/core/extensions/preflight-ownership.js +1 -1
  242. package/dist/core/extensions/read-output-contract.js +1 -1
  243. package/dist/core/extensions/registration-contracts.js +1 -1
  244. package/dist/core/extensions/registration-validation.js +1 -1
  245. package/dist/core/extensions/registration-values.js +1 -1
  246. package/dist/core/extensions/reserved-host-flags.js +1 -1
  247. package/dist/core/extensions/runtime-registrations.js +1 -1
  248. package/dist/core/extensions/service-ownership.js +1 -1
  249. package/dist/core/extensions/version-compat.js +1 -1
  250. package/dist/core/extensions/version-diagnostics.js +1 -1
  251. package/dist/core/fs/atomic-create.js +1 -1
  252. package/dist/core/fs/file-glob.js +1 -1
  253. package/dist/core/fs/fs-utils.js +2 -2
  254. package/dist/core/fs/host-environment-errors.js +1 -1
  255. package/dist/core/fs/index.js +1 -1
  256. package/dist/core/fs/path-utils.js +1 -1
  257. package/dist/core/governance/content-fields.js +1 -1
  258. package/dist/core/governance/issue-codes.js +1 -1
  259. package/dist/core/governance/metadata-coverage.js +1 -1
  260. package/dist/core/history/bridge.js +1 -1
  261. package/dist/core/history/digest.js +1 -1
  262. package/dist/core/history/drift-cache.js +3 -3
  263. package/dist/core/history/drift-scan.js +1 -1
  264. package/dist/core/history/event-classification.js +1 -1
  265. package/dist/core/history/event-index.js +11 -11
  266. package/dist/core/history/history-compact-bulk.js +1 -1
  267. package/dist/core/history/history-diff.js +1 -1
  268. package/dist/core/history/history-rewrite.js +1 -1
  269. package/dist/core/history/history-storage-stats.js +1 -1
  270. package/dist/core/history/history-stream-policy.js +1 -1
  271. package/dist/core/history/history.js +2 -2
  272. package/dist/core/history/identity.js +1 -1
  273. package/dist/core/history/index.js +1 -1
  274. package/dist/core/history/operation-contract.js +1 -1
  275. package/dist/core/history/projection.js +1 -1
  276. package/dist/core/history/read.js +1 -1
  277. package/dist/core/history/replay.js +2 -2
  278. package/dist/core/history/stream-summary.js +2 -2
  279. package/dist/core/history/tombstone.js +1 -1
  280. package/dist/core/history/version-address.js +1 -1
  281. package/dist/core/history/workspace-history.js +2 -2
  282. package/dist/core/io/body-file.js +1 -1
  283. package/dist/core/io/bulk-ids-input.js +2 -2
  284. package/dist/core/item/actionability.js +1 -1
  285. package/dist/core/item/deferred-fields.js +1 -1
  286. package/dist/core/item/dependency-reference.js +1 -1
  287. package/dist/core/item/id.js +1 -1
  288. package/dist/core/item/index.js +1 -1
  289. package/dist/core/item/item-format-version.js +1 -1
  290. package/dist/core/item/item-format.js +7 -7
  291. package/dist/core/item/item-record.js +1 -1
  292. package/dist/core/item/item-type-definition.js +1 -1
  293. package/dist/core/item/literal-mutation-input.js +1 -1
  294. package/dist/core/item/parent-reference-policy.js +1 -1
  295. package/dist/core/item/parse.js +8 -8
  296. package/dist/core/item/plan-lifecycle.js +1 -1
  297. package/dist/core/item/priority.js +1 -1
  298. package/dist/core/item/sprint-release-format.js +1 -1
  299. package/dist/core/item/status-filter.js +1 -1
  300. package/dist/core/item/status.js +1 -1
  301. package/dist/core/item/toon-decode.js +1 -1
  302. package/dist/core/item/type-registry.js +1 -1
  303. package/dist/core/item/type-synonyms.js +1 -1
  304. package/dist/core/lock/index.js +1 -1
  305. package/dist/core/lock/lock-confinement.js +1 -1
  306. package/dist/core/lock/lock-gc.js +1 -1
  307. package/dist/core/lock/lock-owner.js +1 -1
  308. package/dist/core/lock/lock.js +4 -4
  309. package/dist/core/output/linked-test-projection.js +5 -5
  310. package/dist/core/output/mutation-projection.js +1 -1
  311. package/dist/core/output/output-control.js +1 -1
  312. package/dist/core/output/output.js +19 -19
  313. package/dist/core/output/query-summary.js +1 -1
  314. package/dist/core/output/tabular.js +3 -3
  315. package/dist/core/packages/manifest.js +1 -1
  316. package/dist/core/packages/root.js +1 -1
  317. package/dist/core/policy/workflow-policy-schema.js +1 -1
  318. package/dist/core/policy/workflow-policy-store.js +1 -1
  319. package/dist/core/policy/workflow-policy.js +1 -1
  320. package/dist/core/profile/profile-describe.js +1 -1
  321. package/dist/core/profile/profile-lint.d.ts +1 -1
  322. package/dist/core/profile/profile-lint.js +1 -1
  323. package/dist/core/profile/profile-plan.js +1 -1
  324. package/dist/core/profile/profile-presets.js +4 -4
  325. package/dist/core/reproducibility/context.js +1 -1
  326. package/dist/core/schema/fields-file.js +2 -2
  327. package/dist/core/schema/item-types-file.js +2 -2
  328. package/dist/core/schema/runtime-field-filters.js +1 -1
  329. package/dist/core/schema/runtime-field-values.js +1 -1
  330. package/dist/core/schema/runtime-schema.d.ts +2 -0
  331. package/dist/core/schema/runtime-schema.js +2 -2
  332. package/dist/core/schema/status-defs-file.js +2 -2
  333. package/dist/core/schema/status-token.js +1 -1
  334. package/dist/core/schema/type-inference.js +1 -1
  335. package/dist/core/schema/type-presets.js +1 -1
  336. package/dist/core/schema/type-workflows.js +1 -1
  337. package/dist/core/search/background-refresh.js +2 -2
  338. package/dist/core/search/bm25.js +1 -1
  339. package/dist/core/search/cache.js +2 -2
  340. package/dist/core/search/corpus.js +1 -1
  341. package/dist/core/search/embedding-batches.js +1 -1
  342. package/dist/core/search/eval-thresholds.js +1 -1
  343. package/dist/core/search/eval.js +1 -1
  344. package/dist/core/search/http-client.js +1 -1
  345. package/dist/core/search/providers.js +1 -1
  346. package/dist/core/search/relevance.js +1 -1
  347. package/dist/core/search/semantic-defaults.js +1 -1
  348. package/dist/core/search/staleness.js +1 -1
  349. package/dist/core/search/vector-stores.js +2 -2
  350. package/dist/core/search/vectorization-metadata.js +1 -1
  351. package/dist/core/sentry/helpers.js +1 -1
  352. package/dist/core/sentry/instrument.js +1 -1
  353. package/dist/core/sentry/sensitive-assignments.js +1 -1
  354. package/dist/core/session/session-state.js +1 -1
  355. package/dist/core/shared/agent-session-context.js +1 -1
  356. package/dist/core/shared/author.js +5 -5
  357. package/dist/core/shared/command-line.js +1 -1
  358. package/dist/core/shared/command-types.js +0 -1
  359. package/dist/core/shared/conflict-markers.js +1 -1
  360. package/dist/core/shared/constants.js +1 -1
  361. package/dist/core/shared/error-details.js +1 -1
  362. package/dist/core/shared/errors.js +1 -1
  363. package/dist/core/shared/html-entity-decode.js +1 -1
  364. package/dist/core/shared/index.js +1 -1
  365. package/dist/core/shared/item-metadata-contract.js +1 -1
  366. package/dist/core/shared/lazy-module.js +1 -1
  367. package/dist/core/shared/levenshtein.js +1 -1
  368. package/dist/core/shared/memo.js +1 -1
  369. package/dist/core/shared/numeric-parsers.js +1 -1
  370. package/dist/core/shared/option-alias-visibility.js +1 -1
  371. package/dist/core/shared/output-unicode.js +1 -1
  372. package/dist/core/shared/primitives.js +1 -1
  373. package/dist/core/shared/process-tree.js +2 -2
  374. package/dist/core/shared/secret-rules.js +5 -5
  375. package/dist/core/shared/serial-queue.js +1 -1
  376. package/dist/core/shared/serialization.js +1 -1
  377. package/dist/core/shared/split-comma-list.js +1 -1
  378. package/dist/core/shared/text-normalization.js +1 -1
  379. package/dist/core/shared/time.js +2 -2
  380. package/dist/core/shared/url-credentials.js +1 -1
  381. package/dist/core/store/index.js +1 -1
  382. package/dist/core/store/item-format-migration.js +1 -1
  383. package/dist/core/store/item-metadata-cache.js +1 -1
  384. package/dist/core/store/item-metadata-query-index.js +11 -11
  385. package/dist/core/store/item-metadata-read-work.js +1 -1
  386. package/dist/core/store/item-mutation-precondition.js +1 -1
  387. package/dist/core/store/item-store.js +1 -1
  388. package/dist/core/store/paths.js +1 -1
  389. package/dist/core/store/settings-concurrency.js +1 -1
  390. package/dist/core/store/settings-read-cache.js +1 -1
  391. package/dist/core/store/settings-sections.js +2 -2
  392. package/dist/core/store/settings-validator.js +1 -1
  393. package/dist/core/store/settings.d.ts +3 -1
  394. package/dist/core/store/settings.js +6 -6
  395. package/dist/core/store/sqlite-runtime.js +1 -1
  396. package/dist/core/store/tracker-preflight.js +1 -1
  397. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  398. package/dist/core/telemetry/consent.js +3 -3
  399. package/dist/core/telemetry/observability.js +1 -1
  400. package/dist/core/telemetry/policy.js +1 -1
  401. package/dist/core/telemetry/read-sampling.js +2 -2
  402. package/dist/core/telemetry/runtime.js +9 -9
  403. package/dist/core/test/background-runs.js +4 -4
  404. package/dist/core/test/item-test-run-tracking.js +1 -1
  405. package/dist/core/test/run-selectors.js +1 -1
  406. package/dist/core/validate/estimate-defaults.js +1 -1
  407. package/dist/core/validate/fix-planning.js +1 -1
  408. package/dist/core/validate/linked-artifact-reference.js +1 -1
  409. package/dist/core/validate/missing-by-type.js +1 -1
  410. package/dist/core/validate/missing-link-owners.js +1 -1
  411. package/dist/core/validate/stale-file-classification.js +1 -1
  412. package/dist/mcp/http-server.js +5 -5
  413. package/dist/mcp/legacy-adapter.js +1 -1
  414. package/dist/mcp/runtime-capabilities.js +1 -1
  415. package/dist/mcp/server.js +4 -4
  416. package/dist/mcp/tool-definitions.js +1 -1
  417. package/dist/sdk/actionability.js +1 -1
  418. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  419. package/dist/sdk/agent/command-recovery.js +1 -1
  420. package/dist/sdk/agent/command-suggestions.js +1 -1
  421. package/dist/sdk/agent/create-option-policy.js +1 -1
  422. package/dist/sdk/agent/identity-config.js +1 -1
  423. package/dist/sdk/agent/item-addressing.js +1 -1
  424. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  425. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  426. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  427. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  428. package/dist/sdk/agent-capability-contracts.js +3 -3
  429. package/dist/sdk/agent-session-context.js +1 -1
  430. package/dist/sdk/annotations.js +1 -1
  431. package/dist/sdk/author-attribution.js +1 -1
  432. package/dist/sdk/cli-bootstrap.js +1 -1
  433. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  434. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  435. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  436. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  438. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  439. package/dist/sdk/cli-contracts/completeness.js +1 -1
  440. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  441. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  442. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  443. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  444. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  445. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  446. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  447. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  448. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  449. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  450. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  451. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  452. package/dist/sdk/cli-contracts.js +1 -1
  453. package/dist/sdk/cli-program.js +1 -1
  454. package/dist/sdk/command-line.js +1 -1
  455. package/dist/sdk/comments.js +1 -1
  456. package/dist/sdk/compile-cache.js +1 -1
  457. package/dist/sdk/completion/bash.js +2 -2
  458. package/dist/sdk/completion/fish.js +72 -72
  459. package/dist/sdk/completion/shared.js +1 -1
  460. package/dist/sdk/completion/zsh.js +75 -75
  461. package/dist/sdk/completion.js +1 -1
  462. package/dist/sdk/config.js +1 -1
  463. package/dist/sdk/context/recency.js +1 -1
  464. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  465. package/dist/sdk/context/usage-egress.js +1 -1
  466. package/dist/sdk/context/usage-ledger.js +6 -6
  467. package/dist/sdk/context-intent-contracts.js +1 -1
  468. package/dist/sdk/context-intent-runtime.js +1 -1
  469. package/dist/sdk/context-packing.js +1 -1
  470. package/dist/sdk/context-relevance.js +1 -1
  471. package/dist/sdk/context-signal-store.js +2 -2
  472. package/dist/sdk/context-usage.js +1 -1
  473. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  474. package/dist/sdk/dependencies.js +1 -1
  475. package/dist/sdk/dependency-flag-validation.js +1 -1
  476. package/dist/sdk/dependency-provenance.js +1 -1
  477. package/dist/sdk/docs.js +1 -1
  478. package/dist/sdk/duplicates.js +1 -1
  479. package/dist/sdk/environment/host-environment-errors.js +1 -1
  480. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  481. package/dist/sdk/environment/source-context.js +1 -1
  482. package/dist/sdk/environment/tracker-preflight.js +1 -1
  483. package/dist/sdk/error-code-catalog.js +1 -1
  484. package/dist/sdk/error-runtime.js +1 -1
  485. package/dist/sdk/errors.js +1 -1
  486. package/dist/sdk/eval.js +1 -1
  487. package/dist/sdk/extension/author-manifest.js +1 -1
  488. package/dist/sdk/extension/bundled-catalog.js +1 -1
  489. package/dist/sdk/extension/command-options.d.ts +26 -1
  490. package/dist/sdk/extension/command-options.js +1 -1
  491. package/dist/sdk/extension/concurrency.js +1 -1
  492. package/dist/sdk/extension/copy-scope.js +1 -1
  493. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  494. package/dist/sdk/extension/describe.js +3 -3
  495. package/dist/sdk/extension/doctor.js +1 -1
  496. package/dist/sdk/extension/install-plan.js +1 -1
  497. package/dist/sdk/extension/install-receipts.js +1 -1
  498. package/dist/sdk/extension/install-runtime.js +3 -3
  499. package/dist/sdk/extension/install-snapshot.js +1 -1
  500. package/dist/sdk/extension/install-sources.js +5 -5
  501. package/dist/sdk/extension/managed-state.js +2 -2
  502. package/dist/sdk/extension/managed-update-status.js +1 -1
  503. package/dist/sdk/extension/migrations.js +2 -2
  504. package/dist/sdk/extension/native-command-options.js +1 -1
  505. package/dist/sdk/extension/output-ownership.js +1 -1
  506. package/dist/sdk/extension/runtime-summary.js +1 -1
  507. package/dist/sdk/extension/scaffold.js +11 -11
  508. package/dist/sdk/extension/shared.js +1 -1
  509. package/dist/sdk/extension/source-resolution.js +1 -1
  510. package/dist/sdk/extension/static-inventory.js +1 -1
  511. package/dist/sdk/extension/update-check.js +1 -1
  512. package/dist/sdk/extension-command-context.js +2 -2
  513. package/dist/sdk/extension-contracts.js +1 -1
  514. package/dist/sdk/extension.js +1 -1
  515. package/dist/sdk/files.js +1 -1
  516. package/dist/sdk/flag-invocation-contracts.js +1 -1
  517. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  518. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  519. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  520. package/dist/sdk/generated-error-code-catalog.js +1 -1
  521. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  522. package/dist/sdk/governance/assurance-action.js +1 -1
  523. package/dist/sdk/governance/assurance-limits.js +1 -1
  524. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  525. package/dist/sdk/governance/assurance-presets.js +1 -1
  526. package/dist/sdk/governance/assurance-runtime.js +1 -1
  527. package/dist/sdk/governance/assurance.js +4 -4
  528. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  529. package/dist/sdk/governance/closure-timestamps.js +1 -1
  530. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  531. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  532. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  533. package/dist/sdk/governance/defect-recurrence.js +2 -2
  534. package/dist/sdk/governance/extension-host-version.js +1 -1
  535. package/dist/sdk/governance/gc.js +1 -1
  536. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  537. package/dist/sdk/governance/health/projection.js +1 -1
  538. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  539. package/dist/sdk/governance/health.js +2 -2
  540. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  541. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  542. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  543. package/dist/sdk/governance/linked-file-report.js +1 -1
  544. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  545. package/dist/sdk/governance/provenance-health.js +4 -4
  546. package/dist/sdk/governance/reindex.js +5 -5
  547. package/dist/sdk/governance/stale-work.js +1 -1
  548. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  549. package/dist/sdk/governance/storage-integrity.js +1 -1
  550. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  551. package/dist/sdk/governance/upgrade.js +2 -2
  552. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  553. package/dist/sdk/governance/validate-history-drift.js +1 -1
  554. package/dist/sdk/governance/validate-item-reader.js +1 -1
  555. package/dist/sdk/governance/validate-normalization.js +1 -1
  556. package/dist/sdk/governance/validate.js +1 -1
  557. package/dist/sdk/governance/workflow-completeness.js +1 -1
  558. package/dist/sdk/governance/workflow-policy.js +3 -3
  559. package/dist/sdk/governance/workspace-position.js +2 -2
  560. package/dist/sdk/graph/analytics.js +1 -1
  561. package/dist/sdk/graph/assembly.js +1 -1
  562. package/dist/sdk/graph/cache.js +1 -1
  563. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  564. package/dist/sdk/graph/centrality.js +1 -1
  565. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  566. package/dist/sdk/graph/durable-cache.js +1 -1
  567. package/dist/sdk/graph/governance-contracts.js +1 -1
  568. package/dist/sdk/graph/governance.js +1 -1
  569. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  570. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  571. package/dist/sdk/graph/mutation-advisory.js +1 -1
  572. package/dist/sdk/graph/query-contracts.js +1 -1
  573. package/dist/sdk/graph/remediation.js +1 -1
  574. package/dist/sdk/graph/run.js +1 -1
  575. package/dist/sdk/graph/scheduling.js +1 -1
  576. package/dist/sdk/graph/traversal.js +1 -1
  577. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  578. package/dist/sdk/guide-topics.js +1 -1
  579. package/dist/sdk/guide.js +7 -7
  580. package/dist/sdk/history/append-only-repair.js +4 -4
  581. package/dist/sdk/history/attestation-command.js +2 -2
  582. package/dist/sdk/history/attestation-contract.js +1 -1
  583. package/dist/sdk/history/attestation-scan.js +1 -1
  584. package/dist/sdk/history/attestation.js +1 -1
  585. package/dist/sdk/history/maintenance.js +1 -1
  586. package/dist/sdk/history/reanchor-refusal.js +1 -1
  587. package/dist/sdk/history/reseed.js +1 -1
  588. package/dist/sdk/history/salvage.js +5 -5
  589. package/dist/sdk/history/subject.js +1 -1
  590. package/dist/sdk/history-analytics.js +1 -1
  591. package/dist/sdk/history-compact.js +1 -1
  592. package/dist/sdk/history-mcp.js +1 -1
  593. package/dist/sdk/history-provenance.js +1 -1
  594. package/dist/sdk/history-read.js +1 -1
  595. package/dist/sdk/history-redact.js +1 -1
  596. package/dist/sdk/history-repair.js +1 -1
  597. package/dist/sdk/improvement-ledger-validation.js +1 -1
  598. package/dist/sdk/improvement-ledger.js +2 -2
  599. package/dist/sdk/index.d.ts +1 -1
  600. package/dist/sdk/init-agent-guidance.js +10 -10
  601. package/dist/sdk/init.js +14 -14
  602. package/dist/sdk/invocation-author.js +1 -1
  603. package/dist/sdk/item-children.js +1 -1
  604. package/dist/sdk/item-metadata-index.js +1 -1
  605. package/dist/sdk/item-schedule.js +1 -1
  606. package/dist/sdk/item-transaction.js +1 -1
  607. package/dist/sdk/learnings.js +1 -1
  608. package/dist/sdk/lifecycle/append.js +3 -3
  609. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  610. package/dist/sdk/lifecycle/claim.js +1 -1
  611. package/dist/sdk/lifecycle/cli-input.js +1 -1
  612. package/dist/sdk/lifecycle/close-many.js +1 -1
  613. package/dist/sdk/lifecycle/close.js +1 -1
  614. package/dist/sdk/lifecycle/copy.js +1 -1
  615. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  616. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  617. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  618. package/dist/sdk/lifecycle/create.js +1 -1
  619. package/dist/sdk/lifecycle/delete.js +1 -1
  620. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  621. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  622. package/dist/sdk/lifecycle/focus.js +1 -1
  623. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  624. package/dist/sdk/lifecycle/item-revision.js +1 -1
  625. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  626. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  627. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  628. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  629. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  630. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  631. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  632. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  633. package/dist/sdk/lifecycle/plan.js +1 -1
  634. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  635. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  636. package/dist/sdk/lifecycle/reopen.js +1 -1
  637. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  638. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  639. package/dist/sdk/lifecycle/restore.js +1 -1
  640. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  641. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  642. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  643. package/dist/sdk/lifecycle/task-composition.js +1 -1
  644. package/dist/sdk/lifecycle/update-many.js +1 -1
  645. package/dist/sdk/lifecycle/update.js +2 -2
  646. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  647. package/dist/sdk/lifecycle-completion.js +1 -1
  648. package/dist/sdk/lifecycle-policy.js +1 -1
  649. package/dist/sdk/linked-artifacts.js +2 -2
  650. package/dist/sdk/mcp/apps.js +5 -5
  651. package/dist/sdk/mcp/authorization.js +1 -1
  652. package/dist/sdk/mcp/discovery.js +1 -1
  653. package/dist/sdk/mcp/executable.js +4 -4
  654. package/dist/sdk/mcp/interactions.js +1 -1
  655. package/dist/sdk/mcp/protocol.js +1 -1
  656. package/dist/sdk/mcp/skills.js +3 -3
  657. package/dist/sdk/mcp/subscriptions.js +1 -1
  658. package/dist/sdk/mcp/tasks.js +2 -2
  659. package/dist/sdk/mcp/transport.js +1 -1
  660. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  661. package/dist/sdk/merge/driver.js +7 -7
  662. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  663. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  664. package/dist/sdk/merge/index.js +1 -1
  665. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  666. package/dist/sdk/merge/install.js +6 -6
  667. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  668. package/dist/sdk/merge/receipt-operation.js +1 -1
  669. package/dist/sdk/merge/receipt-schema.js +1 -1
  670. package/dist/sdk/merge/receipts.js +4 -4
  671. package/dist/sdk/merge/reconcile.js +1 -1
  672. package/dist/sdk/merge/settlement-hook.js +4 -4
  673. package/dist/sdk/merge/stage.js +1 -1
  674. package/dist/sdk/merge/three-way.js +9 -9
  675. package/dist/sdk/merge/worktree-config.js +2 -2
  676. package/dist/sdk/merge.js +1 -1
  677. package/dist/sdk/mutation-events.js +1 -1
  678. package/dist/sdk/mutation-guard.js +1 -1
  679. package/dist/sdk/notes.js +1 -1
  680. package/dist/sdk/output/fit-envelope.js +1 -1
  681. package/dist/sdk/output/list-envelope.js +1 -1
  682. package/dist/sdk/output/table-rows.js +1 -1
  683. package/dist/sdk/output-contracts.js +1 -1
  684. package/dist/sdk/output-projection.js +1 -1
  685. package/dist/sdk/output-token-accounting.js +1 -1
  686. package/dist/sdk/output.js +2 -2
  687. package/dist/sdk/ownership-source.js +1 -1
  688. package/dist/sdk/package-import-adapters.js +1 -1
  689. package/dist/sdk/package-migrations.js +1 -1
  690. package/dist/sdk/package-runtime-options.js +1 -1
  691. package/dist/sdk/pagination.js +1 -1
  692. package/dist/sdk/profile.js +5 -5
  693. package/dist/sdk/provenance.js +1 -1
  694. package/dist/sdk/public-surface.json +1 -1
  695. package/dist/sdk/query/activity.js +1 -1
  696. package/dist/sdk/query/aggregate.js +1 -1
  697. package/dist/sdk/query/calendar.js +4 -4
  698. package/dist/sdk/query/complete-list.js +1 -1
  699. package/dist/sdk/query/context.js +2 -2
  700. package/dist/sdk/query/declared-blockers.js +1 -1
  701. package/dist/sdk/query/duplicate-candidates.js +1 -1
  702. package/dist/sdk/query/get-facet-roots.js +1 -1
  703. package/dist/sdk/query/get.js +1 -1
  704. package/dist/sdk/query/history.js +1 -1
  705. package/dist/sdk/query/item-filter-options.js +0 -1
  706. package/dist/sdk/query/light-metadata.js +1 -1
  707. package/dist/sdk/query/list-filter-shared.js +1 -1
  708. package/dist/sdk/query/list.js +1 -1
  709. package/dist/sdk/query/multi-value-filters.js +1 -1
  710. package/dist/sdk/query/next-ranking-policy.js +1 -1
  711. package/dist/sdk/query/next-ready-budget.js +1 -1
  712. package/dist/sdk/query/next.js +2 -2
  713. package/dist/sdk/query/parsers.js +1 -1
  714. package/dist/sdk/query/projection-contracts.js +1 -1
  715. package/dist/sdk/query/search/corpus.js +2 -2
  716. package/dist/sdk/query/search/filters.js +1 -1
  717. package/dist/sdk/query/search/input.js +1 -1
  718. package/dist/sdk/query/search/lexical.js +1 -1
  719. package/dist/sdk/query/search/response.js +1 -1
  720. package/dist/sdk/query/search/semantic.js +3 -3
  721. package/dist/sdk/query/search/types.js +0 -1
  722. package/dist/sdk/query/search-contracts.js +1 -1
  723. package/dist/sdk/query/search-pagination.js +1 -1
  724. package/dist/sdk/query/search-rendering.js +1 -1
  725. package/dist/sdk/query/search.js +1 -1
  726. package/dist/sdk/query/window-pagination.js +1 -1
  727. package/dist/sdk/query/workspace-contracts.js +1 -1
  728. package/dist/sdk/read-output/continuation.js +1 -1
  729. package/dist/sdk/read-output/extension.js +1 -1
  730. package/dist/sdk/read-output/options.js +1 -1
  731. package/dist/sdk/read-output/positional-rows.js +1 -1
  732. package/dist/sdk/read-output/provenance.js +1 -1
  733. package/dist/sdk/read-output/session-result.js +0 -1
  734. package/dist/sdk/read-output/surfaces.js +1 -1
  735. package/dist/sdk/read-output/tail-retention.js +1 -1
  736. package/dist/sdk/read-output-budget.js +1 -1
  737. package/dist/sdk/read-output-contracts.d.ts +11 -0
  738. package/dist/sdk/read-output-contracts.js +1 -1
  739. package/dist/sdk/read-output-rows.js +1 -1
  740. package/dist/sdk/read-output-session.js +1 -1
  741. package/dist/sdk/relationship-analytics.js +1 -1
  742. package/dist/sdk/relationship-context.js +1 -1
  743. package/dist/sdk/relationship-history.js +6 -6
  744. package/dist/sdk/relationship-kinds/contract.js +1 -1
  745. package/dist/sdk/relationships.js +1 -1
  746. package/dist/sdk/reproducibility/process.js +1 -1
  747. package/dist/sdk/runtime/actions.js +1 -1
  748. package/dist/sdk/runtime/context.js +1 -1
  749. package/dist/sdk/runtime/mutation-admission.js +1 -1
  750. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  751. package/dist/sdk/runtime/schema-preview.js +1 -1
  752. package/dist/sdk/runtime/schema.js +1 -1
  753. package/dist/sdk/runtime-action-aliases.js +1 -1
  754. package/dist/sdk/runtime-extended-actions.js +1 -1
  755. package/dist/sdk/runtime-input.d.ts +2 -0
  756. package/dist/sdk/runtime-input.js +1 -1
  757. package/dist/sdk/runtime-primitives.js +1 -1
  758. package/dist/sdk/runtime-public-contracts.js +0 -1
  759. package/dist/sdk/runtime-stats-options.js +1 -1
  760. package/dist/sdk/runtime.d.ts +5 -3
  761. package/dist/sdk/runtime.js +1 -1
  762. package/dist/sdk/scheduling-shortcuts.js +1 -1
  763. package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
  764. package/dist/sdk/schema/field-flag-spelling.js +2 -0
  765. package/dist/sdk/schema/field-option-collisions.js +2 -0
  766. package/dist/sdk/schema-migration.js +4 -4
  767. package/dist/sdk/schema.js +7 -7
  768. package/dist/sdk/search-refresh-worker.js +1 -1
  769. package/dist/sdk/similarity-scoring.js +1 -1
  770. package/dist/sdk/similarity.js +1 -1
  771. package/dist/sdk/start-task-status.js +1 -1
  772. package/dist/sdk/stats.js +1 -1
  773. package/dist/sdk/structured-mutations.js +1 -1
  774. package/dist/sdk/telemetry-flush.js +1 -1
  775. package/dist/sdk/telemetry.js +4 -4
  776. package/dist/sdk/templates.js +3 -3
  777. package/dist/sdk/test/batch.js +2 -2
  778. package/dist/sdk/test/command-args.js +1 -1
  779. package/dist/sdk/test/command-resolution.js +2 -2
  780. package/dist/sdk/test/entry.js +2 -2
  781. package/dist/sdk/test/execution-receipts.js +2 -2
  782. package/dist/sdk/test/execution.js +5 -5
  783. package/dist/sdk/test/json-path.js +1 -1
  784. package/dist/sdk/test/linked-command-detection.js +1 -1
  785. package/dist/sdk/test/measurements.js +1 -1
  786. package/dist/sdk/test/parsers.js +1 -1
  787. package/dist/sdk/test/prerequisites.js +1 -1
  788. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  789. package/dist/sdk/test/run-phases.js +1 -1
  790. package/dist/sdk/test/runs.js +1 -1
  791. package/dist/sdk/test/trust.js +2 -2
  792. package/dist/sdk/test/update.js +1 -1
  793. package/dist/sdk/test/workspace-snapshot.js +1 -1
  794. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  795. package/dist/sdk/traceability/source-traceability.js +2 -2
  796. package/dist/sdk/tracker-root-discovery.js +1 -1
  797. package/dist/sdk/transactions/item-finalization.js +1 -1
  798. package/dist/sdk/workspace-contracts-cache.js +1 -1
  799. package/dist/sdk/workspace-contracts.js +1 -1
  800. package/dist/sdk/workspace-memory.js +2 -2
  801. package/dist/sdk/workspace-snapshot.js +5 -5
  802. package/dist/sdk/workspace-transaction-gc.js +1 -1
  803. package/dist/sdk/workspace-transaction.js +2 -2
  804. package/dist/sdk/workspace.js +6 -6
  805. package/dist/types/index.js +1 -1
  806. package/dist/types.js +1 -1
  807. package/docs/COMMANDS.md +1 -1
  808. package/docs/EXTENSIONS.md +2 -2
  809. package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
  810. package/docs/SDK.md +94 -5
  811. package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
  812. package/marketplace.json +1 -1
  813. package/package.json +2 -1
  814. package/packages/pm-beads/package.json +1 -1
  815. package/packages/pm-calendar/package.json +1 -1
  816. package/packages/pm-command-kit/package.json +1 -1
  817. package/packages/pm-digital-twin/package.json +1 -1
  818. package/packages/pm-governance-audit/package.json +1 -1
  819. package/packages/pm-guide-shell/package.json +1 -1
  820. package/packages/pm-kanban/package.json +1 -1
  821. package/packages/pm-lifecycle-hooks/package.json +1 -1
  822. package/packages/pm-linked-test-adapters/package.json +1 -1
  823. package/packages/pm-search-advanced/package.json +1 -1
  824. package/packages/pm-templates/package.json +1 -1
  825. package/packages/pm-todos/package.json +1 -1
  826. package/packages/pm-vcs/package.json +1 -1
  827. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  828. package/plugins/pm-claude/package.json +1 -1
  829. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  830. package/plugins/pm-codex/package.json +1 -1
  831. package/plugins/pm-codex/plugin.json +1 -1
  832. package/runtime-dependencies.json +1 -1
  833. package/scripts/finalize-build.mjs +63 -24
  834. package/scripts/prepare-build-cache.mjs +28 -1
  835. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  836. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  837. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  839. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  840. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  841. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  842. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  843. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  844. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  845. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  846. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  847. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  848. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  849. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  850. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  851. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  852. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  853. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  854. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  855. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  856. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  857. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  858. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  859. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  860. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  861. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  862. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  863. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  864. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  865. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  866. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  867. package/dist/cli-bundle/chunks/item-revision-4QBMZXKX.js +0 -2
  868. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  869. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  870. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  871. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  872. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  873. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  874. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  875. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  876. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  877. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  878. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  879. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  880. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  881. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  882. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  883. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  884. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  886. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  888. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  892. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  893. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  894. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  895. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  896. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  897. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  898. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  899. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  900. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  901. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  902. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  903. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  904. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  905. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  906. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  907. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  908. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  909. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  910. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  911. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  912. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1dcf0d72-10da-51b6-b9f6-ab47bebcbf64")}catch{}})();import{cloneEmptyReplayDocument,tryApplyReplayPatch}from"./replay.js";function decodeJsonPointerSegment(segment){return segment.replaceAll("~1","/").replaceAll("~0","~")}function patchPathToChangedField(path){if(path==="/body"||path.startsWith("/body/"))return"body";if(path==="/metadata"||path.startsWith("/metadata/")||path==="/front_matter"||path.startsWith("/front_matter/")){const segment2=path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return segment2?decodeJsonPointerSegment(segment2):"metadata"}const segment=path.replace(/^\//,"").split("/")[0];return segment?decodeJsonPointerSegment(segment):"root"}function readFieldValue(doc,field){return field==="body"?doc.body:field==="metadata"?doc.metadata:field==="root"?doc:doc.metadata[field]}function computeHistoryDiff(fullEntries,options){const windowStartIndex=options?.windowStartIndex??0,fieldFilter=options?.field;if(fullEntries.length===0||windowStartIndex>=fullEntries.length)return[];let current=cloneEmptyReplayDocument();const result=[];for(let p=0;p<fullEntries.length;p+=1){const entry=fullEntries[p],beforeDoc=current,applied=tryApplyReplayPatch(current,entry.patch);let afterDoc;applied.ok?(afterDoc=applied.document,current=afterDoc):afterDoc=beforeDoc;const changedFieldSet=new Set;for(const patchOp of entry.patch)changedFieldSet.add(patchPathToChangedField(patchOp.path)),patchOp.from!==void 0&&changedFieldSet.add(patchPathToChangedField(patchOp.from));const sortedFields=[...changedFieldSet].sort((a,b)=>a.localeCompare(b));if(p>=windowStartIndex)if(fieldFilter!==void 0){if(!changedFieldSet.has(fieldFilter))continue;const change={field:fieldFilter,before:readFieldValue(beforeDoc,fieldFilter),after:readFieldValue(afterDoc,fieldFilter)};result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:[fieldFilter],changes:[change]})}else{const changes=sortedFields.map(field=>({field,before:readFieldValue(beforeDoc,field),after:readFieldValue(afterDoc,field)}));result.push({index:p+1,ts:entry.ts,op:entry.op,author:entry.author,patch_ops:entry.patch.length,changed_fields:sortedFields,changes})}}return result}export{computeHistoryDiff,patchPathToChangedField};
1
+ import{cloneEmptyReplayDocument as b,tryApplyReplayPatch as _}from"./replay.js";function g(t){return t.replaceAll("~1","/").replaceAll("~0","~")}function y(t){if(t==="/body"||t.startsWith("/body/"))return"body";if(t==="/metadata"||t.startsWith("/metadata/")||t==="/front_matter"||t.startsWith("/front_matter/")){const c=t.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return c?g(c):"metadata"}const e=t.replace(/^\//,"").split("/")[0];return e?g(e):"root"}function f(t,e){return e==="body"?t.body:e==="metadata"?t.metadata:e==="root"?t:t.metadata[e]}function w(t,e){const c=e?.windowStartIndex??0,o=e?.field;if(t.length===0||c>=t.length)return[];let p=b();const l=[];for(let a=0;a<t.length;a+=1){const n=t[a],u=p,h=_(p,n.patch);let s;h.ok?(s=h.document,p=s):s=u;const i=new Set;for(const r of n.patch)i.add(y(r.path)),r.from!==void 0&&i.add(y(r.from));const m=[...i].sort((r,d)=>r.localeCompare(d));if(a>=c)if(o!==void 0){if(!i.has(o))continue;const r={field:o,before:f(u,o),after:f(s,o)};l.push({index:a+1,ts:n.ts,op:n.op,author:n.author,patch_ops:n.patch.length,changed_fields:[o],changes:[r]})}else{const r=m.map(d=>({field:d,before:f(u,d),after:f(s,d)}));l.push({index:a+1,ts:n.ts,op:n.op,author:n.author,patch_ops:n.patch.length,changed_fields:m,changes:r})}}return l}export{w as computeHistoryDiff,y as patchPathToChangedField};
2
2
  //# sourceMappingURL=history-diff.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be6f35e2-0762-5188-b373-bdc7d7302d1c")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,hasActiveItemRevisionScope}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument||params.force)return[];const stored=params.itemDocument.metadata?.assignee?.trim();if(!stored||stored===params.author)return[];const assigned=redactOptionalIdentityCredentials(stored),governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function assertDeclaredRevisionOnDrift(params){if(!hasActiveItemRevisionScope(params.pmRoot))return;const located=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),document=located===null?EMPTY_CANONICAL_DOCUMENT:(await readLocatedItem(located,{schema:params.settings.schema}).catch(()=>null))?.document;document!==void 0&&assertItemMutationPreconditions(params.pmRoot,document,params.subject.id)}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation}),tombstone=EMPTY_CANONICAL_DOCUMENT;if(assertItemMutationPreconditions(params.pmRoot,verified.loadedItemUnderLock?.document??tombstone,params.subject.id),await params.applyRewrite(verified),hasActiveItemRevisionScope(params.pmRoot)){const relocated=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),rewritten=relocated===null?tombstone:(await readLocatedItem(relocated,{schema:params.settings.schema})).document;advanceItemMutationPreconditions(params.pmRoot,rewritten,params.subject.id)}return params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
1
+ import R from"node:fs/promises";import{readFileIfExists as _,writeFileAtomic as I}from"../fs/fs-utils.js";import{acquireLock as k}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT as d,EXIT_CODE as n}from"../shared/constants.js";import{PmCliError as r}from"../shared/errors.js";import{locateItem as c,readLocatedItem as s}from"../store/item-store.js";import{advanceItemMutationPreconditions as b,assertItemMutationPreconditions as l,hasActiveItemRevisionScope as u}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs as L}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath as h}from"./drift-cache.js";import{redactOptionalIdentityCredentials as j}from"../shared/url-credentials.js";function C(t){if(!t.itemDocument||t.force)return[];const o=t.itemDocument.metadata?.assignee?.trim();if(!o||o===t.author)return[];const e=j(o),i=L(t.settings);if(i.ownership_enforcement==="strict")throw new r(`Item ${t.subjectId} is assigned to ${e}. Use --force to override.`,n.CONFLICT);return i.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${t.subjectId}:${e}`]:[]}async function y(t){if(!u(t.pmRoot))return;const o=await c(t.pmRoot,t.subject.id,t.settings.id_prefix,t.settings.item_format,t.typeRegistry.type_to_folder),e=o===null?d:(await s(o,{schema:t.settings.schema}).catch(()=>null))?.document;e!==void 0&&l(t.pmRoot,e,t.subject.id)}async function P(t){const o=await _(t.subject.historyPath);if(o!==t.historyRawBeforeLock)throw await y(t),new r(`History for ${t.subject.id} changed while waiting for lock; retry ${t.operation}.`,n.CONFLICT);const e=await c(t.pmRoot,t.subject.id,t.settings.id_prefix,t.settings.item_format,t.typeRegistry.type_to_folder),i=e?t.readItem?await t.readItem(e):await s(e,{schema:t.settings.schema}):null;if((i?.raw??null)!==(t.currentItemRawBeforeLock??null))throw await y(t),new r(`Item ${t.subject.id} changed while waiting for lock; retry ${t.operation}.`,n.CONFLICT);return{historyRawUnderLock:o,locatedUnderLock:e,loadedItemUnderLock:i}}async function N(t){const o=t.writeHistoryRaw??I;try{await o(t.historyPath,t.nextHistoryRaw),await h(t.historyPath)}catch(e){try{t.historyRawUnderLock===null?await R.rm(t.historyPath,{force:!0}):await o(t.historyPath,t.historyRawUnderLock),await h(t.historyPath)}catch(i){throw new AggregateError([e,i],`History rewrite failed and rollback also failed: ${String(e)}`)}throw e}}async function F(t){const o=[...C({itemDocument:t.itemDocument,subjectId:t.subject.id,author:t.author,force:t.force,settings:t.settings})],e=await k(t.pmRoot,t.subject.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms);try{const i=await P({pmRoot:t.pmRoot,subject:t.subject,settings:t.settings,typeRegistry:t.typeRegistry,historyRawBeforeLock:t.historyRawBeforeLock,currentItemRawBeforeLock:t.currentItemRawBeforeLock,operation:t.operation}),w=d;if(l(t.pmRoot,i.loadedItemUnderLock?.document??w,t.subject.id),await t.applyRewrite(i),u(t.pmRoot)){const f=await c(t.pmRoot,t.subject.id,t.settings.id_prefix,t.settings.item_format,t.typeRegistry.type_to_folder),g=f===null?w:(await s(f,{schema:t.settings.schema})).document;b(t.pmRoot,g,t.subject.id)}return t.applyPostRewrite&&o.push(...await t.applyPostRewrite(i)),o}finally{await e()}}export{C as checkHistoryRewriteOwnership,F as executeHistoryRewrite,P as verifyHistoryRewriteNoDrift,N as writeHistoryRawWithRollback};
2
2
  //# sourceMappingURL=history-rewrite.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="9cd23db4-2411-5c95-a6a0-fa30dd3a9a18")}catch{}})();function shouldReplaceExtreme(candidate,current,candidateTieBreaker,currentTieBreaker,direction,tieDirection="min"){const comparison=direction==="min"?candidate-current:current-candidate,tieComparison=tieDirection==="min"?candidateTieBreaker.localeCompare(currentTieBreaker??candidateTieBreaker):(currentTieBreaker??candidateTieBreaker).localeCompare(candidateTieBreaker);return comparison<0||comparison===0&&currentTieBreaker!==null&&tieComparison<0}function parseStreamStat(id,raw){const bytes=Buffer.byteLength(raw,"utf8");let lines=0,oldestTs=null,newestTs=null,oldestMs=Number.POSITIVE_INFINITY,newestMs=Number.NEGATIVE_INFINITY;for(const rawLine of raw.split(/\r?\n/)){const trimmed=rawLine.trim();if(trimmed==="")continue;lines+=1;let parsed;try{parsed=JSON.parse(trimmed)}catch{continue}if(parsed===null||typeof parsed!="object"||!("ts"in parsed)||typeof parsed.ts!="string")continue;const ts=parsed.ts,ms=Date.parse(ts);Number.isNaN(ms)||(shouldReplaceExtreme(ms,oldestMs,ts,oldestTs,"min")&&(oldestMs=ms,oldestTs=ts),shouldReplaceExtreme(ms,newestMs,ts,newestTs,"max","max")&&(newestMs=ms,newestTs=ts))}return{id,bytes,lines,oldest_ts:oldestTs,newest_ts:newestTs}}function computeHistoryStorageStats(streams,options){const rawTopN=options?.topN??5,topN=Math.max(0,Math.floor(rawTopN)),stats=streams.map(({id,raw})=>parseStreamStat(id,raw));let totalLines=0,totalBytes=0,oldestEntry=null,newestEntry=null,globalOldestMs=Number.POSITIVE_INFINITY,globalNewestMs=Number.NEGATIVE_INFINITY;for(const stat of stats){if(totalLines+=stat.lines,totalBytes+=stat.bytes,stat.oldest_ts!==null){const ms=Date.parse(stat.oldest_ts);shouldReplaceExtreme(ms,globalOldestMs,stat.id,oldestEntry?.id??null,"min")&&(globalOldestMs=ms,oldestEntry={id:stat.id,ts:stat.oldest_ts})}if(stat.newest_ts!==null){const ms=Date.parse(stat.newest_ts);shouldReplaceExtreme(ms,globalNewestMs,stat.id,newestEntry?.id??null,"max")&&(globalNewestMs=ms,newestEntry={id:stat.id,ts:stat.newest_ts})}}const largestByBytes=topN===0?[]:[...stats].sort((a,b)=>b.bytes-a.bytes||a.id.localeCompare(b.id)).slice(0,topN),deepestByLines=topN===0?[]:[...stats].sort((a,b)=>b.lines-a.lines||a.id.localeCompare(b.id)).slice(0,topN);return{total_streams:streams.length,total_lines:totalLines,total_bytes:totalBytes,largest_by_bytes:largestByBytes,deepest_by_lines:deepestByLines,oldest_entry:oldestEntry,newest_entry:newestEntry}}export{computeHistoryStorageStats};
1
+ function y(r,c,o,e,l,i="min"){const a=l==="min"?r-c:c-r,m=i==="min"?o.localeCompare(e??o):(e??o).localeCompare(o);return a<0||a===0&&e!==null&&m<0}function _(r,c){const o=Buffer.byteLength(c,"utf8");let e=0,l=null,i=null,a=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY;for(const f of c.split(/\r?\n/)){const N=f.trim();if(N==="")continue;e+=1;let n;try{n=JSON.parse(N)}catch{continue}if(n===null||typeof n!="object"||!("ts"in n)||typeof n.ts!="string")continue;const u=n.ts,p=Date.parse(u);Number.isNaN(p)||(y(p,a,u,l,"min")&&(a=p,l=u),y(p,m,u,i,"max","max")&&(m=p,i=u))}return{id:r,bytes:o,lines:e,oldest_ts:l,newest_ts:i}}function d(r,c){const o=c?.topN??5,e=Math.max(0,Math.floor(o)),l=r.map(({id:t,raw:s})=>_(t,s));let i=0,a=0,m=null,f=null,N=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const t of l){if(i+=t.lines,a+=t.bytes,t.oldest_ts!==null){const s=Date.parse(t.oldest_ts);y(s,N,t.id,m?.id??null,"min")&&(N=s,m={id:t.id,ts:t.oldest_ts})}if(t.newest_ts!==null){const s=Date.parse(t.newest_ts);y(s,n,t.id,f?.id??null,"max")&&(n=s,f={id:t.id,ts:t.newest_ts})}}const u=e===0?[]:[...l].sort((t,s)=>s.bytes-t.bytes||t.id.localeCompare(s.id)).slice(0,e),p=e===0?[]:[...l].sort((t,s)=>s.lines-t.lines||t.id.localeCompare(s.id)).slice(0,e);return{total_streams:r.length,total_lines:i,total_bytes:a,largest_by_bytes:u,deepest_by_lines:p,oldest_entry:m,newest_entry:f}}export{d as computeHistoryStorageStats};
2
2
  //# sourceMappingURL=history-storage-stats.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2e67dcb3-0d34-5884-8b79-5e98458f8c57")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{hasActiveOnWriteHooks,runActiveOnWriteHooks}from"../extensions/index.js";import{ensureDir,pathExists}from"../fs/fs-utils.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{getHistoryPath}from"../store/paths.js";const EXISTENCE_PROBE_CONCURRENCY=64;function toSortedUniqueItemIds(itemIds){return[...new Set(itemIds.filter(value=>value.trim().length>0))].sort((left,right)=>left.localeCompare(right))}function strictMissingStreamError(itemId,commandLabel){return new PmCliError(`Missing history stream for ${itemId}. ${commandLabel} requires history streams when settings.history.missing_stream is strict_error.`,EXIT_CODE.NOT_FOUND)}async function createStream(historyPath,commandLabel){return await ensureDir(path.dirname(historyPath)),await(await fs.open(historyPath,"a")).close(),runActiveOnWriteHooks({path:historyPath,scope:"project",op:`${commandLabel}:history:auto_create`})}async function probeMissingStreams(pmRoot,ids,stopAtFirstMissing){const missing=[];for(let start=0;start<ids.length;start+=EXISTENCE_PROBE_CONCURRENCY){const chunk=ids.slice(start,start+EXISTENCE_PROBE_CONCURRENCY),present=await Promise.all(chunk.map(itemId=>{let historyPath;try{historyPath=getHistoryPath(pmRoot,itemId)}catch{return!1}return pathExists(historyPath)}));if(chunk.forEach((itemId,index)=>{present[index]||missing.push(itemId)}),stopAtFirstMissing&&missing.length>0)break}return missing}async function enforceHistoryStreamPolicyForItem(params){return enforceHistoryStreamPolicyForItems({pmRoot:params.pmRoot,settings:params.settings,itemIds:[params.itemId],commandLabel:params.commandLabel})}async function enforceHistoryStreamPolicyForItems(params){const ids=toSortedUniqueItemIds(params.itemIds),autoCreated=[],warnings=[],sequential=hasActiveOnWriteHooks(),strict=params.settings.history.missing_stream==="strict_error",candidates=sequential?ids:await probeMissingStreams(params.pmRoot,ids,strict);for(const itemId of candidates.length===0?[]:ids){const historyPath=getHistoryPath(params.pmRoot,itemId);if(!await pathExists(historyPath)){if(strict)throw strictMissingStreamError(itemId,params.commandLabel);warnings.push(...await createStream(historyPath,params.commandLabel)),warnings.push(`history_stream_auto_created:${itemId}`),autoCreated.push(itemId)}}return{auto_created_ids:autoCreated,warnings}}export{enforceHistoryStreamPolicyForItem,enforceHistoryStreamPolicyForItems};
1
+ import h from"node:fs/promises";import l from"node:path";import{hasActiveOnWriteHooks as p,runActiveOnWriteHooks as d}from"../extensions/index.js";import{ensureDir as g,pathExists as m}from"../fs/fs-utils.js";import{EXIT_CODE as y}from"../shared/constants.js";import{PmCliError as _}from"../shared/errors.js";import{getHistoryPath as u}from"../store/paths.js";const f=64;function w(t){return[...new Set(t.filter(r=>r.trim().length>0))].sort((r,o)=>r.localeCompare(o))}function E(t,r){return new _(`Missing history stream for ${t}. ${r} requires history streams when settings.history.missing_stream is strict_error.`,y.NOT_FOUND)}async function I(t,r){return await g(l.dirname(t)),await(await h.open(t,"a")).close(),d({path:t,scope:"project",op:`${r}:history:auto_create`})}async function C(t,r,o){const i=[];for(let n=0;n<r.length;n+=f){const c=r.slice(n,n+f),a=await Promise.all(c.map(e=>{let s;try{s=u(t,e)}catch{return!1}return m(s)}));if(c.forEach((e,s)=>{a[s]||i.push(e)}),o&&i.length>0)break}return i}async function L(t){return S({pmRoot:t.pmRoot,settings:t.settings,itemIds:[t.itemId],commandLabel:t.commandLabel})}async function S(t){const r=w(t.itemIds),o=[],i=[],n=p(),c=t.settings.history.missing_stream==="strict_error",a=n?r:await C(t.pmRoot,r,c);for(const e of a.length===0?[]:r){const s=u(t.pmRoot,e);if(!await m(s)){if(c)throw E(e,t.commandLabel);i.push(...await I(s,t.commandLabel)),i.push(`history_stream_auto_created:${e}`),o.push(e)}}return{auto_created_ids:o,warnings:i}}export{L as enforceHistoryStreamPolicyForItem,S as enforceHistoryStreamPolicyForItems};
2
2
  //# sourceMappingURL=history-stream-policy.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d7f91395-3d21-5046-a8df-e383d66eace9")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function hasNewerRecordSealFormat(entry){const version=entry.record_hash_version;return typeof version=="number"&&Number.isInteger(version)&&version>Math.max(...SUPPORTED_HISTORY_RECORD_HASH_VERSIONS)&&typeof entry.record_hash=="string"&&entry.record_hash.length>0}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function isCompleteHistoryRecord(entry){return isRetainedHistoryRecordShape(entry)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
2
- `,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hasNewerRecordSealFormat,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,isCompleteHistoryRecord,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
1
+ import C from"fast-json-patch";import{normalizeHistoryOperationForWrite as Z}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM as ee,historyDigest as p,resolveHistoryHashAlgorithm as b}from"./digest.js";import I from"node:fs/promises";import re from"node:path";import{EXIT_CODE as T,ITEM_METADATA_KEY_ORDER as A}from"../shared/constants.js";import{runActiveServiceOverride as te}from"../extensions/index.js";import{appendLineAtomic as oe}from"../fs/fs-utils.js";import{canonicalDocument as N}from"../item/item-format.js";import{toItemRecord as D}from"../item/item-record.js";import{orderObject as P,sha256Hex as w,stableStringify as c}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime as M,nowIso as ne}from"../shared/time.js";import{diagnoseAgentIdentity as se,resolveHistoryAgentIdentity as ae,resolveHistoryAuthorSource as ie}from"../shared/author.js";import{appendHistoryEntryWithEventIndex as he,removeHistoryEventIndexForHistoryPath as j}from"./event-index.js";import{classifyHistoryEvent as L}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath as E}from"./drift-cache.js";import{PmCliError as F}from"../shared/errors.js";const ce={front_matter:{},body:""},g=3,de=[1,2,3],_e=1,V=[1];function J(e){return p(c(e),e.hash_algorithm)}function u(e){return w(c(e))}function Fe(e){return w(c(e))}function O(e){const r={...e,record_hash_version:_e},{record_hash:t,...o}=r;return{...r,record_hash:J(o)}}function Ve(e){const r=e.record_hash_version;return typeof r=="number"&&Number.isInteger(r)&&r>Math.max(...V)&&typeof e.record_hash=="string"&&e.record_hash.length>0}function Y(e){try{b(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!V.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:r,...t}=e;return J(t)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function fe(e,r){const t={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:u(e.patch)};return e.hash_algorithm!==void 0&&(t.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(t.item_hash_version=e.item_hash_version),r.retainOriginalPatch&&(t.patch=structuredClone(e.patch)),r.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(t.record_hash_version=e.record_hash_version,t.record_hash=e.record_hash,t.record=structuredClone(e)),t}function Je(e,r,t={}){const o=Y(e);if(!o.ok)throw new TypeError(o.error);const n=u(e.patch),s=t.retainPriorRecord===!0||e.before_hash!==r.before_hash||e.after_hash!==r.after_hash||e.item_hash_version!==r.item_hash_version||e.hash_algorithm!==r.hash_algorithm||n!==u(r.patch),i=O({...r,...s?{reanchor_evidence:[...r.reanchor_evidence??[],fe(e,t)]}:{}}),f=ge(i);if(!f.ok)throw new TypeError(f.error);return i}function U(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(r=>!_(r)||typeof r.path!="string"?!1:r.op==="move"||r.op==="copy"?typeof r.from=="string":["add","replace","test"].includes(r.op)?Object.hasOwn(r,"value"):r.op==="remove")}function z(e){return _(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&U(e.patch)}function Ye(e){return z(e)}function ue(e){const r=e.record_hash_version!==void 0,t=e.record_hash!==void 0;return r===t}function me(e){return!_(e)||!ue(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!U(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||z(e.record)}function pe(e){try{for(const r of e){if(!me(r))return!1;b(r.hash_algorithm)}return!0}catch{return!1}}function le(e){const r=e.record;return r!==void 0&&r.before_hash===e.before_hash&&r.after_hash===e.after_hash&&r.item_hash_version===e.item_hash_version&&r.hash_algorithm===e.hash_algorithm&&r.record_hash_version===e.record_hash_version&&r.record_hash===e.record_hash&&u(r.patch)===e.patch_hash}function ye(e,r,t){if(r.patch&&u(r.patch)!==r.patch_hash)return{kind:"patch_hash_mismatch"};if(r.record)return le(r)?{kind:"record",entry:r.record}:{kind:"record_hash_mismatch"};const o=r.patch??e.patch;if(u(o)!==r.patch_hash)return{kind:"digest_only"};const n={...e,before_hash:r.before_hash,after_hash:r.after_hash,patch:o,hash_algorithm:r.hash_algorithm,...r.item_hash_version===void 0?{}:{item_hash_version:r.item_hash_version},...r.record_hash_version===void 0?{}:{record_hash_version:r.record_hash_version},...r.record_hash===void 0?{}:{record_hash:r.record_hash},...t.length===0?{}:{reanchor_evidence:t}};return r.hash_algorithm===void 0&&delete n.hash_algorithm,t.length===0&&delete n.reanchor_evidence,r.item_hash_version===void 0&&delete n.item_hash_version,r.record_hash_version===void 0||r.record_hash===void 0?{kind:"legacy",entry:n}:{kind:"record",entry:n}}function ge(e){const r=e.reanchor_evidence;if(r===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(r)||!pe(r))return{ok:!1,error:"rewrite_evidence_invalid"};if(r.length===0)return{ok:!0,coverage:"none"};let t=e;for(let o=r.length-1;o>=0;o-=1){const n=r[o],s=ye(t,n,r.slice(0,o));if(s.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(s.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(s.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(s.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!Y(s.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};t=s.entry}return{ok:!0,coverage:"complete"}}function H(e,r){return(e??"").localeCompare(r??"")}function $(e,r){return(e??0)-(r??0)}function d(e,r,t){return JSON.stringify(e??t).localeCompare(JSON.stringify(r??t))}function He(e,r){return[e.scope.localeCompare(r.scope),H(e.path,r.path),H(e.command,r.command),$(e.timeout_seconds,r.timeout_seconds),H(e.pm_context_mode,r.pm_context_mode),+!!e.shared_host_safe-+!!r.shared_host_safe,d(e.env_clear,r.env_clear,[]),d(e.env_set,r.env_set,{}),d(e.assert_stdout_contains,r.assert_stdout_contains,[]),d(e.assert_stdout_regex,r.assert_stdout_regex,[]),d(e.assert_stderr_contains,r.assert_stderr_contains,[]),d(e.assert_stderr_regex,r.assert_stderr_regex,[]),$(e.assert_stdout_min_lines,r.assert_stdout_min_lines),d(e.assert_json_field_equals,r.assert_json_field_equals,{}),d(e.assert_json_field_gte,r.assert_json_field_gte,{}),H(e.note,r.note)].find(o=>o!==0)??0}function W(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(r=>r.replaceAll("~1","/").replaceAll("~0","~")):[]}function q(e,r){const t=W(r);if(t.length===0)return!0;let o=e;for(const n of t){const s=/^(0|[1-9]\d*)$/.test(n)?Number(n):-1,i=Array.isArray(o)?s>=0&&s<o.length?o[s]:void 0:_(o)&&Object.prototype.hasOwnProperty.call(o,n)?o[n]:void 0;if(i===void 0)return!1;o=i}return!0}function Re(e,r){const t=[];let o=structuredClone(e);for(const n of r){const s=n.op==="replace"&&!q(o,n.path)?{...n,op:"add"}:n;t.push(s),o=C.applyPatch(o,[s],!0,!0).newDocument}return t}function R(e,r,t=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};const n=N(e),i=r===1||r===2&&t?{...n.metadata,...n.metadata.dependencies===void 0?{}:{dependencies:n.metadata.dependencies.map(h=>({...h,id:h.id.toLowerCase()}))},...n.metadata.tests===void 0?{}:{tests:n.metadata.tests.map(({workspace_context_mode:h,provenance:m,provenance_invalid:l,...y})=>y)},...n.metadata.test_runs===void 0?{}:{test_runs:n.metadata.test_runs.map(({executions:h,...m})=>m)}}:n.metadata,f=r===1&&i.tests?{...i,tests:[...i.tests].sort(He)}:i;return{front_matter:P(D(f),A),body:n.body}}function G(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};const t=N(e);return{metadata:P(D(t.metadata),A),body:t.body}}function Ue(e){return B(e,g)}function B(e,r,t){if(!de.some(o=>o===r))throw new TypeError(`unsupported_item_hash_version:${String(r)}`);return p(c(R(e,r)),t)}function ze(e,r,t){const o=B(e,r,t);return r===2?[o,p(c(R(e,r,!0)),t)]:[o]}function $e(){return w(c(ce))}function We(e){const r=Z(e.op),t=R(e.before,g),o=R(e.after,g),n=G(e.before),s=G(e.after),i=C.compare(n,s),f=Re(n,i),a=ae(e.author),h=a.harness?Object.fromEntries(Object.entries(se().provenance_outcomes).filter(([Q,S])=>S.resolver!==void 0&&(S.status!=="resolved"||a.provenance?.[Q]?.source==="probe"))):void 0,m=h===void 0||Object.keys(h).length===0?e.context:{...e.context,agent_provenance_outcomes:h},l=e.hashAlgorithm??ee,y={hash_algorithm:l,ts:e.nowIso,author:e.author,author_source:e.authorSource??ie(e.author),...a.harness?{agent_harness:a.harness}:{},...a.model?{agent_model:a.model}:{},...a.model_source?{agent_model_source:a.model_source}:{},...a.instance?{agent_instance:a.instance}:{},...a.provenance?{agent_provenance:a.provenance}:{},...a.episode?{agent_episode:a.episode}:{},op:r,patch:f,before_hash:p(c(t),l),after_hash:p(c(o),l),item_hash_version:g,message:e.message===void 0?void 0:e.message,...m===void 0?{}:{context:m}};return O({...y,event_class:L(y)})}function _(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e){return new F(e,T.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function X(e){const r=e.ts.trim();if(r.length===0)return ne();if(!M(r))throw x("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(r!==e.ts)throw x("History timestamp must not contain surrounding whitespace");return e.ts}function K(e,r){const t=e.ts;if(typeof t=="string"&&t.trim().length>0){if(!M(t))throw x("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:r}}function v(e,r){const t=X(r);if(typeof e=="string"){let o;try{o=JSON.parse(e)}catch{return e}return _(o)?JSON.stringify(K(o,t)):e}return _(e)?JSON.stringify(K(e,t)):JSON.stringify(e)}async function be(e,r,t){if(t===!1)return!0;if(typeof t=="string"){const i=v(t,r);return await k(e,i),await E(e),await j(e),!0}if(typeof t!="object"||t===null)return!1;const o=t;if(o.skip===!0)return!0;const n=typeof o.history_path=="string"?o.history_path:e,s=v(typeof o.line=="string"?o.line:o.entry??r,r);return await k(n,s),await E(n),await j(n),!0}async function k(e,r){let t;try{t=JSON.parse(r)}catch{t=null}if(!_(t)||t.op!=="create"){await oe(e,r);return}await I.mkdir(re.dirname(e),{recursive:!0});try{await I.writeFile(e,`${r}
2
+ `,{encoding:"utf8",flag:"wx"})}catch(o){throw o.code!=="EEXIST"?o:new F("This item identity is reserved by an existing history stream.",T.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function qe(e,r){const t=await te("history_append",{history_path:e,entry:r});if(t.handled&&await be(e,r,t.result))return;const o=r.ts.trim().length>0?r:{...r,ts:X(r)},n=O({...o,hash_algorithm:b(o.hash_algorithm),event_class:L(o)});await he(e,n,async()=>{await k(e,v(n,n))}),await E(e)}const Ge={decodeJsonPointer:W,isDefinedPointerPath:q};export{g as CURRENT_HISTORY_ITEM_HASH_VERSION,_e as CURRENT_HISTORY_RECORD_HASH_VERSION,de as SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,V as SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,Ge as _testOnly,qe as appendHistoryEntry,We as createHistoryEntry,Ve as hasNewerRecordSealFormat,Ue as hashDocument,B as hashDocumentForVersion,ze as hashDocumentVerificationCandidates,$e as hashEmptyDocument,u as hashHistoryPatch,J as hashHistoryRecord,Fe as hashHistoryStream,Ye as isCompleteHistoryRecord,Je as resealHistoryRewrite,O as sealHistoryRecord,Y as verifyHistoryRecordHash,ge as verifyHistoryRewriteEvidence};
3
3
  //# sourceMappingURL=history.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function findHistoryIdentityDiscontinuities(entries){const findings=[],checkpoint=entries[0]?.op==="history_compact_baseline";let genesis=checkpoint?1:void 0,deleted=!1;for(const[index,entry]of entries.entries())entry.op==="delete"&&(deleted=!0),entry.op==="create"&&(genesis!==void 0&&findings.push({prior_genesis_index:genesis,repeated_create_index:index+1,sequence:deleted?"delete_then_create":checkpoint?"checkpoint_then_create":"multiple_creates"}),genesis??=index+1,deleted=!1);return findings}export{findHistoryIdentityDiscontinuities};
1
+ function r(n){const i=[],c=n[0]?.op==="history_compact_baseline";let e=c?1:void 0,t=!1;for(const[o,s]of n.entries())s.op==="delete"&&(t=!0),s.op==="create"&&(e!==void 0&&i.push({prior_genesis_index:e,repeated_create_index:o+1,sequence:t?"delete_then_create":c?"checkpoint_then_create":"multiple_creates"}),e??=o+1,t=!1);return i}export{r as findHistoryIdentityDiscontinuities};
2
2
  //# sourceMappingURL=identity.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2a41f316-31f0-5115-be8b-957da9e233ad")}catch{}})();export*from"./history.js";
1
+ export*from"./history.js";
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();const PM_ITEM_HISTORY_OPERATIONS=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],PM_WORKSPACE_HISTORY_OPERATIONS=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default","transaction_abandon"],PM_HISTORY_OPERATION_ALIASES={"init:type-preset":"init:type_preset"},PM_HISTORY_OPERATION_PATTERNS=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],PM_HISTORY_OPERATION_CONTRACT={version:1,item:PM_ITEM_HISTORY_OPERATIONS,workspace:PM_WORKSPACE_HISTORY_OPERATIONS,aliases:PM_HISTORY_OPERATION_ALIASES,patterns:PM_HISTORY_OPERATION_PATTERNS,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},declared=new Set([...PM_ITEM_HISTORY_OPERATIONS,...PM_WORKSPACE_HISTORY_OPERATIONS]),patterns=PM_HISTORY_OPERATION_PATTERNS.map(pattern=>new RegExp(pattern,"u"));function resolveHistoryOperation(operation){return Object.hasOwn(PM_HISTORY_OPERATION_ALIASES,operation)?PM_HISTORY_OPERATION_ALIASES[operation]:operation}function requireHistoryOperation(operation){const canonical=resolveHistoryOperation(operation);if(declared.has(canonical)||patterns.some(pattern=>pattern.test(canonical)))return canonical;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function normalizeHistoryOperationForWrite(operation){const canonical=resolveHistoryOperation(operation),colon=canonical.indexOf(":"),prefix=colon<0?canonical:canonical.slice(0,colon),validSuffix=colon<0||colon<canonical.length-1&&!/[\s\p{C}]/u.test(canonical.slice(colon+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(prefix)&&validSuffix)return canonical;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}export{PM_HISTORY_OPERATION_ALIASES,PM_HISTORY_OPERATION_CONTRACT,PM_HISTORY_OPERATION_PATTERNS,PM_ITEM_HISTORY_OPERATIONS,PM_WORKSPACE_HISTORY_OPERATIONS,normalizeHistoryOperationForWrite,requireHistoryOperation,resolveHistoryOperation};
1
+ const o=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],s=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default","transaction_abandon"],r={"init:type-preset":"init:type_preset"},n=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],m={version:1,item:o,workspace:s,aliases:r,patterns:n,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},c=new Set([...o,...s]),l=n.map(t=>new RegExp(t,"u"));function p(t){return Object.hasOwn(r,t)?r[t]:t}function d(t){const e=p(t);if(c.has(e)||l.some(a=>a.test(e)))return e;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function u(t){const e=p(t),a=e.indexOf(":"),i=a<0?e:e.slice(0,a),_=a<0||a<e.length-1&&!/[\s\p{C}]/u.test(e.slice(a+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(i)&&_)return e;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}export{r as PM_HISTORY_OPERATION_ALIASES,m as PM_HISTORY_OPERATION_CONTRACT,n as PM_HISTORY_OPERATION_PATTERNS,o as PM_ITEM_HISTORY_OPERATIONS,s as PM_WORKSPACE_HISTORY_OPERATIONS,u as normalizeHistoryOperationForWrite,d as requireHistoryOperation,p as resolveHistoryOperation};
2
2
  //# sourceMappingURL=operation-contract.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cd7d3a47-d37a-55f4-aa60-4fc3ea08d528")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,verifyHistoryChainWithVersion,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function unreconstructableHistoryVersion(targetIndex,liveBridge){return new PmCliError(`History entry ${targetIndex+1} lies between an unrecorded change and the record that repaired it, so its historical state cannot be reconstructed.`,EXIT_CODE.USAGE,{code:"history_version_unreconstructable",required:liveBridge?"Choose a version before the bridged break or from its bridge onward.":"Choose a version whose record is not marked replay_inexact.",nextSteps:[liveBridge?"Run pm history <id> --full to find the bridge record and the versions around it.":"Run pm history <id> --full and pick a version whose record has no replay_inexact marker."]})}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}if(history[targetIndex]?.replay_inexact===!0)throw unreconstructableHistoryVersion(targetIndex,!1);const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok){const bridged=verifyHistoryChainWithVersion([...history]);throw bridged.ok&&bridged.bridged_segments?.some(segment=>segment.start<=targetIndex&&targetIndex<segment.end)?unreconstructableHistoryVersion(targetIndex,!0):new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]})}return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
1
+ import{EXIT_CODE as a}from"../shared/constants.js";import{PmCliError as c}from"../shared/errors.js";import{historyVersionOffset as f}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT as h,verifyHistoryChain as v,verifyHistoryChainWithVersion as g,tryApplyReplayPatch as y}from"./replay.js";function w(i,e){let o=-1;return i.forEach((r,t)=>{const s=Date.parse(r.ts);if(!Number.isFinite(s))throw new c(`History for this item contains invalid timestamp at entry ${t+1}.`,a.GENERIC_FAILURE);s<=e&&(o=t)}),o}function _(i,e){const o=i[0]?.ts??null,r=i.at(-1)?.ts??null,t={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:o,last_timestamp:r}};return r!==null&&(t.examples=[r],e!==null&&(t.examples.unshift(String(e+1),String(e+i.length)),t.valid_range.first_version=e+1,t.valid_range.last_version=e+i.length)),{guidance:t,lastTimestamp:r}}function E(i,e){const o={};if(e instanceof Error&&e.message.trim().length>0&&(o.reason=e.message.trim()),typeof e!="object"||e===null)return o;const r=e;if(typeof r.index=="number"&&Number.isInteger(r.index)&&r.index>=0&&(o.patchIndex=r.index),typeof r.operation=="object"&&r.operation!==null){const t=r.operation;Object.assign(o,Object.fromEntries(["op","path","from"].flatMap(s=>{const n=t[s];return typeof n=="string"?[[s,n]]:[]})))}if(o.patchIndex!==void 0){const t=i[o.patchIndex];t&&(o.op??=t.op,o.path??=t.path,o.from??=t.from)}return o}function A(i,e,o={}){const r=i.trim(),t=o.errorSubject??"history",s=t==="restore"?"Restore":"History",{guidance:n,lastTimestamp:l}=_(e,f(e,!0));if(!r)throw new c(`Missing ${t} target. Use a timestamp or version number.`,a.USAGE,n);if(/^\d+$/.test(r)){const d=f(e),p=Number(r);if(p>=1&&p<=d)throw new c(`History version ${p} was pruned by compaction.`,a.USAGE,{...n,code:"history_version_pruned"});if(!Number.isSafeInteger(p)||p<1||p>d+e.length)throw new c(`${s} version must be between ${d+1} and ${d+e.length} for this item.`,a.USAGE,n);return{kind:"version",raw:r,historyIndex:p-d-1}}const m=Date.parse(r);if(!Number.isFinite(m))throw new c(`Invalid ${t} target "${i}". Use a positive version number or ISO timestamp.`,a.USAGE,n);const u=w(e,m);if(u<0||o.allowFutureTimestamp!==!0&&m>Date.parse(l))throw new c(t==="restore"?`No history entries exist at or before timestamp ${r}.`:`No history entry exists at timestamp ${r}.`,a.USAGE,n);return{kind:"timestamp",raw:r,historyIndex:u}}function x(i,e,o,r){const t=y(i,e);if(t.ok)return t.document;const s=E(e,t.error),n=[`history_op=${r}`,s.patchIndex===void 0?null:`patch_index=${s.patchIndex}`,s.op?`op=${s.op}`:null,s.path?`path=${s.path}`:null,s.from?`from=${s.from}`:null].filter(l=>l!==null);throw new c(`Failed to apply history patch at entry ${o} (${n.join(", ")}). ${s.reason??String(t.error)}`,a.GENERIC_FAILURE)}function b(i,e){return new c(`History entry ${i+1} lies between an unrecorded change and the record that repaired it, so its historical state cannot be reconstructed.`,a.USAGE,{code:"history_version_unreconstructable",required:e?"Choose a version before the bridged break or from its bridge onward.":"Choose a version whose record is not marked replay_inexact.",nextSteps:[e?"Run pm history <id> --full to find the bridge record and the versions around it.":"Run pm history <id> --full and pick a version whose record has no replay_inexact marker."]})}function H(i,e){const o=i[0];if(o&&o.op!=="create"&&o.op!=="history_compact_baseline"){const n=y(h,o.patch);if(!n.ok||typeof n.document.metadata.id!="string")throw new c("History starts without a reconstructable item baseline.",a.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}if(i[e]?.replay_inexact===!0)throw b(e,!1);const r=i.slice(0,e+1),t=v([...r]);let s=structuredClone(h);for(let n=0;n<=e;n+=1){const l=i[n];if(!l)throw new c(`History target entry ${n+1} does not exist.`,a.USAGE);s=x(s,l.patch,n+1,l.op)}if(!t.ok){const n=g([...i]);throw n.ok&&n.bridged_segments?.some(l=>l.start<=e&&e<l.end)?b(e,!0):new c(`History cannot be replayed: ${t.errors.join(", ")}.`,a.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:t.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]})}return s}function T(i,e){if(Object.keys(i.metadata).length>0){if(typeof i.metadata.id!="string"||!Array.isArray(i.metadata.tags))throw new c("History has no complete item baseline for this target.",a.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return i}throw new c(`History target ${e.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,a.USAGE)}export{x as applyHistoryPatch,T as ensureMaterializedHistoryTarget,E as extractPatchFailureContext,H as replayHistoryToTarget,A as resolveHistoryTarget};
2
2
  //# sourceMappingURL=projection.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2560e353-1428-540b-bf0b-3c157bdb3b3b")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error});return decodeHistorySnapshot(historyPath,itemId,rawBytes)}async function readIdentifiedHistorySnapshot(historyPath,itemId){const handle=await fs.open(historyPath,"r").catch(error=>{if(isFileAbsentError(error))return null;throw error});if(handle===null)return{...await decodeHistorySnapshot(historyPath,itemId,null),source:null};try{const source=await handle.stat({bigint:!0}),rawBytes=await handle.readFile();return{...await decodeHistorySnapshot(historyPath,itemId,rawBytes),source}}finally{await handle.close()}}async function decodeHistorySnapshot(historyPath,itemId,rawBytes){const raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}const defect=describeHistoryRecordDefect(parsed);if(defect!==null)throw new PmCliError(`History for ${itemId} holds ${defect} at line ${index+1}, which is not a history record. Remove or restore the line and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_record_invalid",item_id:itemId,reason:defect,details:{line:index+1},required:"Every history line must be one JSON object record.",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run: it removes a line that cannot hold a record (a JSON null, boolean or number) and keeps every record.`,"Otherwise recover the line from version control or a backup."]});entries.push(parsed)}return{raw,raw_bytes:rawBytes,entries}}function describeHistoryRecordDefect(value){return value===null?"a JSON null":Array.isArray(value)?"a JSON array":typeof value=="object"?null:`a JSON ${typeof value}`}function isNonRecordScalar(value){return value===null||typeof value=="boolean"||typeof value=="number"}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{describeHistoryRecordDefect,isNonRecordScalar,readHistoryEntries,readHistorySnapshot,readIdentifiedHistorySnapshot};
1
+ import y from"node:fs/promises";import{isFileAbsentError as p}from"../fs/fs-utils.js";import{runActiveOnReadHooks as m}from"../extensions/index.js";import{EXIT_CODE as c}from"../shared/constants.js";import{findFirstMergeConflictMarker as w}from"../shared/conflict-markers.js";import{PmCliError as l}from"../shared/errors.js";async function b(r,e){const n=await y.readFile(r).catch(t=>{if(p(t))return null;throw t});return f(r,e,n)}async function N(r,e){const n=await y.open(r,"r").catch(t=>{if(p(t))return null;throw t});if(n===null)return{...await f(r,e,null),source:null};try{const t=await n.stat({bigint:!0}),o=await n.readFile();return{...await f(r,e,o),source:t}}finally{await n.close()}}async function f(r,e,n){const t=n?.toString("utf8")??null;if(t===null)return{raw:t,raw_bytes:n,entries:[]};if(await m({path:r,scope:"project"}),t.trim()==="")return{raw:t,raw_bytes:n,entries:[]};const o=w(t);if(o)throw new l(`History for ${e} contains merge conflict markers at line ${o.line} (${o.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,c.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${e}`,`pm restore ${e} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const u=[];for(const[i,h]of t.split(/\r?\n/).entries()){const d=h.trim();if(!d)continue;let a;try{a=JSON.parse(d)}catch{throw new l(`History for ${e} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,c.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${e} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}const s=R(a);if(s!==null)throw new l(`History for ${e} holds ${s} at line ${i+1}, which is not a history record. Remove or restore the line and retry.`,c.GENERIC_FAILURE,{code:"history_record_invalid",item_id:e,reason:s,details:{line:i+1},required:"Every history line must be one JSON object record.",nextSteps:[`Run pm history-repair ${e} --salvage-tail --dry-run: it removes a line that cannot hold a record (a JSON null, boolean or number) and keeps every record.`,"Otherwise recover the line from version control or a backup."]});u.push(a)}return{raw:t,raw_bytes:n,entries:u}}function R(r){return r===null?"a JSON null":Array.isArray(r)?"a JSON array":typeof r=="object"?null:`a JSON ${typeof r}`}function g(r){return r===null||typeof r=="boolean"||typeof r=="number"}async function x(r,e){return(await b(r,e)).entries}export{R as describeHistoryRecordDefect,g as isNonRecordScalar,x as readHistoryEntries,b as readHistorySnapshot,N as readIdentifiedHistorySnapshot};
2
2
  //# sourceMappingURL=read.js.map
@@ -1,4 +1,4 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b329322c-71f1-57f9-b678-5e1166ecb938")}catch{}})();import jsonPatch from"fast-json-patch";import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{digestBridgedSegment,findNextHistoryBridge,locateBridgedSegments,matchesHistoryBreak,readHistoryBridge}from"./bridge.js";import{ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,stableStringify}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates,isCompleteHistoryRecord,resealHistoryRewrite,verifyHistoryRecordHash,verifyHistoryRewriteEvidence}from"./history.js";const EMPTY_REPLAY_DOCUMENT={metadata:{},body:""};function cloneEmptyReplayDocument(){return structuredClone(EMPTY_REPLAY_DOCUMENT)}function replayHash(document,version=CURRENT_HISTORY_ITEM_HASH_VERSION,algorithm){return replayHashVerificationCandidates(document,version,algorithm)[0]}function replayHashVerificationCandidates(document,version,algorithm){if(Object.keys(document.metadata).length===0||Array.isArray(document.metadata.tags))try{return hashDocumentVerificationCandidates(replayToItemDocument(document),version,algorithm)}catch{}const fallback=historyDigest(stableStringify({replay_fallback:!0,metadata:document.metadata,body:document.body}),algorithm);return version===2?[fallback,fallback]:[fallback]}function matchReplayHashCandidates(before,after,version,entry,memo){const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),memoKey=`${version}:${algorithm}`,beforeHashes=memo?.before.get(memoKey)??replayHashVerificationCandidates(before,version,algorithm),afterHashes=replayHashVerificationCandidates(after,version,algorithm);return memo?.after.set(memoKey,afterHashes),{beforeHashes,afterHashes,pairIndex:beforeHashes.findIndex((beforeHash,hashIndex)=>beforeHash===entry.before_hash&&afterHashes[hashIndex]===entry.after_hash),beforeIndex:beforeHashes.indexOf(entry.before_hash),afterIndex:afterHashes.indexOf(entry.after_hash)}}function replayToItemDocument(document){return{metadata:document.metadata,body:document.body}}function replayToCanonicalItemDocument(document,options={}){return canonicalDocument(replayToItemDocument(document),options)}function toReplayDocument(document){if(!document.metadata||Object.keys(document.metadata).length===0)return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function normalizeReplayPatchPath(path){return path==="/front_matter"?"/metadata":path.startsWith("/front_matter/")?`/metadata/${path.slice(14)}`:path}function isHistoryPatchOp(value){return typeof value=="object"&&value!==null&&typeof value.op=="string"&&typeof value.path=="string"}function normalizeReplayPatchOps(patch){return Array.isArray(patch)?patch.filter(isHistoryPatchOp).map(operation=>({...operation,...(operation.op==="add"||operation.op==="replace")&&Object.hasOwn(operation,"value")?{value:structuredClone(operation.value)}:{},path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})):[]}function isReplayDocumentShape(value){return typeof value=="object"&&value!==null&&"metadata"in value&&"body"in value&&typeof value.body=="string"&&typeof value.metadata=="object"&&value.metadata!==null}function tryApplyReplayPatch(current,patch){try{const normalizedPatch=normalizeReplayPatchOps(patch),applied=jsonPatch.applyPatch(structuredClone(current),normalizedPatch,!0,!0).newDocument;return isReplayDocumentShape(applied)?{ok:!0,document:{metadata:applied.metadata,body:applied.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(error){return{ok:!1,error}}}function supportedExplicitHistoryItemHashVersions(entries){return[...new Set(entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)))]}function isUnsupportedExplicitHistoryItemHashVersion(version){return version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(version)}function historyEntryHashCandidates(explicitVersion,authoritativeVersion){return explicitVersion!==void 0?[explicitVersion]:authoritativeVersion===void 0?[...SUPPORTED_HISTORY_ITEM_HASH_VERSIONS]:[authoritativeVersion]}function historyEntryIntegrityError(entry){const recordVerification=verifyHistoryRecordHash(entry);if(!recordVerification.ok)return recordVerification.error;const rewriteVerification=verifyHistoryRewriteEvidence(entry);return rewriteVerification.ok?void 0:rewriteVerification.error}function verifyHistoryEntryInput(entry,replay){const integrityError=historyEntryIntegrityError(entry);if(integrityError)return{ok:!1,error:integrityError};const applied=tryApplyReplayPatch(replay,entry.patch);return applied.ok?{ok:!0,document:applied.document}:{ok:!1,error:"patch_apply_failed"}}function assertHistoryEntryIntegrity(entry,index){const integrityError=historyEntryIntegrityError(entry);if(integrityError)throw new TypeError(`${integrityError}:entry_${index+1}`)}function matchReplayEpochCandidates(before,after,candidates,entry,memo){const matches=[];for(const version of candidates){const match=matchReplayHashCandidates(before,after,version,entry,memo);if(matches.push({version,match}),match.pairIndex>=0)break}return matches}function isBridgeableRecord(entry){if(!isCompleteHistoryRecord(entry))return!1;let length;try{length=resolveHistoryHashAlgorithm(entry.hash_algorithm)==="sha512"?128:64}catch{return!1}const digest=new RegExp(`^[a-f0-9]{${length}}$`,"u");return!digest.test(entry.before_hash)||!digest.test(entry.after_hash)?!1:!entry.patch.filter(isHistoryPatchOp).map(operation=>({op:operation.op,path:normalizeReplayPatchPath(operation.path),from:typeof operation.from=="string"?normalizeReplayPatchPath(operation.from):void 0})).every(operation=>isEffectFreeOperation(operation))||entry.before_hash===entry.after_hash||Object.hasOwn(entry,"bridge")}function isEffectFreeOperation(operation){return operation.op==="test"?!0:operation.from!==operation.path?!1:operation.op==="move"||operation.op==="copy"&&!/\/(?:\d+|-)$/u.test(operation.path)}const BRIDGED_SEGMENT_EPOCHS=new WeakMap;function openBridgedSegment(entries,index){if(index===0||!isBridgeableRecord(entries[index]))return;const closer=findNextHistoryBridge(entries,index);if(closer<0)return;const bridge=readHistoryBridge(entries[closer]);if(!(typeof bridge!="object"||!matchesHistoryBreak(bridge.breaks[0],entries[index-1],entries[index])))return{start:index,closer,bridge,next:1}}function verifyBridgedInteriorEntry(entries,index,segment,replay,candidates){const entry=entries[index],previous=entries[index-1];if(!isBridgeableRecord(entry))return{ok:!1,error:"record_incomplete"};const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return input;const matches=candidates.map(version=>matchReplayHashCandidates(replay,input.document,version,entry));return matches.some(match=>match.beforeIndex>=0)&&!matches.some(match=>match.pairIndex>=0)?{ok:!1,error:"after_hash_mismatch"}:entry.before_hash===previous.after_hash?input:matchesHistoryBreak(segment.bridge.breaks[segment.next],previous,entry)?(segment.next+=1,input):{ok:!1,error:"bridge_unnamed_break"}}function verifyBridgeCloser(entries,index,segment,replay,candidates){const entry=entries[index];if(!isBridgeableRecord(entry))return{ok:!1,error:"record_incomplete"};const input=verifyHistoryEntryInput(entry,replay);if(!input.ok)return input;if(segment.next!==segment.bridge.breaks.length)return{ok:!1,error:"bridge_names_absent_break"};if(entry.before_hash!==entries[index-1].after_hash)return{ok:!1,error:"bridge_link_mismatch"};if(digestBridgedSegment(entries.slice(segment.start,index),entry)!==segment.bridge.segment_digest)return{ok:!1,error:"bridge_segment_mismatch"};const algorithm=resolveHistoryHashAlgorithm(entry.hash_algorithm),version=candidates.find(candidate=>replayHashVerificationCandidates(input.document,candidate,algorithm).includes(entry.after_hash));return version===void 0?{ok:!1,error:"bridge_after_hash_mismatch"}:{ok:!0,document:input.document,version}}function acceptHistoryEpoch(walk,entry,version,document,memo){walk.replay=document,walk.beforeHashMemo=memo,walk.detectedVersion=version,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion}function stepBridgedSegment(entries,index,walk){const segment=walk.segment,entry=entries[index];if(index===segment.closer&&walk.authoritativeExplicitVersion!==void 0&&entry.item_hash_version!==walk.authoritativeExplicitVersion)return"bridge_epoch_mismatch";const bridged=(index<segment.closer?verifyBridgedInteriorEntry:verifyBridgeCloser)(entries,index,segment,walk.replay,historyEntryHashCandidates(entry.item_hash_version,walk.authoritativeExplicitVersion));if(!bridged.ok)return bridged.error;if(bridged.version===void 0){walk.replay=bridged.document,walk.beforeHashMemo=new Map,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion;return}const closed={start:segment.start,end:index};BRIDGED_SEGMENT_EPOCHS.set(closed,bridged.version),walk.bridgedSegments.push(closed),walk.segment=void 0,acceptHistoryEpoch(walk,entry,bridged.version,bridged.document,new Map)}function stepAnchoredEntry(entries,index,walk,unsupportedVersion){const entry=entries[index];if(Object.hasOwn(entry,"bridge"))return"bridge_without_break";const input=verifyHistoryEntryInput(entry,walk.replay);if(!input.ok)return input.error;if(unsupportedVersion){walk.replay=input.document,walk.beforeHashMemo=new Map,walk.detectedVersion=void 0,walk.authoritativeExplicitVersion=void 0;return}const memo={before:walk.beforeHashMemo,after:new Map},candidateMatches=matchReplayEpochCandidates(walk.replay,input.document,historyEntryHashCandidates(entry.item_hash_version,walk.authoritativeExplicitVersion),entry,memo),matching=candidateMatches.find(({match})=>match.pairIndex>=0);if(matching!==void 0){acceptHistoryEpoch(walk,entry,matching.version,input.document,memo.after);return}const beforeMatches=candidateMatches.some(({match})=>match.beforeIndex>=0);if(walk.segment=beforeMatches?void 0:openBridgedSegment(entries,index),walk.segment===void 0)return`${beforeMatches?"after":"before"}_hash_mismatch`;walk.replay=input.document,walk.beforeHashMemo=new Map,walk.authoritativeExplicitVersion=entry.item_hash_version??walk.authoritativeExplicitVersion}function verifyHistoryChainWithVersion(entries){const walk={replay:cloneEmptyReplayDocument(),beforeHashMemo:new Map,bridgedSegments:[]},errors=findHistoryIdentityDiscontinuities(entries).map(finding=>`verify_failed:duplicate_create:entry_${finding.repeated_create_index}:prior_${finding.prior_genesis_index}`),finish=(ok,details)=>({ok,errors:ok?[]:errors,...details,...walk.bridgedSegments.length===0?{}:{bridged_segments:walk.bridgedSegments}}),failure=(error,index)=>(errors.push(`verify_failed:${error}:entry_${index+1}`),finish(!1,{})),invalidBridge=entries.findIndex(entry=>readHistoryBridge(entry)==="invalid");if(invalidBridge>=0)return failure("bridge_invalid",invalidBridge);for(let index=0;index<entries.length;index+=1){const explicitVersion=entries[index].item_hash_version,unsupportedVersion=isUnsupportedExplicitHistoryItemHashVersion(explicitVersion);unsupportedVersion&&errors.push(`verify_failed:unsupported_item_hash_version:${String(explicitVersion)}:entry_${index+1}`);const error=walk.segment===void 0?stepAnchoredEntry(entries,index,walk,unsupportedVersion):stepBridgedSegment(entries,index,walk);if(error!==void 0)return failure(error,index)}return finish(errors.length===0,walk.detectedVersion===void 0?{}:{item_hash_version:walk.detectedVersion})}function verifyHistoryChain(entries){const result=verifyHistoryChainWithVersion(entries);return{ok:result.ok,errors:result.errors}}function isObjectRoot(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function tryApplySingleOp(document,op,requireObjectRoot){try{const applied=jsonPatch.applyPatch(structuredClone(document),[op],!0,!1).newDocument;return requireObjectRoot&&!isObjectRoot(applied)?{ok:!1}:{ok:!0,document:applied}}catch{return{ok:!1}}}function applyPatchLeniently(current,patch,requireObjectRoot){let working=structuredClone(current),convertedReplaceToAdd=0,skippedOps=0;for(const op of normalizeReplayPatchOps(patch)){const direct=tryApplySingleOp(working,op,requireObjectRoot);if(direct.ok){working=direct.document;continue}if(op.op==="replace"){const asAdd=tryApplySingleOp(working,{...op,op:"add"},requireObjectRoot);if(asAdd.ok){working=asAdd.document,convertedReplaceToAdd+=1;continue}}skippedOps+=1}return{working,convertedReplaceToAdd,skippedOps}}function lenientApplyReplayPatch(current,patch,operation){const first=applyPatchLeniently(current,patch,!1);if(!isObjectRoot(first.working)&&operation==="delete")return{document:{metadata:{},body:""},convertedReplaceToAdd:first.convertedReplaceToAdd,skippedOps:first.skippedOps};const{working,convertedReplaceToAdd,skippedOps}=isObjectRoot(first.working)?first:applyPatchLeniently(current,patch,!0),candidate=working;return{document:{metadata:typeof candidate.metadata=="object"&&candidate.metadata!==null?candidate.metadata:{},body:typeof candidate.body=="string"?candidate.body:current.body},convertedReplaceToAdd,skippedOps}}function resolveHistoryRepairItemHashVersion(entries){const explicitVersions=supportedExplicitHistoryItemHashVersions(entries);if(explicitVersions.length===1)return explicitVersions[0];const verified=verifyHistoryChainWithVersion(entries);return verified.ok&&verified.item_hash_version!==void 0?verified.item_hash_version:explicitVersions.length===0?1:CURRENT_HISTORY_ITEM_HASH_VERSION}function applyReanchorPatch(replay,entry,projectedPatch=entry.patch){const strict=tryApplyReplayPatch(replay,projectedPatch);if(strict.ok)return{next:strict.document,patch:projectedPatch,repaired:stableStringify(projectedPatch)!==stableStringify(entry.patch),converted:0,skipped:0};const lenient=lenientApplyReplayPatch(replay,projectedPatch,entry.op);return{next:lenient.document,patch:jsonPatch.compare(replay,lenient.document),repaired:!0,converted:lenient.convertedReplaceToAdd,skipped:lenient.skippedOps}}function applyProjectedReanchorPatch(replay,entry,options){return applyReanchorPatch(replay,entry,options.projectPatch?.(entry,replay))}function indexBridgedSegments(entries,options,itemHashVersion,explicitItemHashVersion){const verification=verifyHistoryChainWithVersion(entries),verified=options.projectPatch===void 0&&options.continuousHashSurface!==!0?(verification.bridged_segments??[]).filter(segment=>BRIDGED_SEGMENT_EPOCHS.get(segment)===itemHashVersion&&(!explicitItemHashVersion||entries[segment.end].item_hash_version===itemHashVersion)&&entries.slice(segment.start,segment.end+1).every(entry=>entry.item_hash_version===void 0||entry.item_hash_version===itemHashVersion)):[];return{inputVerifies:verification.ok,preservable:new Map(verified.map(segment=>[segment.start,segment.end])),inexact:collectBridgedInteriorIndexes(options.callerMarksBridgeCoverage===!0?[]:locateBridgedSegments(entries).segments)}}function collectBridgedInteriorIndexes(segments){const interior=new Set;for(const{start,end,exact}of segments){const last=exact===!1?end:end-1;for(let index=start;index<=last;index+=1)interior.add(index)}return interior}function markHistoryEntryInexact(entry){return resealHistoryRewrite(entry,{...entry,replay_inexact:!0},{retainPriorRecord:!0,retainPriorRecordHash:!1})}function materializeBridgedSegments(entries){const interior=collectBridgedInteriorIndexes(locateBridgedSegments(entries).segments);return entries.map((entry,index)=>interior.has(index)&&entry.replay_inexact!==!0?markHistoryEntryInexact(entry):entry)}function keepBridgedSegment(entries,start,end,replay,rewritten,details){let current=replay;for(let index=start;index<=end;index+=1){const kept=entries[index],applied=tryApplyReplayPatch(current,kept.patch);if(!applied.ok)throw new TypeError(`patch_apply_failed:entry_${index+1}`);current=applied.document,rewritten.push(kept),details.push({index:index+1,rehashed:!1,patch_repaired:!1,converted_replace_to_add:0,skipped_ops:0})}return current}function finalizeReanchoredEntry(entry,rewrittenEntry,flags){flags.itemHashVersion===void 0?delete rewrittenEntry.item_hash_version:rewrittenEntry.item_hash_version=flags.itemHashVersion,flags.inexact&&(rewrittenEntry.replay_inexact=!0);const bridgeDissolved=Object.hasOwn(entry,"bridge");delete rewrittenEntry.bridge;const unbridged=bridgeDissolved||rewrittenEntry.replay_inexact!==entry.replay_inexact,changed=flags.rehashed||flags.patchRepaired||unbridged||rewrittenEntry.item_hash_version!==entry.item_hash_version;return{changed,persist:flags.inputVerifies?unbridged:changed,anchorsChanged:flags.rehashed||flags.patchRepaired,entry:changed?resealHistoryRewrite(entry,rewrittenEntry,{retainOriginalPatch:flags.patchRepaired,retainPriorRecord:bridgeDissolved}):rewrittenEntry}}function reanchorHistoryEntries(entries,itemHashVersion=resolveHistoryRepairItemHashVersion(entries),options={}){const unsupportedIndex=entries.findIndex(entry=>isUnsupportedExplicitHistoryItemHashVersion(entry.item_hash_version));if(unsupportedIndex>=0)throw new TypeError(`unsupported_item_hash_version:${String(entries[unsupportedIndex]?.item_hash_version)}:entry_${unsupportedIndex+1}`);let replay=cloneEmptyReplayDocument();const rewritten=[],details=[];let entriesRehashed=0,entriesPatchRepaired=0,convertedReplaceToAdd=0,skippedOps=0,entriesResealed=0,semanticIndex;const explicitItemHashVersion=itemHashVersion!==1||entries.some(entry=>entry.item_hash_version!==void 0),bridged=indexBridgedSegments(entries,options,itemHashVersion,explicitItemHashVersion);let unchangedPrefix=!0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];assertHistoryEntryIntegrity(entry,index);const preservedEnd=unchangedPrefix?bridged.preservable.get(index):void 0;if(preservedEnd!==void 0){replay=keepBridgedSegment(entries,index,preservedEnd,replay,rewritten,details),index=preservedEnd;continue}const patchApplication=applyProjectedReanchorPatch(replay,entry,options),{next,patch:outPatch,repaired:patchRepaired,converted:entryConverted,skipped:entrySkipped}=patchApplication;convertedReplaceToAdd+=entryConverted,skippedOps+=entrySkipped,entriesPatchRepaired+=Number(patchRepaired);const hashMatch=matchReplayHashCandidates(replay,next,itemHashVersion,entry);semanticIndex===void 0||options.continuousHashSurface!==!0?semanticIndex=[hashMatch.pairIndex,hashMatch.beforeIndex,hashMatch.afterIndex,Math.min(semanticIndex??0,hashMatch.beforeHashes.length-1)].find(candidate=>candidate>=0):semanticIndex=Math.min(semanticIndex,hashMatch.beforeHashes.length-1);const beforeHash=hashMatch.beforeHashes[semanticIndex],afterHash=hashMatch.afterHashes[semanticIndex],rehashed=beforeHash!==entry.before_hash||afterHash!==entry.after_hash;rehashed&&(entriesRehashed+=1);const finalized=finalizeReanchoredEntry(entry,{...entry,patch:outPatch,before_hash:beforeHash,after_hash:afterHash},{itemHashVersion:explicitItemHashVersion?itemHashVersion:void 0,rehashed,patchRepaired,inexact:bridged.inexact.has(index),inputVerifies:bridged.inputVerifies});unchangedPrefix&&=!finalized.anchorsChanged,entriesResealed+=Number(finalized.persist),rewritten.push(finalized.entry),details.push({index:index+1,rehashed,patch_repaired:patchRepaired,converted_replace_to_add:entryConverted,skipped_ops:entrySkipped}),replay=next}return{entries:rewritten,finalDocument:replay,entriesRehashed,entriesPatchRepaired,convertedReplaceToAdd,skippedOps,entriesResealed,details,itemHashVersion,explicitItemHashVersion}}function historyEntriesToRaw(entries){return entries.length===0?"":`${entries.map(entry=>JSON.stringify(entry)).join(`
1
+ import R from"fast-json-patch";import{historyDigest as de,resolveHistoryHashAlgorithm as E}from"./digest.js";import{findHistoryIdentityDiscontinuities as ce}from"./identity.js";import{digestBridgedSegment as fe,findNextHistoryBridge as ue,locateBridgedSegments as z,matchesHistoryBreak as Y,readHistoryBridge as U}from"./bridge.js";import{ITEM_METADATA_KEY_ORDER as pe}from"../shared/constants.js";import{canonicalDocument as W}from"../item/item-format.js";import{toItemRecord as he}from"../item/item-record.js";import{orderObject as me,stableStringify as k}from"../shared/serialization.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION as G,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as I,hashDocumentVerificationCandidates as le,isCompleteHistoryRecord as _e,resealHistoryRewrite as K,verifyHistoryRecordHash as ye,verifyHistoryRewriteEvidence as be}from"./history.js";const ge={metadata:{},body:""};function L(){return structuredClone(ge)}function Le(e,t=G,r){return l(e,t,r)[0]}function l(e,t,r){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return le(F(e),t,r)}catch{}const n=de(k({replay_fallback:!0,metadata:e.metadata,body:e.body}),r);return t===2?[n,n]:[n]}function O(e,t,r,n,i){const s=E(n.hash_algorithm),o=`${r}:${s}`,a=i?.before.get(o)??l(e,r,s),d=l(t,r,s);return i?.after.set(o,d),{beforeHashes:a,afterHashes:d,pairIndex:a.findIndex((c,u)=>c===n.before_hash&&d[u]===n.after_hash),beforeIndex:a.indexOf(n.before_hash),afterIndex:d.indexOf(n.after_hash)}}function F(e){return{metadata:e.metadata,body:e.body}}function Fe(e,t={}){return W(F(e),t)}function Je(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};const t=W(e);return{metadata:me(he(t.metadata),pe),body:t.body}}function _(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function J(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Q(e){return Array.isArray(e)?e.filter(J).map(t=>({...t,...(t.op==="add"||t.op==="replace")&&Object.hasOwn(t,"value")?{value:structuredClone(t.value)}:{},path:_(t.path),from:typeof t.from=="string"?_(t.from):void 0})):[]}function xe(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function S(e,t){try{const r=Q(t),n=R.applyPatch(structuredClone(e),r,!0,!0).newDocument;return xe(n)?{ok:!0,document:{metadata:n.metadata,body:n.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(r){return{ok:!1,error:r}}}function ve(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&I.includes(t)))]}function X(e){return e!==void 0&&!I.includes(e)}function Z(e,t){return e!==void 0?[e]:t===void 0?[...I]:[t]}function q(e){const t=ye(e);if(!t.ok)return t.error;const r=be(e);return r.ok?void 0:r.error}function V(e,t){const r=q(e);if(r)return{ok:!1,error:r};const n=S(t,e.patch);return n.ok?{ok:!0,document:n.document}:{ok:!1,error:"patch_apply_failed"}}function He(e,t){const r=q(e);if(r)throw new TypeError(`${r}:entry_${t+1}`)}function Re(e,t,r,n,i){const s=[];for(const o of r){const a=O(e,t,o,n,i);if(s.push({version:o,match:a}),a.pairIndex>=0)break}return s}function M(e){if(!_e(e))return!1;let t;try{t=E(e.hash_algorithm)==="sha512"?128:64}catch{return!1}const r=new RegExp(`^[a-f0-9]{${t}}$`,"u");return!r.test(e.before_hash)||!r.test(e.after_hash)?!1:!e.patch.filter(J).map(i=>({op:i.op,path:_(i.path),from:typeof i.from=="string"?_(i.from):void 0})).every(i=>w(i))||e.before_hash===e.after_hash||Object.hasOwn(e,"bridge")}function w(e){return e.op==="test"?!0:e.from!==e.path?!1:e.op==="move"||e.op==="copy"&&!/\/(?:\d+|-)$/u.test(e.path)}const ee=new WeakMap;function Ee(e,t){if(t===0||!M(e[t]))return;const r=ue(e,t);if(r<0)return;const n=U(e[r]);if(!(typeof n!="object"||!Y(n.breaks[0],e[t-1],e[t])))return{start:t,closer:r,bridge:n,next:1}}function ke(e,t,r,n,i){const s=e[t],o=e[t-1];if(!M(s))return{ok:!1,error:"record_incomplete"};const a=V(s,n);if(!a.ok)return a;const d=i.map(c=>O(n,a.document,c,s));return d.some(c=>c.beforeIndex>=0)&&!d.some(c=>c.pairIndex>=0)?{ok:!1,error:"after_hash_mismatch"}:s.before_hash===o.after_hash?a:Y(r.bridge.breaks[r.next],o,s)?(r.next+=1,a):{ok:!1,error:"bridge_unnamed_break"}}function Ie(e,t,r,n,i){const s=e[t];if(!M(s))return{ok:!1,error:"record_incomplete"};const o=V(s,n);if(!o.ok)return o;if(r.next!==r.bridge.breaks.length)return{ok:!1,error:"bridge_names_absent_break"};if(s.before_hash!==e[t-1].after_hash)return{ok:!1,error:"bridge_link_mismatch"};if(fe(e.slice(r.start,t),s)!==r.bridge.segment_digest)return{ok:!1,error:"bridge_segment_mismatch"};const a=E(s.hash_algorithm),d=i.find(c=>l(o.document,c,a).includes(s.after_hash));return d===void 0?{ok:!1,error:"bridge_after_hash_mismatch"}:{ok:!0,document:o.document,version:d}}function te(e,t,r,n,i){e.replay=n,e.beforeHashMemo=i,e.detectedVersion=r,e.authoritativeExplicitVersion=t.item_hash_version??e.authoritativeExplicitVersion}function Oe(e,t,r){const n=r.segment,i=e[t];if(t===n.closer&&r.authoritativeExplicitVersion!==void 0&&i.item_hash_version!==r.authoritativeExplicitVersion)return"bridge_epoch_mismatch";const o=(t<n.closer?ke:Ie)(e,t,n,r.replay,Z(i.item_hash_version,r.authoritativeExplicitVersion));if(!o.ok)return o.error;if(o.version===void 0){r.replay=o.document,r.beforeHashMemo=new Map,r.authoritativeExplicitVersion=i.item_hash_version??r.authoritativeExplicitVersion;return}const a={start:n.start,end:t};ee.set(a,o.version),r.bridgedSegments.push(a),r.segment=void 0,te(r,i,o.version,o.document,new Map)}function Se(e,t,r,n){const i=e[t];if(Object.hasOwn(i,"bridge"))return"bridge_without_break";const s=V(i,r.replay);if(!s.ok)return s.error;if(n){r.replay=s.document,r.beforeHashMemo=new Map,r.detectedVersion=void 0,r.authoritativeExplicitVersion=void 0;return}const o={before:r.beforeHashMemo,after:new Map},a=Re(r.replay,s.document,Z(i.item_hash_version,r.authoritativeExplicitVersion),i,o),d=a.find(({match:u})=>u.pairIndex>=0);if(d!==void 0){te(r,i,d.version,s.document,o.after);return}const c=a.some(({match:u})=>u.beforeIndex>=0);if(r.segment=c?void 0:Ee(e,t),r.segment===void 0)return`${c?"after":"before"}_hash_mismatch`;r.replay=s.document,r.beforeHashMemo=new Map,r.authoritativeExplicitVersion=i.item_hash_version??r.authoritativeExplicitVersion}function A(e){const t={replay:L(),beforeHashMemo:new Map,bridgedSegments:[]},r=ce(e).map(o=>`verify_failed:duplicate_create:entry_${o.repeated_create_index}:prior_${o.prior_genesis_index}`),n=(o,a)=>({ok:o,errors:o?[]:r,...a,...t.bridgedSegments.length===0?{}:{bridged_segments:t.bridgedSegments}}),i=(o,a)=>(r.push(`verify_failed:${o}:entry_${a+1}`),n(!1,{})),s=e.findIndex(o=>U(o)==="invalid");if(s>=0)return i("bridge_invalid",s);for(let o=0;o<e.length;o+=1){const a=e[o].item_hash_version,d=X(a);d&&r.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${o+1}`);const c=t.segment===void 0?Se(e,o,t,d):Oe(e,o,t);if(c!==void 0)return i(c,o)}return n(r.length===0,t.detectedVersion===void 0?{}:{item_hash_version:t.detectedVersion})}function Qe(e){const t=A(e);return{ok:t.ok,errors:t.errors}}function P(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function re(e,t,r){try{const n=R.applyPatch(structuredClone(e),[t],!0,!1).newDocument;return r&&!P(n)?{ok:!1}:{ok:!0,document:n}}catch{return{ok:!1}}}function ne(e,t,r){let n=structuredClone(e),i=0,s=0;for(const o of Q(t)){const a=re(n,o,r);if(a.ok){n=a.document;continue}if(o.op==="replace"){const d=re(n,{...o,op:"add"},r);if(d.ok){n=d.document,i+=1;continue}}s+=1}return{working:n,convertedReplaceToAdd:i,skippedOps:s}}function Ve(e,t,r){const n=ne(e,t,!1);if(!P(n.working)&&r==="delete")return{document:{metadata:{},body:""},convertedReplaceToAdd:n.convertedReplaceToAdd,skippedOps:n.skippedOps};const{working:i,convertedReplaceToAdd:s,skippedOps:o}=P(n.working)?n:ne(e,t,!0),a=i;return{document:{metadata:typeof a.metadata=="object"&&a.metadata!==null?a.metadata:{},body:typeof a.body=="string"?a.body:e.body},convertedReplaceToAdd:s,skippedOps:o}}function Me(e){const t=ve(e);if(t.length===1)return t[0];const r=A(e);return r.ok&&r.item_hash_version!==void 0?r.item_hash_version:t.length===0?1:G}function Ae(e,t,r=t.patch){const n=S(e,r);if(n.ok)return{next:n.document,patch:r,repaired:k(r)!==k(t.patch),converted:0,skipped:0};const i=Ve(e,r,t.op);return{next:i.document,patch:R.compare(e,i.document),repaired:!0,converted:i.convertedReplaceToAdd,skipped:i.skippedOps}}function Pe(e,t,r){return Ae(e,t,r.projectPatch?.(t,e))}function Te(e,t,r,n){const i=A(e),o=t.projectPatch===void 0&&t.continuousHashSurface!==!0?(i.bridged_segments??[]).filter(a=>ee.get(a)===r&&(!n||e[a.end].item_hash_version===r)&&e.slice(a.start,a.end+1).every(d=>d.item_hash_version===void 0||d.item_hash_version===r)):[];return{inputVerifies:i.ok,preservable:new Map(o.map(a=>[a.start,a.end])),inexact:oe(t.callerMarksBridgeCoverage===!0?[]:z(e).segments)}}function oe(e){const t=new Set;for(const{start:r,end:n,exact:i}of e){const s=i===!1?n:n-1;for(let o=r;o<=s;o+=1)t.add(o)}return t}function Ce(e){return K(e,{...e,replay_inexact:!0},{retainPriorRecord:!0,retainPriorRecordHash:!1})}function Xe(e){const t=oe(z(e).segments);return e.map((r,n)=>t.has(n)&&r.replay_inexact!==!0?Ce(r):r)}function De(e,t,r,n,i,s){let o=n;for(let a=t;a<=r;a+=1){const d=e[a],c=S(o,d.patch);if(!c.ok)throw new TypeError(`patch_apply_failed:entry_${a+1}`);o=c.document,i.push(d),s.push({index:a+1,rehashed:!1,patch_repaired:!1,converted_replace_to_add:0,skipped_ops:0})}return o}function $e(e,t,r){r.itemHashVersion===void 0?delete t.item_hash_version:t.item_hash_version=r.itemHashVersion,r.inexact&&(t.replay_inexact=!0);const n=Object.hasOwn(e,"bridge");delete t.bridge;const i=n||t.replay_inexact!==e.replay_inexact,s=r.rehashed||r.patchRepaired||i||t.item_hash_version!==e.item_hash_version;return{changed:s,persist:r.inputVerifies?i:s,anchorsChanged:r.rehashed||r.patchRepaired,entry:s?K(e,t,{retainOriginalPatch:r.patchRepaired,retainPriorRecord:n}):t}}function Ze(e,t=Me(e),r={}){const n=e.findIndex(f=>X(f.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let i=L();const s=[],o=[];let a=0,d=0,c=0,u=0,T=0,p;const y=t!==1||e.some(f=>f.item_hash_version!==void 0),b=Te(e,r,t,y);let C=!0;for(let f=0;f<e.length;f+=1){const h=e[f];He(h,f);const g=C?b.preservable.get(f):void 0;if(g!==void 0){i=De(e,f,g,i,s,o),f=g;continue}const ie=Pe(i,h,r),{next:D,patch:ae,repaired:x,converted:$,skipped:B}=ie;c+=$,u+=B,d+=Number(x);const m=O(i,D,t,h);p===void 0||r.continuousHashSurface!==!0?p=[m.pairIndex,m.beforeIndex,m.afterIndex,Math.min(p??0,m.beforeHashes.length-1)].find(se=>se>=0):p=Math.min(p,m.beforeHashes.length-1);const j=m.beforeHashes[p],N=m.afterHashes[p],v=j!==h.before_hash||N!==h.after_hash;v&&(a+=1);const H=$e(h,{...h,patch:ae,before_hash:j,after_hash:N},{itemHashVersion:y?t:void 0,rehashed:v,patchRepaired:x,inexact:b.inexact.has(f),inputVerifies:b.inputVerifies});C&&=!H.anchorsChanged,T+=Number(H.persist),s.push(H.entry),o.push({index:f+1,rehashed:v,patch_repaired:x,converted_replace_to_add:$,skipped_ops:B}),i=D}return{entries:s,finalDocument:i,entriesRehashed:a,entriesPatchRepaired:d,convertedReplaceToAdd:c,skippedOps:u,entriesResealed:T,details:o,itemHashVersion:t,explicitItemHashVersion:y}}function qe(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
2
2
  `)}
3
- `}const _testOnly={isEffectFreeOperation};export{EMPTY_REPLAY_DOCUMENT,_testOnly,cloneEmptyReplayDocument,collectBridgedInteriorIndexes,historyEntriesToRaw,lenientApplyReplayPatch,markHistoryEntryInexact,materializeBridgedSegments,normalizeReplayPatchOps,normalizeReplayPatchPath,reanchorHistoryEntries,replayHash,replayHashVerificationCandidates,replayToCanonicalItemDocument,replayToItemDocument,resolveHistoryRepairItemHashVersion,toReplayDocument,tryApplyReplayPatch,verifyHistoryChain,verifyHistoryChainWithVersion};
3
+ `}const we={isEffectFreeOperation:w};export{ge as EMPTY_REPLAY_DOCUMENT,we as _testOnly,L as cloneEmptyReplayDocument,oe as collectBridgedInteriorIndexes,qe as historyEntriesToRaw,Ve as lenientApplyReplayPatch,Ce as markHistoryEntryInexact,Xe as materializeBridgedSegments,Q as normalizeReplayPatchOps,_ as normalizeReplayPatchPath,Ze as reanchorHistoryEntries,Le as replayHash,l as replayHashVerificationCandidates,Fe as replayToCanonicalItemDocument,F as replayToItemDocument,Me as resolveHistoryRepairItemHashVersion,Je as toReplayDocument,S as tryApplyReplayPatch,Qe as verifyHistoryChain,A as verifyHistoryChainWithVersion};
4
4
  //# sourceMappingURL=replay.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0a7f878e-2354-5f40-9217-81b86d7b5423")}catch{}})();import{createHash}from"node:crypto";import fs from"node:fs/promises";import os from"node:os";import path from"node:path";import{hasActiveOnReadHooks}from"../extensions/index.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";const HISTORY_STREAM_SUMMARY_RELATIVE_PATH="runtime/history-stream-summary.json",SUMMARY_VERSION=1,STAT_CONCURRENCY=64,RACY_WINDOW_NS=2000000000n,HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS=500;let minimumStreams=HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,wallClockMs=()=>Date.now(),readerIdentity=()=>readerDigest(readerIdentityOf(process,os.userInfo));function readerDigest(identity){return identity===void 0?void 0:createHash("sha256").update(identity).digest("hex").slice(0,16)}function readerIdentityOf(credentials,userInfo){try{if(credentials.geteuid&&credentials.getegid&&credentials.getgroups){const groups=[...new Set(credentials.getgroups())].sort((left,right)=>left-right);return`uid:${credentials.geteuid()}:gid:${credentials.getegid()}:groups:${groups.join(",")}`}const{username}=userInfo();return username.length>0?`user:${username}`:void 0}catch{return}}const CANONICAL_TIMESTAMP=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;function daysInMonth(year,month){return month===2?year%4===0&&year%100!==0||year%400===0?29:28:month===4||month===6||month===9||month===11?30:31}function isCanonicalHistoryTimestamp(value){if(typeof value!="string"||!CANONICAL_TIMESTAMP.test(value))return!1;const year=Number(value.slice(0,4)),month=Number(value.slice(5,7)),day=Number(value.slice(8,10));return month>=1&&month<=12&&day>=1&&day<=daysInMonth(year,month)&&Number(value.slice(11,13))<24&&Number(value.slice(14,16))<60&&Number(value.slice(17,19))<60}function summarizeHistoryStreamBounds(entries){let oldest=null,newest=null,irregular=!1;for(const entry of entries){const timestamp=typeof entry=="object"&&entry!==null?entry.ts:void 0;if(!isCanonicalHistoryTimestamp(timestamp)){irregular=!0;continue}(oldest===null||timestamp<oldest)&&(oldest=timestamp),(newest===null||timestamp>newest)&&(newest=timestamp)}return{count:entries.length,oldest,newest,irregular}}function setMinimumStreams(value){const previous=minimumStreams;return minimumStreams=value,()=>{minimumStreams=previous}}function setReaderIdentity(identity){const previous=readerIdentity;return readerIdentity=identity,()=>{readerIdentity=previous}}function setWallClock(clock){const previous=wallClockMs;return wallClockMs=clock,()=>{wallClockMs=previous}}function isFileExistsError(error){return typeof error=="object"&&error!==null&&"code"in error&&error.code==="EEXIST"}function summaryPath(pmRoot){return path.join(pmRoot,...HISTORY_STREAM_SUMMARY_RELATIVE_PATH.split("/"))}function signatureOf(stats,reader){if(!(!stats.isFile()||stats.ino===0n||reader===void 0))return{size:stats.size,signature:[stats.dev,stats.ino,stats.size,stats.mtimeNs,stats.ctimeNs,reader].join(":"),changedAtNs:stats.mtimeNs>stats.ctimeNs?stats.mtimeNs:stats.ctimeNs}}async function observeStreams(historyDir,files,reader){const observed=new Map;for(let start=0;start<files.length;start+=STAT_CONCURRENCY){const chunk=files.slice(start,start+STAT_CONCURRENCY);(await Promise.all(chunk.map(file=>fs.stat(path.join(historyDir,file),{bigint:!0}).catch(()=>{})))).forEach((stat,index)=>{const signature=stat===void 0?void 0:signatureOf(stat,reader);signature!==void 0&&observed.set(chunk[index],signature)})}return observed}function isNullableCanonical(value){return value===null||isCanonicalHistoryTimestamp(value)}function areConsistentBounds(bounds){return bounds.oldest===null!=(bounds.newest===null)?!1:bounds.count===0?bounds.oldest===null&&!bounds.irregular:bounds.oldest===null?bounds.irregular:bounds.oldest<=bounds.newest}function parseStoredStream(value){if(!Array.isArray(value)||value.length!==5)return;const[signature,count,oldest,newest,irregular]=value;if(typeof signature!="string"||!Number.isSafeInteger(count)||count<0||!isNullableCanonical(oldest)||!isNullableCanonical(newest)||typeof irregular!="boolean")return;const bounds={count,oldest,newest,irregular};return areConsistentBounds(bounds)?{signature,bounds}:void 0}function summaryByteCap(streamCount){return 4096+streamCount*1024}function isTrustedSummaryFile(stats,streamCount,euid){return!stats.isFile()||stats.nlink!==1||stats.size>summaryByteCap(streamCount)?!1:euid===void 0||stats.uid===euid&&(stats.mode&18)===0}async function hasRealRuntimeDirectory(pmRoot){return(await fs.lstat(path.join(pmRoot,"runtime"))).isDirectory()}async function hasNonRegularSummaryEntry(pmRoot){try{return!(await fs.lstat(summaryPath(pmRoot))).isFile()}catch{return!1}}async function isSummaryUnwritable(pmRoot){try{if(!await hasRealRuntimeDirectory(pmRoot))return!0}catch{return!1}return hasNonRegularSummaryEntry(pmRoot)}async function readSummaryText(pmRoot,streamCount){if(!await hasRealRuntimeDirectory(pmRoot))throw new Error("runtime directory is redirected");if((await fs.lstat(summaryPath(pmRoot))).isSymbolicLink())throw new Error("history stream summary is a link");const handle=await fs.open(summaryPath(pmRoot),fs.constants.O_RDONLY|fs.constants.O_NOFOLLOW|fs.constants.O_NONBLOCK);try{const stats=await handle.stat();if(!isTrustedSummaryFile(stats,streamCount,process.geteuid?.()))throw new Error("history stream summary is not a trusted file");return await readAtMost(handle,summaryByteCap(streamCount),stats.size)}finally{await handle.close()}}async function readAtMost(handle,cap,expectedSize){let buffer=Buffer.alloc(Math.min(Math.max(expectedSize,0),cap)+1),length=0;for(;;){if(length===buffer.length){const grown=Buffer.alloc(Math.min(buffer.length*2,cap+1));buffer.copy(grown,0,0,length),buffer=grown}const{bytesRead}=await handle.read(buffer,length,buffer.length-length,length);if(bytesRead===0)break;if(length+=bytesRead,length>cap)throw new Error("history stream summary grew past its size cap")}return buffer.subarray(0,length).toString("utf8")}async function readStoredSummary(pmRoot,streamCount){let raw;try{raw=await readSummaryText(pmRoot,streamCount)}catch(error){return{state:isFileMissingError(error)?"missing":"invalid",streams:new Map}}try{const parsed=JSON.parse(raw);if(parsed.version!==SUMMARY_VERSION||typeof parsed.streams!="object"||parsed.streams===null||Array.isArray(parsed.streams)||parsed.checksum!==checksumOf(parsed.streams))return{state:"invalid",streams:new Map};const streams=new Map;for(const[file,value]of Object.entries(parsed.streams)){const stream=parseStoredStream(value);if(stream===void 0)return{state:"invalid",streams:new Map};streams.set(file,stream)}return{state:"loaded",streams}}catch{return{state:"invalid",streams:new Map}}}function serializeSummary(streams){const ordered=[...streams.entries()].sort(([left],[right])=>left<right?-1:1),encoded={};for(const[file,{signature,bounds}]of ordered)encoded[file]=[signature,bounds.count,bounds.oldest,bounds.newest,bounds.irregular];return`${JSON.stringify({version:SUMMARY_VERSION,checksum:checksumOf(encoded),streams:encoded})}
2
- `}function checksumOf(streams){return createHash("sha256").update(JSON.stringify(streams)).digest("hex")}function summaryFallback(state,current,streamCount){if(state==="missing")return"summary_missing";if(state==="invalid")return"summary_invalid";const stale=streamCount-current.size;let irregular=0;for(const{bounds}of current.values())bounds.irregular&&(irregular+=1);if(!((stale+irregular)*2<=streamCount))return stale>=irregular?"summary_stale":"irregular_timestamps"}function disabledSession(fallback){return{enabled:!1,staleAtOpen:0,fallback,trusted:()=>{},record:()=>{},revalidate:async()=>[],commit:async()=>{}}}async function openHistoryStreamSummary(params){if(params.files.length<minimumStreams)return disabledSession(void 0);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");if(await isSummaryUnwritable(params.pmRoot))return disabledSession("summary_invalid");const observedAtNs=BigInt(Math.floor(wallClockMs()))*1000000n,reader=readerIdentity(),[stored,observed]=await Promise.all([readStoredSummary(params.pmRoot,params.files.length),observeStreams(params.historyDir,params.files,reader)]);if(hasActiveOnReadHooks())return disabledSession("read_hooks_active");const next=new Map;for(const[file,stream]of stored.streams)observed.get(file)?.signature===stream.signature&&next.set(file,stream);let dirty=!1;return{enabled:!0,staleAtOpen:params.files.length-next.size,fallback:summaryFallback(stored.state,next,params.files.length),trusted:file=>next.get(file)?.bounds,record:(file,{entries,raw_bytes:rawBytes,source})=>{const observation=source===null||rawBytes===null?void 0:signatureOf(source,reader);observation===void 0||BigInt(rawBytes.length)!==observation.size||observation.changedAtNs+RACY_WINDOW_NS>=observedAtNs||next.get(file)?.signature===observation.signature||(next.set(file,{signature:observation.signature,bounds:summarizeHistoryStreamBounds(entries)}),dirty=!0)},revalidate:async files=>{const current=await observeStreams(params.historyDir,files,reader),changed=files.filter(file=>current.get(file)?.signature!==next.get(file)?.signature);for(const file of changed)next.delete(file);return changed},commit:async()=>{dirty&&(dirty=!1,await persistSummary(params.pmRoot,next))}}}async function persistSummary(pmRoot,streams){try{if(await fs.mkdir(path.join(pmRoot,"runtime")).catch(error=>{if(!isFileExistsError(error))throw error}),!await hasRealRuntimeDirectory(pmRoot)||await hasNonRegularSummaryEntry(pmRoot))return;await writeFileAtomic(summaryPath(pmRoot),serializeSummary(streams),{createParentDirectories:!1,mode:384})}catch{}}const _testOnly={areConsistentBounds,readAtMost,readerDigest,isTrustedSummaryFile,summaryByteCap,readerIdentityOf,checksumOf,setMinimumStreams,setReaderIdentity,setWallClock,signatureOf,RACY_WINDOW_NS,SUMMARY_VERSION,serializeSummary,parseStoredStream};export{HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,HISTORY_STREAM_SUMMARY_RELATIVE_PATH,_testOnly,isCanonicalHistoryTimestamp,openHistoryStreamSummary,summarizeHistoryStreamBounds};
1
+ import{createHash as O}from"node:crypto";import a from"node:fs/promises";import Y from"node:os";import m from"node:path";import{hasActiveOnReadHooks as A}from"../extensions/index.js";import{isFileMissingError as B,writeFileAtomic as L}from"../fs/fs-utils.js";const P="runtime/history-stream-summary.json",S=1,E=64,I=2000000000n,U=500;let y=U,g=()=>Date.now(),h=()=>v(R(process,Y.userInfo));function v(e){return e===void 0?void 0:O("sha256").update(e).digest("hex").slice(0,16)}function R(e,t){try{if(e.geteuid&&e.getegid&&e.getgroups){const n=[...new Set(e.getgroups())].sort((i,s)=>i-s);return`uid:${e.geteuid()}:gid:${e.getegid()}:groups:${n.join(",")}`}const{username:r}=t();return r.length>0?`user:${r}`:void 0}catch{return}}const $=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u;function W(e,t){return t===2?e%4===0&&e%100!==0||e%400===0?29:28:t===4||t===6||t===9||t===11?30:31}function k(e){if(typeof e!="string"||!$.test(e))return!1;const t=Number(e.slice(0,4)),r=Number(e.slice(5,7)),n=Number(e.slice(8,10));return r>=1&&r<=12&&n>=1&&n<=W(t,r)&&Number(e.slice(11,13))<24&&Number(e.slice(14,16))<60&&Number(e.slice(17,19))<60}function J(e){let t=null,r=null,n=!1;for(const i of e){const s=typeof i=="object"&&i!==null?i.ts:void 0;if(!k(s)){n=!0;continue}(t===null||s<t)&&(t=s),(r===null||s>r)&&(r=s)}return{count:e.length,oldest:t,newest:r,irregular:n}}function V(e){const t=y;return y=e,()=>{y=t}}function K(e){const t=h;return h=e,()=>{h=t}}function X(e){const t=g;return g=e,()=>{g=t}}function Z(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}function w(e){return m.join(e,...P.split("/"))}function N(e,t){if(!(!e.isFile()||e.ino===0n||t===void 0))return{size:e.size,signature:[e.dev,e.ino,e.size,e.mtimeNs,e.ctimeNs,t].join(":"),changedAtNs:e.mtimeNs>e.ctimeNs?e.mtimeNs:e.ctimeNs}}async function T(e,t,r){const n=new Map;for(let i=0;i<t.length;i+=E){const s=t.slice(i,i+E);(await Promise.all(s.map(o=>a.stat(m.join(e,o),{bigint:!0}).catch(()=>{})))).forEach((o,c)=>{const f=o===void 0?void 0:N(o,r);f!==void 0&&n.set(s[c],f)})}return n}function x(e){return e===null||k(e)}function j(e){return e.oldest===null!=(e.newest===null)?!1:e.count===0?e.oldest===null&&!e.irregular:e.oldest===null?e.irregular:e.oldest<=e.newest}function z(e){if(!Array.isArray(e)||e.length!==5)return;const[t,r,n,i,s]=e;if(typeof t!="string"||!Number.isSafeInteger(r)||r<0||!x(n)||!x(i)||typeof s!="boolean")return;const u={count:r,oldest:n,newest:i,irregular:s};return j(u)?{signature:t,bounds:u}:void 0}function M(e){return 4096+e*1024}function C(e,t,r){return!e.isFile()||e.nlink!==1||e.size>M(t)?!1:r===void 0||e.uid===r&&(e.mode&18)===0}async function b(e){return(await a.lstat(m.join(e,"runtime"))).isDirectory()}async function D(e){try{return!(await a.lstat(w(e))).isFile()}catch{return!1}}async function q(e){try{if(!await b(e))return!0}catch{return!1}return D(e)}async function G(e,t){if(!await b(e))throw new Error("runtime directory is redirected");if((await a.lstat(w(e))).isSymbolicLink())throw new Error("history stream summary is a link");const r=await a.open(w(e),a.constants.O_RDONLY|a.constants.O_NOFOLLOW|a.constants.O_NONBLOCK);try{const n=await r.stat();if(!C(n,t,process.geteuid?.()))throw new Error("history stream summary is not a trusted file");return await F(r,M(t),n.size)}finally{await r.close()}}async function F(e,t,r){let n=Buffer.alloc(Math.min(Math.max(r,0),t)+1),i=0;for(;;){if(i===n.length){const u=Buffer.alloc(Math.min(n.length*2,t+1));n.copy(u,0,0,i),n=u}const{bytesRead:s}=await e.read(n,i,n.length-i,i);if(s===0)break;if(i+=s,i>t)throw new Error("history stream summary grew past its size cap")}return n.subarray(0,i).toString("utf8")}async function Q(e,t){let r;try{r=await G(e,t)}catch(n){return{state:B(n)?"missing":"invalid",streams:new Map}}try{const n=JSON.parse(r);if(n.version!==S||typeof n.streams!="object"||n.streams===null||Array.isArray(n.streams)||n.checksum!==_(n.streams))return{state:"invalid",streams:new Map};const i=new Map;for(const[s,u]of Object.entries(n.streams)){const o=z(u);if(o===void 0)return{state:"invalid",streams:new Map};i.set(s,o)}return{state:"loaded",streams:i}}catch{return{state:"invalid",streams:new Map}}}function H(e){const t=[...e.entries()].sort(([n],[i])=>n<i?-1:1),r={};for(const[n,{signature:i,bounds:s}]of t)r[n]=[i,s.count,s.oldest,s.newest,s.irregular];return`${JSON.stringify({version:S,checksum:_(r),streams:r})}
2
+ `}function _(e){return O("sha256").update(JSON.stringify(e)).digest("hex")}function ee(e,t,r){if(e==="missing")return"summary_missing";if(e==="invalid")return"summary_invalid";const n=r-t.size;let i=0;for(const{bounds:s}of t.values())s.irregular&&(i+=1);if(!((n+i)*2<=r))return n>=i?"summary_stale":"irregular_timestamps"}function p(e){return{enabled:!1,staleAtOpen:0,fallback:e,trusted:()=>{},record:()=>{},revalidate:async()=>[],commit:async()=>{}}}async function ce(e){if(e.files.length<y)return p(void 0);if(A())return p("read_hooks_active");if(await q(e.pmRoot))return p("summary_invalid");const t=BigInt(Math.floor(g()))*1000000n,r=h(),[n,i]=await Promise.all([Q(e.pmRoot,e.files.length),T(e.historyDir,e.files,r)]);if(A())return p("read_hooks_active");const s=new Map;for(const[o,c]of n.streams)i.get(o)?.signature===c.signature&&s.set(o,c);let u=!1;return{enabled:!0,staleAtOpen:e.files.length-s.size,fallback:ee(n.state,s,e.files.length),trusted:o=>s.get(o)?.bounds,record:(o,{entries:c,raw_bytes:f,source:l})=>{const d=l===null||f===null?void 0:N(l,r);d===void 0||BigInt(f.length)!==d.size||d.changedAtNs+I>=t||s.get(o)?.signature===d.signature||(s.set(o,{signature:d.signature,bounds:J(c)}),u=!0)},revalidate:async o=>{const c=await T(e.historyDir,o,r),f=o.filter(l=>c.get(l)?.signature!==s.get(l)?.signature);for(const l of f)s.delete(l);return f},commit:async()=>{u&&(u=!1,await te(e.pmRoot,s))}}}async function te(e,t){try{if(await a.mkdir(m.join(e,"runtime")).catch(r=>{if(!Z(r))throw r}),!await b(e)||await D(e))return;await L(w(e),H(t),{createParentDirectories:!1,mode:384})}catch{}}const fe={areConsistentBounds:j,readAtMost:F,readerDigest:v,isTrustedSummaryFile:C,summaryByteCap:M,readerIdentityOf:R,checksumOf:_,setMinimumStreams:V,setReaderIdentity:K,setWallClock:X,signatureOf:N,RACY_WINDOW_NS:I,SUMMARY_VERSION:S,serializeSummary:H,parseStoredStream:z};export{U as HISTORY_STREAM_SUMMARY_MINIMUM_STREAMS,P as HISTORY_STREAM_SUMMARY_RELATIVE_PATH,fe as _testOnly,k as isCanonicalHistoryTimestamp,ce as openHistoryStreamSummary,J as summarizeHistoryStreamBounds};
3
3
  //# sourceMappingURL=stream-summary.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();import{statSync}from"node:fs";import{normalizeItemId,normalizeRawItemId}from"../item/id.js";import{getHistoryPath}from"../store/paths.js";import{EXIT_CODE}from"../shared/constants.js";import{renderPmCommand}from"../shared/command-line.js";import{PmCliError}from"../shared/errors.js";import{readHistoryEntries}from"./read.js";import{applyHistoryPatch,replayHistoryToTarget,resolveHistoryTarget}from"./projection.js";import{EMPTY_REPLAY_DOCUMENT}from"./replay.js";import{historyVersionOffset}from"./version-address.js";function resolveDeletedRecoveryTarget(entries,id){let materializedIndex=-1,document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(const[index,entry]of entries.entries()){if(document=applyHistoryPatch(document,entry.patch,index+1,entry.op),document.metadata.id!==void 0&&document.metadata.id!==id)throw new PmCliError(`History belongs to item ${String(document.metadata.id)}, expected ${id}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});document.metadata.id===id&&Array.isArray(document.metadata.tags)&&(materializedIndex=index)}const offset=historyVersionOffset(entries,!0),version=materializedIndex<0||offset===null?null:offset+materializedIndex+1;let target=version===null?void 0:String(version);if(materializedIndex>=0&&target===void 0){const timestamp=entries[materializedIndex].ts;resolveHistoryTarget(timestamp,entries).historyIndex===materializedIndex&&(target=timestamp)}return{version,target}}async function buildDeletedItemError(pmRoot,rawId,idPrefix){const candidates=new Set([normalizeItemId(rawId,idPrefix),normalizeRawItemId(rawId)]);for(const id of candidates){const historyPath=getHistoryPath(pmRoot,id);if(!statSync(historyPath,{throwIfNoEntry:!1})?.isFile())continue;const entries=await readHistoryEntries(historyPath,id);let deletionIndex=-1;if(entries.forEach((entry,index)=>{entry.op==="delete"&&(deletionIndex=index)}),deletionIndex<0)continue;const final=replayHistoryToTarget(entries,entries.length-1);if(Object.keys(final.metadata).length!==0)continue;const{version,target}=resolveDeletedRecoveryTarget(entries,id),readArgs=target===void 0?["history",id,"--verify"]:["get",id,"--at",target],readCommand=renderPmCommand(readArgs);return new PmCliError(`Item ${id} was deleted at ${entries[deletionIndex].ts}; its history is retained.`,EXIT_CODE.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:id,tombstone:{deleted:!0,deleted_at:entries[deletionIndex].ts,recoverable:target!==void 0,last_materialized_version:version},nextSteps:[readCommand,...target===void 0?["Recover the pre-compaction history from version control."]:[renderPmCommand(["restore",id,target])]],recovery:{suggested_retry:readCommand,suggested_retry_args:readArgs}})}}export{buildDeletedItemError};
1
+ import{statSync as _}from"node:fs";import{normalizeItemId as v,normalizeRawItemId as E}from"../item/id.js";import{getHistoryPath as I}from"../store/paths.js";import{EXIT_CODE as c}from"../shared/constants.js";import{renderPmCommand as u}from"../shared/command-line.js";import{PmCliError as y}from"../shared/errors.js";import{readHistoryEntries as x}from"./read.js";import{applyHistoryPatch as R,replayHistoryToTarget as T,resolveHistoryTarget as w}from"./projection.js";import{EMPTY_REPLAY_DOCUMENT as C}from"./replay.js";import{historyVersionOffset as P}from"./version-address.js";function b(n,a){let i=-1,o=structuredClone(C);for(const[r,m]of n.entries()){if(o=R(o,m.patch,r+1,m.op),o.metadata.id!==void 0&&o.metadata.id!==a)throw new y(`History belongs to item ${String(o.metadata.id)}, expected ${a}.`,c.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===a&&Array.isArray(o.metadata.tags)&&(i=r)}const e=P(n,!0),s=i<0||e===null?null:e+i+1;let t=s===null?void 0:String(s);if(i>=0&&t===void 0){const r=n[i].ts;w(r,n).historyIndex===i&&(t=r)}return{version:s,target:t}}async function q(n,a,i){const o=new Set([v(a,i),E(a)]);for(const e of o){const s=I(n,e);if(!_(s,{throwIfNoEntry:!1})?.isFile())continue;const t=await x(s,e);let r=-1;if(t.forEach((h,g)=>{h.op==="delete"&&(r=g)}),r<0)continue;const m=T(t,t.length-1);if(Object.keys(m.metadata).length!==0)continue;const{version:p,target:d}=b(t,e),f=d===void 0?["history",e,"--verify"]:["get",e,"--at",d],l=u(f);return new y(`Item ${e} was deleted at ${t[r].ts}; its history is retained.`,c.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:e,tombstone:{deleted:!0,deleted_at:t[r].ts,recoverable:d!==void 0,last_materialized_version:p},nextSteps:[l,...d===void 0?["Recover the pre-compaction history from version control."]:[u(["restore",e,d])]],recovery:{suggested_retry:l,suggested_retry_args:f}})}}export{q as buildDeletedItemError};
2
2
  //# sourceMappingURL=tombstone.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";function historyVersionOffset(history,allowUnknown=!1){const first=history[0];if(first?.op!=="history_compact_baseline")return 0;const receipt=first.context?.history_compaction,offset=typeof receipt=="object"&&receipt!==null&&"version_offset"in receipt?receipt.version_offset:void 0;if(typeof offset=="number"&&Number.isSafeInteger(offset)&&offset>=0&&Number.isSafeInteger(offset+history.length))return offset;if(allowUnknown)return null;throw new PmCliError("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",EXIT_CODE.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}export{historyVersionOffset};
1
+ import{EXIT_CODE as i}from"../shared/constants.js";import{PmCliError as s}from"../shared/errors.js";function c(r,n=!1){const o=r[0];if(o?.op!=="history_compact_baseline")return 0;const t=o.context?.history_compaction,e=typeof t=="object"&&t!==null&&"version_offset"in t?t.version_offset:void 0;if(typeof e=="number"&&Number.isSafeInteger(e)&&e>=0&&Number.isSafeInteger(e+r.length))return e;if(n)return null;throw new s("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",i.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}export{c as historyVersionOffset};
2
2
  //# sourceMappingURL=version-address.js.map
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();import fs from"node:fs/promises";import path from"node:path";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{stableStringify}from"../shared/serialization.js";import{nowIso}from"../shared/time.js";import{appendHistoryEntry,createHistoryEntry}from"./history.js";import{readHistoryEntries}from"./read.js";import{cloneEmptyReplayDocument,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChain}from"./replay.js";const WORKSPACE_HISTORY_ID="_workspace";function getWorkspaceHistoryPath(pmRoot){return path.join(pmRoot,"history",`${WORKSPACE_HISTORY_ID}.jsonl`)}function workspaceDocument(documents,timestamp){return{metadata:{id:WORKSPACE_HISTORY_ID,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:timestamp,updated_at:timestamp,documents},body:""}}function replayWorkspaceEntries(entries,count=entries.length){let replay=cloneEmptyReplayDocument();for(const entry of entries.slice(0,count))replay=tryApplyReplayPatch(replay,entry.patch).document;return replayToItemDocument(replay)}function workspaceDocuments(document){return"documents"in document.metadata&&typeof document.metadata.documents=="object"&&document.metadata.documents!==null&&!Array.isArray(document.metadata.documents)?document.metadata.documents:{}}function throwWorkspaceHistoryVerificationFailure(errors){throw new PmCliError(`Workspace history verification failed: ${errors.join(", ")}`,EXIT_CODE.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...errors],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function resolveGovernedDocumentPath(pmRoot,filePath){const absolutePath=path.resolve(filePath),documentPath=path.relative(pmRoot,absolutePath).replaceAll("\\","/");if(documentPath.length===0||documentPath===".."||documentPath.startsWith("../")||path.isAbsolute(documentPath))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath,absolutePath}}async function inspectWorkspaceHistoryState(pmRoot){const entries=await readHistoryEntries(getWorkspaceHistoryPath(pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const documents=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries)),matching=[],mismatched=[],missing=[],unreadable=[];for(const documentPath of Object.keys(documents).sort()){let raw;try{const resolved=resolveGovernedDocumentPath(pmRoot,path.resolve(pmRoot,documentPath));if(raw=await readFileIfExists(resolved.absolutePath),raw===null){missing.push(documentPath);continue}const current=JSON.parse(raw);(stableStringify(current)===stableStringify(documents[documentPath])?matching:mismatched).push(documentPath)}catch{unreadable.push(documentPath)}}return{ok:mismatched.length===0&&missing.length===0&&unreadable.length===0,document_count:Object.keys(documents).length,matching_documents:matching,mismatched_documents:mismatched,missing_documents:missing,unreadable_documents:unreadable}}async function appendWorkspaceHistoryChangeLocked(change){const historyPath=getWorkspaceHistoryPath(change.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const idempotentEntry=change.idempotencyKey===void 0?void 0:entries.find(entry2=>entry2.op===`${change.op}:${change.idempotencyKey}`);if(idempotentEntry)return{entry:idempotentEntry,historyPath};const timestamp=nowIso(),beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument),recordedBefore=priorDocuments[change.documentPath];if(recordedBefore!==void 0&&stableStringify(recordedBefore)!==stableStringify(change.before))throw new PmCliError(`Workspace history state for "${change.documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});const afterDocument=workspaceDocument({...priorDocuments,[change.documentPath]:change.after},entries.length===0?timestamp:beforeDocument.metadata.created_at),entry=createHistoryEntry({nowIso:timestamp,author:change.author,op:change.idempotencyKey===void 0?change.op:`${change.op}:${change.idempotencyKey}`,before:beforeDocument,after:afterDocument,message:change.message});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}async function appendWorkspaceHistoryChange(change){const release=await acquireLock(change.pmRoot,"workspace-history",change.lockTtlSeconds,change.author,!1,!1,change.lockWaitMs);try{return await appendWorkspaceHistoryChangeLocked(change)}finally{await release()}}async function appendWorkspaceAuditEvent(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries),entry=createHistoryEntry({nowIso:nowIso(),author:options.author,op:options.op,before:beforeDocument,after:beforeDocument,message:options.message,context:options.context});return await appendHistoryEntry(historyPath,entry),{entry,historyPath}}finally{await release()}}async function writeWorkspaceJsonWithHistoryLocked(params,beforeRaw){if(beforeRaw===params.raw)return!1;const before=beforeRaw===null?null:JSON.parse(beforeRaw),after=JSON.parse(params.raw);await writeFileAtomic(params.filePath,params.raw);try{(beforeRaw!==null||params.recordCreation!==!1)&&await appendWorkspaceHistoryChangeLocked({pmRoot:params.pmRoot,documentPath:path.relative(params.pmRoot,params.filePath).replaceAll("\\","/"),before,after,op:params.op,idempotencyKey:params.idempotencyKey,author:params.author,lockTtlSeconds:params.lockTtlSeconds,lockWaitMs:params.lockWaitMs,message:params.message})}catch(error){throw beforeRaw===null?await fs.rm(params.filePath,{force:!0}):await writeFileAtomic(params.filePath,beforeRaw),error}return!0}async function mutateWorkspaceJsonWithHistory(params){const{documentPath}=resolveGovernedDocumentPath(params.pmRoot,params.filePath),release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{const beforeRaw=await readFileIfExists(params.filePath);if(params.dryRun===!0||params.idempotencyKey!==void 0){const entries=await readHistoryEntries(getWorkspaceHistoryPath(params.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const recorded=workspaceDocuments(entries.length===0?EMPTY_CANONICAL_DOCUMENT:replayWorkspaceEntries(entries))[documentPath];if(recorded!==void 0&&stableStringify(recorded)!==stableStringify(beforeRaw===null?null:JSON.parse(beforeRaw)))throw new PmCliError(`Workspace history state for "${documentPath}" changed outside the audited mutation path.`,EXIT_CODE.CONFLICT,{code:"workspace_history_state_conflict"});if(params.idempotencyKey!==void 0&&entries.some(entry=>entry.op===`${params.op}:${params.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}const mutation=await params.mutate(beforeRaw);return JSON.parse(mutation.raw),params.dryRun===!0?{changed:beforeRaw!==mutation.raw,result:mutation.result}:{changed:await writeWorkspaceJsonWithHistoryLocked({...params,raw:mutation.raw},beforeRaw),result:mutation.result}}finally{await release()}}async function writeWorkspaceJsonWithHistory(params){const release=await acquireLock(params.pmRoot,"workspace-history",params.lockTtlSeconds,params.author,!1,!1,params.lockWaitMs);try{return await writeWorkspaceJsonWithHistoryLocked(params,await readFileIfExists(params.filePath))}finally{await release()}}async function reconcileWorkspaceJsonHistory(options){const authorizationDecision=options.authorizationDecision.trim();if(!authorizationDecision)throw new TypeError("Workspace history reconciliation requires an authorization decision");const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),historyPath=getWorkspaceHistoryPath(options.pmRoot),entries=await readHistoryEntries(historyPath,WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors);const beforeDocument=replayWorkspaceEntries(entries),priorDocuments=workspaceDocuments(beforeDocument);if(!Object.hasOwn(priorDocuments,documentPath))throw new TypeError(`Workspace history does not govern document ${documentPath}`);const raw=await readFileIfExists(absolutePath);if(raw===null)throw new TypeError(`Workspace history document is missing: ${documentPath}`);const current=JSON.parse(raw);if(stableStringify(priorDocuments[documentPath])===stableStringify(current))return{changed:!1,historyPath};const timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...priorDocuments,[documentPath]:current},beforeDocument.metadata.created_at),message:options.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:documentPath,authorization_decision:authorizationDecision}});return await appendHistoryEntry(historyPath,entry),{changed:!0,entry,historyPath}}finally{await release()}}async function restoreWorkspaceJsonFromHistory(options){const release=await acquireLock(options.pmRoot,"workspace-history",options.lockTtlSeconds,options.author,!1,!1,options.lockWaitMs);try{const{documentPath,absolutePath}=resolveGovernedDocumentPath(options.pmRoot,options.filePath),entries=await readHistoryEntries(getWorkspaceHistoryPath(options.pmRoot),WORKSPACE_HISTORY_ID),verification=verifyHistoryChain(entries);if(verification.ok||throwWorkspaceHistoryVerificationFailure(verification.errors),!Number.isInteger(options.targetVersion)||options.targetVersion<1||options.targetVersion>entries.length)throw new TypeError(`Invalid workspace history target version: ${String(options.targetVersion)}`);const target=workspaceDocuments(replayWorkspaceEntries(entries,options.targetVersion))[documentPath];if(target===void 0)throw new TypeError(`Workspace history version ${options.targetVersion} does not contain ${documentPath}`);const beforeRaw=await readFileIfExists(absolutePath),targetRaw=`${JSON.stringify(target,null,2)}
2
- `;if(beforeRaw===targetRaw)return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!1};const beforeDocument=replayWorkspaceEntries(entries),timestamp=nowIso(),entry=createHistoryEntry({nowIso:timestamp,author:options.author,op:options.op,before:beforeDocument,after:workspaceDocument({...workspaceDocuments(beforeDocument),[documentPath]:target},beforeDocument.metadata.created_at),message:options.message,context:{reason:"workspace_state_restore",document_path:documentPath,restored_from_version:options.targetVersion,replaced_out_of_band_state:!0}});await writeFileAtomic(absolutePath,targetRaw);try{await appendHistoryEntry(getWorkspaceHistoryPath(options.pmRoot),entry)}catch(error){throw beforeRaw===null?await fs.rm(absolutePath,{force:!0}):await writeFileAtomic(absolutePath,beforeRaw),error}return{document_path:documentPath,restored_from_version:options.targetVersion,changed:!0}}finally{await release()}}export{WORKSPACE_HISTORY_ID,appendWorkspaceAuditEvent,appendWorkspaceHistoryChange,getWorkspaceHistoryPath,inspectWorkspaceHistoryState,mutateWorkspaceJsonWithHistory,reconcileWorkspaceJsonHistory,restoreWorkspaceJsonFromHistory,writeWorkspaceJsonWithHistory};
1
+ import $ from"node:fs/promises";import p from"node:path";import{readFileIfExists as W,writeFileAtomic as b}from"../fs/fs-utils.js";import{acquireLock as w}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT as P,EXIT_CODE as O}from"../shared/constants.js";import{PmCliError as C}from"../shared/errors.js";import{stableStringify as h}from"../shared/serialization.js";import{nowIso as R}from"../shared/time.js";import{appendHistoryEntry as x,createHistoryEntry as S}from"./history.js";import{readHistoryEntries as k}from"./read.js";import{cloneEmptyReplayDocument as A,replayToItemDocument as J,tryApplyReplayPatch as j,verifyHistoryChain as _}from"./replay.js";const f="_workspace";function y(t){return p.join(t,"history",`${f}.jsonl`)}function D(t,o){return{metadata:{id:f,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:o,updated_at:o,documents:t},body:""}}function m(t,o=t.length){let r=A();for(const e of t.slice(0,o))r=j(r,e.patch).document;return J(r)}function g(t){return"documents"in t.metadata&&typeof t.metadata.documents=="object"&&t.metadata.documents!==null&&!Array.isArray(t.metadata.documents)?t.metadata.documents:{}}function v(t){throw new C(`Workspace history verification failed: ${t.join(", ")}`,O.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...t],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function T(t,o){const r=p.resolve(o),e=p.relative(t,r).replaceAll("\\","/");if(e.length===0||e===".."||e.startsWith("../")||p.isAbsolute(e))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:e,absolutePath:r}}async function X(t){const o=await k(y(t),f),r=_(o);r.ok||v(r.errors);const e=g(o.length===0?P:m(o)),a=[],n=[],i=[],c=[];for(const s of Object.keys(e).sort()){let u;try{const l=T(t,p.resolve(t,s));if(u=await W(l.absolutePath),u===null){i.push(s);continue}const d=JSON.parse(u);(h(d)===h(e[s])?a:n).push(s)}catch{c.push(s)}}return{ok:n.length===0&&i.length===0&&c.length===0,document_count:Object.keys(e).length,matching_documents:a,mismatched_documents:n,missing_documents:i,unreadable_documents:c}}async function H(t){const o=y(t.pmRoot),r=await k(o,f),e=_(r);e.ok||v(e.errors);const a=t.idempotencyKey===void 0?void 0:r.find(d=>d.op===`${t.op}:${t.idempotencyKey}`);if(a)return{entry:a,historyPath:o};const n=R(),i=r.length===0?P:m(r),c=g(i),s=c[t.documentPath];if(s!==void 0&&h(s)!==h(t.before))throw new C(`Workspace history state for "${t.documentPath}" changed outside the audited mutation path.`,O.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});const u=D({...c,[t.documentPath]:t.after},r.length===0?n:i.metadata.created_at),l=S({nowIso:n,author:t.author,op:t.idempotencyKey===void 0?t.op:`${t.op}:${t.idempotencyKey}`,before:i,after:u,message:t.message});return await x(o,l),{entry:l,historyPath:o}}async function Q(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{return await H(t)}finally{await o()}}async function Z(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const r=y(t.pmRoot),e=await k(r,f),a=_(e);a.ok||v(a.errors);const n=e.length===0?P:m(e),i=S({nowIso:R(),author:t.author,op:t.op,before:n,after:n,message:t.message,context:t.context});return await x(r,i),{entry:i,historyPath:r}}finally{await o()}}async function N(t,o){if(o===t.raw)return!1;const r=o===null?null:JSON.parse(o),e=JSON.parse(t.raw);await b(t.filePath,t.raw);try{(o!==null||t.recordCreation!==!1)&&await H({pmRoot:t.pmRoot,documentPath:p.relative(t.pmRoot,t.filePath).replaceAll("\\","/"),before:r,after:e,op:t.op,idempotencyKey:t.idempotencyKey,author:t.author,lockTtlSeconds:t.lockTtlSeconds,lockWaitMs:t.lockWaitMs,message:t.message})}catch(a){throw o===null?await $.rm(t.filePath,{force:!0}):await b(t.filePath,o),a}return!0}async function tt(t){const{documentPath:o}=T(t.pmRoot,t.filePath),r=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const e=await W(t.filePath);if(t.dryRun===!0||t.idempotencyKey!==void 0){const n=await k(y(t.pmRoot),f),i=_(n);i.ok||v(i.errors);const c=g(n.length===0?P:m(n))[o];if(c!==void 0&&h(c)!==h(e===null?null:JSON.parse(e)))throw new C(`Workspace history state for "${o}" changed outside the audited mutation path.`,O.CONFLICT,{code:"workspace_history_state_conflict"});if(t.idempotencyKey!==void 0&&n.some(s=>s.op===`${t.op}:${t.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}const a=await t.mutate(e);return JSON.parse(a.raw),t.dryRun===!0?{changed:e!==a.raw,result:a.result}:{changed:await N({...t,raw:a.raw},e),result:a.result}}finally{await r()}}async function et(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{return await N(t,await W(t.filePath))}finally{await o()}}async function ot(t){const o=t.authorizationDecision.trim();if(!o)throw new TypeError("Workspace history reconciliation requires an authorization decision");const r=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const{documentPath:e,absolutePath:a}=T(t.pmRoot,t.filePath),n=y(t.pmRoot),i=await k(n,f),c=_(i);c.ok||v(c.errors);const s=m(i),u=g(s);if(!Object.hasOwn(u,e))throw new TypeError(`Workspace history does not govern document ${e}`);const l=await W(a);if(l===null)throw new TypeError(`Workspace history document is missing: ${e}`);const d=JSON.parse(l);if(h(u[e])===h(d))return{changed:!1,historyPath:n};const E=R(),I=S({nowIso:E,author:t.author,op:t.op,before:s,after:D({...u,[e]:d},s.metadata.created_at),message:t.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:e,authorization_decision:o}});return await x(n,I),{changed:!0,entry:I,historyPath:n}}finally{await r()}}async function rt(t){const o=await w(t.pmRoot,"workspace-history",t.lockTtlSeconds,t.author,!1,!1,t.lockWaitMs);try{const{documentPath:r,absolutePath:e}=T(t.pmRoot,t.filePath),a=await k(y(t.pmRoot),f),n=_(a);if(n.ok||v(n.errors),!Number.isInteger(t.targetVersion)||t.targetVersion<1||t.targetVersion>a.length)throw new TypeError(`Invalid workspace history target version: ${String(t.targetVersion)}`);const i=g(m(a,t.targetVersion))[r];if(i===void 0)throw new TypeError(`Workspace history version ${t.targetVersion} does not contain ${r}`);const c=await W(e),s=`${JSON.stringify(i,null,2)}
2
+ `;if(c===s)return{document_path:r,restored_from_version:t.targetVersion,changed:!1};const u=m(a),l=R(),d=S({nowIso:l,author:t.author,op:t.op,before:u,after:D({...g(u),[r]:i},u.metadata.created_at),message:t.message,context:{reason:"workspace_state_restore",document_path:r,restored_from_version:t.targetVersion,replaced_out_of_band_state:!0}});await b(e,s);try{await x(y(t.pmRoot),d)}catch(E){throw c===null?await $.rm(e,{force:!0}):await b(e,c),E}return{document_path:r,restored_from_version:t.targetVersion,changed:!0}}finally{await o()}}export{f as WORKSPACE_HISTORY_ID,Z as appendWorkspaceAuditEvent,Q as appendWorkspaceHistoryChange,y as getWorkspaceHistoryPath,X as inspectWorkspaceHistoryState,tt as mutateWorkspaceJsonWithHistory,ot as reconcileWorkspaceJsonHistory,rt as restoreWorkspaceJsonFromHistory,et as writeWorkspaceJsonWithHistory};
3
3
  //# sourceMappingURL=workspace-history.js.map