@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,6 +1,6 @@
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]="28c1b131-2a07-5308-96de-40bac827a210")}catch{}})();import{isUtf8}from"node:buffer";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{readFile}from"node:fs/promises";import{isFileMissingError,readFileIfExists}from"../../core/fs/fs-utils.js";import{acquireLock}from"../../core/lock/lock.js";import{createHistoryEntry,sealHistoryRecord}from"../../core/history/history.js";import{checkHistoryRewriteOwnership,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{replayHistoryToTarget}from"../../core/history/projection.js";import{cloneEmptyReplayDocument,lenientApplyReplayPatch,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChainWithVersion}from"../../core/history/replay.js";import{SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../../core/history/history.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{describeHistoryRecordDefect,isNonRecordScalar}from"../../core/history/read.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../../core/shared/constants.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../../core/extensions/index.js";import{locateItem,readLocatedItemSnapshot}from"../../core/store/item-store.js";function decodeSalvageLine(line){const text=line.trim();let parsed;try{parsed=JSON.parse(text)}catch{if(text.startsWith("{")&&text.includes("}"))throw new PmCliError("History salvage cannot discard a potentially complete record with trailing corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(isNonRecordScalar(parsed))return{kind:"non_record"};if(describeHistoryRecordDefect(parsed)!==null)throw new PmCliError("History salvage would conceal interior corruption or a malformed record.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});const entry=parsed;if(!Array.isArray(entry.patch)||![entry.ts,entry.author,entry.op,entry.before_hash,entry.after_hash].every(field=>typeof field=="string"))throw new PmCliError("History salvage requires complete history records before the invalid tail.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry}}function newestDeclaredEpoch(entries){return[...entries].reverse().find(entry=>SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version))?.item_hash_version}function inspectHistoryTail(raw){if(findFirstMergeConflictMarker(raw))throw new PmCliError("Resolve history merge conflicts before salvage.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});const scan=scanSalvageLines(raw),judged=judgeRetainedChain(scan);return{entries:scan.entries,...judged,...selectSalvagedBytes(raw,scan.nonRecord,scan.invalidOffset,scan.invalidLine,scan.entries.length)}}function scanSalvageLines(raw){const scan={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0};let offset=0;for(const[index,line]of raw.split(`
2
- `).entries()){const start=offset;if(offset+=line.length+1,!line.trim())continue;const decoded=decodeSalvageLine(line);if(decoded.kind==="record"){if(scan.invalidOffset!==void 0)throw new PmCliError("History salvage would discard a record or conceal interior corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});scan.entries.push(decoded.entry)}else decoded.kind==="non_record"&&scan.invalidOffset===void 0?scan.nonRecord.push({start,end:Math.min(offset,raw.length),line:index+1}):scan.invalidOffset===void 0&&(scan.invalidOffset=start,scan.invalidLine=index+1)}return scan}function judgeRetainedChain(scan){const verification=verifyHistoryChainWithVersion(scan.entries),verified=verification.ok&&verification.item_hash_version!==void 0;if(!(scan.invalidOffset===void 0&&scan.nonRecord.length>0)&&(scan.entries.length===0||!verified)){const nothingToDiscard=scan.entries.length>0&&scan.invalidOffset===void 0;throw new PmCliError("History salvage requires a nonempty verified prefix.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",verification_errors:verification.errors,required:"Recover an intact history prefix from version control or a backup.",...nothingToDiscard?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:verified?verification.item_hash_version:newestDeclaredEpoch(scan.entries),verification:{ok:verification.ok,errors:verification.errors}}}function salvageHashAlgorithm(last){try{return resolveHistoryHashAlgorithm(last.hash_algorithm)}catch{const unknownLabel=typeof last.hash_algorithm=="string";throw new PmCliError(unknownLabel?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:unknownLabel?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[unknownLabel?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function salvagedStream(selected,author,message){const last=selected.entries.at(-1);if(last===void 0)return selected.prefix;const empty=EMPTY_CANONICAL_DOCUMENT,{item_hash_version:_stamped,...entry}=createHistoryEntry({hashAlgorithm:salvageHashAlgorithm(last),nowIso:nowIso(),author,op:"history_salvage",before:empty,after:empty,message,context:{history_salvage:selected.receipt}}),audit=sealHistoryRecord({...entry,before_hash:last.after_hash,after_hash:last.after_hash,...selected.itemHashVersion===void 0?{}:{item_hash_version:selected.itemHashVersion}});return`${selected.prefix}${JSON.stringify(audit)}
3
- `}function assertSalvageIdentity(id,replay){if(typeof replay.metadata.id=="string"&&replay.metadata.id!==id)throw new PmCliError("History belongs to another item; salvage refused.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"})}function replayRetainedRecords(id,selected){const strict=selected.verification.ok;let replay=cloneEmptyReplayDocument(),lastItem=replay;for(const entry of selected.entries){const applied=strict?tryApplyReplayPatch(replay,entry.patch):void 0;replay=applied?.ok===!0?applied.document:lenientApplyReplayPatch(replay,entry.patch,entry.op).document,assertSalvageIdentity(id,replay),Object.keys(replay.metadata).length>0&&(lastItem=replay)}return strict&&selected.entries.length>0?{final:replayHistoryToTarget(selected.entries,selected.entries.length-1),lastItem}:{final:replay,lastItem}}function selectSalvagedBytes(raw,nonRecord,invalidOffset,invalidLine,retainedEntries){const retainedEnd=invalidOffset??raw.length,discarded=[...nonRecord.map(({start,end})=>raw.slice(start,end)),raw.slice(retainedEnd)].join("");let prefix="",cursor=0;for(const{start,end}of nonRecord)prefix+=raw.slice(cursor,start),cursor=end;return prefix+=raw.slice(cursor,retainedEnd),prefix!==""&&!prefix.endsWith(`
4
- `)&&(prefix+=`
5
- `),discarded===""?{prefix,receipt:null}:{prefix,receipt:{first_invalid_line:nonRecord[0]?.line??invalidLine,discarded_bytes:Buffer.byteLength(discarded),discarded_sha256:sha256Hex(discarded),retained_entries:retainedEntries,...nonRecord.length>0?{non_record_lines:nonRecord.length}:{}}}}function assertJudgeableSalvageOwner(id,document,force){const assignee=document.metadata?.assignee;if(!(force||assignee===void 0||assignee===null||typeof assignee=="string"))throw new PmCliError(`The recorded owner of ${id} is not a name, so salvage cannot check ownership.`,EXIT_CODE.CONFLICT,{code:"history_salvage_refused",item_id:id,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${id}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function readSalvageOwnership(located,settings,fallback){if(!located)return{itemRaw:null,document:fallback,live:null};const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return{itemRaw:snapshot.raw,document:snapshot.document??fallback,live:snapshot.document}}function assertSalvageRevision(pmRoot,id,ownership){ownership.itemRaw!==null&&ownership.live===null&&assertItemRevisionExpectationsOnUnreadable(pmRoot,id,ownership.itemRaw);const live=ownership.live??EMPTY_CANONICAL_DOCUMENT;return assertItemMutationPreconditions(pmRoot,live,id),live}async function readSalvageStream(historyPath){let bytes;try{bytes=await readFile(historyPath)}catch(error){if(isFileMissingError(error))return null;throw error}if(!isUtf8(bytes))throw new PmCliError("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return bytes.toString("utf8")}async function salvageHistoryTail(params){const{subject,settings,options,author}=params;if([options.normalizeProvenance,options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById].some(Boolean))throw new PmCliError("Tail salvage cannot be combined with other repair modes.",EXIT_CODE.USAGE);const raw=await readSalvageStream(subject.historyPath);if(raw===null)throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND);await runActiveOnReadHooks({path:subject.historyPath,scope:"project"});const selected=inspectHistoryTail(raw),replayed=replayRetainedRecords(subject.id,selected),document=replayToItemDocument(replayed.final),nextHistoryRaw=selected.receipt===null?raw:salvagedStream(selected,author,options.message),ownership=await readSalvageOwnership(subject.located,settings,replayToItemDocument(replayed.lastItem));assertJudgeableSalvageOwner(subject.id,ownership.document,options.force===!0);const warnings=checkHistoryRewriteOwnership({itemDocument:ownership.document,subjectId:subject.id,author,force:options.force,settings}),dryRun=options.dryRun===!0,changed=selected.receipt!==null;if(changed&&!dryRun){const release=await acquireLock(params.pmRoot,subject.id,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const currentRaw=await readSalvageStream(subject.historyPath),located=await locateItem(params.pmRoot,subject.id,settings.id_prefix,settings.item_format,params.typeRegistry.type_to_folder),currentItem=located?await readFileIfExists(located.itemPath):null;if(currentRaw!==raw||currentItem!==ownership.itemRaw)throw assertSalvageRevision(params.pmRoot,subject.id,await readSalvageOwnership(located,settings,document)),new PmCliError("History or item changed while waiting for salvage lock; retry.",EXIT_CODE.CONFLICT);const live=assertSalvageRevision(params.pmRoot,subject.id,ownership);await writeHistoryRawWithRollback({historyPath:subject.historyPath,historyRawUnderLock:raw,nextHistoryRaw}),advanceItemMutationPreconditions(params.pmRoot,live,subject.id),warnings.push(...await runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await release()}}return reportSalvage(subject,selected,{changed,dryRun,warnings})}function salvageFollowUp(subject,selected){return selected.entries.length===0?subject.located===null?[]:[`history_stream_empty:${subject.id}:run pm history-repair ${subject.id}`]:selected.verification.ok?[]:[`history_chain_unverified:${subject.id}:run pm history-repair ${subject.id} --append-only --dry-run, or pm history-repair ${subject.id} --dry-run when a bridge refuses`]}function reportSalvage(subject,selected,outcome){const version=selected.itemHashVersion,{ok,errors}=selected.verification;return{id:subject.id,dry_run:outcome.dryRun,changed:outcome.changed,history:{path:subject.historyPath,entries_scanned:selected.entries.length,chain_drift_before:!ok,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:outcome.changed&&!outcome.dryRun&&selected.entries.length>0,verify_ok:ok,verify_errors:errors,item_hash_version_before:version??null,item_hash_version_after:version??1,version_disposition:"preserved"},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...selected.receipt?{salvage:selected.receipt}:{},warnings:[...outcome.warnings,...salvageFollowUp(subject,selected)],generated_at:nowIso()}}export{inspectHistoryTail,salvageHistoryTail};
1
+ import{isUtf8 as C}from"node:buffer";import{resolveHistoryHashAlgorithm as T}from"../../core/history/digest.js";import{readFile as S}from"node:fs/promises";import{isFileMissingError as L,readFileIfExists as N}from"../../core/fs/fs-utils.js";import{acquireLock as x}from"../../core/lock/lock.js";import{createHistoryEntry as P,sealHistoryRecord as F}from"../../core/history/history.js";import{checkHistoryRewriteOwnership as E,writeHistoryRawWithRollback as A}from"../../core/history/history-rewrite.js";import{replayHistoryToTarget as q}from"../../core/history/projection.js";import{cloneEmptyReplayDocument as D,lenientApplyReplayPatch as U,replayToItemDocument as v,tryApplyReplayPatch as $,verifyHistoryChainWithVersion as M}from"../../core/history/replay.js";import{SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as B}from"../../core/history/history.js";import{findFirstMergeConflictMarker as V}from"../../core/shared/conflict-markers.js";import{describeHistoryRecordDefect as W,isNonRecordScalar as J}from"../../core/history/read.js";import{EMPTY_CANONICAL_DOCUMENT as g,EXIT_CODE as s}from"../../core/shared/constants.js";import{advanceItemMutationPreconditions as z,assertItemMutationPreconditions as Y,assertItemRevisionExpectationsOnUnreadable as G}from"../../core/store/item-mutation-precondition.js";import{PmCliError as d}from"../../core/shared/errors.js";import{sha256Hex as X}from"../../core/shared/serialization.js";import{nowIso as _}from"../../core/shared/time.js";import{runActiveOnReadHooks as K,runActiveOnWriteHooks as Q}from"../../core/extensions/index.js";import{locateItem as Z,readLocatedItemSnapshot as j}from"../../core/store/item-store.js";function ee(r){const e=r.trim();let i;try{i=JSON.parse(e)}catch{if(e.startsWith("{")&&e.includes("}"))throw new d("History salvage cannot discard a potentially complete record with trailing corruption.",s.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(J(i))return{kind:"non_record"};if(W(i)!==null)throw new d("History salvage would conceal interior corruption or a malformed record.",s.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});const t=i;if(!Array.isArray(t.patch)||![t.ts,t.author,t.op,t.before_hash,t.after_hash].every(o=>typeof o=="string"))throw new d("History salvage requires complete history records before the invalid tail.",s.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry:t}}function re(r){return[...r].reverse().find(e=>B.includes(e.item_hash_version))?.item_hash_version}function te(r){if(V(r))throw new d("Resolve history merge conflicts before salvage.",s.CONFLICT,{code:"history_salvage_refused"});const e=ie(r),i=oe(e);return{entries:e.entries,...i,...ce(r,e.nonRecord,e.invalidOffset,e.invalidLine,e.entries.length)}}function ie(r){const e={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0};let i=0;for(const[t,o]of r.split(`
2
+ `).entries()){const n=i;if(i+=o.length+1,!o.trim())continue;const a=ee(o);if(a.kind==="record"){if(e.invalidOffset!==void 0)throw new d("History salvage would discard a record or conceal interior corruption.",s.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});e.entries.push(a.entry)}else a.kind==="non_record"&&e.invalidOffset===void 0?e.nonRecord.push({start:n,end:Math.min(i,r.length),line:t+1}):e.invalidOffset===void 0&&(e.invalidOffset=n,e.invalidLine=t+1)}return e}function oe(r){const e=M(r.entries),i=e.ok&&e.item_hash_version!==void 0;if(!(r.invalidOffset===void 0&&r.nonRecord.length>0)&&(r.entries.length===0||!i)){const o=r.entries.length>0&&r.invalidOffset===void 0;throw new d("History salvage requires a nonempty verified prefix.",s.CONFLICT,{code:"history_salvage_refused",verification_errors:e.errors,required:"Recover an intact history prefix from version control or a backup.",...o?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:i?e.item_hash_version:re(r.entries),verification:{ok:e.ok,errors:e.errors}}}function ne(r){try{return T(r.hash_algorithm)}catch{const e=typeof r.hash_algorithm=="string";throw new d(e?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",s.CONFLICT,{code:"history_salvage_refused",required:e?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[e?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function ae(r,e,i){const t=r.entries.at(-1);if(t===void 0)return r.prefix;const o=g,{item_hash_version:n,...a}=P({hashAlgorithm:ne(t),nowIso:_(),author:e,op:"history_salvage",before:o,after:o,message:i,context:{history_salvage:r.receipt}}),c=F({...a,before_hash:t.after_hash,after_hash:t.after_hash,...r.itemHashVersion===void 0?{}:{item_hash_version:r.itemHashVersion}});return`${r.prefix}${JSON.stringify(c)}
3
+ `}function se(r,e){if(typeof e.metadata.id=="string"&&e.metadata.id!==r)throw new d("History belongs to another item; salvage refused.",s.CONFLICT,{code:"history_salvage_refused"})}function de(r,e){const i=e.verification.ok;let t=D(),o=t;for(const n of e.entries){const a=i?$(t,n.patch):void 0;t=a?.ok===!0?a.document:U(t,n.patch,n.op).document,se(r,t),Object.keys(t.metadata).length>0&&(o=t)}return i&&e.entries.length>0?{final:q(e.entries,e.entries.length-1),lastItem:o}:{final:t,lastItem:o}}function ce(r,e,i,t,o){const n=i??r.length,a=[...e.map(({start:f,end:l})=>r.slice(f,l)),r.slice(n)].join("");let c="",h=0;for(const{start:f,end:l}of e)c+=r.slice(h,f),h=l;return c+=r.slice(h,n),c!==""&&!c.endsWith(`
4
+ `)&&(c+=`
5
+ `),a===""?{prefix:c,receipt:null}:{prefix:c,receipt:{first_invalid_line:e[0]?.line??t,discarded_bytes:Buffer.byteLength(a),discarded_sha256:X(a),retained_entries:o,...e.length>0?{non_record_lines:e.length}:{}}}}function le(r,e,i){const t=e.metadata?.assignee;if(!(i||t===void 0||t===null||typeof t=="string"))throw new d(`The recorded owner of ${r} is not a name, so salvage cannot check ownership.`,s.CONFLICT,{code:"history_salvage_refused",item_id:r,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${r}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function w(r,e,i){if(!r)return{itemRaw:null,document:i,live:null};const t=await j(r,{schema:e.schema});return{itemRaw:t.raw,document:t.document??i,live:t.document}}function R(r,e,i){i.itemRaw!==null&&i.live===null&&G(r,e,i.itemRaw);const t=i.live??g;return Y(r,t,e),t}async function O(r){let e;try{e=await S(r)}catch(i){if(L(i))return null;throw i}if(!C(e))throw new d("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",s.CONFLICT,{code:"history_salvage_refused"});return e.toString("utf8")}async function xe(r){const{subject:e,settings:i,options:t,author:o}=r;if([t.normalizeProvenance,t.auditOperation,t.auditContext,t.auditContextById,t.forceAuditEntry,t.mergeReceiptProof,t.mergeReceiptProofById].some(Boolean))throw new d("Tail salvage cannot be combined with other repair modes.",s.USAGE);const n=await O(e.historyPath);if(n===null)throw new d(`No history stream exists for ${e.id}.`,s.NOT_FOUND);await K({path:e.historyPath,scope:"project"});const a=te(n),c=de(e.id,a),h=v(c.final),f=a.receipt===null?n:ae(a,o,t.message),l=await w(e.located,i,v(c.lastItem));le(e.id,l.document,t.force===!0);const m=E({itemDocument:l.document,subjectId:e.id,author:o,force:t.force,settings:i}),p=t.dryRun===!0,y=a.receipt!==null;if(y&&!p){const k=await x(r.pmRoot,e.id,i.locks.ttl_seconds,o,!!t.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{const H=await O(e.historyPath),u=await Z(r.pmRoot,e.id,i.id_prefix,i.item_format,r.typeRegistry.type_to_folder),I=u?await N(u.itemPath):null;if(H!==n||I!==l.itemRaw)throw R(r.pmRoot,e.id,await w(u,i,h)),new d("History or item changed while waiting for salvage lock; retry.",s.CONFLICT);const b=R(r.pmRoot,e.id,l);await A({historyPath:e.historyPath,historyRawUnderLock:n,nextHistoryRaw:f}),z(r.pmRoot,b,e.id),m.push(...await Q({path:e.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await k()}}return fe(e,a,{changed:y,dryRun:p,warnings:m})}function he(r,e){return e.entries.length===0?r.located===null?[]:[`history_stream_empty:${r.id}:run pm history-repair ${r.id}`]:e.verification.ok?[]:[`history_chain_unverified:${r.id}:run pm history-repair ${r.id} --append-only --dry-run, or pm history-repair ${r.id} --dry-run when a bridge refuses`]}function fe(r,e,i){const t=e.itemHashVersion,{ok:o,errors:n}=e.verification;return{id:r.id,dry_run:i.dryRun,changed:i.changed,history:{path:r.historyPath,entries_scanned:e.entries.length,chain_drift_before:!o,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:i.changed&&!i.dryRun&&e.entries.length>0,verify_ok:o,verify_errors:n,item_hash_version_before:t??null,item_hash_version_after:t??1,version_disposition:"preserved"},item:{exists:r.located!==null,path:r.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...e.receipt?{salvage:e.receipt}:{},warnings:[...i.warnings,...he(r,e)],generated_at:_()}}export{te as inspectHistoryTail,xe as salvageHistoryTail};
6
6
  //# sourceMappingURL=salvage.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]="59842825-3a81-53f4-845d-db2257ec6286")}catch{}})();import{pathExists}from"../../core/fs/fs-utils.js";import{normalizeItemId,normalizeRawItemId}from"../../core/item/id.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{locateItem}from"../../core/store/item-store.js";import{getHistoryPath}from"../../core/store/paths.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{assertInitializedTracker}from"../environment/tracker-preflight.js";async function resolveHistoryWorkspace(pmPath){const pmRoot=resolvePmRoot(process.cwd(),pmPath);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());return{pmRoot,settings,typeRegistry}}async function resolveHistorySubject(pmRoot,id,settings,typeToFolder){getHistoryPath(pmRoot,normalizeRawItemId(id));const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(located)return{id:located.id,historyPath:getHistoryPath(pmRoot,located.id),located};const normalizedId=normalizeItemId(id,settings.id_prefix),rawNormalizedId=normalizeRawItemId(id),candidateIds=normalizedId===rawNormalizedId?[normalizedId]:[normalizedId,rawNormalizedId];for(const candidateId of candidateIds){const historyPath=getHistoryPath(pmRoot,candidateId);if(await pathExists(historyPath))return{id:candidateId,historyPath,located:null}}throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND)}export{resolveHistorySubject,resolveHistoryWorkspace};
1
+ import{pathExists as p}from"../../core/fs/fs-utils.js";import{normalizeItemId as l,normalizeRawItemId as f}from"../../core/item/id.js";import{EXIT_CODE as I}from"../../core/shared/constants.js";import{PmCliError as y}from"../../core/shared/errors.js";import{locateItem as w}from"../../core/store/item-store.js";import{getHistoryPath as m}from"../../core/store/paths.js";import{getActiveExtensionRegistrations as u}from"../../core/extensions/index.js";import{resolveItemTypeRegistry as h}from"../../core/item/type-registry.js";import{resolvePmRoot as x}from"../../core/store/paths.js";import{readSettings as g}from"../../core/store/settings.js";import{assertInitializedTracker as v}from"../environment/tracker-preflight.js";async function D(r){const t=x(process.cwd(),r);await v(t);const o=await g(t),i=h(o,u());return{pmRoot:t,settings:o,typeRegistry:i}}async function S(r,t,o,i){m(r,f(t));const e=await w(r,t,o.id_prefix,o.item_format,i);if(e)return{id:e.id,historyPath:m(r,e.id),located:e};const a=l(t,o.id_prefix),s=f(t),d=a===s?[a]:[a,s];for(const n of d){const c=m(r,n);if(await p(c))return{id:n,historyPath:c,located:null}}throw new y(`Item ${t} not found`,I.NOT_FOUND)}export{S as resolveHistorySubject,D as resolveHistoryWorkspace};
2
2
  //# sourceMappingURL=subject.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]="6b51fdd9-9923-53c5-a798-41c15fd847a0")}catch{}})();import{AGENT_PROVENANCE_DIMENSIONS,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{listMutationEvents}from"./mutation-events.js";import{analyzeAgentProvenanceDescriptorCoverage,summarizeAgentProvenance}from"./provenance.js";const DEFAULT_HISTORY_ANALYTICS_LIMIT=1e4,MAX_HISTORY_ANALYTICS_LIMIT=1e5,HISTORY_EVENT_PAGE_LIMIT=1e3,DEFAULT_HISTORY_WINDOW_DAYS=30,ANNOTATION_OPERATION_PREFIXES=["append","comment","docs","file","learning","note","test_run"];function parseHistoryAnalyticsLimit(value){const limit=value??DEFAULT_HISTORY_ANALYTICS_LIMIT;if(!Number.isSafeInteger(limit)||limit<1||limit>MAX_HISTORY_ANALYTICS_LIMIT)throw new PmCliError(`History analytics event limit must be an integer from 1 to ${MAX_HISTORY_ANALYTICS_LIMIT}.`,EXIT_CODE.USAGE,{code:"invalid_history_analytics_limit"});return limit}function parseMinimumSample(value){const minimum=value??5;if(!Number.isSafeInteger(minimum)||minimum<1||minimum>1e4)throw new PmCliError("History analytics minimum sample must be an integer from 1 to 10000.",EXIT_CODE.USAGE,{code:"invalid_history_analytics_minimum_sample"});return minimum}function resolveHistoryAnalyticsSince(value){const raw=value?.trim();if(!raw)return new Date(Date.now()-DEFAULT_HISTORY_WINDOW_DAYS*864e5).toISOString();const relative=/^-(\d+)([dh])$/u.exec(raw);if(relative){const amount=Number(relative[1]),multiplier=relative[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(amount)||amount<1)throw new PmCliError("History analytics --since duration must be positive.",EXIT_CODE.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-amount*multiplier).toISOString()}const milliseconds=Date.parse(raw);if(!Number.isFinite(milliseconds))throw new PmCliError("History analytics --since must be an ISO timestamp or negative duration such as -30d.",EXIT_CODE.USAGE,{code:"invalid_history_analytics_since"});return new Date(milliseconds).toISOString()}async function readHistoryAnalyticsWindow(pmRoot,options){const eventLimit=parseHistoryAnalyticsLimit(options.eventLimit),since=resolveHistoryAnalyticsSince(options.since),events=[];let cursor=since,hasMore=!1;for(;events.length<eventLimit;){const page=await listMutationEvents({pmRoot,since:cursor,limit:Math.min(HISTORY_EVENT_PAGE_LIMIT,eventLimit-events.length),full:!0}),pageEvents=page.events.map(event=>({item_id:event.item_id,entry:event.entry}));if(events.push(...pageEvents),hasMore=page.has_more,cursor=page.next_cursor,!page.has_more)break}return{events,receipt:{since,events:events.length,truncated:hasMore,...hasMore?{next_cursor:cursor}:{},source:"history_event_index"}}}function provenanceValue(entry,dimension){return dimension==="harness"?entry.agent_harness:dimension==="author_source"?entry.author_source:entry.agent_model??entry.agent_provenance?.model?.value}function statusFromEntry(entry){for(let index=entry.patch.length-1;index>=0;index-=1){const operation=entry.patch[index];if(operation.path==="/metadata/status"&&"value"in operation&&typeof operation.value=="string")return operation.value}}function annotationOperation(op){return ANNOTATION_OPERATION_PREFIXES.some(prefix=>op.startsWith(prefix))}function bucketFor(buckets,value){const existing=buckets.get(value);if(existing)return existing;const created={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return buckets.set(value,created),created}function accumulateFleetEvents(dimension,events,terminalStatuses){const buckets=new Map,streamTerminal=new Map,lastCloseValue=new Map;for(const event of events){const value=provenanceValue(event.entry,dimension),status=statusFromEntry(event.entry),wasTerminal=streamTerminal.get(event.item_id)===!0,isTerminal=status===void 0?wasTerminal:terminalStatuses.has(status);if(status!==void 0&&streamTerminal.set(event.item_id,isTerminal),!value)continue;const bucket=bucketFor(buckets,value);bucket.events+=1,annotationOperation(event.entry.op)?bucket.annotationEvents+=1:bucket.stateEvents+=1,status!==void 0&&!wasTerminal&&isTerminal?(bucket.closes+=1,lastCloseValue.set(event.item_id,value)):status!==void 0&&wasTerminal&&!isTerminal&&(bucket.reopens+=1)}return{buckets,lastCloseValue}}function attributeDefectEscapes(buckets,lastCloseValue,items){for(const item of items){if(item.type!=="Issue")continue;const sources=new Set((item.dependencies??[]).filter(dependency=>dependency.kind==="discovered_from").map(dependency=>dependency.id));for(const source of sources){const value=lastCloseValue.get(source);value&&(bucketFor(buckets,value).defectEscapes+=1)}}}function fleetRow(value,bucket,minimumSample,windowDays){const sampleStatus=bucket.closes>=minimumSample?"available":"insufficient";return{value,events:bucket.events,state_events:bucket.stateEvents,annotation_events:bucket.annotationEvents,closes:bucket.closes,reopens:bucket.reopens,defect_escapes:bucket.defectEscapes,throughput_per_day:sampleStatus==="available"?bucket.closes/windowDays:null,rework_rate:sampleStatus==="available"?bucket.reopens/bucket.closes:null,defect_escape_rate:sampleStatus==="available"?bucket.defectEscapes/bucket.closes:null,sample_status:sampleStatus}}function buildFleetDimension(dimension,events,items,terminalStatuses,minimumSample,windowDays){const{buckets,lastCloseValue}=accumulateFleetEvents(dimension,events,terminalStatuses);return attributeDefectEscapes(buckets,lastCloseValue,items),{dimension,status:buckets.size===0?"unavailable":"available",rows:[...buckets].map(([value,bucket])=>fleetRow(value,bucket,minimumSample,windowDays)).sort((left,right)=>right.events-left.events||left.value.localeCompare(right.value))}}function resolveHistoryWindowDays(events,since){const firstTimestamp=events[0]?.entry.ts??since,lastTimestamp=events[events.length-1]?.entry.ts??firstTimestamp,firstMilliseconds=Date.parse(firstTimestamp),lastMilliseconds=Date.parse(lastTimestamp);return!Number.isFinite(firstMilliseconds)||!Number.isFinite(lastMilliseconds)?1:Math.max(1,(lastMilliseconds-firstMilliseconds)/864e5)}function evaluateProvenanceCoverage(entries,descriptors,minimumSample){const descriptorCoverage=analyzeAgentProvenanceDescriptorCoverage(descriptors),observations=summarizeAgentProvenance(entries,AGENT_PROVENANCE_DIMENSIONS,minimumSample),inert=observations.filter(row=>row.inert).map(row=>({harness:row.harness,dimension:row.dimension,explicit_samples:row.observed+row.unavailable})),undeclared=descriptorCoverage.filter(row=>!row.covered).map(row=>row.dimension);return{descriptors:descriptorCoverage,observations,inert,undeclared,warnings:[...inert.map(row=>`provenance_dimension_inert:${row.harness}:${row.dimension}:${String(row.explicit_samples)}`),...undeclared.map(dimension=>`provenance_dimension_undeclared:${dimension}`)]}}async function runProvenanceCoverageAnalytics(pmRoot,descriptors=BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,options={}){return projectProvenanceCoverageAnalytics(await readHistoryAnalyticsWindow(pmRoot,options),descriptors,options)}function projectProvenanceCoverageAnalytics(window2,descriptors=BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,options={}){const minimumSample=parseMinimumSample(options.minimumSample);return{...evaluateProvenanceCoverage(window2.events.map(event=>event.entry),descriptors,minimumSample),window:window2.receipt}}async function runFleetAttributionAnalytics(pmRoot,items,terminalStatuses,options={}){return projectFleetAttributionAnalytics(await readHistoryAnalyticsWindow(pmRoot,options),items,terminalStatuses,options)}function projectFleetAttributionAnalytics(window2,items,terminalStatuses,options={}){const minimumSample=parseMinimumSample(options.minimumSample),windowDays=resolveHistoryWindowDays(window2.events,window2.receipt.since);return{dimensions:["harness","model","author_source"].map(dimension=>buildFleetDimension(dimension,window2.events,items,terminalStatuses,minimumSample,windowDays)),minimum_sample:minimumSample,policy:"observational_only_not_for_authorization_or_routing",window:window2.receipt}}const _testOnlyHistoryAnalytics={annotationOperation,buildFleetDimension,parseHistoryAnalyticsLimit,parseMinimumSample,provenanceValue,resolveHistoryAnalyticsSince,resolveHistoryWindowDays,statusFromEntry};export{_testOnlyHistoryAnalytics,evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics};
1
+ import{AGENT_PROVENANCE_DIMENSIONS as w,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS as d}from"../core/shared/author.js";import{EXIT_CODE as m}from"../core/shared/constants.js";import{PmCliError as p}from"../core/shared/errors.js";import{listMutationEvents as D}from"./mutation-events.js";import{analyzeAgentProvenanceDescriptorCoverage as O,summarizeAgentProvenance as b}from"./provenance.js";const x=1e4,v=1e5,M=1e3,C=30,H=["append","comment","docs","file","learning","note","test_run"];function y(t){const e=t??x;if(!Number.isSafeInteger(e)||e<1||e>v)throw new p(`History analytics event limit must be an integer from 1 to ${v}.`,m.USAGE,{code:"invalid_history_analytics_limit"});return e}function f(t){const e=t??5;if(!Number.isSafeInteger(e)||e<1||e>1e4)throw new p("History analytics minimum sample must be an integer from 1 to 10000.",m.USAGE,{code:"invalid_history_analytics_minimum_sample"});return e}function h(t){const e=t?.trim();if(!e)return new Date(Date.now()-C*864e5).toISOString();const n=/^-(\d+)([dh])$/u.exec(e);if(n){const s=Number(n[1]),r=n[2]==="d"?864e5:36e5;if(!Number.isSafeInteger(s)||s<1)throw new p("History analytics --since duration must be positive.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(Date.now()-s*r).toISOString()}const i=Date.parse(e);if(!Number.isFinite(i))throw new p("History analytics --since must be an ISO timestamp or negative duration such as -30d.",m.USAGE,{code:"invalid_history_analytics_since"});return new Date(i).toISOString()}async function S(t,e){const n=y(e.eventLimit),i=h(e.since),s=[];let r=i,o=!1;for(;s.length<n;){const a=await D({pmRoot:t,since:r,limit:Math.min(M,n-s.length),full:!0}),c=a.events.map(l=>({item_id:l.item_id,entry:l.entry}));if(s.push(...c),o=a.has_more,r=a.next_cursor,!a.has_more)break}return{events:s,receipt:{since:i,events:s.length,truncated:o,...o?{next_cursor:r}:{},source:"history_event_index"}}}function E(t,e){return e==="harness"?t.agent_harness:e==="author_source"?t.author_source:t.agent_model??t.agent_provenance?.model?.value}function g(t){for(let e=t.patch.length-1;e>=0;e-=1){const n=t.patch[e];if(n.path==="/metadata/status"&&"value"in n&&typeof n.value=="string")return n.value}}function A(t){return H.some(e=>t.startsWith(e))}function I(t,e){const n=t.get(e);if(n)return n;const i={events:0,stateEvents:0,annotationEvents:0,closes:0,reopens:0,defectEscapes:0};return t.set(e,i),i}function F(t,e,n){const i=new Map,s=new Map,r=new Map;for(const o of e){const a=E(o.entry,t),c=g(o.entry),l=s.get(o.item_id)===!0,_=c===void 0?l:n.has(c);if(c!==void 0&&s.set(o.item_id,_),!a)continue;const u=I(i,a);u.events+=1,A(o.entry.op)?u.annotationEvents+=1:u.stateEvents+=1,c!==void 0&&!l&&_?(u.closes+=1,r.set(o.item_id,a)):c!==void 0&&l&&!_&&(u.reopens+=1)}return{buckets:i,lastCloseValue:r}}function L(t,e,n){for(const i of n){if(i.type!=="Issue")continue;const s=new Set((i.dependencies??[]).filter(r=>r.kind==="discovered_from").map(r=>r.id));for(const r of s){const o=e.get(r);o&&(I(t,o).defectEscapes+=1)}}}function P(t,e,n,i){const s=e.closes>=n?"available":"insufficient";return{value:t,events:e.events,state_events:e.stateEvents,annotation_events:e.annotationEvents,closes:e.closes,reopens:e.reopens,defect_escapes:e.defectEscapes,throughput_per_day:s==="available"?e.closes/i:null,rework_rate:s==="available"?e.reopens/e.closes:null,defect_escape_rate:s==="available"?e.defectEscapes/e.closes:null,sample_status:s}}function T(t,e,n,i,s,r){const{buckets:o,lastCloseValue:a}=F(t,e,i);return L(o,a,n),{dimension:t,status:o.size===0?"unavailable":"available",rows:[...o].map(([c,l])=>P(c,l,s,r)).sort((c,l)=>l.events-c.events||c.value.localeCompare(l.value))}}function N(t,e){const n=t[0]?.entry.ts??e,i=t[t.length-1]?.entry.ts??n,s=Date.parse(n),r=Date.parse(i);return!Number.isFinite(s)||!Number.isFinite(r)?1:Math.max(1,(r-s)/864e5)}function R(t,e,n){const i=O(e),s=b(t,w,n),r=s.filter(a=>a.inert).map(a=>({harness:a.harness,dimension:a.dimension,explicit_samples:a.observed+a.unavailable})),o=i.filter(a=>!a.covered).map(a=>a.dimension);return{descriptors:i,observations:s,inert:r,undeclared:o,warnings:[...r.map(a=>`provenance_dimension_inert:${a.harness}:${a.dimension}:${String(a.explicit_samples)}`),...o.map(a=>`provenance_dimension_undeclared:${a}`)]}}async function X(t,e=d,n={}){return G(await S(t,n),e,n)}function G(t,e=d,n={}){const i=f(n.minimumSample);return{...R(t.events.map(s=>s.entry),e,i),window:t.receipt}}async function j(t,e,n,i={}){return U(await S(t,i),e,n,i)}function U(t,e,n,i={}){const s=f(i.minimumSample),r=N(t.events,t.receipt.since);return{dimensions:["harness","model","author_source"].map(o=>T(o,t.events,e,n,s,r)),minimum_sample:s,policy:"observational_only_not_for_authorization_or_routing",window:t.receipt}}const B={annotationOperation:A,buildFleetDimension:T,parseHistoryAnalyticsLimit:y,parseMinimumSample:f,provenanceValue:E,resolveHistoryAnalyticsSince:h,resolveHistoryWindowDays:N,statusFromEntry:g};export{B as _testOnlyHistoryAnalytics,R as evaluateProvenanceCoverage,U as projectFleetAttributionAnalytics,G as projectProvenanceCoverageAnalytics,S as readHistoryAnalyticsWindow,j as runFleetAttributionAnalytics,X as runProvenanceCoverageAnalytics};
2
2
  //# sourceMappingURL=history-analytics.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]="822ae2f6-91d4-51db-96c9-bb5c5db5c337")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import path from"node:path";import{createHistoryEntry,hashHistoryStream,sealHistoryRecord,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../core/history/history.js";import{selectHistoryCompactBulkTargets}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument,replayHashVerificationCandidates,replayToItemDocument,toReplayDocument,verifyHistoryChainWithVersion}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{historyVersionOffset}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{pathExists}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue,parseBulkIdsText}from"../core/io/bulk-ids-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnReadHooks}from"../core/extensions/index.js";import{isJudgeableHistoryRecord,recordedPrefixActivity}from"./governance/stale-work.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";function parseBeforeBoundary(before,entries){if(before===void 0)return{kind:"default",raw:null,compactCount:entries.length,retainedCount:0};const raw=before.trim();if(raw.length===0)throw new PmCliError("history-compact --before requires a non-empty value.",EXIT_CODE.USAGE);if(/^\d+$/.test(raw)){const version=Number.parseInt(raw,10),offset=historyVersionOffset(entries);if(!Number.isSafeInteger(version)||version<offset+1||version>offset+entries.length+1)throw new PmCliError(`history-compact --before version must be between ${offset+1} and ${offset+entries.length+1}.`,EXIT_CODE.USAGE);const compactCount2=version-offset-1;return{kind:"version",raw,compactCount:compactCount2,retainedCount:entries.length-compactCount2}}const beforeTs=Date.parse(raw);if(!Number.isFinite(beforeTs))throw new PmCliError(`Invalid history-compact --before value "${before}". Use a version number or ISO timestamp.`,EXIT_CODE.USAGE);let compactCount=0;for(const[index,entry]of entries.entries()){const entryTs=Date.parse(entry.ts);if(!Number.isFinite(entryTs))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);if(entryTs>=beforeTs)break;compactCount+=1}return{kind:"timestamp",raw,compactCount,retainedCount:entries.length-compactCount}}function replayHistoryAndResolveCheckpoint(entries,compactCount){let replay=cloneEmptyReplayDocument(),checkpoint=cloneEmptyReplayDocument();for(let index=0;index<entries.length;index+=1){const entry=entries[index];replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),index+1===compactCount&&(checkpoint=structuredClone(replay))}return{checkpoint,finalReplay:replay}}function describeHistoryCompactCurrentItem(loadedItem,historyEntries){if(!loadedItem)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const lastEntry=historyEntries[historyEntries.length-1];return{loadedItem,currentItemRawBeforeLock:loadedItem.raw,matchedChainBefore:SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(version=>(lastEntry.item_hash_version===void 0||lastEntry.item_hash_version===version)&&replayHashVerificationCandidates(toReplayDocument(loadedItem.document),version,resolveHistoryHashAlgorithm(lastEntry.hash_algorithm)).includes(lastEntry.after_hash))}}function buildHistoryCompactMessage(options,boundary){return typeof options.message=="string"&&options.message.trim().length>0?options.message:boundary.raw===null?`history-compact compacted full stream (${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}).`:`history-compact compacted ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"} before ${boundary.raw}.`}function buildHistoryCompactBaselineMessage(boundary){return boundary.raw===null?`history-compact baseline snapshot after compacting ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${boundary.raw}.`}function assertPrunedRecordsJudgeable(entries,compactCount){const index=entries.slice(0,compactCount).findIndex(entry=>!isJudgeableHistoryRecord(entry));if(index===-1)return;const damage=Number.isFinite(Date.parse(entries[index].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new PmCliError(`History for this item contains ${damage} at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}function timestampBoundaryGuidance(entries,segment){const earliest=entries[segment.start].ts,times=entries.slice(0,segment.end+1).map(entry=>Date.parse(entry.ts));if(!times.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${earliest}".`,`Run pm history-compact <id> --before "${earliest}".`];const latest=new Date(times.reduce((max,time)=>Math.max(max,time),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${earliest}", or after "${latest}".`,`Run pm history-compact <id> --before "${earliest}", or with a timestamp after "${latest}".`]}function assertReconstructableCompactBoundary(entries,compactCount){const checkpoint=compactCount-1,segment=(verifyHistoryChainWithVersion(entries).bridged_segments??[]).find(({start,end})=>start<=checkpoint&&checkpoint<end);if(segment===void 0)return;const offset=historyVersionOffset(entries,!0),[checkpointName,required,nextStep]=offset===null?timestampBoundaryGuidance(entries,segment):[`version ${offset+compactCount}`,`Choose --before ${offset+segment.start+1} or lower, or --before ${offset+segment.end+2} or higher.`,`Run pm history-compact <id> --before ${offset+segment.start+1} or --before ${offset+segment.end+2}.`];throw new PmCliError(`history-compact cannot checkpoint ${checkpointName}: it lies inside a bridged segment whose states cannot be reconstructed.`,EXIT_CODE.USAGE,{code:"history_compact_boundary_bridged",required,nextSteps:[nextStep]})}function buildHistoryCompactEntries(params){if(!params.changed)return{rewrittenEntries:params.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};assertReconstructableCompactBoundary(params.historyEntries,params.boundary.compactCount);const{checkpoint,finalReplay}=replayHistoryAndResolveCheckpoint(params.historyEntries,params.boundary.compactCount),retained=params.historyEntries.slice(params.boundary.compactCount),offset=historyVersionOffset(params.historyEntries,!0),checkpointEntry=params.historyEntries[params.boundary.compactCount-1],baselineEntry=createHistoryEntry({hashAlgorithm:resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm),nowIso:params.historyEntries[params.boundary.compactCount-1].ts,author:params.author,op:"history_compact_baseline",before:replayToItemDocument(cloneEmptyReplayDocument()),after:replayToItemDocument(checkpoint),message:buildHistoryCompactBaselineMessage(params.boundary),context:{history_compaction:{contract_version:1,version_offset:offset===null?null:offset+params.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:recordedPrefixActivity(params.historyEntries.slice(0,params.boundary.compactCount)),pruned_entry_count:params.boundary.compactCount,pruned_stream_digest:hashHistoryStream(params.historyEntries.slice(0,params.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),rewrittenEntries=[sealHistoryRecord({...baselineEntry,before_hash:replayHashVerificationCandidates(cloneEmptyReplayDocument(),checkpointEntry.item_hash_version??1,resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm))[0],after_hash:checkpointEntry.after_hash,item_hash_version:checkpointEntry.item_hash_version,...checkpointEntry.replay_inexact===!0?{replay_inexact:!0}:{}}),...retained];return params.dryRun||rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_compact",before:replayToItemDocument(finalReplay),after:replayToItemDocument(finalReplay),message:buildHistoryCompactMessage(params.options,params.boundary)})),{rewrittenEntries,baselineEntryAdded:!0,auditEntryAdded:!params.dryRun}}async function runHistoryCompact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-compact",options,transform:snapshot=>buildHistoryCompactPlan(subject,options,snapshot)})}function buildHistoryCompactPlan(subject,options,snapshot){const historyPath=subject.historyPath,historyEntries=snapshot.entries,chainVerification=snapshot.verification;if(!chainVerification.ok)throw new PmCliError(`history-compact requires a valid history chain (${chainVerification.errors.join(", ")}). Run pm history-repair ${subject.id} first.`,EXIT_CODE.CONFLICT);const boundary=parseBeforeBoundary(options.before,historyEntries);assertPrunedRecordsJudgeable(historyEntries,boundary.compactCount);const changed=boundary.compactCount>0,dryRun=!!options.dryRun,author=snapshot.author,warnings=[];changed||warnings.push("history_compact_noop_before_boundary");const currentItem=describeHistoryCompactCurrentItem(snapshot.loadedItem,historyEntries);currentItem.matchedChainBefore===!1&&warnings.push("history_compact_item_chain_mismatch");const{rewrittenEntries,baselineEntryAdded,auditEntryAdded}=buildHistoryCompactEntries({historyEntries,boundary,changed,dryRun,author,options}),offset=historyVersionOffset(historyEntries,!0),firstRetainedEntry=boundary.retainedCount>0&&offset!==null?offset+boundary.compactCount+1:null;return{changed,rewrittenEntries,report:({verification:rewrittenVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,compact_boundary:{kind:boundary.kind,before:boundary.raw,entries_compacted:boundary.compactCount,entries_retained:boundary.retainedCount,first_retained_entry:firstRetainedEntry},history:{path:historyPath,entries_scanned:historyEntries.length,entries_after:rewrittenEntries.length,baseline_entry_added:baselineEntryAdded,audit_entry_added:auditEntryAdded,verify_ok:rewrittenVerify.ok,verify_errors:rewrittenVerify.errors},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:currentItem.matchedChainBefore},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES=3;function normalizeHistoryCompactBulkOptions(options){for(const key of["allOver","minEntries"]){const value=options[key];if(value!==void 0&&(!Number.isSafeInteger(value)||value<0))throw new PmCliError(`history-compact ${key} must be a non-negative safe integer.`,EXIT_CODE.USAGE)}const normalizedIdsText=normalizeBulkIdsValue(options.ids);if(options.ids!==void 0&&normalizedIdsText==="")throw new PmCliError("history-compact ids requires at least one valid item ID.",EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...options,ids:normalizedIdsText===void 0?void 0:parseBulkIdsText(normalizedIdsText)}}function assertHistoryCompactTarget(id,bulk){const hasIds=bulk.ids!==void 0&&bulk.ids.length>0,hasScan=bulk.allOver!==void 0||bulk.scope!==void 0;if((id!==void 0?1:0)+(hasIds?1:0)+(hasScan?1:0)==0)throw new PmCliError("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",EXIT_CODE.USAGE);if(id!==void 0&&(hasIds||hasScan))throw new PmCliError("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",EXIT_CODE.USAGE);if(hasIds&&hasScan)throw new PmCliError("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",EXIT_CODE.USAGE)}function countHistoryStreamEntries(raw){let count=0;for(const line of raw.split(/\r?\n/))line.trim().length>0&&(count+=1);return count}async function collectHistoryCompactBulkCandidates(params){const statusRegistry=resolveRuntimeStatusRegistry(params.settings.schema),classifier=lifecycleClassifierFromStatusRegistry(statusRegistry),items=await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema),bucketById=new Map(items.map(item=>[item.id,classifier.classify(item.status)])),historyDir=path.join(params.pmRoot,"history"),candidates=[],preselectionErrors=[];if(!await pathExists(historyDir))return{candidates,preselectionErrors};const historyFiles=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right));for(const fileName of historyFiles){const historyPath=path.join(historyDir,fileName),id=fileName.slice(0,-6);try{const raw=await fs.readFile(historyPath,"utf8");await runActiveOnReadHooks({path:historyPath,scope:"project"}),candidates.push({id,entries:countHistoryStreamEntries(raw),bucket:bucketById.get(id)??null})}catch(error){preselectionErrors.push({id,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error)})}}return{candidates,preselectionErrors}}async function runHistoryCompactBulkRow(params){if(!params.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:params.row.id,outcome:"skipped",entries_before:params.row.entries,entries_after:null,skip_reason:params.row.skip_reason,changed:!1,error:null}};try{const result=await runHistoryCompact(params.row.id,{dryRun:params.dryRun,author:params.options.author,message:params.options.message,force:params.options.force},params.global);return{selected:!0,compacted:!0,errored:!1,result:{id:params.row.id,outcome:"compacted",entries_before:params.row.entries,entries_after:result.history.entries_after,skip_reason:null,changed:result.changed,error:null}}}catch(error){return{selected:!0,compacted:!1,errored:!0,result:{id:params.row.id,outcome:"errored",entries_before:params.row.entries,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,params.pmRoot)}}}}async function runHistoryCompactBulk(options,global2){const normalizedOptions=normalizeHistoryCompactBulkOptions(options),{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),{candidates,preselectionErrors}=await collectHistoryCompactBulkCandidates({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder}),mode=normalizedOptions.ids!==void 0&&normalizedOptions.ids.length>0?"ids":"scan",minEntries=options.minEntries??HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,policy=settings.history.compact_policy,policyThresholdApplied=mode==="scan"&&options.allOver===void 0&&policy.enabled,allOver=options.allOver??(policyThresholdApplied?policy.max_entries:void 0),selection=selectHistoryCompactBulkTargets(candidates,{ids:normalizedOptions.ids,scope:options.scope,minEntries,allOver}),dryRun=!!options.dryRun,results=[...preselectionErrors],totals={streams_considered:candidates.length+preselectionErrors.length,selected:0,items_compacted:0,items_skipped:0,items_errored:preselectionErrors.length};for(const row of selection){const outcome=await runHistoryCompactBulkRow({pmRoot,row,options:normalizedOptions,dryRun,global:global2});if(results.push(outcome.result),!outcome.selected){totals.items_skipped+=1;continue}totals.selected+=1,outcome.compacted&&(totals.items_compacted+=1),outcome.errored&&(totals.items_errored+=1)}return{bulk:!0,dry_run:dryRun,mode,scope:options.scope??null,criteria:{min_entries:minEntries,all_over:allOver??null,policy_threshold_applied:policyThresholdApplied},totals,results,generated_at:nowIso()}}export{HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk};
1
+ import{itemRevisionConflictRowFields as T}from"./lifecycle/item-revision.js";import I from"node:fs/promises";import{resolveHistoryHashAlgorithm as R}from"../core/history/digest.js";import H from"node:path";import{createHistoryEntry as S,hashHistoryStream as N,sealHistoryRecord as O,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS as F}from"../core/history/history.js";import{selectHistoryCompactBulkTargets as U}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument as b,replayHashVerificationCandidates as $,replayToItemDocument as C,toReplayDocument as D,verifyHistoryChainWithVersion as G}from"../core/history/replay.js";import{applyHistoryPatch as P}from"../core/history/projection.js";import{historyVersionOffset as E}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry as M}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry as L}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight as q}from"../core/store/item-store.js";import{pathExists as V}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue as j,parseBulkIdsText as z}from"../core/io/bulk-ids-input.js";import{EXIT_CODE as d}from"../core/shared/constants.js";import{PmCliError as l}from"../core/shared/errors.js";import{nowIso as k}from"../core/shared/time.js";import{runActiveOnReadHooks as W}from"../core/extensions/index.js";import{isJudgeableHistoryRecord as Y,recordedPrefixActivity as J}from"./governance/stale-work.js";import{resolveHistoryWorkspace as A,resolveHistorySubject as K}from"./history/subject.js";import{runHistoryMaintenance as X}from"./history/maintenance.js";function Q(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};const o=e.trim();if(o.length===0)throw new l("history-compact --before requires a non-empty value.",d.USAGE);if(/^\d+$/.test(o)){const i=Number.parseInt(o,10),s=E(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new l(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,d.USAGE);const c=i-s-1;return{kind:"version",raw:o,compactCount:c,retainedCount:t.length-c}}const r=Date.parse(o);if(!Number.isFinite(r))throw new l(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,d.USAGE);let n=0;for(const[i,s]of t.entries()){const c=Date.parse(s.ts);if(!Number.isFinite(c))throw new l(`History for this item contains invalid timestamp at entry ${i+1}.`,d.GENERIC_FAILURE);if(c>=r)break;n+=1}return{kind:"timestamp",raw:o,compactCount:n,retainedCount:t.length-n}}function Z(e,t){let o=b(),r=b();for(let n=0;n<e.length;n+=1){const i=e[n];o=P(o,i.patch,n+1,i.op),n+1===t&&(r=structuredClone(o))}return{checkpoint:r,finalReplay:o}}function ee(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const o=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:F.some(r=>(o.item_hash_version===void 0||o.item_hash_version===r)&&$(D(e.document),r,R(o.hash_algorithm)).includes(o.after_hash))}}function te(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function oe(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function re(e,t){const o=e.slice(0,t).findIndex(n=>!Y(n));if(o===-1)return;const r=Number.isFinite(Date.parse(e[o].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new l(`History for this item contains ${r} at entry ${o+1}.`,d.GENERIC_FAILURE)}function ne(e,t){const o=e[t.start].ts,r=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!r.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${o}".`,`Run pm history-compact <id> --before "${o}".`];const n=new Date(r.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${o}", or after "${n}".`,`Run pm history-compact <id> --before "${o}", or with a timestamp after "${n}".`]}function ie(e,t){const o=t-1,r=(G(e).bridged_segments??[]).find(({start:f,end:a})=>f<=o&&o<a);if(r===void 0)return;const n=E(e,!0),[i,s,c]=n===null?ne(e,r):[`version ${n+t}`,`Choose --before ${n+r.start+1} or lower, or --before ${n+r.end+2} or higher.`,`Run pm history-compact <id> --before ${n+r.start+1} or --before ${n+r.end+2}.`];throw new l(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,d.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[c]})}function se(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};ie(e.historyEntries,e.boundary.compactCount);const{checkpoint:t,finalReplay:o}=Z(e.historyEntries,e.boundary.compactCount),r=e.historyEntries.slice(e.boundary.compactCount),n=E(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=S({hashAlgorithm:R(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:C(b()),after:C(t),message:oe(e.boundary),context:{history_compaction:{contract_version:1,version_offset:n===null?null:n+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:J(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:N(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),c=[O({...s,before_hash:$(b(),i.item_hash_version??1,R(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...r];return e.dryRun||c.push(S({nowIso:k(),author:e.author,op:"history_compact",before:C(o),after:C(o),message:te(e.options,e.boundary)})),{rewrittenEntries:c,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function ce(e,t,o){const{pmRoot:r,settings:n,typeRegistry:i}=await A(o.path),s=await K(r,e,n,i.type_to_folder);return X({pmRoot:r,subject:s,settings:n,typeRegistry:i,operation:"history-compact",options:t,transform:c=>ae(s,t,c)})}function ae(e,t,o){const r=e.historyPath,n=o.entries,i=o.verification;if(!i.ok)throw new l(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,d.CONFLICT);const s=Q(t.before,n);re(n,s.compactCount);const c=s.compactCount>0,f=!!t.dryRun,a=o.author,u=[];c||u.push("history_compact_noop_before_boundary");const h=ee(o.loadedItem,n);h.matchedChainBefore===!1&&u.push("history_compact_item_chain_mismatch");const{rewrittenEntries:m,baselineEntryAdded:v,auditEntryAdded:g}=se({historyEntries:n,boundary:s,changed:c,dryRun:f,author:a,options:t}),_=E(n,!0),p=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:c,rewrittenEntries:m,report:({verification:w,warnings:y})=>({id:e.id,dry_run:f,changed:c,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:p},history:{path:r,entries_scanned:n.length,entries_after:m.length,baseline_entry_added:v,audit_entry_added:g,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:h.matchedChainBefore},warnings:[...new Set([...u,...y])].sort((x,B)=>x.localeCompare(B)),generated_at:k()})}}const de=3;function le(e){for(const o of["allOver","minEntries"]){const r=e[o];if(r!==void 0&&(!Number.isSafeInteger(r)||r<0))throw new l(`history-compact ${o} must be a non-negative safe integer.`,d.USAGE)}const t=j(e.ids);if(e.ids!==void 0&&t==="")throw new l("history-compact ids requires at least one valid item ID.",d.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:z(t)}}function Oe(e,t){const o=t.ids!==void 0&&t.ids.length>0,r=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(o?1:0)+(r?1:0)===0)throw new l("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",d.USAGE);if(e!==void 0&&(o||r))throw new l("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",d.USAGE);if(o&&r)throw new l("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",d.USAGE)}function ue(e){let t=0;for(const o of e.split(/\r?\n/))o.trim().length>0&&(t+=1);return t}async function me(e){const t=L(e.settings.schema),o=M(t),r=await q(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),n=new Map(r.map(a=>[a.id,o.classify(a.status)])),i=H.join(e.pmRoot,"history"),s=[],c=[];if(!await V(i))return{candidates:s,preselectionErrors:c};const f=(await I.readdir(i)).filter(a=>a.endsWith(".jsonl")).sort((a,u)=>a.localeCompare(u));for(const a of f){const u=H.join(i,a),h=a.slice(0,-6);try{const m=await I.readFile(u,"utf8");await W({path:u,scope:"project"}),s.push({id:h,entries:ue(m),bucket:n.get(h)??null})}catch(m){c.push({id:h,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:c}}async function fe(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{const t=await ce(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await T(t,e.pmRoot)}}}}async function Fe(e,t){const o=le(e),{pmRoot:r,settings:n,typeRegistry:i}=await A(t.path),{candidates:s,preselectionErrors:c}=await me({pmRoot:r,settings:n,typeToFolder:i.type_to_folder}),f=o.ids!==void 0&&o.ids.length>0?"ids":"scan",a=e.minEntries??de,u=n.history.compact_policy,h=f==="scan"&&e.allOver===void 0&&u.enabled,m=e.allOver??(h?u.max_entries:void 0),v=U(s,{ids:o.ids,scope:e.scope,minEntries:a,allOver:m}),g=!!e.dryRun,_=[...c],p={streams_considered:s.length+c.length,selected:0,items_compacted:0,items_skipped:0,items_errored:c.length};for(const w of v){const y=await fe({pmRoot:r,row:w,options:o,dryRun:g,global:t});if(_.push(y.result),!y.selected){p.items_skipped+=1;continue}p.selected+=1,y.compacted&&(p.items_compacted+=1),y.errored&&(p.items_errored+=1)}return{bulk:!0,dry_run:g,mode:f,scope:e.scope??null,criteria:{min_entries:a,all_over:m??null,policy_threshold_applied:h},totals:p,results:_,generated_at:k()}}export{de as HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,Oe as assertHistoryCompactTarget,ce as runHistoryCompact,Fe as runHistoryCompactBulk};
2
2
  //# sourceMappingURL=history-compact.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]="feb8c44f-a6bd-5a7e-9600-eb5c45c0a5b4")}catch{}})();import{normalizeBulkIdsValue,parseBulkIdsText}from"../core/io/bulk-ids-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk}from"./history-compact.js";import{assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll}from"./history-repair.js";import{parseRuntimeInteger,readRuntimeString}from"./runtime-input.js";function runMcpHistoryRepairAction(context){const repairAll=context.options.all===!0,repairId=context.id??readRuntimeString(context.options,"id");return assertHistoryRepairTarget(repairId,repairAll),repairAll?runHistoryRepairAll(context.options,context.global):runHistoryRepair(repairId,context.options,context.global)}function runMcpHistoryCompactAction(context){const idsSource=context.options.ids,normalizedIds=normalizeBulkIdsValue(idsSource);if(idsSource!==void 0&&normalizedIds==="")throw new PmCliError("history-compact ids requires at least one valid item ID.",EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});const ids=normalizedIds===void 0?void 0:parseBulkIdsText(normalizedIds),allOver=parseRuntimeInteger(context.options.allOver??context.options.all_over,"history-compact allOver"),minEntries=parseRuntimeInteger(context.options.minEntries??context.options.min_entries,"history-compact minEntries"),explicitScope=readRuntimeString(context.options,"scope"),requestedScopes=[];context.options.closed===!0&&requestedScopes.push("closed"),(context.options.allStreams===!0||context.options.all_streams===!0)&&requestedScopes.push("all-streams"),(explicitScope==="closed"||explicitScope==="all-streams")&&requestedScopes.push(explicitScope);const distinctScopes=[...new Set(requestedScopes)];if(distinctScopes.length>1)throw new PmCliError("history-compact: closed and all-streams scopes are mutually exclusive.",EXIT_CODE.USAGE);const scope=distinctScopes[0];return assertHistoryCompactTarget(context.id,{ids,allOver,scope}),context.id!==void 0?runHistoryCompact(context.id,{before:readRuntimeString(context.options,"before"),dryRun:context.options.dryRun===!0||context.options.dry_run===!0,author:readRuntimeString(context.options,"author"),message:readRuntimeString(context.options,"message"),force:context.force},context.global):runHistoryCompactBulk({ids,scope,allOver,minEntries,dryRun:context.options.dryRun===!0||context.options.dry_run===!0,author:readRuntimeString(context.options,"author"),message:readRuntimeString(context.options,"message"),force:context.force},context.global)}export{runMcpHistoryCompactAction,runMcpHistoryRepairAction};
1
+ import{normalizeBulkIdsValue as c,parseBulkIdsText as y}from"../core/io/bulk-ids-input.js";import{EXIT_CODE as l}from"../core/shared/constants.js";import{PmCliError as d}from"../core/shared/errors.js";import{assertHistoryCompactTarget as g,runHistoryCompact as h,runHistoryCompactBulk as R}from"./history-compact.js";import{assertHistoryRepairTarget as S,runHistoryRepair as _,runHistoryRepairAll as v}from"./history-repair.js";import{parseRuntimeInteger as m,readRuntimeString as o}from"./runtime-input.js";function w(r){const i=r.options.all===!0,s=r.id??o(r.options,"id");return S(s,i),i?v(r.options,r.global):_(s,r.options,r.global)}function k(r){const i=r.options.ids,s=c(i);if(i!==void 0&&s==="")throw new d("history-compact ids requires at least one valid item ID.",l.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});const p=s===void 0?void 0:y(s),a=m(r.options.allOver??r.options.all_over,"history-compact allOver"),f=m(r.options.minEntries??r.options.min_entries,"history-compact minEntries"),n=o(r.options,"scope"),e=[];r.options.closed===!0&&e.push("closed"),(r.options.allStreams===!0||r.options.all_streams===!0)&&e.push("all-streams"),(n==="closed"||n==="all-streams")&&e.push(n);const t=[...new Set(e)];if(t.length>1)throw new d("history-compact: closed and all-streams scopes are mutually exclusive.",l.USAGE);const u=t[0];return g(r.id,{ids:p,allOver:a,scope:u}),r.id!==void 0?h(r.id,{before:o(r.options,"before"),dryRun:r.options.dryRun===!0||r.options.dry_run===!0,author:o(r.options,"author"),message:o(r.options,"message"),force:r.force},r.global):R({ids:p,scope:u,allOver:a,minEntries:f,dryRun:r.options.dryRun===!0||r.options.dry_run===!0,author:o(r.options,"author"),message:o(r.options,"message"),force:r.force},r.global)}export{k as runMcpHistoryCompactAction,w as runMcpHistoryRepairAction};
2
2
  //# sourceMappingURL=history-mcp.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]="07067ff1-a1d0-51f5-bd2d-e0980519b7a4")}catch{}})();import{AGENT_PROVENANCE_DIMENSIONS}from"../core/shared/author.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const DEFAULT_AUTHOR_IDENTITY_VOCABULARY={version:1,aliases:{}};function resolveHistoryProvenanceDimensions(descriptors=[]){const dimensions=new Set(AGENT_PROVENANCE_DIMENSIONS),addDimension=dimension=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(dimension)&&dimensions.add(dimension)};for(const descriptor of descriptors){for(const dimension of Object.keys(descriptor.provenance_environment_keys??{}))addDimension(dimension);for(const dimension of Object.keys(descriptor.provenance_resolvers??{}))addDimension(dimension);for(const dimension of descriptor.provenance_unavailable_dimensions??[])addDimension(dimension)}return[...dimensions].sort()}function normalizeSet(value){if(value===void 0)return;const normalized=(typeof value=="string"?[value]:value).flatMap(entry=>entry.split(",")).map(entry=>entry.trim()).filter(entry=>entry.length>0);return normalized.length===0?void 0:new Set(normalized)}function resolveCanonicalHarness(entry,vocabulary){if(typeof entry.agent_harness=="string"&&entry.agent_harness.trim())return{agent_harness:entry.agent_harness,harness_source:"recorded"};const interpreted=Object.hasOwn(vocabulary.aliases,entry.author)?vocabulary.aliases[entry.author]:void 0;return typeof interpreted=="string"&&interpreted.length>0?{agent_harness:interpreted,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function parseHistoryProvenanceFilters(filters,dimensions=AGENT_PROVENANCE_DIMENSIONS){const allowed=new Set(dimensions),predicates=new Map,values=filters.provenance===void 0?[]:typeof filters.provenance=="string"?[filters.provenance]:filters.provenance;for(const raw of values.flatMap(entry=>entry.split(","))){const separator=raw.indexOf("=");if(separator<0)throw new PmCliError(`Provenance predicate must use dimension=value; received "${raw.trim()}".`,EXIT_CODE.USAGE,{code:"invalid_provenance_predicate"});const dimension=raw.slice(0,separator).trim().toLowerCase(),value=raw.slice(separator+1).trim();if(!allowed.has(dimension))throw new PmCliError(`Unknown provenance dimension "${dimension||raw.trim()}". Declared dimensions: ${[...allowed].sort().join(", ")}.`,EXIT_CODE.USAGE,{code:"unknown_provenance_dimension"});if(value.length===0)throw new PmCliError(`Provenance predicate must use dimension=value; received "${raw.trim()}".`,EXIT_CODE.USAGE,{code:"invalid_provenance_predicate"});const accepted=predicates.get(dimension)??new Set;accepted.add(value),predicates.set(dimension,accepted)}return predicates}function projectHistoryProvenance(entry,vocabulary=DEFAULT_AUTHOR_IDENTITY_VOCABULARY,coordinates={}){const harness=resolveCanonicalHarness(entry,vocabulary);return{...coordinates.itemId===void 0?{}:{item_id:coordinates.itemId},...coordinates.version===void 0?{}:{version:coordinates.version},ts:entry.ts,op:entry.op,author:entry.author,...entry.author_source===void 0?{}:{author_source:entry.author_source},...harness,vocabulary_version:vocabulary.version,...entry.agent_instance===void 0?{}:{agent_instance:entry.agent_instance},agent_provenance:entry.agent_provenance??{},...entry.message===void 0?{}:{message:entry.message}}}function historyEntryMatchesProvenance(entry,filters,vocabulary=DEFAULT_AUTHOR_IDENTITY_VOCABULARY,dimensions=AGENT_PROVENANCE_DIMENSIONS){return compileHistoryProvenanceMatcher(filters,vocabulary,dimensions)(entry)}function compileHistoryProvenanceMatcher(filters,vocabulary=DEFAULT_AUTHOR_IDENTITY_VOCABULARY,dimensions=AGENT_PROVENANCE_DIMENSIONS){const harnesses=normalizeSet(filters.harness),instances=normalizeSet(filters.agentInstance),predicates=parseHistoryProvenanceFilters(filters,dimensions);return entry=>{const resolvedHarness=resolveCanonicalHarness(entry,vocabulary).agent_harness;if(harnesses&&(!resolvedHarness||!harnesses.has(resolvedHarness))||instances&&!instances.has(entry.agent_instance??""))return!1;for(const[dimension,accepted]of predicates){const observation=entry.agent_provenance?.[dimension];if(!observation||!accepted.has(observation.value))return!1}return!0}}function summarizeHistoryProvenance(entries,vocabulary=DEFAULT_AUTHOR_IDENTITY_VOCABULARY,dimensions=AGENT_PROVENANCE_DIMENSIONS){const allDimensions=new Set(dimensions),unresolvedAuthors=new Map;let resolvedHarnesses=0;for(const entry of entries){for(const dimension of Object.keys(entry.agent_provenance??{}))allDimensions.add(dimension);resolveCanonicalHarness(entry,vocabulary).agent_harness?resolvedHarnesses+=1:unresolvedAuthors.set(entry.author,(unresolvedAuthors.get(entry.author)??0)+1)}return{entries:entries.length,vocabulary_version:vocabulary.version,harness:{resolved:resolvedHarnesses,unresolved:entries.length-resolvedHarnesses,unresolved_authors:[...unresolvedAuthors].map(([author,count])=>({author,entries:count})).sort((left,right)=>right.entries-left.entries||left.author.localeCompare(right.author)).slice(0,20)},dimensions:[...allDimensions].sort().map(dimension=>{let observed=0,unavailable=0;for(const entry of entries){const observation=entry.agent_provenance?.[dimension];observation===null?unavailable+=1:observation!==void 0&&(observed+=1)}return{dimension,observed,unavailable,legacy_missing:entries.length-observed-unavailable}})}}export{DEFAULT_AUTHOR_IDENTITY_VOCABULARY,compileHistoryProvenanceMatcher,historyEntryMatchesProvenance,parseHistoryProvenanceFilters,projectHistoryProvenance,resolveHistoryProvenanceDimensions,summarizeHistoryProvenance};
1
+ import{AGENT_PROVENANCE_DIMENSIONS as u}from"../core/shared/author.js";import{EXIT_CODE as f}from"../core/shared/constants.js";import{PmCliError as p}from"../core/shared/errors.js";const v={version:1,aliases:{}};function A(e=[]){const r=new Set(u),s=n=>{/^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(n)&&r.add(n)};for(const n of e){for(const a of Object.keys(n.provenance_environment_keys??{}))s(a);for(const a of Object.keys(n.provenance_resolvers??{}))s(a);for(const a of n.provenance_unavailable_dimensions??[])s(a)}return[...r].sort()}function _(e){if(e===void 0)return;const s=(typeof e=="string"?[e]:e).flatMap(n=>n.split(",")).map(n=>n.trim()).filter(n=>n.length>0);return s.length===0?void 0:new Set(s)}function m(e,r){if(typeof e.agent_harness=="string"&&e.agent_harness.trim())return{agent_harness:e.agent_harness,harness_source:"recorded"};const s=Object.hasOwn(r.aliases,e.author)?r.aliases[e.author]:void 0;return typeof s=="string"&&s.length>0?{agent_harness:s,harness_source:"vocabulary"}:{harness_source:"unresolved"}}function g(e,r=u){const s=new Set(r),n=new Map,a=e.provenance===void 0?[]:typeof e.provenance=="string"?[e.provenance]:e.provenance;for(const i of a.flatMap(o=>o.split(","))){const o=i.indexOf("=");if(o<0)throw new p(`Provenance predicate must use dimension=value; received "${i.trim()}".`,f.USAGE,{code:"invalid_provenance_predicate"});const t=i.slice(0,o).trim().toLowerCase(),c=i.slice(o+1).trim();if(!s.has(t))throw new p(`Unknown provenance dimension "${t||i.trim()}". Declared dimensions: ${[...s].sort().join(", ")}.`,f.USAGE,{code:"unknown_provenance_dimension"});if(c.length===0)throw new p(`Provenance predicate must use dimension=value; received "${i.trim()}".`,f.USAGE,{code:"invalid_provenance_predicate"});const d=n.get(t)??new Set;d.add(c),n.set(t,d)}return n}function P(e,r=v,s={}){const n=m(e,r);return{...s.itemId===void 0?{}:{item_id:s.itemId},...s.version===void 0?{}:{version:s.version},ts:e.ts,op:e.op,author:e.author,...e.author_source===void 0?{}:{author_source:e.author_source},...n,vocabulary_version:r.version,...e.agent_instance===void 0?{}:{agent_instance:e.agent_instance},agent_provenance:e.agent_provenance??{},...e.message===void 0?{}:{message:e.message}}}function b(e,r,s=v,n=u){return w(r,s,n)(e)}function w(e,r=v,s=u){const n=_(e.harness),a=_(e.agentInstance),i=g(e,s);return o=>{const c=m(o,r).agent_harness;if(n&&(!c||!n.has(c))||a&&!a.has(o.agent_instance??""))return!1;for(const[d,l]of i){const h=o.agent_provenance?.[d];if(!h||!l.has(h.value))return!1}return!0}}function H(e,r=v,s=u){const n=new Set(s),a=new Map;let i=0;for(const o of e){for(const c of Object.keys(o.agent_provenance??{}))n.add(c);m(o,r).agent_harness?i+=1:a.set(o.author,(a.get(o.author)??0)+1)}return{entries:e.length,vocabulary_version:r.version,harness:{resolved:i,unresolved:e.length-i,unresolved_authors:[...a].map(([o,t])=>({author:o,entries:t})).sort((o,t)=>t.entries-o.entries||o.author.localeCompare(t.author)).slice(0,20)},dimensions:[...n].sort().map(o=>{let t=0,c=0;for(const d of e){const l=d.agent_provenance?.[o];l===null?c+=1:l!==void 0&&(t+=1)}return{dimension:o,observed:t,unavailable:c,legacy_missing:e.length-t-c}})}}export{v as DEFAULT_AUTHOR_IDENTITY_VOCABULARY,w as compileHistoryProvenanceMatcher,b as historyEntryMatchesProvenance,g as parseHistoryProvenanceFilters,P as projectHistoryProvenance,A as resolveHistoryProvenanceDimensions,H as summarizeHistoryProvenance};
2
2
  //# sourceMappingURL=history-provenance.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]="eb2e6046-156c-56ee-a03a-ecaa1cccfb45")}catch{}})();import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../core/extensions/index.js";import{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget}from"../core/history/projection.js";import{readHistoryEntries}from"../core/history/read.js";import{historyVersionOffset}from"../core/history/version-address.js";import{hashDocument,hashDocumentVerificationCandidates,hashEmptyDocument}from"../core/history/history.js";import{replayToCanonicalItemDocument,verifyHistoryChainWithVersion}from"../core/history/replay.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{resolveHistorySubject}from"./history/subject.js";import{findHistoryIdentityDiscontinuities}from"../core/history/identity.js";function verifyHistoryEntries(history,currentDocument){const verification=verifyHistoryChainWithVersion(history),latestAfterHash=history.length>0?history[history.length-1].after_hash:hashEmptyDocument(),currentItemHashCandidates=currentDocument===void 0||verification.item_hash_version===void 0?void 0:hashDocumentVerificationCandidates(currentDocument,verification.item_hash_version,resolveHistoryHashAlgorithm(history.at(-1)?.hash_algorithm)),currentItemHash=currentDocument===void 0?void 0:currentItemHashCandidates===void 0?hashDocument(currentDocument):currentItemHashCandidates[Math.max(0,currentItemHashCandidates.indexOf(latestAfterHash))],currentMatchesLatest=currentItemHash===void 0?void 0:currentItemHash===latestAfterHash,errors=[...verification.errors];return currentMatchesLatest===!1&&errors.push("verify_failed:current_item_hash_mismatch"),{ok:errors.length===0,entries:history.length,errors,latest_after_hash:history.length>0?history[history.length-1].after_hash:void 0,current_item_hash:currentItemHash,current_matches_latest:currentMatchesLatest}}async function getItemAt(id,target,options={}){const pmRoot=resolvePmRoot(options.cwd??process.cwd(),options.pmRoot);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder),history=await readHistoryEntries(subject.historyPath,subject.id);if(history.length===0)throw new PmCliError(`No history exists for ${subject.id}; point-in-time reads are unavailable.`,EXIT_CODE.NOT_FOUND);const resolvedTarget=resolveHistoryTarget(target,history),replay=ensureMaterializedHistoryTarget(replayHistoryToTarget(history,resolvedTarget.historyIndex),resolvedTarget),document=replayToCanonicalItemDocument(replay,{schema:settings.schema});if(document.metadata.id!==subject.id)throw new PmCliError(`History target resolved to item ${document.metadata.id}, expected ${subject.id}.`,EXIT_CODE.GENERIC_FAILURE);const targetEntry=history[resolvedTarget.historyIndex],offset=historyVersionOffset(history,!0);return{document,reconstructed:!0,as_of_version:offset===null?null:offset+resolvedTarget.historyIndex+1,as_of_timestamp:targetEntry.ts,target:resolvedTarget,history_length:history.length}}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,findHistoryIdentityDiscontinuities,getItemAt,readHistoryEntries,replayHistoryToTarget,resolveHistoryTarget,verifyHistoryEntries};
1
+ import{resolveHistoryHashAlgorithm as v}from"../core/history/digest.js";import{assertInitializedTracker as H}from"./environment/tracker-preflight.js";import{getActiveExtensionRegistrations as x}from"../core/extensions/index.js";import{applyHistoryPatch as I,ensureMaterializedHistoryTarget as f,extractPatchFailureContext as E,replayHistoryToTarget as c,resolveHistoryTarget as l}from"../core/history/projection.js";import{readHistoryEntries as p}from"../core/history/read.js";import{historyVersionOffset as w}from"../core/history/version-address.js";import{hashDocument as T,hashDocumentVerificationCandidates as C,hashEmptyDocument as R}from"../core/history/history.js";import{replayToCanonicalItemDocument as A,verifyHistoryChainWithVersion as O}from"../core/history/replay.js";import{resolveItemTypeRegistry as P}from"../core/item/type-registry.js";import{EXIT_CODE as u}from"../core/shared/constants.js";import{PmCliError as y}from"../core/shared/errors.js";import{resolvePmRoot as D}from"../core/store/paths.js";import{readSettings as N}from"../core/store/settings.js";import{resolveHistorySubject as b}from"./history/subject.js";import{findHistoryIdentityDiscontinuities as Y}from"../core/history/identity.js";function B(t,i){const s=O(t),n=t.length>0?t[t.length-1].after_hash:R(),o=i===void 0||s.item_hash_version===void 0?void 0:C(i,s.item_hash_version,v(t.at(-1)?.hash_algorithm)),a=i===void 0?void 0:o===void 0?T(i):o[Math.max(0,o.indexOf(n))],r=a===void 0?void 0:a===n,e=[...s.errors];return r===!1&&e.push("verify_failed:current_item_hash_mismatch"),{ok:e.length===0,entries:t.length,errors:e,latest_after_hash:t.length>0?t[t.length-1].after_hash:void 0,current_item_hash:a,current_matches_latest:r}}async function J(t,i,s={}){const n=D(s.cwd??process.cwd(),s.pmRoot);await H(n);const o=await N(n),a=P(o,x()),r=await b(n,t,o,a.type_to_folder),e=await p(r.historyPath,r.id);if(e.length===0)throw new y(`No history exists for ${r.id}; point-in-time reads are unavailable.`,u.NOT_FOUND);const m=l(i,e),_=f(c(e,m.historyIndex),m),h=A(_,{schema:o.schema});if(h.metadata.id!==r.id)throw new y(`History target resolved to item ${h.metadata.id}, expected ${r.id}.`,u.GENERIC_FAILURE);const g=e[m.historyIndex],d=w(e,!0);return{document:h,reconstructed:!0,as_of_version:d===null?null:d+m.historyIndex+1,as_of_timestamp:g.ts,target:m,history_length:e.length}}export{I as applyHistoryPatch,f as ensureMaterializedHistoryTarget,E as extractPatchFailureContext,Y as findHistoryIdentityDiscontinuities,J as getItemAt,p as readHistoryEntries,c as replayHistoryToTarget,l as resolveHistoryTarget,B as verifyHistoryEntries};
2
2
  //# sourceMappingURL=history-read.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]="57ff5a29-e0cf-5fb2-9068-b9e2ad45fab6")}catch{}})();import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{resolveHistorySubject as resolveHistorySubject2}from"./history/subject.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{locateBridgedSegments}from"../core/history/bridge.js";import{writeFileAtomic}from"../core/fs/fs-utils.js";import{createHistoryEntry,resealHistoryRewrite,verifyHistoryRecordHash}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath}from"../core/history/drift-cache.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT,collectBridgedInteriorIndexes,historyEntriesToRaw,replayHash,replayToItemDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{canonicalDocument,serializeItemDocument}from"../core/item/item-format.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../core/store/item-metadata-cache.js";import{getItemPath}from"../core/store/paths.js";function normalizeStringArrayInput(value){return Array.isArray(value)?value:typeof value=="string"?[value]:[]}function normalizeRegexFlags(flags){const unique=[];for(const token of flags)unique.includes(token)||unique.push(token);return unique.includes("g")||unique.push("g"),unique.join("")}function invalidRegexRule(index,reason){return new PmCliError(`Invalid --regex value at --regex #${index}: ${reason}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${index}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function parseRegexRule(spec,index=1){const trimmed=spec.trim();if(trimmed.length===0)throw invalidRegexRule(index,"provide a non-empty pattern.");let source=trimmed,flags="g";if(trimmed.startsWith("/")&&trimmed.length>1){const slashIndex=trimmed.lastIndexOf("/");let backslashes=0;for(let index2=slashIndex-1;index2>=0&&trimmed[index2]==="\\";index2--)backslashes++;slashIndex>0&&backslashes%2===0&&/^[dgimsuvy]*$/u.test(trimmed.slice(slashIndex+1))&&(source=trimmed.slice(1,slashIndex),flags=normalizeRegexFlags(trimmed.slice(slashIndex+1)))}if(source.length===0)throw invalidRegexRule(index,"an empty pattern is not allowed.");try{new RegExp(source,flags)}catch{throw invalidRegexRule(index,"provide a valid JavaScript regular expression.")}return{kind:"regex",source,flags}}function buildRedactionRules(literalInput,regexInput){const literalRules=[...new Set(normalizeStringArrayInput(literalInput).map(entry=>entry.trim()))].filter(entry=>entry.length>0).map(entry=>({kind:"literal",value:entry})),seen=new Set,regexRules=normalizeStringArrayInput(regexInput).flatMap((entry,index)=>{const spec=entry.trim();return seen.has(spec)?[]:(seen.add(spec),[parseRegexRule(spec,index+1)])}),rules=[...literalRules,...regexRules];if(rules.length===0)throw new PmCliError("history-redact requires at least one matcher via --literal or --regex.",EXIT_CODE.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return rules}function applyLiteralRule(value,literal,replacement){if(literal.length===0)return{value,replacements:0};let cursor=0,replacements=0;for(;cursor<=value.length;){const index=value.indexOf(literal,cursor);if(index===-1)break;replacements+=1,cursor=index+Math.max(1,literal.length)}return replacements===0?{value,replacements:0}:{value:value.split(literal).join(replacement),replacements}}function applyRegexRule(value,rule,replacement){const regex=new RegExp(rule.source,rule.flags),matches=[...value.matchAll(regex)];return matches.length===0?{value,replacements:0}:{value:value.replace(regex,replacement),replacements:matches.length}}function redactStringValue(value,rules,replacement){let next=value,replacements=0;for(const rule of rules){const result=rule.kind==="literal"?applyLiteralRule(next,rule.value,replacement):applyRegexRule(next,rule,replacement);next=result.value,replacements+=result.replacements}return{value:next,replacements}}function redactUnknownValue(value,rules,replacement){if(typeof value=="string")return redactStringValue(value,rules,replacement);if(Array.isArray(value)){let replacements=0;return{value:value.map(entry=>{const redacted=redactUnknownValue(entry,rules,replacement);return replacements+=redacted.replacements,redacted.value}),replacements}}if(typeof value=="object"&&value!==null){let replacements=0;const nextRecord={};for(const[key,entry]of Object.entries(value)){const redacted=redactUnknownValue(entry,rules,replacement);replacements+=redacted.replacements,nextRecord[key]=redacted.value}return{value:nextRecord,replacements}}return{value,replacements:0}}function redactHistoryPatch(patch,rules,replacement){let replacements=0;return{patch:patch.map(operation=>{if(!Object.prototype.hasOwnProperty.call(operation,"value"))return operation;const redactedValue=redactUnknownValue(operation.value,rules,replacement);return replacements+=redactedValue.replacements,redactedValue.replacements>0?{...operation,value:redactedValue.value}:operation}),replacements}}function inspectHistoryIntegrity(entries){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),hashMismatchesBefore=0,hashMismatchesAfter=0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.before_hash&&(hashMismatchesBefore+=1),replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.after_hash&&(hashMismatchesAfter+=1)}return{hashMismatchesBefore,hashMismatchesAfter,finalDocument:replay}}function redactHistoryEntry(entry,rules,replacement){let replacements=0,changed=!1,reanchorEvidenceRedacted=!1,nextMessage=entry.message;if(typeof entry.message=="string"){const redactedMessage=redactStringValue(entry.message,rules,replacement);nextMessage=redactedMessage.value,replacements+=redactedMessage.replacements,redactedMessage.replacements>0&&(changed=!0)}const redactedPatch=redactHistoryPatch(entry.patch,rules,replacement);replacements+=redactedPatch.replacements,changed||=redactedPatch.replacements>0;const nextReanchorEvidence=entry.reanchor_evidence?.map(evidence=>{const redactedEvidencePatch=evidence.patch?redactHistoryPatch(evidence.patch,rules,replacement):{patch:void 0,replacements:0},redactedEvidenceRecord=evidence.record?redactUnknownValue(evidence.record,rules,replacement):{value:void 0,replacements:0};replacements+=redactedEvidencePatch.replacements,replacements+=redactedEvidenceRecord.replacements;const evidenceChanged=redactedEvidencePatch.replacements>0||redactedEvidenceRecord.replacements>0;if(changed||=evidenceChanged,!evidenceChanged)return evidence;reanchorEvidenceRedacted=!0;const{patch:_sensitivePatch,record:_sensitiveRecord,record_hash:_priorRecordHash,record_hash_version:_priorRecordHashVersion,...digestOnlyEvidence}=evidence;return redactedEvidencePatch.replacements>0?digestOnlyEvidence:{...digestOnlyEvidence,patch:evidence.patch}});return{entry:{...entry,message:nextMessage,patch:redactedPatch.patch,...nextReanchorEvidence?{reanchor_evidence:nextReanchorEvidence}:{}},replacements,changed,reanchorEvidenceRedacted}}function rewriteHistoryEntries(entries,rules,replacement){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),entriesChanged=0,replacements=0;const rewrittenEntries=[],located=locateBridgedSegments(entries),unproven=[...located.unlocated,...located.undigested];if(unproven.length>0)throw new PmCliError(`history-redact refuses a stream whose bridge at record ${Math.min(...unproven)+1} does not prove its segment; repair the history first.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});const inexact=collectBridgedInteriorIndexes(located.segments);for(let index=0;index<entries.length;index+=1){const original=entries[index],recordVerification=verifyHistoryRecordHash(original);if(!recordVerification.ok)throw new PmCliError(`history-redact refuses invalid immutable record ${index+1} (${recordVerification.error}).`,EXIT_CODE.GENERIC_FAILURE);const redacted=redactHistoryEntry(original,rules,replacement);replacements+=redacted.replacements,redacted.changed&&(entriesChanged+=1);const beforeHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));replay=applyHistoryPatch(replay,redacted.entry.patch,index+1,redacted.entry.op);const afterHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm)),{bridge:_dissolvedBridge,...unbridged}=redacted.entry;rewrittenEntries.push(resealHistoryRewrite(original,{...unbridged,...inexact.has(index)?{replay_inexact:!0}:{},before_hash:beforeHash,after_hash:afterHash},{retainPriorRecord:redacted.changed||_dissolvedBridge!==void 0,retainPriorRecordHash:!redacted.changed}))}return{entries:rewrittenEntries,finalDocument:replay,entriesChanged,replacements}}function hasItemMetadata(replay){return Object.keys(replay.metadata).length>0}function resolveHistoryRedactNextItem(params){if(!hasItemMetadata(params.finalDocument))return{raw:null,path:null,document:null};const canonical=canonicalDocument(replayToItemDocument(params.finalDocument),{schema:params.settings.schema});if(canonical.metadata.id!==params.subject.id)throw new PmCliError("history-redact would change the item id; narrow your patterns.",EXIT_CODE.USAGE);return{document:canonical,path:getItemPath(params.pmRoot,canonical.metadata.type,params.subject.id,"toon",params.typeToFolder),raw:serializeItemDocument(canonical,{format:"toon",schema:params.settings.schema})}}function buildHistoryRedactMessage(options,rewritten){return typeof options.message=="string"&&options.message.trim().length>0?options.message:`history-redact replaced ${rewritten.replacements} match(es) across ${rewritten.entriesChanged} entr${rewritten.entriesChanged===1?"y":"ies"}.`}function buildHistoryRedactEntries(params){const rewrittenEntries=[...params.rewritten.entries];if(params.dryRun||!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const finalDocument=params.nextItemDocument??replayToItemDocument(params.rewritten.finalDocument);return rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_redact",before:finalDocument,after:finalDocument,message:params.message})),{rewrittenEntries,auditEntryAdded:!0}}function createHistoryRedactTransaction(params){let derivedIndexWarnings=[];return{applyRewrite:async({historyRawUnderLock})=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author),affectedItemPaths=new Set;params.currentItem.path&&affectedItemPaths.add(params.currentItem.path),params.nextItem.path&&affectedItemPaths.add(params.nextItem.path);const itemSnapshots=new Map;params.currentItem.path&&params.currentItem.raw!==null&&itemSnapshots.set(params.currentItem.path,params.currentItem.raw);let rethrowReleaseFailure=()=>{};try{try{params.nextItem.path&&params.nextItem.raw!==null&&params.nextItem.raw!==params.currentItem.raw&&await writeFileAtomic(params.nextItem.path,params.nextItem.raw),params.currentItem.path&&(!params.nextItem.path||params.nextItem.path!==params.currentItem.path)&&await fs.rm(params.currentItem.path,{force:!0}),await writeFileAtomic(params.subject.historyPath,historyEntriesToRaw(params.rewrittenEntries))}catch(error){try{await rollbackHistoryRedactRewrite(params.subject.historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots)}finally{await invalidateHistoryDriftCacheForPath(params.subject.historyPath)}throw error}await invalidateHistoryDriftCacheForPath(params.subject.historyPath);const itemPath=params.nextItem.path??params.currentItem.path;itemPath&&(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:params.typeRegistry.type_to_folder,schema:params.settings.schema,itemPath,...params.currentItem.path?{previousItemPath:params.currentItem.path}:{},document:params.nextItem.document}))}finally{await releaseDerivedIndexLock().catch(error=>{rethrowReleaseFailure=()=>{throw error}})}rethrowReleaseFailure()},afterWrite:async()=>[...derivedIndexWarnings,...await runHistoryRedactWriteHooks(params.subject.historyPath,[params.nextItem.path,params.currentItem.path])]}}async function rollbackHistoryRedactRewrite(historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots){historyRawUnderLock===null?await fs.rm(historyPath,{force:!0}):await writeFileAtomic(historyPath,historyRawUnderLock);for(const itemPath of affectedItemPaths){const snapshot=itemSnapshots.get(itemPath);snapshot===void 0?await fs.rm(itemPath,{force:!0}):await writeFileAtomic(itemPath,snapshot)}}async function runHistoryRedactWriteHooks(historyPath,itemHookPaths){const hookWarnings=[],uniqueItemHookPaths=new Set(itemHookPaths.filter(itemPath=>itemPath!==null));for(const itemHookPath of uniqueItemHookPaths)hookWarnings.push(...await runActiveOnWriteHooks({path:itemHookPath,scope:"project",op:"history_redact"}));return hookWarnings.push(...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"history_redact:history"})),hookWarnings}async function runHistoryRedact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),replacementInput=options.replacement??"",replacementIsDefault=replacementInput.length===0,replacement=replacementIsDefault?"[redacted]":replacementInput,rules=buildRedactionRules(options.literal,options.regex),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-redact",options,transform:snapshot=>buildHistoryRedactPlan({pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault},snapshot)})}function buildHistoryRedactPlan(params,snapshot){const{pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault}=params,historyEntries=snapshot.entries,integritySnapshot=inspectHistoryIntegrity(historyEntries),rewritten=rewriteHistoryEntries(historyEntries,rules,replacement),preexistingHashMismatches=integritySnapshot.hashMismatchesBefore+integritySnapshot.hashMismatchesAfter,dryRun=!!options.dryRun,changed=rewritten.replacements>0,warnings=[];preexistingHashMismatches>0&&warnings.push(`history_redact_preexisting_hash_mismatches:${preexistingHashMismatches}`),changed||warnings.push("history_redact_no_matches");const currentItem={raw:snapshot.loadedItem?.raw??null,path:subject.located?.itemPath??null,document:snapshot.loadedItem?.document??null},nextItem=resolveHistoryRedactNextItem({pmRoot,subject,settings,typeToFolder:typeRegistry.type_to_folder,finalDocument:rewritten.finalDocument}),itemChanged=(currentItem.path??null)!==(nextItem.path??null)||(currentItem.raw??null)!==(nextItem.raw??null),author=snapshot.author,redactionMessage=buildHistoryRedactMessage(options,rewritten),{rewrittenEntries,auditEntryAdded}=buildHistoryRedactEntries({rewritten,dryRun,changed,nextItemDocument:nextItem.document,author,message:redactionMessage});return{changed,rewrittenEntries,...createHistoryRedactTransaction({pmRoot,subject,settings,typeRegistry,currentItem,nextItem,author,rewrittenEntries}),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,patterns:{literal_count:rules.filter(rule=>rule.kind==="literal").length,regex_count:rules.filter(rule=>rule.kind==="regex").length,total_count:rules.length,replacement_is_default:replacementIsDefault},history:{path:subject.historyPath,entries_scanned:historyEntries.length,entries_changed:rewritten.entriesChanged,replacements:rewritten.replacements,hash_mismatches_before:integritySnapshot.hashMismatchesBefore,hash_mismatches_after:integritySnapshot.hashMismatchesAfter,preexisting_hash_mismatches:preexistingHashMismatches,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors},item:{existed_before:currentItem.path!==null,exists_after:nextItem.path!==null,path_before:currentItem.path,path_after:nextItem.path,changed:itemChanged},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const _testOnly={applyLiteralRule,applyRegexRule,buildRedactionRules,hasItemMetadata,normalizeRegexFlags,normalizeStringArrayInput,parseRegexRule,redactStringValue,redactUnknownValue};export{_testOnly,resolveHistorySubject2 as resolveHistorySubject,runHistoryRedact};
1
+ import{resolveHistoryWorkspace as K,resolveHistorySubject as Q}from"./history/subject.js";import{resolveHistorySubject as Ue}from"./history/subject.js";import H from"node:fs/promises";import{resolveHistoryHashAlgorithm as v}from"../core/history/digest.js";import{locateBridgedSegments as Z}from"../core/history/bridge.js";import{writeFileAtomic as b}from"../core/fs/fs-utils.js";import{createHistoryEntry as ee,resealHistoryRewrite as te,verifyHistoryRecordHash as re}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath as S}from"../core/history/drift-cache.js";import{runHistoryMaintenance as ne}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT as C,collectBridgedInteriorIndexes as oe,historyEntriesToRaw as ae,replayHash as E,replayToItemDocument as O}from"../core/history/replay.js";import{applyHistoryPatch as $}from"../core/history/projection.js";import{canonicalDocument as ie,serializeItemDocument as se}from"../core/item/item-format.js";import{EXIT_CODE as x}from"../core/shared/constants.js";import{PmCliError as I}from"../core/shared/errors.js";import{nowIso as F}from"../core/shared/time.js";import{runActiveOnWriteHooks as T}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock as ce,refreshItemMetadataDerivedIndex as le}from"../core/store/item-metadata-cache.js";import{getItemPath as he}from"../core/store/paths.js";function P(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function q(e){const t=[];for(const n of e)t.includes(n)||t.push(n);return t.includes("g")||t.push("g"),t.join("")}function k(e,t){return new I(`Invalid --regex value at --regex #${e}: ${t}`,x.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function B(e,t=1){const n=e.trim();if(n.length===0)throw k(t,"provide a non-empty pattern.");let r=n,o="g";if(n.startsWith("/")&&n.length>1){const a=n.lastIndexOf("/");let i=0;for(let s=a-1;s>=0&&n[s]==="\\";s--)i++;a>0&&i%2===0&&/^[dgimsuvy]*$/u.test(n.slice(a+1))&&(r=n.slice(1,a),o=q(n.slice(a+1)))}if(r.length===0)throw k(t,"an empty pattern is not allowed.");try{new RegExp(r,o)}catch{throw k(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:r,flags:o}}function W(e,t){const n=[...new Set(P(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=new Set,o=P(t).flatMap((i,s)=>{const h=i.trim();return r.has(h)?[]:(r.add(h),[B(h,s+1)])}),a=[...n,...o];if(a.length===0)throw new I("history-redact requires at least one matcher via --literal or --regex.",x.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return a}function U(e,t,n){if(t.length===0)return{value:e,replacements:0};let r=0,o=0;for(;r<=e.length;){const a=e.indexOf(t,r);if(a===-1)break;o+=1,r=a+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(n),replacements:o}}function V(e,t,n){const r=new RegExp(t.source,t.flags),o=[...e.matchAll(r)];return o.length===0?{value:e,replacements:0}:{value:e.replace(r,n),replacements:o.length}}function A(e,t,n){let r=e,o=0;for(const a of t){const i=a.kind==="literal"?U(r,a.value,n):V(r,a,n);r=i.value,o+=i.replacements}return{value:r,replacements:o}}function R(e,t,n){if(typeof e=="string")return A(e,t,n);if(Array.isArray(e)){let r=0;return{value:e.map(a=>{const i=R(a,t,n);return r+=i.replacements,i.value}),replacements:r}}if(typeof e=="object"&&e!==null){let r=0;const o={};for(const[a,i]of Object.entries(e)){const s=R(i,t,n);r+=s.replacements,o[a]=s.value}return{value:o,replacements:r}}return{value:e,replacements:0}}function G(e,t,n){let r=0;return{patch:e.map(a=>{if(!Object.prototype.hasOwnProperty.call(a,"value"))return a;const i=R(a.value,t,n);return r+=i.replacements,i.replacements>0?{...a,value:i.value}:a}),replacements:r}}function de(e){let t=structuredClone(C),n=0,r=0;for(let o=0;o<e.length;o+=1){const a=e[o];E(t,void 0,v(a.hash_algorithm))!==a.before_hash&&(n+=1),t=$(t,a.patch,o+1,a.op),E(t,void 0,v(a.hash_algorithm))!==a.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:t}}function ue(e,t,n){let r=0,o=!1,a=!1,i=e.message;if(typeof e.message=="string"){const c=A(e.message,t,n);i=c.value,r+=c.replacements,c.replacements>0&&(o=!0)}const s=G(e.patch,t,n);r+=s.replacements,o||=s.replacements>0;const h=e.reanchor_evidence?.map(c=>{const l=c.patch?G(c.patch,t,n):{patch:void 0,replacements:0},d=c.record?R(c.record,t,n):{value:void 0,replacements:0};r+=l.replacements,r+=d.replacements;const u=l.replacements>0||d.replacements>0;if(o||=u,!u)return c;a=!0;const{patch:m,record:w,record_hash:p,record_hash_version:g,...f}=c;return l.replacements>0?f:{...f,patch:c.patch}});return{entry:{...e,message:i,patch:s.patch,...h?{reanchor_evidence:h}:{}},replacements:r,changed:o,reanchorEvidenceRedacted:a}}function me(e,t,n){let r=structuredClone(C),o=0,a=0;const i=[],s=Z(e),h=[...s.unlocated,...s.undigested];if(h.length>0)throw new I(`history-redact refuses a stream whose bridge at record ${Math.min(...h)+1} does not prove its segment; repair the history first.`,x.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});const c=oe(s.segments);for(let l=0;l<e.length;l+=1){const d=e[l],u=re(d);if(!u.ok)throw new I(`history-redact refuses invalid immutable record ${l+1} (${u.error}).`,x.GENERIC_FAILURE);const m=ue(d,t,n);a+=m.replacements,m.changed&&(o+=1);const w=E(r,void 0,v(d.hash_algorithm));r=$(r,m.entry.patch,l+1,m.entry.op);const p=E(r,void 0,v(d.hash_algorithm)),{bridge:g,...f}=m.entry;i.push(te(d,{...f,...c.has(l)?{replay_inexact:!0}:{},before_hash:w,after_hash:p},{retainPriorRecord:m.changed||g!==void 0,retainPriorRecordHash:!m.changed}))}return{entries:i,finalDocument:r,entriesChanged:o,replacements:a}}function L(e){return Object.keys(e.metadata).length>0}function fe(e){if(!L(e.finalDocument))return{raw:null,path:null,document:null};const t=ie(O(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new I("history-redact would change the item id; narrow your patterns.",x.USAGE);return{document:t,path:he(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:se(t,{format:"toon",schema:e.settings.schema})}}function pe(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function ge(e){const t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};const n=e.nextItemDocument??O(e.rewritten.finalDocument);return t.push(ee({nowIso:F(),author:e.author,op:"history_redact",before:n,after:n,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function ye(e){let t=[];return{applyRewrite:async({historyRawUnderLock:n})=>{const r=await ce(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);const a=new Map;e.currentItem.path&&e.currentItem.raw!==null&&a.set(e.currentItem.path,e.currentItem.raw);let i=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await b(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await H.rm(e.currentItem.path,{force:!0}),await b(e.subject.historyPath,ae(e.rewrittenEntries))}catch(h){try{await we(e.subject.historyPath,n,o,a)}finally{await S(e.subject.historyPath)}throw h}await S(e.subject.historyPath);const s=e.nextItem.path??e.currentItem.path;s&&(t=await le({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:s,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await r().catch(s=>{i=()=>{throw s}})}i()},afterWrite:async()=>[...t,...await _e(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function we(e,t,n,r){t===null?await H.rm(e,{force:!0}):await b(e,t);for(const o of n){const a=r.get(o);a===void 0?await H.rm(o,{force:!0}):await b(o,a)}}async function _e(e,t){const n=[],r=new Set(t.filter(o=>o!==null));for(const o of r)n.push(...await T({path:o,scope:"project",op:"history_redact"}));return n.push(...await T({path:e,scope:"project",op:"history_redact:history"})),n}async function Te(e,t,n){const{pmRoot:r,settings:o,typeRegistry:a}=await K(n.path),i=t.replacement??"",s=i.length===0,h=s?"[redacted]":i,c=W(t.literal,t.regex),l=await Q(r,e,o,a.type_to_folder);return ne({pmRoot:r,subject:l,settings:o,typeRegistry:a,operation:"history-redact",options:t,transform:d=>xe({pmRoot:r,subject:l,settings:o,typeRegistry:a,options:t,rules:c,replacement:h,replacementIsDefault:s},d)})}function xe(e,t){const{pmRoot:n,subject:r,settings:o,typeRegistry:a,options:i,rules:s,replacement:h,replacementIsDefault:c}=e,l=t.entries,d=de(l),u=me(l,s,h),m=d.hashMismatchesBefore+d.hashMismatchesAfter,w=!!i.dryRun,p=u.replacements>0,g=[];m>0&&g.push(`history_redact_preexisting_hash_mismatches:${m}`),p||g.push("history_redact_no_matches");const f={raw:t.loadedItem?.raw??null,path:r.located?.itemPath??null,document:t.loadedItem?.document??null},y=fe({pmRoot:n,subject:r,settings:o,typeToFolder:a.type_to_folder,finalDocument:u.finalDocument}),N=(f.path??null)!==(y.path??null)||(f.raw??null)!==(y.raw??null),D=t.author,z=pe(i,u),{rewrittenEntries:M,auditEntryAdded:J}=ge({rewritten:u,dryRun:w,changed:p,nextItemDocument:y.document,author:D,message:z});return{changed:p,rewrittenEntries:M,...ye({pmRoot:n,subject:r,settings:o,typeRegistry:a,currentItem:f,nextItem:y,author:D,rewrittenEntries:M}),report:({verification:j,warnings:Y})=>({id:r.id,dry_run:w,changed:p,patterns:{literal_count:s.filter(_=>_.kind==="literal").length,regex_count:s.filter(_=>_.kind==="regex").length,total_count:s.length,replacement_is_default:c},history:{path:r.historyPath,entries_scanned:l.length,entries_changed:u.entriesChanged,replacements:u.replacements,hash_mismatches_before:d.hashMismatchesBefore,hash_mismatches_after:d.hashMismatchesAfter,preexisting_hash_mismatches:m,audit_entry_added:J,verify_ok:j.ok,verify_errors:j.errors},item:{existed_before:f.path!==null,exists_after:y.path!==null,path_before:f.path,path_after:y.path,changed:N},warnings:[...new Set([...g,...Y])].sort((_,X)=>_.localeCompare(X)),generated_at:F()})}}const qe={applyLiteralRule:U,applyRegexRule:V,buildRedactionRules:W,hasItemMetadata:L,normalizeRegexFlags:q,normalizeStringArrayInput:P,parseRegexRule:B,redactStringValue:A,redactUnknownValue:R};export{qe as _testOnly,Ue as resolveHistorySubject,Te as runHistoryRedact};
2
2
  //# sourceMappingURL=history-redact.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]="59addcc3-b4f7-5d72-9be4-50192a780fb1")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import{salvageHistoryTail}from"./history/salvage.js";import{assertAppendOnlyStreamEncoding,assertRegularStreamEntry,buildAppendOnlyRepairPlan}from"./history/append-only-repair.js";import{buildHistoryReseedPlan}from"./history/reseed.js";import{reanchorOrRefuse}from"./history/reanchor-refusal.js";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{realpath}from"node:fs/promises";import path from"node:path";import jsonPatch from"fast-json-patch";import{patchPathToChangedField}from"../core/history/history-diff.js";import{normalizeReplayPatchOps,reanchorHistoryEntries,replayHashVerificationCandidates,resolveHistoryRepairItemHashVersion,toReplayDocument,verifyHistoryChainWithVersion,materializeBridgedSegments}from"../core/history/replay.js";import{sealHistoryRecord}from"../core/history/history.js";import{classifyHistoryEvent}from"../core/history/event-classification.js";import{scanHistoryDrift}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache}from"../core/history/drift-cache.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{sha256Hex,stableStringify}from"../core/shared/serialization.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{listAllItemMetadataWithBody}from"../core/store/item-store.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{isOriginalGitStateRestored}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,summarizeMergeReceipt}from"./merge/receipts.js";import{encodeItemScalarDecisionValue,hashItemScalarDecisionValue}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds,normalizeInvalidHistoryProvenance}from"./governance/provenance-health.js";function replayFieldValue(document,field){return field==="body"?document.body:document.metadata[field]}function isDiagnosticCollectionRow(field,value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const row=value;return field==="comments"?typeof row.created_at=="string"&&typeof row.author=="string"&&typeof row.text=="string":typeof row.path=="string"||field==="tests"&&typeof row.command=="string"}function diagnosticLinkedRecord(value){const result={...value};if(result.source_kind==="merge_union"&&(result.source_kind="local_mutation"),result.provenance!==null&&typeof result.provenance=="object"&&!Array.isArray(result.provenance)){const provenance={...result.provenance};provenance.source_kind==="merge_union"&&(provenance.source_kind="local_mutation"),result.provenance=provenance}return result}function diagnosticCollectionValue(field,value){if(!Array.isArray(value)||!["comments","docs","tests"].includes(field)||!value.every(row=>isDiagnosticCollectionRow(field,row)))return value;const rows=value.map(row=>field==="comments"?row:diagnosticLinkedRecord(row));return[...new Map(rows.map(row=>[stableStringify(row),row])).values()]}function isReplayValuePreserved(replayed,reconciled){if(replayed===void 0||Object.is(replayed,reconciled))return!0;if(Array.isArray(replayed)){if(!Array.isArray(reconciled))return!1;const matched=new Set;return replayed.every(expected=>{const index=reconciled.findIndex((candidate,candidateIndex)=>!matched.has(candidateIndex)&&isReplayValuePreserved(expected,candidate));return index<0?!1:(matched.add(index),!0)})}if(replayed===null||reconciled===null||typeof replayed!="object"||typeof reconciled!="object"||Array.isArray(reconciled))return!1;const reconciledRecord=reconciled;return Object.entries(replayed).every(([key,value])=>Object.hasOwn(reconciledRecord,key)&&isReplayValuePreserved(value,reconciledRecord[key]))}function collectReconciliationEvents(entries,fields){const remaining=new Set(fields),events=[];for(let index=entries.length-1;index>=0&&remaining.size>0;index-=1){const entry=entries[index],entryFields=new Set;for(const op of normalizeReplayPatchOps(entry.patch))entryFields.add(patchPathToChangedField(op.path)),op.from&&entryFields.add(patchPathToChangedField(op.from));const overlap=[...remaining].filter(field=>entryFields.has(field));if(overlap.length!==0){for(const field of overlap)remaining.delete(field);events.push({index:index+1,ts:entry.ts,author:entry.author,op:entry.op,fields:overlap.sort((left,right)=>left.localeCompare(right))})}}return events.reverse()}function analyzeReconciliationDiscard(entries,finalReplay,currentItemReplay){const reconcilePatch=jsonPatch.compare(finalReplay,currentItemReplay);if(reconcilePatch.length===0)return;const reconciledFields=new Set;for(const op of reconcilePatch)reconciledFields.add(patchPathToChangedField(op.path));const preservedFields=new Set([...reconciledFields].filter(field=>isReplayValuePreserved(diagnosticCollectionValue(field,replayFieldValue(finalReplay,field)),diagnosticCollectionValue(field,replayFieldValue(currentItemReplay,field))))),revertedFields=new Set([...reconciledFields].filter(field=>!preservedFields.has(field))),discardedEvents=collectReconciliationEvents(entries,revertedFields),preservedEvents=collectReconciliationEvents(entries,preservedFields),sortedReconciledFields=[...reconciledFields].sort((left,right)=>left.localeCompare(right)),sortedRevertedFields=[...revertedFields].sort((left,right)=>left.localeCompare(right)),sortedPreservedFields=[...preservedFields].sort((left,right)=>left.localeCompare(right)),discardedAuthors=[...new Set(discardedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right)),preservedAuthors=[...new Set(preservedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right));return{reconciled_field_count:reconciledFields.size,reconciled_fields:sortedReconciledFields,reverted_field_count:revertedFields.size,reverted_fields:sortedRevertedFields,discarded_events:discardedEvents,discarded_authors:discardedAuthors,preserved_field_count:preservedFields.size,preserved_fields:sortedPreservedFields,preserved_events:preservedEvents,preserved_authors:preservedAuthors,recovery_hint:discardedEvents.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function canonicalRealPath(value){try{return await realpath(value)}catch{return null}}async function verifyReceiptAgainstSnapshot(params){if(await canonicalRealPath(path.resolve(params.gitWorkspaceRoot,params.receipt.item_path))!==params.currentPath)return null;const declaredFields=[...new Set([...params.receipt.fields_from_theirs,...params.receipt.union_fields,...params.receipt.decisions.map(decision=>decision.field)])].sort(),hashes=params.receipt.merged_field_hashes;if(!hashes||declaredFields.length===0)return null;const hashFields=Object.keys(hashes).sort();if(declaredFields.length!==hashFields.length||declaredFields.some((field,index)=>field!==hashFields[index]))return null;const currentMetadata=params.currentItemReplay.metadata;return declaredFields.every(field=>{const value=field==="body"?params.currentItemReplay.body:currentMetadata[field];return[hashItemScalarDecisionValue(value),sha256Hex(stableStringify(encodeItemScalarDecisionValue(value)))].includes(hashes[field])})?{receipt:params.receipt,declaredFields}:null}async function verifyMergeReceiptProof(params){if(params.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(params.itemPath===null||params.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const itemReceipts=params.proof.receipts.filter(receipt=>receipt.item_id===params.id);if(itemReceipts.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const currentPath=await realpath(params.itemPath),trustedReceipts=[];for(const receipt of itemReceipts){const trusted=await verifyReceiptAgainstSnapshot({receipt,gitWorkspaceRoot:params.proof.gitWorkspaceRoot,currentPath,currentItemReplay:params.currentItemReplay});trusted&&trustedReceipts.push(trusted)}const trustedFields=new Set(trustedReceipts.flatMap(({declaredFields})=>declaredFields)),reconciliationFields=params.reconciliation?.reconciled_fields;return trustedReceipts.length>0&&(reconciliationFields===void 0||reconciliationFields.length>0&&reconciliationFields.every(field=>trustedFields.has(field)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:trustedReceipts.map(({receipt})=>receipt.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function assertHistoryRepairAbandonmentProof(proof,context,chainOk,reanchor){if(proof===void 0)return;const{receipt,gitWorkspaceRoot}=proof,canonicalPath=context.currentItemPath===null?null:path.relative(gitWorkspaceRoot,context.currentItemPath).split(path.sep).join("/");if(!chainOk||reanchor.entriesRehashed!==0||reanchor.entriesPatchRepaired!==0||context.matchedChainBefore!==!0||context.currentItemRawBeforeLock===null||canonicalPath!==receipt.item_path||receipt.operation===void 0||!await isOriginalGitStateRestored(gitWorkspaceRoot,receipt.item_path,receipt.operation,context.currentItemRawBeforeLock))throw new PmCliError("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function resolveHistoryRepairMergeEvidence(params){const requestedReceiptIds=new Set(params.options.mergeReceiptProof?.receipts.filter(receipt=>receipt.item_id===params.subjectId).map(receipt=>receipt.id)??[]),authoritativeReceiptEvidence=params.options.mergeReceiptProof?await inspectMergeReceiptEvidence(params.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:params.pmRoot}):void 0,subjectMergeReceipts=authoritativeReceiptEvidence?.receipts.filter(receipt=>receipt.item_id===params.subjectId&&requestedReceiptIds.has(receipt.id))??[];assertPortableMergeReceiptReferences(requestedReceiptIds,authoritativeReceiptEvidence,params.options.dryRun===!0);const mergeReceiptProof=params.options.mergeReceiptProof?await verifyMergeReceiptProof({proof:{...params.options.mergeReceiptProof,receipts:subjectMergeReceipts},id:params.subjectId,itemPath:params.itemReplayContext.currentItemPath,currentItemReplay:params.itemReplayContext.currentItemReplay,reconciliation:params.reconciliation}):void 0;if(mergeReceiptProof&&!mergeReceiptProof.trusted&&params.options.force!==!0)throw new PmCliError(`Merge receipt evidence for ${params.subjectId} does not prove the exact item snapshot (${mergeReceiptProof.reason}).`,EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const provenMergeReceipts=mergeReceiptProof?.trusted?subjectMergeReceipts.filter(receipt=>mergeReceiptProof.receipt_ids.includes(receipt.id)):[];return{mergeReceiptProof,effectiveAuditContext:provenMergeReceipts.length>0&&params.options.force!==!0?{...params.options.auditContext,merge:{receipts:provenMergeReceipts.map(summarizeMergeReceipt)}}:params.options.auditContext}}function describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion){const currentItemPath=subject.located?.itemPath??null,loadedItem=snapshot.loadedItem,historyEntries=snapshot.entries;if(!loadedItem)return{currentItemReplay:null,currentItemPath,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const currentItemReplay=toReplayDocument(loadedItem.document),lastOriginalAfterHash=historyEntries[historyEntries.length-1].after_hash;return{currentItemReplay,currentItemPath,matchedChainBefore:replayHashVerificationCandidates(currentItemReplay,itemHashVersion,resolveHistoryHashAlgorithm(historyEntries.at(-1)?.hash_algorithm)).includes(lastOriginalAfterHash),currentItemRawBeforeLock:loadedItem.raw,loadedItem}}function buildHistoryRepairMessage(params){return typeof params.message=="string"&&params.message.trim().length>0?params.message:`history-repair re-anchored ${params.entriesRehashed} entr${params.entriesRehashed===1?"y":"ies"}${params.entriesPatchRepaired>0?`, repaired ${params.entriesPatchRepaired} patch(es)`:""}${params.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function buildHistoryRepairEntries(params){const rewrittenEntries=[...params.reanchorEntries];if(!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const afterReplay=params.reconcileNeeded&&params.currentItemReplay?params.currentItemReplay:params.finalReplay,algorithm=resolveHistoryHashAlgorithm(params.reanchorEntries.at(-1)?.hash_algorithm),beforeHashes=replayHashVerificationCandidates(params.finalReplay,params.itemHashVersion,algorithm),previousAfterHash=params.reanchorEntries[params.reanchorEntries.length-1].after_hash,semanticIndex=beforeHashes.indexOf(previousAfterHash),afterHashes=replayHashVerificationCandidates(afterReplay,params.itemHashVersion,algorithm),auditEntry={hash_algorithm:algorithm,ts:nowIso(),author:params.author,op:params.auditOperation,patch:params.reconcileNeeded&&params.currentItemReplay?jsonPatch.compare(params.finalReplay,params.currentItemReplay):[],before_hash:beforeHashes[semanticIndex],after_hash:afterHashes[semanticIndex],message:params.message,...params.explicitItemHashVersion?{item_hash_version:params.itemHashVersion}:{},...params.auditContext===void 0?{}:{context:params.auditContext}};return rewrittenEntries.push(sealHistoryRecord({...auditEntry,event_class:classifyHistoryEvent(auditEntry)})),{rewrittenEntries,auditEntryAdded:!0}}function collectHistoryRepairWarnings(changed,skippedOps,reconciliation){const warnings=[];return changed||warnings.push("history_repair_no_changes"),skippedOps>0&&warnings.push(`history_repair_skipped_unresolvable_ops:${skippedOps}`),reconciliation&&reconciliation.discarded_events.length>0&&warnings.push(`history_repair_reconcile_discards_events:${reconciliation.discarded_events.length}`,`history_repair_discarded_authors:${reconciliation.discarded_authors.join(",")}`),warnings}async function runHistoryRepair(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);if(options.salvageTail===!0){if(options.appendOnly===!0)throw new PmCliError("Tail salvage cannot be combined with other repair modes.",EXIT_CODE.USAGE);return salvageHistoryTail({pmRoot,subject,settings,typeRegistry,options,author:resolveAuthor(options.author,settings.author_default)})}if(options.appendOnly===!0)return assertAppendOnlyRepairOptions(options),await assertAppendOnlyStreamEncoding(subject.id,subject.historyPath),runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildAppendOnlyRepairPlan(subject,options,snapshot,{analyzeDiscard:analyzeReconciliationDiscard,collectWarnings:collectHistoryRepairWarnings}),reseed:(snapshot,stream)=>buildHistoryReseedPlan(subject,options,snapshot,stream)});const reseed=isEvidenceBoundRepair(options)?void 0:async(snapshot,stream)=>(await assertRegularStreamEntry(subject.id,subject.historyPath),buildHistoryReseedPlan(subject,options,snapshot,stream));return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildHistoryRepairPlan({pmRoot,subject,options},snapshot),reseed})}function isEvidenceBoundRepair(options){return[options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById,options.mergeAbandonmentProof].some(value=>value!==void 0&&value!==!1)}function assertAppendOnlyRepairOptions(options){if([options.normalizeProvenance,options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById,options.mergeAbandonmentProof].some(value=>value!==void 0&&value!==!1))throw new PmCliError("An append-only repair cannot be combined with other repair modes.",EXIT_CODE.USAGE)}function shouldAppendForcedHistoryAudit(options,verifiedHistoryEntries,auditContext){const alreadyRecorded=(options.mergeAbandonmentProof!==void 0||options.mergeReceiptProof!==void 0&&options.force!==!0)&&auditContext!==void 0&&verifiedHistoryEntries.some(entry=>entry.record_hash_version!==void 0&&entry.op==="merge_reconcile"&&stableStringify(entry.context)===stableStringify(auditContext));return options.forceAuditEntry===!0&&!alreadyRecorded}function normalizeHistoryProvenancePreservingBridges(entries){const probe=normalizeInvalidHistoryProvenance(entries);return probe.receipt.changed?normalizeInvalidHistoryProvenance(materializeBridgedSegments(entries)):probe}async function buildHistoryRepairPlan(params,snapshot){const{pmRoot,subject,options}=params,historyEntries=snapshot.entries,chainBefore=snapshot.verification,chainVersionBefore=verifyHistoryChainWithVersion(historyEntries),provenanceNormalization=options.normalizeProvenance?normalizeHistoryProvenancePreservingBridges(historyEntries):{entries:historyEntries,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},itemHashVersion=resolveHistoryRepairItemHashVersion(provenanceNormalization.entries),explicitVersionsBefore=new Set(provenanceNormalization.entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0)),reanchor=reanchorOrRefuse(subject.id,provenanceNormalization.entries,()=>reanchorHistoryEntries(provenanceNormalization.entries,itemHashVersion,{callerMarksBridgeCoverage:provenanceNormalization.receipt.changed})),itemReplayContext=describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion);await assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor);const finalReplay=reanchor.finalDocument,finalReplayHashes=replayHashVerificationCandidates(finalReplay,itemHashVersion);let reconcileNeeded=!1;if(itemReplayContext.currentItemReplay!==null){const currentItemReplayHashes=replayHashVerificationCandidates(itemReplayContext.currentItemReplay,itemHashVersion);reconcileNeeded=!finalReplayHashes.some((hash,hashIndex)=>hash===currentItemReplayHashes[hashIndex])}const reconciliation=reconcileNeeded&&itemReplayContext.currentItemReplay?analyzeReconciliationDiscard(reanchor.entries,finalReplay,itemReplayContext.currentItemReplay):void 0,{mergeReceiptProof,effectiveAuditContext}=await resolveHistoryRepairMergeEvidence({options,pmRoot,subjectId:subject.id,itemReplayContext,reconciliation}),changed=[reanchor.entriesRehashed>0,reanchor.entriesPatchRepaired>0,reanchor.entriesResealed>0,reconcileNeeded,shouldAppendForcedHistoryAudit(options,reanchor.entries,effectiveAuditContext),provenanceNormalization.receipt.changed].some(Boolean),author=snapshot.author,dryRun=!!options.dryRun,repairMessage=buildHistoryRepairMessage({message:options.message,entriesRehashed:reanchor.entriesRehashed,entriesPatchRepaired:reanchor.entriesPatchRepaired,reconcileNeeded}),{rewrittenEntries,auditEntryAdded}=buildHistoryRepairEntries({reanchorEntries:reanchor.entries,changed,reconcileNeeded,currentItemReplay:itemReplayContext.currentItemReplay,finalReplay,author,message:repairMessage,auditOperation:options.auditOperation??"history_repair",auditContext:provenanceNormalization.receipt.changed?{...effectiveAuditContext,provenance_normalization:provenanceNormalization.receipt}:effectiveAuditContext,itemHashVersion,explicitItemHashVersion:reanchor.explicitItemHashVersion}),warnings=collectHistoryRepairWarnings(changed,reanchor.skippedOps,reconciliation);return{changed,rewrittenEntries,beforeWrite:async()=>assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,history:{path:subject.historyPath,entries_scanned:historyEntries.length,chain_drift_before:!chainBefore.ok,entries_rehashed:reanchor.entriesRehashed,entries_patch_repaired:reanchor.entriesPatchRepaired,converted_replace_to_add:reanchor.convertedReplaceToAdd,skipped_ops:reanchor.skippedOps,reconciled_with_item:reconcileNeeded,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors,item_hash_version_before:chainVersionBefore.item_hash_version??null,item_hash_version_after:itemHashVersion,version_disposition:explicitVersionsBefore.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:itemReplayContext.currentItemPath!==null,path:itemReplayContext.currentItemPath,matched_chain_before:itemReplayContext.matchedChainBefore},provenance_normalization:{requested:options.normalizeProvenance===!0,...provenanceNormalization.receipt},...reconciliation?{reconciliation}:{},...mergeReceiptProof?{merge_receipt_proof:mergeReceiptProof}:{},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}function assertHistoryRepairTarget(id,all){if(all&&id!==void 0)throw new PmCliError("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",EXIT_CODE.USAGE);if(!all&&id===void 0)throw new PmCliError("history-repair: provide an item <id> or pass --all to repair every drifted stream.",EXIT_CODE.USAGE)}async function runHistoryRepairAll(options,global2){if(options.salvageTail===!0)throw new PmCliError("Tail salvage requires one explicit item ID; --all is not supported.",EXIT_CODE.USAGE);const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),itemReadWarnings=[],items=await listAllItemMetadataWithBody(pmRoot,settings.item_format,typeRegistry.type_to_folder,itemReadWarnings,settings.schema,{forceSourceScan:!0}),drift=await scanHistoryDrift(pmRoot,items),invalidProvenanceIds=options.normalizeProvenance?await listInvalidProvenanceHistoryStreamIds(pmRoot):[],targetedIds=[...new Set([...drift.driftedItems,...invalidProvenanceIds])].sort((left,right)=>left.localeCompare(right)),streams=[],repairWarnings=[],totals={repaired:0,skipped_clean:0,failed:0};for(const driftedId of targetedIds)try{const result=await runHistoryRepair(driftedId,{...options,auditContext:options.auditContextById?.[driftedId],auditContextById:void 0,mergeReceiptProof:options.mergeReceiptProofById?.[driftedId]??options.mergeReceiptProof,mergeReceiptProofById:void 0},global2),outcome=result.changed?"repaired":"skipped_clean";totals[outcome]+=1,repairWarnings.push(...result.warnings.map(warning=>`${driftedId}:${warning}`)),streams.push({id:driftedId,outcome,entries_rehashed:result.history.entries_rehashed,entries_patch_repaired:result.history.entries_patch_repaired,reconciled_with_item:result.history.reconciled_with_item,...result.reconciliation?{reconciliation:result.reconciliation}:{},...result.merge_receipt_proof?{merge_receipt_proof:result.merge_receipt_proof}:{},warnings:result.warnings})}catch(error){totals.failed+=1,streams.push({id:driftedId,outcome:"failed",error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,pmRoot)})}return options.dryRun||await invalidateHistoryDriftCache(pmRoot),{all:!0,dry_run:!!options.dryRun,scanned_streams:items.length,drifted_streams:drift.driftedItems.length,provenance_invalid_streams:invalidProvenanceIds.length,streams,totals,warnings:[...new Set([...itemReadWarnings,...repairWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()}}export{analyzeReconciliationDiscard,assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll};
1
+ import{itemRevisionConflictRowFields as Q}from"./lifecycle/item-revision.js";import{salvageHistoryTail as Y}from"./history/salvage.js";import{assertAppendOnlyStreamEncoding as Z,assertRegularStreamEntry as ee,buildAppendOnlyRepairPlan as te}from"./history/append-only-repair.js";import{buildHistoryReseedPlan as k}from"./history/reseed.js";import{reanchorOrRefuse as re}from"./history/reanchor-refusal.js";import{resolveHistoryHashAlgorithm as B}from"../core/history/digest.js";import{realpath as O}from"node:fs/promises";import H from"node:path";import j from"fast-json-patch";import{patchPathToChangedField as C}from"../core/history/history-diff.js";import{normalizeReplayPatchOps as ne,reanchorHistoryEntries as ie,replayHashVerificationCandidates as v,resolveHistoryRepairItemHashVersion as oe,toReplayDocument as se,verifyHistoryChainWithVersion as ae,materializeBridgedSegments as ce}from"../core/history/replay.js";import{sealHistoryRecord as de}from"../core/history/history.js";import{classifyHistoryEvent as le}from"../core/history/event-classification.js";import{scanHistoryDrift as ue}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache as he}from"../core/history/drift-cache.js";import{EXIT_CODE as _}from"../core/shared/constants.js";import{PmCliError as g}from"../core/shared/errors.js";import{sha256Hex as fe,stableStringify as I}from"../core/shared/serialization.js";import{resolveAuthor as pe}from"../core/shared/author.js";import{nowIso as E}from"../core/shared/time.js";import{listAllItemMetadataWithBody as me}from"../core/store/item-store.js";import{resolveHistoryWorkspace as z,resolveHistorySubject as ye}from"./history/subject.js";import{runHistoryMaintenance as M}from"./history/maintenance.js";import{isOriginalGitStateRestored as _e}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences as ge,inspectMergeReceiptEvidence as Re,summarizeMergeReceipt as ve}from"./merge/receipts.js";import{encodeItemScalarDecisionValue as we,hashItemScalarDecisionValue as Ie}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds as Pe,normalizeInvalidHistoryProvenance as F}from"./governance/provenance-health.js";function V(e,t){return t==="body"?e.body:e.metadata[t]}function be(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const i=t;return e==="comments"?typeof i.created_at=="string"&&typeof i.author=="string"&&typeof i.text=="string":typeof i.path=="string"||e==="tests"&&typeof i.command=="string"}function Ae(e){const t={...e};if(t.source_kind==="merge_union"&&(t.source_kind="local_mutation"),t.provenance!==null&&typeof t.provenance=="object"&&!Array.isArray(t.provenance)){const i={...t.provenance};i.source_kind==="merge_union"&&(i.source_kind="local_mutation"),t.provenance=i}return t}function W(e,t){if(!Array.isArray(t)||!["comments","docs","tests"].includes(e)||!t.every(r=>be(e,r)))return t;const i=t.map(r=>e==="comments"?r:Ae(r));return[...new Map(i.map(r=>[I(r),r])).values()]}function x(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;const r=new Set;return e.every(n=>{const a=t.findIndex((o,d)=>!r.has(d)&&x(n,o));return a<0?!1:(r.add(a),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;const i=t;return Object.entries(e).every(([r,n])=>Object.hasOwn(i,r)&&x(n,i[r]))}function T(e,t){const i=new Set(t),r=[];for(let n=e.length-1;n>=0&&i.size>0;n-=1){const a=e[n],o=new Set;for(const c of ne(a.patch))o.add(C(c.path)),c.from&&o.add(C(c.from));const d=[...i].filter(c=>o.has(c));if(d.length!==0){for(const c of d)i.delete(c);r.push({index:n+1,ts:a.ts,author:a.author,op:a.op,fields:d.sort((c,f)=>c.localeCompare(f))})}}return r.reverse()}function $(e,t,i){const r=j.compare(t,i);if(r.length===0)return;const n=new Set;for(const s of r)n.add(C(s.path));const a=new Set([...n].filter(s=>x(W(s,V(t,s)),W(s,V(i,s))))),o=new Set([...n].filter(s=>!a.has(s))),d=T(e,o),c=T(e,a),f=[...n].sort((s,u)=>s.localeCompare(u)),y=[...o].sort((s,u)=>s.localeCompare(u)),l=[...a].sort((s,u)=>s.localeCompare(u)),h=[...new Set(d.map(s=>s.author))].sort((s,u)=>s.localeCompare(u)),p=[...new Set(c.map(s=>s.author))].sort((s,u)=>s.localeCompare(u));return{reconciled_field_count:n.size,reconciled_fields:f,reverted_field_count:o.size,reverted_fields:y,discarded_events:d,discarded_authors:h,preserved_field_count:a.size,preserved_fields:l,preserved_events:c,preserved_authors:p,recovery_hint:d.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function He(e){try{return await O(e)}catch{return null}}async function Ce(e){if(await He(H.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;const i=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(d=>d.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||i.length===0)return null;const n=Object.keys(r).sort();if(i.length!==n.length||i.some((d,c)=>d!==n[c]))return null;const a=e.currentItemReplay.metadata;return i.every(d=>{const c=d==="body"?e.currentItemReplay.body:a[d];return[Ie(c),fe(I(we(c)))].includes(r[d])})?{receipt:e.receipt,declaredFields:i}:null}async function Ee(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const t=e.proof.receipts.filter(o=>o.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const i=await O(e.itemPath),r=[];for(const o of t){const d=await Ce({receipt:o,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:i,currentItemReplay:e.currentItemReplay});d&&r.push(d)}const n=new Set(r.flatMap(({declaredFields:o})=>o)),a=e.reconciliation?.reconciled_fields;return r.length>0&&(a===void 0||a.length>0&&a.every(o=>n.has(o)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:o})=>o.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function D(e,t,i,r){if(e===void 0)return;const{receipt:n,gitWorkspaceRoot:a}=e,o=t.currentItemPath===null?null:H.relative(a,t.currentItemPath).split(H.sep).join("/");if(!i||r.entriesRehashed!==0||r.entriesPatchRepaired!==0||t.matchedChainBefore!==!0||t.currentItemRawBeforeLock===null||o!==n.item_path||n.operation===void 0||!await _e(a,n.item_path,n.operation,t.currentItemRawBeforeLock))throw new g("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function xe(e){const t=new Set(e.options.mergeReceiptProof?.receipts.filter(o=>o.item_id===e.subjectId).map(o=>o.id)??[]),i=e.options.mergeReceiptProof?await Re(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0,r=i?.receipts.filter(o=>o.item_id===e.subjectId&&t.has(o.id))??[];ge(t,i,e.options.dryRun===!0);const n=e.options.mergeReceiptProof?await Ee({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(n&&!n.trusted&&e.options.force!==!0)throw new g(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${n.reason}).`,_.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const a=n?.trusted?r.filter(o=>n.receipt_ids.includes(o.id)):[];return{mergeReceiptProof:n,effectiveAuditContext:a.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:a.map(ve)}}:e.options.auditContext}}function Se(e,t,i){const r=e.located?.itemPath??null,n=t.loadedItem,a=t.entries;if(!n)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const o=se(n.document),d=a[a.length-1].after_hash;return{currentItemReplay:o,currentItemPath:r,matchedChainBefore:v(o,i,B(a.at(-1)?.hash_algorithm)).includes(d),currentItemRawBeforeLock:n.raw,loadedItem:n}}function ke(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function Be(e){const t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};const i=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=B(e.reanchorEntries.at(-1)?.hash_algorithm),n=v(e.finalReplay,e.itemHashVersion,r),a=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,o=n.indexOf(a),d=v(i,e.itemHashVersion,r),c={hash_algorithm:r,ts:E(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?j.compare(e.finalReplay,e.currentItemReplay):[],before_hash:n[o],after_hash:d[o],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}};return t.push(de({...c,event_class:le(c)})),{rewrittenEntries:t,auditEntryAdded:!0}}function L(e,t,i){const r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),i&&i.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${i.discarded_events.length}`,`history_repair_discarded_authors:${i.discarded_authors.join(",")}`),r}async function Oe(e,t,i){const{pmRoot:r,settings:n,typeRegistry:a}=await z(i.path),o=await ye(r,e,n,a.type_to_folder);if(t.salvageTail===!0){if(t.appendOnly===!0)throw new g("Tail salvage cannot be combined with other repair modes.",_.USAGE);return Y({pmRoot:r,subject:o,settings:n,typeRegistry:a,options:t,author:pe(t.author,n.author_default)})}if(t.appendOnly===!0)return ze(t),await Z(o.id,o.historyPath),M({pmRoot:r,subject:o,settings:n,typeRegistry:a,operation:"history-repair",options:t,transform:c=>te(o,t,c,{analyzeDiscard:$,collectWarnings:L}),reseed:(c,f)=>k(o,t,c,f)});const d=je(t)?void 0:async(c,f)=>(await ee(o.id,o.historyPath),k(o,t,c,f));return M({pmRoot:r,subject:o,settings:n,typeRegistry:a,operation:"history-repair",options:t,transform:c=>Ve({pmRoot:r,subject:o,options:t},c),reseed:d})}function je(e){return[e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1)}function ze(e){if([e.normalizeProvenance,e.auditOperation,e.auditContext,e.auditContextById,e.forceAuditEntry,e.mergeReceiptProof,e.mergeReceiptProofById,e.mergeAbandonmentProof].some(t=>t!==void 0&&t!==!1))throw new g("An append-only repair cannot be combined with other repair modes.",_.USAGE)}function Me(e,t,i){const r=(e.mergeAbandonmentProof!==void 0||e.mergeReceiptProof!==void 0&&e.force!==!0)&&i!==void 0&&t.some(n=>n.record_hash_version!==void 0&&n.op==="merge_reconcile"&&I(n.context)===I(i));return e.forceAuditEntry===!0&&!r}function Fe(e){const t=F(e);return t.receipt.changed?F(ce(e)):t}async function Ve(e,t){const{pmRoot:i,subject:r,options:n}=e,a=t.entries,o=t.verification,d=ae(a),c=n.normalizeProvenance?Fe(a):{entries:a,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=oe(c.entries),y=new Set(c.entries.map(m=>m.item_hash_version).filter(m=>m!==void 0)),l=re(r.id,c.entries,()=>ie(c.entries,f,{callerMarksBridgeCoverage:c.receipt.changed})),h=Se(r,t,f);await D(n.mergeAbandonmentProof,h,o.ok,l);const p=l.finalDocument,s=v(p,f);let u=!1;if(h.currentItemReplay!==null){const m=v(h.currentItemReplay,f);u=!s.some((b,A)=>b===m[A])}const R=u&&h.currentItemReplay?$(l.entries,p,h.currentItemReplay):void 0,{mergeReceiptProof:S,effectiveAuditContext:P}=await xe({options:n,pmRoot:i,subjectId:r.id,itemReplayContext:h,reconciliation:R}),w=[l.entriesRehashed>0,l.entriesPatchRepaired>0,l.entriesResealed>0,u,Me(n,l.entries,P),c.receipt.changed].some(Boolean),N=t.author,G=!!n.dryRun,U=ke({message:n.message,entriesRehashed:l.entriesRehashed,entriesPatchRepaired:l.entriesPatchRepaired,reconcileNeeded:u}),{rewrittenEntries:q,auditEntryAdded:X}=Be({reanchorEntries:l.entries,changed:w,reconcileNeeded:u,currentItemReplay:h.currentItemReplay,finalReplay:p,author:N,message:U,auditOperation:n.auditOperation??"history_repair",auditContext:c.receipt.changed?{...P,provenance_normalization:c.receipt}:P,itemHashVersion:f,explicitItemHashVersion:l.explicitItemHashVersion}),J=L(w,l.skippedOps,R);return{changed:w,rewrittenEntries:q,beforeWrite:async()=>D(n.mergeAbandonmentProof,h,o.ok,l),report:({verification:m,warnings:b})=>({id:r.id,dry_run:G,changed:w,history:{path:r.historyPath,entries_scanned:a.length,chain_drift_before:!o.ok,entries_rehashed:l.entriesRehashed,entries_patch_repaired:l.entriesPatchRepaired,converted_replace_to_add:l.convertedReplaceToAdd,skipped_ops:l.skippedOps,reconciled_with_item:u,audit_entry_added:X,verify_ok:m.ok,verify_errors:m.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:y.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:h.currentItemPath!==null,path:h.currentItemPath,matched_chain_before:h.matchedChainBefore},provenance_normalization:{requested:n.normalizeProvenance===!0,...c.receipt},...R?{reconciliation:R}:{},...S?{merge_receipt_proof:S}:{},warnings:[...new Set([...J,...b])].sort((A,K)=>A.localeCompare(K)),generated_at:E()})}}function ht(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",_.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",_.USAGE)}async function ft(e,t){if(e.salvageTail===!0)throw new g("Tail salvage requires one explicit item ID; --all is not supported.",_.USAGE);const{pmRoot:i,settings:r,typeRegistry:n}=await z(t.path),a=[],o=await me(i,r.item_format,n.type_to_folder,a,r.schema,{forceSourceScan:!0}),d=await ue(i,o),c=e.normalizeProvenance?await Pe(i):[],f=[...new Set([...d.driftedItems,...c])].sort((p,s)=>p.localeCompare(s)),y=[],l=[],h={repaired:0,skipped_clean:0,failed:0};for(const p of f)try{const s=await Oe(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),u=s.changed?"repaired":"skipped_clean";h[u]+=1,l.push(...s.warnings.map(R=>`${p}:${R}`)),y.push({id:p,outcome:u,entries_rehashed:s.history.entries_rehashed,entries_patch_repaired:s.history.entries_patch_repaired,reconciled_with_item:s.history.reconciled_with_item,...s.reconciliation?{reconciliation:s.reconciliation}:{},...s.merge_receipt_proof?{merge_receipt_proof:s.merge_receipt_proof}:{},warnings:s.warnings})}catch(s){h.failed+=1,y.push({id:p,outcome:"failed",error:s instanceof Error?s.message:String(s),...await Q(s,i)})}return e.dryRun||await he(i),{all:!0,dry_run:!!e.dryRun,scanned_streams:o.length,drifted_streams:d.driftedItems.length,provenance_invalid_streams:c.length,streams:y,totals:h,warnings:[...new Set([...a,...l])].sort((p,s)=>p.localeCompare(s)),generated_at:E()}}export{$ as analyzeReconciliationDiscard,ht as assertHistoryRepairTarget,Oe as runHistoryRepair,ft as runHistoryRepairAll};
2
2
  //# sourceMappingURL=history-repair.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]="ed03b6c8-6275-55a6-8e5f-4f27a23d6696")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const IMPROVEMENT_LEDGER_FORMAT_VERSION=1;function isValidLedgerObservation(observation){if(typeof observation!="object"||observation===null)return!1;const candidate=observation;return typeof candidate.id=="string"&&typeof candidate.metric=="string"&&typeof candidate.value=="number"&&Number.isFinite(candidate.value)&&["higher","lower","target"].includes(String(candidate.direction))&&typeof candidate.observed_at=="string"&&typeof candidate.revision=="string"&&["caller","git","unversioned"].includes(String(candidate.revision_source))&&typeof candidate.author=="string"?candidate.direction!=="target"||typeof candidate.threshold=="number"&&Number.isFinite(candidate.threshold):!1}function parseImprovementLedgerDocument(raw){if(raw===null)return{format_version:IMPROVEMENT_LEDGER_FORMAT_VERSION,observations:[]};let parsed;try{parsed=JSON.parse(raw)}catch{throw new PmCliError("Improvement ledger contains invalid JSON.",EXIT_CODE.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed)||parsed.format_version!==IMPROVEMENT_LEDGER_FORMAT_VERSION||!Array.isArray(parsed.observations))throw new PmCliError("Improvement ledger has an unsupported shape or format version.",EXIT_CODE.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});const observations=parsed.observations;for(const observation of observations)if(!isValidLedgerObservation(observation))throw new PmCliError("Improvement ledger contains an invalid observation.",EXIT_CODE.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return parsed}export{parseImprovementLedgerDocument};
1
+ import{EXIT_CODE as t}from"../core/shared/constants.js";import{PmCliError as i}from"../core/shared/errors.js";const n=1;function a(r){if(typeof r!="object"||r===null)return!1;const e=r;return typeof e.id=="string"&&typeof e.metric=="string"&&typeof e.value=="number"&&Number.isFinite(e.value)&&["higher","lower","target"].includes(String(e.direction))&&typeof e.observed_at=="string"&&typeof e.revision=="string"&&["caller","git","unversioned"].includes(String(e.revision_source))&&typeof e.author=="string"?e.direction!=="target"||typeof e.threshold=="number"&&Number.isFinite(e.threshold):!1}function m(r){if(r===null)return{format_version:n,observations:[]};let e;try{e=JSON.parse(r)}catch{throw new i("Improvement ledger contains invalid JSON.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"})}if(typeof e!="object"||e===null||Array.isArray(e)||e.format_version!==n||!Array.isArray(e.observations))throw new i("Improvement ledger has an unsupported shape or format version.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});const o=e.observations;for(const s of o)if(!a(s))throw new i("Improvement ledger contains an invalid observation.",t.GENERIC_FAILURE,{code:"invalid_improvement_ledger"});return e}export{m as parseImprovementLedgerDocument};
2
2
  //# sourceMappingURL=improvement-ledger-validation.js.map