@unbrained/pm-cli 2026.11.21 → 2026.11.22

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 (203) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/dist/cli/register-history-maintenance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
  6. package/dist/cli-bundle/chunks/{chunk-PJXKA4QU.js → chunk-4TB5D6HL.js} +37 -37
  7. package/dist/cli-bundle/chunks/{chunk-WELSVDPU.js → chunk-5ZMVLWE3.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
  9. package/dist/cli-bundle/chunks/{chunk-JVGRFU5H.js → chunk-AR4NP5HI.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-XHJ3H5PL.js → chunk-B4PPFOPY.js} +3 -3
  11. package/dist/cli-bundle/chunks/{chunk-5647LU3A.js → chunk-B76TFRO2.js} +47 -45
  12. package/dist/cli-bundle/chunks/{chunk-YJEBK7HU.js → chunk-CAR2L5NW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-D6ILFXZY.js → chunk-EIGUKEV6.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-XWHJIRNV.js → chunk-GTPCAJMZ.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-CASX6SFI.js → chunk-HC2OPETM.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-NCFCBKIP.js → chunk-HKUV74K3.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
  19. package/dist/cli-bundle/chunks/{chunk-S6HB3WL2.js → chunk-J2LABXBL.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-BKSVHOWI.js → chunk-J52BEBSS.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-NT5AKFE5.js → chunk-OJTMGDON.js} +31 -31
  22. package/dist/cli-bundle/chunks/{chunk-SRVTCYAU.js → chunk-TC6XLIYO.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-AHQB7W2H.js → chunk-U7EL3AYA.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
  25. package/dist/cli-bundle/chunks/{chunk-CIKGG34F.js → chunk-X6MIWTTT.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-RMIRNYRG.js → chunk-XFHPKXAE.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-6QLEXRUG.js → chunk-YHVLVSEZ.js} +2 -2
  29. package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-4QBMZXKX.js} +2 -2
  30. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
  31. package/dist/cli-bundle/chunks/{mutation-actor-3TG636XG.js → mutation-actor-FWLYWJ37.js} +2 -2
  32. package/dist/cli-bundle/chunks/{mutation-admission-LICSDNNO.js → mutation-admission-7ZDCK3G2.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-RR5KACJ3.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-mutation-WWVECKFQ.js → register-mutation-57AJQWFV.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-operations-L6HFJNWD.js → register-operations-RKWST7CU.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-setup-K7UFG5TD.js → register-setup-CMI23PC5.js} +2 -2
  37. package/dist/cli-bundle/chunks/{stage-57KH3KAC.js → stage-4KDVXC5Z.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-YOAYY3HE.js → chunk-2ZD7275J.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-532WZV65.js → chunk-324AHXJO.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-QGKLRXP7.js → chunk-4JZITIJB.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-CU2BRAOX.js → chunk-4KTFKSS3.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-MKM5NKD7.js → chunk-BRZV7BFV.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-RPE6IX26.js → chunk-HDEKFSOK.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-LNHUE4VV.js → chunk-IWOXAUDU.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-J63D6QST.js → chunk-ML3JHCC6.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-JMQJBZQ5.js → chunk-OPGOOP25.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-XCJSHNXK.js → chunk-RE7ZWT7D.js} +3 -3
  51. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-WXMI4AV5.js → chunk-RQ252B6V.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-7A4QWNZX.js → chunk-URGHTTT3.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-IQK5NPMG.js → chunk-USPYKWQG.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-UOC6257J.js → chunk-WZWXGDYY.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-NP72ZDXE.js → chunk-YKSLZPLT.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-2O6MLPEX.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{mutation-actor-62HKR5IO.js → mutation-actor-TCYDPUGG.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{mutation-admission-X4PF2SG3.js → mutation-admission-LY73EJWM.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{stage-O7T7CXBB.js → stage-DQ7RQQ52.js} +2 -2
  65. package/dist/cli-bundle/main.js +2 -2
  66. package/dist/cli-bundle/sdk-authoring.js +1 -1
  67. package/dist/cli-bundle/sdk-contracts.js +2 -2
  68. package/dist/cli-bundle/sdk-core.js +1 -1
  69. package/dist/cli-bundle/sdk-governance.js +1 -1
  70. package/dist/cli-bundle/sdk-graph.js +1 -1
  71. package/dist/cli-bundle/sdk-merge.js +70 -58
  72. package/dist/cli-bundle/sdk-query.js +1 -1
  73. package/dist/cli-bundle/sdk-runtime.js +1 -1
  74. package/dist/cli-bundle/sdk-testing.js +1 -1
  75. package/dist/cli-bundle/sdk.js +11 -11
  76. package/dist/core/diagnostics/remediation.js +1 -1
  77. package/dist/core/fs/atomic-create.js +1 -1
  78. package/dist/core/fs/file-glob.js +1 -1
  79. package/dist/core/history/bridge.js +2 -0
  80. package/dist/core/history/drift-scan.js +1 -1
  81. package/dist/core/history/history-rewrite.js +1 -1
  82. package/dist/core/history/history.d.ts +12 -0
  83. package/dist/core/history/history.js +2 -2
  84. package/dist/core/history/projection.js +1 -1
  85. package/dist/core/history/read.d.ts +9 -0
  86. package/dist/core/history/read.js +1 -1
  87. package/dist/core/history/replay.d.ts +46 -5
  88. package/dist/core/history/replay.js +2 -2
  89. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  90. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  91. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  92. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  93. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  94. package/dist/sdk/completion/fish.js +3 -2
  95. package/dist/sdk/completion/zsh.js +3 -2
  96. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  97. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  98. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  99. package/dist/sdk/governance/health.js +2 -2
  100. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  101. package/dist/sdk/history/append-only-repair.js +6 -0
  102. package/dist/sdk/history/maintenance.d.ts +8 -2
  103. package/dist/sdk/history/maintenance.js +1 -1
  104. package/dist/sdk/history/reanchor-refusal.js +2 -0
  105. package/dist/sdk/history/reseed.d.ts +15 -0
  106. package/dist/sdk/history/reseed.js +2 -0
  107. package/dist/sdk/history/salvage.d.ts +19 -8
  108. package/dist/sdk/history/salvage.js +5 -3
  109. package/dist/sdk/history-compact.js +1 -1
  110. package/dist/sdk/history-redact.js +1 -1
  111. package/dist/sdk/history-repair.d.ts +8 -2
  112. package/dist/sdk/history-repair.js +1 -1
  113. package/dist/sdk/index.d.ts +1 -1
  114. package/dist/sdk/item-transaction.d.ts +33 -1
  115. package/dist/sdk/item-transaction.js +1 -1
  116. package/dist/sdk/lifecycle/restore.js +1 -1
  117. package/dist/sdk/merge/three-way.d.ts +22 -3
  118. package/dist/sdk/merge/three-way.js +8 -2
  119. package/dist/sdk/public-surface.json +1 -1
  120. package/dist/sdk/runtime/actions.js +1 -1
  121. package/dist/sdk/runtime-input.d.ts +6 -2
  122. package/dist/sdk/runtime-input.js +1 -1
  123. package/dist/sdk/runtime-primitives.d.ts +1 -1
  124. package/dist/sdk/runtime-primitives.js +1 -1
  125. package/dist/sdk/runtime.d.ts +7 -0
  126. package/dist/sdk/runtime.js +1 -1
  127. package/dist/sdk/structured-mutations.d.ts +5 -5
  128. package/dist/sdk/structured-mutations.js +1 -1
  129. package/dist/sdk/transactions/item-finalization.js +2 -0
  130. package/dist/types.d.ts +20 -0
  131. package/dist/types.js +1 -1
  132. package/docs/AGENT_GUIDE.md +1 -1
  133. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  134. package/docs/COMMANDS.md +6 -2
  135. package/docs/HISTORY_RECOVERY.md +229 -5
  136. package/docs/README.md +2 -2
  137. package/docs/SDK.md +103 -4
  138. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  139. package/marketplace.json +1 -1
  140. package/node_modules/tar/package.json +2 -3
  141. package/package.json +30 -2
  142. package/packages/pm-beads/package.json +1 -1
  143. package/packages/pm-calendar/package.json +1 -1
  144. package/packages/pm-command-kit/package.json +1 -1
  145. package/packages/pm-digital-twin/package.json +1 -1
  146. package/packages/pm-governance-audit/package.json +1 -1
  147. package/packages/pm-guide-shell/package.json +1 -1
  148. package/packages/pm-kanban/package.json +1 -1
  149. package/packages/pm-lifecycle-hooks/package.json +1 -1
  150. package/packages/pm-linked-test-adapters/package.json +1 -1
  151. package/packages/pm-search-advanced/package.json +1 -1
  152. package/packages/pm-templates/package.json +1 -1
  153. package/packages/pm-todos/package.json +1 -1
  154. package/packages/pm-vcs/package.json +1 -1
  155. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  156. package/plugins/pm-claude/package.json +1 -1
  157. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  158. package/plugins/pm-codex/package.json +1 -1
  159. package/plugins/pm-codex/plugin.json +1 -1
  160. package/runtime-dependencies.json +1 -1
  161. package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
  162. package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
  163. package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
  164. package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
  167. package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
  171. package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
  172. package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
  173. package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
  174. package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
  175. package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
  176. package/dist/sdk/agent/refusal-closure.js +0 -2
  177. package/dist/sdk/agent/refusal-reachability.js +0 -4
  178. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  179. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  180. package/dist/sdk/authoring.js +0 -2
  181. package/dist/sdk/compose.js +0 -2
  182. package/dist/sdk/contracts.js +0 -2
  183. package/dist/sdk/core-governance.js +0 -2
  184. package/dist/sdk/core.js +0 -2
  185. package/dist/sdk/corpus-shape.js +0 -2
  186. package/dist/sdk/define.js +0 -2
  187. package/dist/sdk/environment/agent-environment.js +0 -2
  188. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  189. package/dist/sdk/governance/coverage-assurance.js +0 -2
  190. package/dist/sdk/governance/reliability.js +0 -2
  191. package/dist/sdk/governance.js +0 -2
  192. package/dist/sdk/graph/adapter.js +0 -2
  193. package/dist/sdk/graph/conformance.js +0 -2
  194. package/dist/sdk/graph/index.js +0 -2
  195. package/dist/sdk/graph.js +0 -2
  196. package/dist/sdk/index.js +0 -2
  197. package/dist/sdk/query.js +0 -2
  198. package/dist/sdk/relationship-migration.js +0 -2
  199. package/dist/sdk/testing.js +0 -8
  200. package/dist/sdk/workspace-recipe.js +0 -2
  201. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  202. package/docs/DEFECT_RECURRENCE.md +0 -257
  203. package/docs/PERFORMANCE.md +0 -204
@@ -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]="f9317f5b-f007-5882-aafe-898d1f76f2ae")}catch{}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!="string")return;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)&&(map[entry.code]=entry.command)}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
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]="2000c9e7-7cba-5f6f-adea-d980569b4869")}catch{}})();const REMEDIATION_REGISTRY=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"merge_driver_configuration_missing",command:"pm merge install",summary:"Install the clone-local Git drivers required by the tracker merge fence."},{code:"merge_driver_configuration_drift",command:"pm merge install",summary:"Reinstall clone-local Git drivers after runtime or package paths change."},{code:"merge_fence_missing",command:"pm merge install",summary:"Install the active tracker's committed Git merge attributes."},{code:"merge_fence_drift",command:"pm merge install",summary:"Restore the active tracker's merge mappings while retaining sibling tracker fences."},{code:"validate_merge_driver_configuration",command:"pm merge install",summary:"Restore missing or drifted clone-local Git merge driver commands."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_artifacts_ignored",command:"pm health --check-only --full",summary:"Remove or narrow the owning ignore rules listed in integrity.ignored_merge_artifacts. Merge receipts must be committed with their audit history; preserve those files, then preview pm merge reconcile --stage --dry-run before applying settlement."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:'Review pending receipt summaries, re-apply intended discarded values, then run pm merge reconcile. If proof is unavailable or receipt decisions are lossy, explicit review authority is required for pm merge reconcile --force --message "<reviewed receipt disposition and rationale>"; this records acceptance rather than restoring discarded values.'},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:'A lossless receipt is pending; preview with pm merge reconcile --dry-run, then apply. If no receipt set proves the snapshot, review the summaries and only with explicit authority run pm merge reconcile --force --message "<reviewed receipt disposition and rationale>" to record an audited acceptance.'},{code:"merge_receipt_evidence_invalid",command:"pm merge report --include-reconciled --json",summary:"One or more receipt candidates failed bounded-file, schema, identity, or copy-consistency validation; inspect the report's privacy-safe source, receipt id, and reason before repairing only the named evidence."},{code:"merge_receipt_history_reference_missing",command:"pm merge reconcile --dry-run",summary:"Review the bounded coordinates and recover available evidence first; for exact pre-durable clone-local-only references, rerun with --force so pm appends an audited disposition and proves the health finding is cleared without rewriting history."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history record; the repair rebuilds the stream as one audited baseline from the on-disk item, and earlier versions stay unrecorded. When the stream was deleted by mistake, restore it from version control first (pm history-repair --all, with or without --append-only, rebuilds every missing stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"The item's history stream cannot be read; preview salvage, which removes lines that cannot hold a record and an invalid tail after a verified prefix, then apply it without --dry-run. Salvage refuses interior corruption, which needs recovery from version control, and a permission error needs the file's access fixed."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id> --append-only",summary:"The item's history chain is broken; append one record that bridges every break in the stream and keeps every recorded line byte-identical (pm history-repair <id> re-anchors the recorded entries instead). pm health previews the bridge for every chain mismatch, so a break a bridge cannot repair is reported as history_drift_chain_unbridgeable, and a stream no repair can keep as history_drift_unrepairable_stream, instead."},{code:"history_drift_chain_unbridgeable",command:"pm history-repair <id>",summary:"The item's history chain is broken in a way an append-only bridge cannot repair, for example a recorded patch that applies only on top of the unrecorded change (details.repair_refusals names the refusal reason); re-anchor the recorded entries instead (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unrepairable_stream",command:"pm history <id> --verify --full",summary:"Neither history repair can keep this stream (details.repair_refusals names both refusal reasons). Inspect it: a record that no longer matches its seal, or a malformed chain, needs the item's own stream restored from version control or a backup; a stream entry that is a link (reason stream_not_regular_file) needs the item's own stream restored as a regular file. Then run pm history <id> --verify --strict-exit."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"stale_in_progress_items",command:"pm list --status in_progress --assignee-filter unassigned --updated-before -72h",summary:"List unowned in-progress candidates idle past mutation_guard.stale_in_progress_hours by metadata time (pm health substitutes the configured status id and threshold); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_unowned",command:"pm list --status in_progress --assignee-filter unassigned",summary:"List in-progress items nobody holds (pm health substitutes the configured status id); claim each with pm claim <id> or return it to open with pm update <id> --status open."},{code:"in_progress_idle",command:"pm list --status in_progress --updated-before -72h",summary:"List in-progress candidates not updated within mutation_guard.stale_in_progress_hours (pm health substitutes the configured status id and threshold; a restored item can appear although its history is recent); resume, release or return each one, or take another holder's with pm claim <id> --takeover-stale, which re-judges under the item lock."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_closed_at",command:"pm validate --check-metadata --auto-fix --fix-scope timestamps --dry-run",summary:"Preview closure dates proven by verified lifecycle history; inspect residuals and omit --dry-run to apply only proven dates."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Rebuild the history streams of the items without a history record as one audited baseline from each on-disk item."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id> --salvage-tail --dry-run",summary:"Preview salvage of the unreadable history streams, then apply it without --dry-run; interior corruption needs recovery from version control."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function resolveRemediation(warning){if(typeof warning!="string")return;const normalized=warning.trim();for(const entry of REMEDIATION_REGISTRY)if(normalized===entry.code||normalized.startsWith(`${entry.code}:`))return entry}function buildRemediationMap(warnings){const map={};for(const warning of warnings){const entry=resolveRemediation(warning);entry!==void 0&&!Object.prototype.hasOwnProperty.call(map,entry.code)&&(map[entry.code]=entry.command)}return map}function buildRemediationCommands(warnings){return Object.values(buildRemediationMap(warnings))}export{REMEDIATION_REGISTRY,buildRemediationCommands,buildRemediationMap,resolveRemediation};
2
2
  //# sourceMappingURL=remediation.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]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();import{link,mkdir,mkdtemp,rm,writeFile}from"node:fs/promises";import path from"node:path";async function createFileAtomic(targetPath,contents){const parent=path.dirname(targetPath);await mkdir(parent,{recursive:!0});const staging=await mkdtemp(path.join(parent,".pm-seed-")),stagedFile=path.join(staging,"value");try{await writeFile(stagedFile,contents,"utf8");try{return await link(stagedFile,targetPath),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}}finally{await rm(staging,{recursive:!0,force:!0})}}export{createFileAtomic};
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]="1c52c822-3fe3-5afd-8ac1-182e7a18dbde")}catch{}})();import{link,mkdir,mkdtemp,open,rm,writeFile}from"node:fs/promises";import path from"node:path";const HARD_LINK_UNSUPPORTED=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);class AtomicLinkUnsupportedError extends Error{code;constructor(code,cause){super(`The filesystem cannot publish a file by hard link (${code}).`,{cause}),this.name="AtomicLinkUnsupportedError",this.code=code}}async function writeDurably(file,contents){const handle=await open(file,"wx");try{await handle.writeFile(contents,"utf8"),await handle.sync()}finally{await handle.close()}}async function createFileAtomic(targetPath,contents,options={}){const parent=path.dirname(targetPath);await mkdir(parent,{recursive:!0});const staging=await mkdtemp(path.join(parent,".pm-seed-")),stagedFile=path.join(staging,"value");try{await(options.sync===!0?writeDurably(stagedFile,contents):writeFile(stagedFile,contents,"utf8"));try{return await link(stagedFile,targetPath),!0}catch(error){const code=error.code??"";if(code==="EEXIST")return!1;throw HARD_LINK_UNSUPPORTED.has(code)?new AtomicLinkUnsupportedError(code,error):error}}finally{await rm(staging,{recursive:!0,force:!0}).catch(()=>{})}}export{AtomicLinkUnsupportedError,createFileAtomic};
2
2
  //# sourceMappingURL=atomic-create.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]="30379998-be47-5176-bfd4-a02bca99bd16")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
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]="427dd932-a013-557c-b3d8-5d7bb042e88c")}catch{}})();import{readdir,realpath,stat}from"node:fs/promises";import path from"node:path";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const MAX_PATTERN_LENGTH=4096,MAX_NESTING=32,MAX_RANGE_SIZE=1e3,MAX_STATES=5e4,DFA_LIMITS={nodes:1e4,edges:4e4,stateIds:2e6},SLASH=47;class GlobTooComplex extends Error{}const POSIX_CLASSES=new Map(Object.entries({alnum:[[48,57],[65,90],[97,122]],alpha:[[65,90],[97,122]],ascii:[[0,127]],blank:[[9,9],[32,32]],cntrl:[[0,31],[127,127]],digit:[[48,57]],graph:[[33,126]],lower:[[97,122]],print:[[32,126]],punct:[[33,47],[58,64],[91,96],[123,126]],space:[[9,13],[32,32]],upper:[[65,90]],word:[[48,57],[65,90],[95,95],[97,122]],xdigit:[[48,57],[65,70],[97,102]]}));function negationRefusal(){return new PmCliError("--add-glob does not support negated patterns (a leading ! or !(...)); list the files or patterns to link instead",EXIT_CODE.USAGE)}function bracketEnd(chars,start){let index=start+1;for((chars[index]==="!"||chars[index]==="^")&&(index+=1),chars[index]==="]"&&(index+=1);index<chars.length;){const char=chars[index];if(char==="\\")index+=2;else if(char==="["&&chars[index+1]===":"){const close=chars.indexOf(":",index+2);close===-1||chars[close+1]!=="]"?index+=1:index=close+2}else{if(char==="]")return index+1;index+=1}}return-1}function openerAt(chars,index,open){const char=chars[index];if(char==="{")return{index,kind:"{"};if(char!=="(")return;const operator=chars[index-1];return operator!==void 0&&"@?*+!".includes(operator)&&!isEscaped(chars,index-1)?{index:index-1,kind:"("}:open.some(opener=>opener.kind==="(")?{index,kind:"plain"}:void 0}function closeAt(chars,index,open,closers,groups){const char=chars[index],top=open.at(-1);if(char===")"&&top?.kind==="plain"){open.pop(),groups.set(top.index,index);return}const kind=char==="}"?"{":char===")"?"(":void 0;if(!(kind===void 0||top?.kind!==kind)&&(open.pop(),closers.set(top.index,index),chars[top.index]==="!"))throw negationRefusal()}function pairConstructs(chars){const closers=new Map,brackets=new Map,groups=new Map,open=[];let index=0;for(;index<chars.length;){if(chars[index]==="\\"){index+=2;continue}const end=chars[index]==="["?bracketEnd(chars,index):-1;if(end!==-1){brackets.set(index,end),index=end;continue}const opener=openerAt(chars,index,open);if(opener!==void 0?open.push(opener):closeAt(chars,index,open,closers,groups),open.length>MAX_NESTING)throw new GlobTooComplex;index+=1}return{closers,brackets,groups}}function isEscaped(chars,index){let count=0;for(let cursor=index-1;cursor>=0&&chars[cursor]==="\\";cursor-=1)count+=1;return count%2===1}function literalNodes(text){return Array.from(text,char=>({kind:"char",value:char.codePointAt(0)}))}function braceRange(content){const numeric=/^(-?(?:0|[1-9]\d{0,8}))\.\.(-?(?:0|[1-9]\d{0,8}))$/u.exec(content),alphabetic=/^([A-Za-z])\.\.([A-Za-z])$/u.exec(content);if(numeric===null&&alphabetic===null)return;const[from,to]=numeric!==null?[Number(numeric[1]),Number(numeric[2])]:[alphabetic[1].codePointAt(0),alphabetic[2].codePointAt(0)];if(Math.abs(to-from)+1>MAX_RANGE_SIZE)throw new GlobTooComplex;const step=from<=to?1:-1,values=[];for(let value=from;value!==to+step;value+=step)values.push(numeric!==null?String(value):String.fromCodePoint(value));return values}function posixClassAt(chars,index){if(chars[index]!=="["||chars[index+1]!==":")return;const colon=chars.indexOf(":",index+2);if(!(colon===-1||chars[colon+1]!=="]"))return{ranges:POSIX_CLASSES.get(chars.slice(index+2,colon).join(""))??[],next:colon+2}}function memberAt(chars,index,close){const escaped=chars[index]==="\\"&&index+1<close;return{codePoint:chars[escaped?index+1:index].codePointAt(0),next:index+(escaped?2:1)}}function bracketLiteral(chars,start,end){const literal=[];for(let cursor=start;cursor<end;cursor+=1)chars[cursor]==="\\"&&cursor+1<end&&(cursor+=1),literal.push(chars[cursor].codePointAt(0));return literal}function parseClass(chars,start,end){let index=start+1;const negated=chars[index]==="!"||chars[index]==="^";negated&&(index+=1);const ranges=[],close=end-1;for(;index<close;){const posix=posixClassAt(chars,index);if(posix!==void 0){ranges.push(...posix.ranges),index=posix.next;continue}const low=memberAt(chars,index,close);if(index=low.next,chars[index]!=="-"||index+1>=close){ranges.push([low.codePoint,low.codePoint]);continue}const high=memberAt(chars,index+1,close);index=high.next,low.codePoint<=high.codePoint&&ranges.push([low.codePoint,high.codePoint])}return{kind:"class",negated,ranges,literal:bracketLiteral(chars,start,end)}}class Parser{chars;closers;brackets;groups;constructor(chars,pairs){this.chars=chars,this.closers=pairs.closers,this.brackets=pairs.brackets,this.groups=pairs.groups}alternatives(start,end,separator){const options=[];let cursor=start;for(;;){const{nodes,stop}=this.sequence(cursor,end,separator);if(options.push(nodes),stop>=end)return options;cursor=stop+1}}sequence(start,end,separator){const nodes=[];let index=start;for(;index<end;){if(this.chars[index]===separator)return{nodes,stop:index};const token=this.token(index,end);nodes.push(...token.nodes),index=token.next}return{nodes,stop:end}}token(index,end){const char=this.chars[index];if(char==="\\")return{nodes:literalNodes(index+1<end?this.chars[index+1]:"\\"),next:index+2};const closer=this.closers.get(index);if(closer!==void 0)return{nodes:char==="{"?this.brace(index,closer):this.extglob(char,index,closer),next:closer+1};const group=this.groups.get(index);if(group!==void 0)return{nodes:[...literalNodes("("),...this.sequence(index+1,group,void 0).nodes,...literalNodes(")")],next:group+1};const bracket=this.brackets.get(index);return bracket!==void 0?{nodes:[parseClass(this.chars,index,bracket)],next:bracket}:char==="*"?this.stars(index,end):{nodes:char==="?"?[{kind:"any"}]:literalNodes(char),next:index+1}}extglob(operator,index,closer){const options=this.alternatives(index+2,closer,"|");return[operator==="@"?{kind:"alt",options}:{kind:"repeat",optional:operator!=="+",many:operator!=="?",options}]}brace(index,closer){const options=this.alternatives(index+1,closer,",");if(options.length>1)return[{kind:"alt",options}];const range=braceRange(this.chars.slice(index+1,closer).join(""));return range!==void 0?[{kind:"alt",options:range.map(literalNodes)}]:[...literalNodes("{"),...options[0],...literalNodes("}")]}stars(index,end){let run=1;for(;this.chars[index+run]==="*"&&index+run<end&&!this.closers.has(index+run);)run+=1;if(run!==2)return{nodes:[{kind:"star"}],next:index+run};const slash=index+run<end&&this.chars[index+run]==="/";return{nodes:[{kind:"globstar",slash}],next:index+run+(slash?1:0)}}}const END_KINDS=["segment","inside"],ANY={kind:"any"};function entriesOf(ends){return END_KINDS.flatMap(kind=>ends[kind]===void 0?[]:[ends[kind]])}class Nfa{states=[];add(){if(this.states.length>=MAX_STATES)throw new GlobTooComplex;return this.states.push({epsilon:[],syntactic:[],edges:[]}),this.states.length-1}epsilon(from,to,syntactic=!0){this.states[from].epsilon.push(to),syntactic&&this.states[from].syntactic.push(to)}consume(from,test,kind){const to=this.add();for(const entry of entriesOf(from))this.states[entry].edges.push({test,to});return{[kind]:to}}join(parts){const joined={};for(const kind of END_KINDS){const states=parts.flatMap(part=>part[kind]===void 0?[]:[part[kind]]);if(states.length===1&&(joined[kind]=states[0]),states.length>1){const merged=this.add();for(const state of states)this.epsilon(state,merged);joined[kind]=merged}}return joined}feed(ends,loop){for(const kind of END_KINDS)ends[kind]!==void 0&&this.epsilon(ends[kind],loop[kind])}build(nodes,from){let current=from;for(const node of nodes)current=this.node(node,current);return current}alternation(options,from){return this.join(options.map(option=>this.build(option,from)))}star(from){const loop=this.add();for(const entry of entriesOf(from))this.epsilon(entry,loop,!1);return this.states[loop].edges.push({test:ANY,to:loop}),{inside:loop}}segments(from){const between=this.add();this.epsilon(from,between,!1);const inside=this.add();return this.states[between].edges.push({test:ANY,to:inside}),this.states[inside].edges.push({test:ANY,to:inside},{test:{kind:"char",value:SLASH},to:between}),between}globstar(from,slash){if(slash){const parts=[];return from.segment!==void 0&&parts.push({segment:this.segments(from.segment)}),from.inside!==void 0&&parts.push(this.consume(this.star({inside:from.inside}),{kind:"char",value:SLASH},"segment")),this.join(parts)}const star=this.star(from);return from.segment!==void 0&&this.globstars.push({continuation:star.inside,entry:from.segment}),star}globstars=[];syntacticClosure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.states[stack.pop()].syntactic)seen.has(next)||(seen.add(next),stack.push(next));return seen}resolveGlobstars(accept){for(const{continuation,entry}of this.globstars){const reachable=this.syntacticClosure([continuation]);if(reachable.has(accept)){const rest=this.add();this.epsilon(entry,rest,!1),this.states[rest].edges.push({test:{kind:"all"},to:rest}),this.epsilon(rest,accept,!1)}const targets=new Set;for(const state of reachable)for(const{test,to}of this.states[state].edges)accepts(test,SLASH)&&targets.add(to);if(targets.size===0)continue;const segments=this.segments(entry);for(const target of targets)this.epsilon(segments,target,!1)}}repeat(node,from){if(!node.many)return this.join([from,this.alternation(node.options,from)]);const loop={segment:this.add(),inside:this.add()};return this.feed(node.optional?from:this.alternation(node.options,from),loop),this.feed(this.alternation(node.options,loop),loop),loop}node(node,from){switch(node.kind){case"char":return this.consume(from,{kind:"char",value:node.value},node.value===SLASH?"segment":"inside");case"any":return this.consume(from,ANY,"inside");case"star":return this.star(from);case"globstar":return this.globstar(from,node.slash);case"class":return this.join([this.consume(from,{kind:"class",negated:node.negated,ranges:node.ranges},"inside"),this.build(node.literal.map(value=>({kind:"char",value})),from)]);case"alt":return this.alternation(node.options,from);case"repeat":return this.repeat(node,from)}}}function accepts(test,codePoint){switch(test.kind){case"char":return test.value===codePoint;case"any":return codePoint!==SLASH;case"all":return!0;case"class":return codePoint!==SLASH&&test.ranges.some(([low,high])=>codePoint>=low&&codePoint<=high)!==test.negated}}class PathMatcher{generation=0;nextId=0;nodes=new Map;edges=new Map;stateIds=0;nfa;acceptState;limits;start;constructor(nfa,startState,acceptState,limits){this.nfa=nfa,this.acceptState=acceptState,this.limits=limits,this.start=this.node(this.closure([startState]))}retained(){return{nodes:this.nodes.size,edges:this.edges.size,stateIds:this.stateIds}}reset(){this.generation+=1,this.nodes=new Map,this.edges=new Map,this.stateIds=0}closure(seed){const seen=new Set(seed),stack=[...seed];for(;stack.length>0;)for(const next of this.nfa.states[stack.pop()].epsilon)seen.has(next)||(seen.add(next),stack.push(next));return[...seen].sort((left,right)=>left-right)}node(states){const key=states.join(","),cached=this.nodes.get(key);if(cached!==void 0)return cached;(this.nodes.size>=this.limits.nodes||this.stateIds+states.length>this.limits.stateIds)&&this.reset();const created={id:this.nextId,generation:this.generation,states,accepting:states.includes(this.acceptState)};return this.nextId+=1,this.nodes.set(key,created),this.stateIds+=states.length,created}step(from,codePoint){const key=`${from.id}:${codePoint}`,known=from.generation===this.generation?this.edges.get(key):void 0;if(known!==void 0)return known;const reached=[];for(const state of from.states)for(const{test,to}of this.nfa.states[state].edges)accepts(test,codePoint)&&reached.push(to);const next=this.node(this.closure(reached));return this.edges.size>=this.limits.edges&&this.reset(),from.generation===this.generation&&this.edges.set(key,next),next}advance(from,text){let node=from;for(const char of text){if(node.states.length===0)return node;node=this.step(node,char.codePointAt(0))}return node}}function compile(text,limits=DFA_LIMITS){const chars=Array.from(text),nodes=new Parser(chars,pairConstructs(chars)).sequence(0,chars.length,void 0).nodes,nfa=new Nfa,start=nfa.add(),accept=nfa.add();for(const end of entriesOf(nfa.build(nodes,{segment:start})))nfa.epsilon(end,accept);return nfa.resolveGlobstars(accept),new PathMatcher(nfa,start,accept,limits)}function isStaticSegment(segment){return!/[*?[\]{}()!@+\\]/u.test(segment)}function kindOf(entry){return entry.isFile()?"file":entry.isDirectory()?"directory":"other"}async function resolveEntry(directory,real,entry){if(!entry.isSymbolicLink())return{kind:kindOf(entry),real:path.join(real,entry.name)};try{const target=await realpath(path.join(directory,entry.name));return{kind:kindOf(await stat(target)),real:target}}catch{return}}async function walk(matcher,directory,real,prefix,node,ancestors,out){let entries;try{entries=await readdir(directory,{withFileTypes:!0})}catch{return}for(const entry of entries){const afterName=matcher.advance(node,entry.name);if(afterName.states.length===0)continue;const resolved=await resolveEntry(directory,real,entry);if(resolved===void 0)continue;const relative=path.posix.join(prefix,entry.name);if(resolved.kind==="file"&&afterName.accepting&&out.push(relative),resolved.kind!=="directory")continue;const afterSlash=matcher.step(afterName,SLASH);afterSlash.states.length===0||ancestors.has(resolved.real)||(ancestors.add(resolved.real),await walk(matcher,path.join(directory,entry.name),resolved.real,relative,afterSlash,ancestors,out),ancestors.delete(resolved.real))}}function normalizePattern(pattern){const normalized=path.posix.normalize(pattern);return/^\/\/[^/]/u.test(pattern)?`/${normalized}`:normalized}function trimTrailingSeparators(pattern){let text=pattern;for(;text.length>1&&text.endsWith("/")&&!isEscaped(text,text.length-1);)text=text.slice(0,-1);return text}async function listed(directory,name){return(await readdir(directory).catch(()=>[])).includes(name)}async function exactCase(cwd,segments){let directory=cwd,index=0;for(;segments[index]==="..";)directory=path.dirname(directory),index+=1;for(;index<segments.length;index+=1){if(!await listed(directory,segments[index]))return!1;directory=path.join(directory,segments[index])}return!0}function isAbsolutePattern(text,platform=process.platform){return text.startsWith("/")||platform==="win32"&&/^[A-Za-z]:\//u.test(text)}async function literalMatch(text,cwd){const target=path.resolve(cwd,text),found=await stat(target).catch(()=>{});if(found===void 0||!found.isFile())return[];const absolute=isAbsolutePattern(text);return(absolute?await listed(path.dirname(target),path.basename(target)):await exactCase(cwd,text.split("/")))?[absolute?target.replaceAll("\\","/"):path.posix.normalize(text)]:[]}function splitStatic(text,cwd){const segments=text.split("/");let count=0;for(;count<segments.length&&isStaticSegment(segments[count]);)count+=1;if(count===segments.length)return;const prefix=count===0?"":`${segments.slice(0,count).join("/")}/`,root=path.resolve(cwd,prefix),rest=segments.slice(count).join("/");if(isAbsolutePattern(text))return{root,base:root.replaceAll("\\","/"),rest,prefix:[]};const relative=path.posix.normalize(prefix===""?".":prefix).replace(/\/$/u,"");return{root,base:relative==="."?"":relative,rest,prefix:segments.slice(0,count)}}function compileWithinBounds(text){try{return compile(text)}catch(error){if(error instanceof GlobTooComplex)return;throw error}}async function expandFileGlob(pattern,cwd){if(pattern.startsWith("!"))throw negationRefusal();if(Array.from(pattern).length>MAX_PATTERN_LENGTH)return[];const text=trimTrailingSeparators(normalizePattern(pattern)),parts=splitStatic(text,cwd);if(parts===void 0)return literalMatch(text,cwd);const matcher=compileWithinBounds(parts.rest);if(matcher===void 0||!await exactCase(cwd,parts.prefix))return[];const real=await realpath(parts.root).catch(()=>{});if(real===void 0)return[];const out=[];return await walk(matcher,parts.root,real,"",matcher.start,new Set([real]),out),out.map(relative=>joinOutput(parts.base,relative))}function joinOutput(base,relative){return base.startsWith("//")?`/${path.posix.join(base.slice(1),relative)}`:path.posix.join(base,relative)}const _testOnly={compile,isAbsolutePattern,joinOutput,normalizePattern};export{_testOnly,expandFileGlob};
2
2
  //# sourceMappingURL=file-glob.js.map
@@ -0,0 +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]="01a75358-2a0c-531d-bf79-ff353e1990c9")}catch{}})();import{historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";const HISTORY_BRIDGE_VERSION=1;function isHistoryBridgeBreak(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;return Object.keys(candidate).length===3&&typeof candidate.gap_from=="string"&&typeof candidate.gap_to=="string"&&candidate.gap_from!==candidate.gap_to&&(candidate.record_hash===null||typeof candidate.record_hash=="string")}function readHistoryBridge(entry){if(!Object.hasOwn(entry,"bridge"))return;const bridge=entry.bridge;if(entry.op!=="history_repair"||typeof entry.record_hash!="string"||typeof bridge!="object"||bridge===null||Array.isArray(bridge))return"invalid";const candidate=bridge;return candidate.version===HISTORY_BRIDGE_VERSION&&Object.keys(candidate).length===3&&typeof candidate.segment_digest=="string"&&Array.isArray(candidate.breaks)&&candidate.breaks.length>0&&[...candidate.breaks].every(isHistoryBridgeBreak)?candidate:"invalid"}function describeHistoryBreak(previous,entry){return{gap_from:previous.after_hash,gap_to:entry.before_hash,record_hash:entry.record_hash??null}}function matchesHistoryBreak(descriptor,previous,entry){return descriptor!==void 0&&descriptor.gap_from===previous.after_hash&&descriptor.gap_to===entry.before_hash&&descriptor.record_hash===(entry.record_hash??null)}function digestBridgedSegment(segment,bridge){return historyDigest(canonicalBridgeJson(segment),resolveHistoryHashAlgorithm(bridge.hash_algorithm))}const ARRAY_INDEX_KEY=/^(?:0|[1-9]\d*)$/u,isArrayIndexKey=key=>ARRAY_INDEX_KEY.test(key)&&Number(key)<2**32-1;function canonicalBridgeJson(value){if(Array.isArray(value))return`[${value.map(item=>canonicalBridgeJson(item??null)).join(",")}]`;if(value===null||typeof value!="object")return JSON.stringify(value);const record=value,keys=Object.keys(record).filter(key=>record[key]!==void 0);return`{${[...keys.filter(isArrayIndexKey),...keys.filter(key=>!isArrayIndexKey(key)).sort()].map(key=>`${JSON.stringify(key)}:${canonicalBridgeJson(record[key])}`).join(",")}}`}function findNextHistoryBridge(entries,index){for(let candidate=index+1;candidate<entries.length;candidate+=1)if(Object.hasOwn(entries[candidate],"bridge"))return candidate;return-1}function safeSegmentDigest(segment,bridge){try{return digestBridgedSegment(segment,bridge)}catch{return null}}function findBridgedSegmentStart(entries,bridge,floor,end){const first=bridge.breaks[0];let materialized=-1;for(let start=Math.max(1,floor);start<end;start+=1){const entry=entries[start],anchored=entries[start-1].after_hash===first.gap_from&&entry.before_hash===first.gap_to,named=first.record_hash!==null&&entry.record_hash===first.record_hash;if(!anchored&&!named)continue;const covered=entries.slice(start,end);if(safeSegmentDigest(covered,entries[end])===bridge.segment_digest)return{start,digest:!0};materialized<0&&anchored&&covered.every(record=>record.replay_inexact===!0)&&(materialized=start)}return{start:materialized,digest:!1}}function locateBridgedSegments(entries){const located={segments:[],unlocated:[],undigested:[]};let floor=1;return entries.forEach((entry,index)=>{if(!Object.hasOwn(entry,"bridge"))return;const bridge=readHistoryBridge(entry),found=typeof bridge=="object"?findBridgedSegmentStart(entries,bridge,floor,index):{start:-1,digest:!1},start=found.start;start<0?located.unlocated.push(index):found.digest||located.undigested.push(index),located.segments.push({start:start<0?floor:start,end:index,exact:start>=0}),start>=0&&(floor=index+1)}),located}export{HISTORY_BRIDGE_VERSION,describeHistoryBreak,digestBridgedSegment,findNextHistoryBridge,locateBridgedSegments,matchesHistoryBreak,readHistoryBridge};
2
+ //# sourceMappingURL=bridge.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]="97537e2a-b8cb-559e-82bc-3c98b0c51db1")}catch{}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]),DRIFT_CACHE_VERSION=11,DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8"),parsed=JSON.parse(raw);return parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!="boolean"||typeof entry.latest_hash_comparable!="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==!0||entry.chain_ok&&entry.version_skew!==!0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)?null:parsed}catch{return null}}function createDriftScanAccumulator(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function buildDriftScanResult(accumulator){const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){return isFileMissingError(error)||accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID),!1}const missingCount=accumulator.missingStreams.length,resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});return resolved.verification?(resolved.verification.versionSkew&&accumulator.versionSkews.push(WORKSPACE_HISTORY_ID),resolved.verification.chainOk||accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID),nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm},resolved.cacheDirty):(accumulator.missingStreams.splice(missingCount),resolved.cacheDirty)}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8"),contentHash=createHash("sha256").update(raw).digest("hex");if(raw.trim().length===0)return null;const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0)continue;const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!="string"||parsed.after_hash.trim().length===0)throw new Error("missing after_hash");entries.push(parsed),latestAfterHash=parsed.after_hash}if(!latestAfterHash)return null;const verification=verifyHistoryChainWithVersion(entries),versionSkew=entries.some(hasUnsupportedHistoryCapability),latestEntry=entries[entries.length-1],algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm),latestExplicitVersion=latestEntry.item_hash_version,latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion),latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{return await verifyHistoryStream(historyPath)||(accumulator.missingStreams.push(itemId),null)}catch{return accumulator.unreadableStreams.push(itemId),null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===!0)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash=="string"&&params.cached.content_hash.length>0?params.cached.content_hash:void 0;if(!(cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0)||!params.cached||!params.cached.chain_ok)return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:!0};if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===!0,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:!1}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath,stat;try{historyPath=getHistoryPath(pmRoot,item.id),stat=await fs.stat(historyPath)}catch(error){return(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id),!1}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;resolved.verification.identityDiscontinuities.length>0&&(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id}))),resolved.verification.versionSkew&&accumulator.versionSkews.push(item.id),resolved.verification.chainOk||accumulator.chainMismatches.push(item.id),cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;return resolved.verification.latestHashComparable&&(hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm).includes(resolved.verification.latestAfterHash)||accumulator.hashMismatches.push(item.id)),resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(!(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID)))try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents),accumulator.workspaceStateMissing.push(...agreement.missing_documents),accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanItemHistoryDrift(pmRoot,item){const accumulator=createDriftScanAccumulator();return await scanItemHistory(pmRoot,item,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},accumulator),buildDriftScanResult(accumulator)}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator=createDriftScanAccumulator(),previousEntries=(await loadDriftCache(pmRoot))?.entries??{},nextEntries={};let cacheDirty=!1;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata",cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items)await scanItemHistory(pmRoot,item,cacheState,accumulator)&&(cacheDirty=!0);const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);if(cacheDirty||=workspaceCacheDirty,await scanWorkspaceStateAgreement(pmRoot,accumulator),cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}return buildDriftScanResult(accumulator)}export{scanHistoryDrift,scanItemHistoryDrift};
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]="a535e1be-f99b-5898-af76-0c9d5b8a681d")}catch{}})();import{HISTORY_HASH_ALGORITHMS,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import{createHash}from"node:crypto";import path from"node:path";import{getHistoryPath}from"../store/paths.js";import{isFileMissingError,writeFileAtomic}from"../fs/fs-utils.js";import{CURRENT_HISTORY_ITEM_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,hasNewerRecordSealFormat,hashDocumentVerificationCandidates}from"./history.js";import{verifyHistoryChainWithVersion}from"./replay.js";import{findHistoryIdentityDiscontinuities}from"./identity.js";import{getWorkspaceHistoryPath,inspectWorkspaceHistoryState,WORKSPACE_HISTORY_ID}from"./workspace-history.js";const READABLE_HISTORY_HASH_ALGORITHMS=new Set([void 0,...HISTORY_HASH_ALGORITHMS]),DRIFT_CACHE_VERSION=13,DRIFT_CACHE_FILENAME="history-drift-cache.json";function getDriftCachePath(pmRoot){return path.join(pmRoot,"runtime",DRIFT_CACHE_FILENAME)}async function loadDriftCache(pmRoot){try{const raw=await fs.readFile(getDriftCachePath(pmRoot),"utf8"),parsed=JSON.parse(raw);return parsed.version!==DRIFT_CACHE_VERSION||parsed.history_item_hash_version!==CURRENT_HISTORY_ITEM_HASH_VERSION||typeof parsed.entries!="object"||parsed.entries===null||Object.values(parsed.entries).some(entry=>typeof entry.chain_ok!="boolean"||typeof entry.latest_hash_comparable!="boolean"||!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&entry.version_skew!==!0||entry.chain_ok&&entry.version_skew!==!0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)&&!entry.latest_hash_comparable)?null:parsed}catch{return null}}function createDriftScanAccumulator(){return{missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]}}function buildDriftScanResult(accumulator){const driftedItems=[...new Set([...accumulator.missingStreams,...accumulator.unreadableStreams,...accumulator.hashMismatches,...accumulator.chainMismatches,...accumulator.versionSkews,...accumulator.workspaceStateMismatches.length>0||accumulator.workspaceStateMissing.length>0||accumulator.workspaceStateUnreadable.length>0?[WORKSPACE_HISTORY_ID]:[]])].sort((a,b)=>a.localeCompare(b));return{...accumulator,driftedItems}}async function scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator){const historyPath=getWorkspaceHistoryPath(pmRoot);let stat;try{stat=await fs.stat(historyPath)}catch(error){return isFileMissingError(error)||accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID),!1}const missingCount=accumulator.missingStreams.length,resolved=await resolveStreamVerification({itemId:WORKSPACE_HISTORY_ID,historyPath,stat,cached:previousEntries[WORKSPACE_HISTORY_ID],verifyCacheHitByContent,accumulator});return resolved.verification?(resolved.verification.versionSkew&&accumulator.versionSkews.push(WORKSPACE_HISTORY_ID),resolved.verification.chainOk||accumulator.chainMismatches.push(WORKSPACE_HISTORY_ID),nextEntries[WORKSPACE_HISTORY_ID]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm},resolved.cacheDirty):(accumulator.missingStreams.splice(missingCount),resolved.cacheDirty)}function hasUnsupportedHistoryCapability(entry){return!READABLE_HISTORY_HASH_ALGORITHMS.has(entry.hash_algorithm)||entry.item_hash_version!==void 0&&!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version)||hasNewerRecordSealFormat(entry)}async function verifyHistoryStream(historyPath){const raw=await fs.readFile(historyPath,"utf8"),contentHash=createHash("sha256").update(raw).digest("hex");if(raw.trim().length===0)return null;const entries=[];let latestAfterHash=null;for(const line of raw.split(/\r?\n/)){const trimmed=line.trim();if(trimmed.length===0)continue;const parsed=JSON.parse(trimmed);if(typeof parsed.after_hash!="string"||parsed.after_hash.trim().length===0)throw new Error("missing after_hash");entries.push(parsed),latestAfterHash=parsed.after_hash}if(!latestAfterHash)return null;const verification=verifyHistoryChainWithVersion(entries),versionSkew=entries.some(hasUnsupportedHistoryCapability),latestEntry=entries[entries.length-1],algorithmSupported=READABLE_HISTORY_HASH_ALGORITHMS.has(latestEntry.hash_algorithm),latestExplicitVersion=latestEntry.item_hash_version,latestExplicitVersionSupported=latestExplicitVersion!==void 0&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(latestExplicitVersion),latestHashVersion=latestExplicitVersionSupported?latestExplicitVersion:verification.item_hash_version;return{latestAfterHash,hashAlgorithm:algorithmSupported?resolveHistoryHashAlgorithm(latestEntry.hash_algorithm):void 0,identityDiscontinuities:findHistoryIdentityDiscontinuities(entries),chainOk:verification.ok,versionSkew,latestHashComparable:algorithmSupported&&latestHashVersion!==void 0&&(!versionSkew||latestExplicitVersionSupported||latestExplicitVersion===void 0),contentHash,itemHashVersion:latestHashVersion??CURRENT_HISTORY_ITEM_HASH_VERSION}}function cacheMetadataMatches(cached,stat){return cached!==void 0&&cached.mtime_ms===stat.mtimeMs&&cached.ctime_ms===stat.ctimeMs&&cached.size===stat.size}async function loadFreshStreamVerification(itemId,historyPath,accumulator){try{return await verifyHistoryStream(historyPath)||(accumulator.missingStreams.push(itemId),null)}catch{return accumulator.unreadableStreams.push(itemId),null}}function matchesCachedVerification(verification,cached){return verification!==null&&verification.contentHash===cached.content_hash&&verification.latestAfterHash===cached.latest_after_hash&&verification.chainOk===cached.chain_ok&&verification.versionSkew===(cached.version_skew===!0)&&verification.latestHashComparable===cached.latest_hash_comparable&&verification.itemHashVersion===cached.item_hash_version&&verification.hashAlgorithm===cached.hash_algorithm}async function resolveStreamVerification(params){const cachedContentHash=typeof params.cached?.content_hash=="string"&&params.cached.content_hash.length>0?params.cached.content_hash:void 0;if(!(cacheMetadataMatches(params.cached,params.stat)&&cachedContentHash!==void 0)||!params.cached||!params.cached.chain_ok)return{verification:await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator),cacheDirty:!0};if(params.verifyCacheHitByContent){const verification=await loadFreshStreamVerification(params.itemId,params.historyPath,params.accumulator);return{verification,cacheDirty:!matchesCachedVerification(verification,params.cached)}}return{verification:{identityDiscontinuities:[],latestAfterHash:params.cached.latest_after_hash,chainOk:params.cached.chain_ok,versionSkew:params.cached.version_skew===!0,latestHashComparable:params.cached.latest_hash_comparable&&SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(params.cached.item_hash_version),contentHash:cachedContentHash,itemHashVersion:params.cached.item_hash_version,hashAlgorithm:params.cached.hash_algorithm},cacheDirty:!1}}async function scanItemHistory(pmRoot,item,cache,accumulator){let historyPath,stat;try{historyPath=getHistoryPath(pmRoot,item.id),stat=await fs.stat(historyPath)}catch(error){return(isFileMissingError(error)?accumulator.missingStreams:accumulator.unreadableStreams).push(item.id),!1}const resolved=await resolveStreamVerification({itemId:item.id,historyPath,stat,cached:cache.previousEntries[item.id],verifyCacheHitByContent:cache.verifyCacheHitByContent,accumulator});if(!resolved.verification)return resolved.cacheDirty;resolved.verification.identityDiscontinuities.length>0&&(accumulator.identityDiscontinuities??=[]).push(...resolved.verification.identityDiscontinuities.map(finding=>({...finding,item_id:item.id}))),resolved.verification.versionSkew&&accumulator.versionSkews.push(item.id),resolved.verification.chainOk||accumulator.chainMismatches.push(item.id),cache.nextEntries[item.id]={mtime_ms:stat.mtimeMs,ctime_ms:stat.ctimeMs,size:stat.size,content_hash:resolved.verification.contentHash,latest_after_hash:resolved.verification.latestAfterHash,chain_ok:resolved.verification.chainOk,version_skew:resolved.verification.versionSkew,latest_hash_comparable:resolved.verification.latestHashComparable,item_hash_version:resolved.verification.itemHashVersion,hash_algorithm:resolved.verification.hashAlgorithm};const{body,...itemMetadata}=item;return resolved.verification.latestHashComparable&&(hashDocumentVerificationCandidates({metadata:itemMetadata,body},resolved.verification.itemHashVersion,resolved.verification.hashAlgorithm).includes(resolved.verification.latestAfterHash)||accumulator.hashMismatches.push(item.id)),resolved.cacheDirty}async function scanWorkspaceStateAgreement(pmRoot,accumulator){if(!(accumulator.unreadableStreams.includes(WORKSPACE_HISTORY_ID)||accumulator.chainMismatches.includes(WORKSPACE_HISTORY_ID)||accumulator.versionSkews.includes(WORKSPACE_HISTORY_ID)))try{const agreement=await inspectWorkspaceHistoryState(pmRoot);accumulator.workspaceStateMismatches.push(...agreement.mismatched_documents),accumulator.workspaceStateMissing.push(...agreement.missing_documents),accumulator.workspaceStateUnreadable.push(...agreement.unreadable_documents)}catch{accumulator.unreadableStreams.push(WORKSPACE_HISTORY_ID)}}async function scanItemHistoryDrift(pmRoot,item){const accumulator=createDriftScanAccumulator();return await scanItemHistory(pmRoot,item,{previousEntries:{},nextEntries:{},verifyCacheHitByContent:!0},accumulator),buildDriftScanResult(accumulator)}async function scanHistoryDrift(pmRoot,items,options={}){const accumulator=createDriftScanAccumulator(),previousEntries=(await loadDriftCache(pmRoot))?.entries??{},nextEntries={};let cacheDirty=!1;const verifyCacheHitByContent=options.cacheHitVerification!=="metadata",cacheState={previousEntries,nextEntries,verifyCacheHitByContent};for(const item of items)await scanItemHistory(pmRoot,item,cacheState,accumulator)&&(cacheDirty=!0);const workspaceCacheDirty=await scanWorkspaceHistory(pmRoot,previousEntries,nextEntries,verifyCacheHitByContent,accumulator);if(cacheDirty||=workspaceCacheDirty,await scanWorkspaceStateAgreement(pmRoot,accumulator),cacheDirty||Object.keys(previousEntries).length!==Object.keys(nextEntries).length){const cachePath=getDriftCachePath(pmRoot);try{await fs.mkdir(path.dirname(cachePath),{recursive:!0}),await writeFileAtomic(cachePath,JSON.stringify({version:DRIFT_CACHE_VERSION,history_item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,entries:nextEntries}))}catch{}}return buildDriftScanResult(accumulator)}export{scanHistoryDrift,scanItemHistoryDrift};
2
2
  //# sourceMappingURL=drift-scan.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]="19c6ac90-0c95-5f1b-99fa-631c64b6302f")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,hasActiveItemRevisionScope}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument)return[];const stored=params.itemDocument.metadata?.assignee?.trim();if(!stored||stored===params.author||params.force)return[];const assigned=redactOptionalIdentityCredentials(stored),governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function assertDeclaredRevisionOnDrift(params){if(!hasActiveItemRevisionScope(params.pmRoot))return;const located=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),document=located===null?EMPTY_CANONICAL_DOCUMENT:(await readLocatedItem(located,{schema:params.settings.schema}).catch(()=>null))?.document;document!==void 0&&assertItemMutationPreconditions(params.pmRoot,document,params.subject.id)}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation}),tombstone=EMPTY_CANONICAL_DOCUMENT;if(assertItemMutationPreconditions(params.pmRoot,verified.loadedItemUnderLock?.document??tombstone,params.subject.id),await params.applyRewrite(verified),hasActiveItemRevisionScope(params.pmRoot)){const relocated=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),rewritten=relocated===null?tombstone:(await readLocatedItem(relocated,{schema:params.settings.schema})).document;advanceItemMutationPreconditions(params.pmRoot,rewritten,params.subject.id)}return params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be6f35e2-0762-5188-b373-bdc7d7302d1c")}catch{}})();import fs from"node:fs/promises";import{readFileIfExists,writeFileAtomic}from"../fs/fs-utils.js";import{acquireLock}from"../lock/lock.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{locateItem,readLocatedItem}from"../store/item-store.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,hasActiveItemRevisionScope}from"../store/item-mutation-precondition.js";import{resolveGovernanceKnobs}from"../store/settings.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{redactOptionalIdentityCredentials}from"../shared/url-credentials.js";function checkHistoryRewriteOwnership(params){if(!params.itemDocument||params.force)return[];const stored=params.itemDocument.metadata?.assignee?.trim();if(!stored||stored===params.author)return[];const assigned=redactOptionalIdentityCredentials(stored),governance=resolveGovernanceKnobs(params.settings);if(governance.ownership_enforcement==="strict")throw new PmCliError(`Item ${params.subjectId} is assigned to ${assigned}. Use --force to override.`,EXIT_CODE.CONFLICT);return governance.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${params.subjectId}:${assigned}`]:[]}async function assertDeclaredRevisionOnDrift(params){if(!hasActiveItemRevisionScope(params.pmRoot))return;const located=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),document=located===null?EMPTY_CANONICAL_DOCUMENT:(await readLocatedItem(located,{schema:params.settings.schema}).catch(()=>null))?.document;document!==void 0&&assertItemMutationPreconditions(params.pmRoot,document,params.subject.id)}async function verifyHistoryRewriteNoDrift(params){const historyRawUnderLock=await readFileIfExists(params.subject.historyPath);if(historyRawUnderLock!==params.historyRawBeforeLock)throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`History for ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);const locatedUnderLock=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),loadedItemUnderLock=locatedUnderLock?params.readItem?await params.readItem(locatedUnderLock):await readLocatedItem(locatedUnderLock,{schema:params.settings.schema}):null;if((loadedItemUnderLock?.raw??null)!==(params.currentItemRawBeforeLock??null))throw await assertDeclaredRevisionOnDrift(params),new PmCliError(`Item ${params.subject.id} changed while waiting for lock; retry ${params.operation}.`,EXIT_CODE.CONFLICT);return{historyRawUnderLock,locatedUnderLock,loadedItemUnderLock}}async function writeHistoryRawWithRollback(params){const writeHistoryRaw=params.writeHistoryRaw??writeFileAtomic;try{await writeHistoryRaw(params.historyPath,params.nextHistoryRaw),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(error){try{params.historyRawUnderLock===null?await fs.rm(params.historyPath,{force:!0}):await writeHistoryRaw(params.historyPath,params.historyRawUnderLock),await invalidateHistoryDriftCacheForPath(params.historyPath)}catch(rollbackError){throw new AggregateError([error,rollbackError],`History rewrite failed and rollback also failed: ${String(error)}`)}throw error}}async function executeHistoryRewrite(params){const warnings=[...checkHistoryRewriteOwnership({itemDocument:params.itemDocument,subjectId:params.subject.id,author:params.author,force:params.force,settings:params.settings})],releaseLock=await acquireLock(params.pmRoot,params.subject.id,params.settings.locks.ttl_seconds,params.author,!!params.force,params.settings.governance.force_required_for_stale_lock,params.settings.locks.wait_ms);try{const verified=await verifyHistoryRewriteNoDrift({pmRoot:params.pmRoot,subject:params.subject,settings:params.settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:params.historyRawBeforeLock,currentItemRawBeforeLock:params.currentItemRawBeforeLock,operation:params.operation}),tombstone=EMPTY_CANONICAL_DOCUMENT;if(assertItemMutationPreconditions(params.pmRoot,verified.loadedItemUnderLock?.document??tombstone,params.subject.id),await params.applyRewrite(verified),hasActiveItemRevisionScope(params.pmRoot)){const relocated=await locateItem(params.pmRoot,params.subject.id,params.settings.id_prefix,params.settings.item_format,params.typeRegistry.type_to_folder),rewritten=relocated===null?tombstone:(await readLocatedItem(relocated,{schema:params.settings.schema})).document;advanceItemMutationPreconditions(params.pmRoot,rewritten,params.subject.id)}return params.applyPostRewrite&&warnings.push(...await params.applyPostRewrite(verified)),warnings}finally{await releaseLock()}}export{checkHistoryRewriteOwnership,executeHistoryRewrite,verifyHistoryRewriteNoDrift,writeHistoryRawWithRollback};
2
2
  //# sourceMappingURL=history-rewrite.js.map
@@ -19,10 +19,22 @@ export declare function hashHistoryPatch(patch:readonly HistoryPatchOp[]):string
19
19
  export declare function hashHistoryStream(entries:readonly HistoryEntry[]):string;
20
20
  /** Attach the current immutable-record integrity envelope to one history event. */
21
21
  export declare function sealHistoryRecord(entry:HistoryEntry):HistoryEntry;
22
+ /**
23
+ * Whether a record carries a complete seal in a numeric record format newer
24
+ * than this runtime reads. A malformed or incomplete seal is damage, not a
25
+ * newer format, so it never qualifies (pm-3os5p6).
26
+ */
27
+ export declare function hasNewerRecordSealFormat(entry:HistoryEntry):boolean;
22
28
  /** Verify record-level attribution coverage while accepting explicit legacy item-state-only entries. */
23
29
  export declare function verifyHistoryRecordHash(entry:HistoryEntry):{ok:true;coverage:"record_and_item_state"|"item_state_only";}|{ok:false;error:"incomplete_record_hash_envelope"|"record_hash_mismatch"|"unsupported_record_hash_version"|"unsupported_history_hash_algorithm";};
24
30
  /** Reseal a maintenance rewrite and retain the anchors and patch digest it replaced. */
25
31
  export declare function resealHistoryRewrite(original:HistoryEntry,rewritten:HistoryEntry,options?:Readonly<{retainOriginalPatch?:boolean;retainPriorRecord?:boolean;retainPriorRecordHash?:boolean;}>):HistoryEntry;
32
+ /**
33
+ * Whether an entry carries every field replay and chain verification read:
34
+ * string ts, author, op and anchors, and a well-formed patch. Bridged segments
35
+ * check recorded links instead of replayed states, so they require this.
36
+ */
37
+ export declare function isCompleteHistoryRecord(entry:HistoryEntry):boolean;
26
38
  /** Verify that retained rewrite evidence reconstructs every available prior record envelope. */
27
39
  export declare function verifyHistoryRewriteEvidence(entry:HistoryEntry):{ok:true;coverage:"complete"|"digest_only"|"legacy_anchor_only"|"none";}|{ok:false;error:"rewrite_evidence_invalid"|"rewrite_evidence_patch_hash_mismatch"|"rewrite_evidence_record_hash_mismatch";};declare function decodeJsonPointer(path:string):string[];declare function isDefinedPointerPath(document:unknown,path:string):boolean;
28
40
  /** Implements hash document for the public runtime surface of this module. */
@@ -1,3 +1,3 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
2
- `,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d7f91395-3d21-5046-a8df-e383d66eace9")}catch{}})();import jsonPatch from"fast-json-patch";import{normalizeHistoryOperationForWrite}from"./operation-contract.js";import{CURRENT_HISTORY_HASH_ALGORITHM,historyDigest,resolveHistoryHashAlgorithm}from"./digest.js";import fs from"node:fs/promises";import path from"node:path";import{EXIT_CODE,ITEM_METADATA_KEY_ORDER}from"../shared/constants.js";import{runActiveServiceOverride}from"../extensions/index.js";import{appendLineAtomic}from"../fs/fs-utils.js";import{canonicalDocument}from"../item/item-format.js";import{toItemRecord}from"../item/item-record.js";import{orderObject,sha256Hex,stableStringify}from"../shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../shared/time.js";import{diagnoseAgentIdentity,resolveHistoryAgentIdentity,resolveHistoryAuthorSource}from"../shared/author.js";import{appendHistoryEntryWithEventIndex,removeHistoryEventIndexForHistoryPath}from"./event-index.js";import{classifyHistoryEvent}from"./event-classification.js";import{invalidateHistoryDriftCacheForPath}from"./drift-cache.js";import{PmCliError}from"../shared/errors.js";const EMPTY_LEGACY_HASH_DOCUMENT={front_matter:{},body:""},CURRENT_HISTORY_ITEM_HASH_VERSION=3,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS=[1,2,3],CURRENT_HISTORY_RECORD_HASH_VERSION=1,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS=[1];function hashHistoryRecord(entry){return historyDigest(stableStringify(entry),entry.hash_algorithm)}function hashHistoryPatch(patch){return sha256Hex(stableStringify(patch))}function hashHistoryStream(entries){return sha256Hex(stableStringify(entries))}function sealHistoryRecord(entry){const sealed={...entry,record_hash_version:CURRENT_HISTORY_RECORD_HASH_VERSION},{record_hash:_recordHash,...canonical}=sealed;return{...sealed,record_hash:hashHistoryRecord(canonical)}}function hasNewerRecordSealFormat(entry){const version=entry.record_hash_version;return typeof version=="number"&&Number.isInteger(version)&&version>Math.max(...SUPPORTED_HISTORY_RECORD_HASH_VERSIONS)&&typeof entry.record_hash=="string"&&entry.record_hash.length>0}function verifyHistoryRecordHash(entry){try{resolveHistoryHashAlgorithm(entry.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(entry.record_hash_version===void 0&&entry.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(entry.record_hash_version===void 0||entry.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!SUPPORTED_HISTORY_RECORD_HASH_VERSIONS.includes(entry.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};const{record_hash:_recordHash,...canonical}=entry;return hashHistoryRecord(canonical)===entry.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function createHistoryRewriteEvidence(original,options){const evidence={before_hash:original.before_hash,after_hash:original.after_hash,patch_hash:hashHistoryPatch(original.patch)};return original.hash_algorithm!==void 0&&(evidence.hash_algorithm=original.hash_algorithm),original.item_hash_version!==void 0&&(evidence.item_hash_version=original.item_hash_version),options.retainOriginalPatch&&(evidence.patch=structuredClone(original.patch)),options.retainPriorRecordHash!==!1&&original.record_hash_version!==void 0&&original.record_hash!==void 0&&(evidence.record_hash_version=original.record_hash_version,evidence.record_hash=original.record_hash,evidence.record=structuredClone(original)),evidence}function resealHistoryRewrite(original,rewritten,options={}){const originalRecordVerification=verifyHistoryRecordHash(original);if(!originalRecordVerification.ok)throw new TypeError(originalRecordVerification.error);const originalPatchHash=hashHistoryPatch(original.patch),retainsRewriteEvidence=options.retainPriorRecord===!0||original.before_hash!==rewritten.before_hash||original.after_hash!==rewritten.after_hash||original.item_hash_version!==rewritten.item_hash_version||original.hash_algorithm!==rewritten.hash_algorithm||originalPatchHash!==hashHistoryPatch(rewritten.patch),sealed=sealHistoryRecord({...rewritten,...retainsRewriteEvidence?{reanchor_evidence:[...rewritten.reanchor_evidence??[],createHistoryRewriteEvidence(original,options)]}:{}}),evidenceVerification=verifyHistoryRewriteEvidence(sealed);if(!evidenceVerification.ok)throw new TypeError(evidenceVerification.error);return sealed}function isHistoryPatch(value){return!Array.isArray(value)||Object.keys(value).length!==value.length?!1:value.every(operation=>!isRecord(operation)||typeof operation.path!="string"?!1:operation.op==="move"||operation.op==="copy"?typeof operation.from=="string":["add","replace","test"].includes(operation.op)?Object.hasOwn(operation,"value"):operation.op==="remove")}function isRetainedHistoryRecordShape(value){return isRecord(value)&&typeof value.ts=="string"&&typeof value.author=="string"&&typeof value.op=="string"&&typeof value.before_hash=="string"&&typeof value.after_hash=="string"&&isHistoryPatch(value.patch)}function isCompleteHistoryRecord(entry){return isRetainedHistoryRecordShape(entry)}function hasCompleteRetainedRecordHashEnvelope(evidence){const hasVersion=evidence.record_hash_version!==void 0,hasHash=evidence.record_hash!==void 0;return hasVersion===hasHash}function isHistoryReanchorEvidence(evidence){return!isRecord(evidence)||!hasCompleteRetainedRecordHashEnvelope(evidence)||typeof evidence.before_hash!="string"||typeof evidence.after_hash!="string"||typeof evidence.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(evidence.patch_hash)||evidence.patch!==void 0&&!isHistoryPatch(evidence.patch)||evidence.record_hash_version!==void 0&&typeof evidence.record_hash_version!="number"||evidence.record_hash!==void 0&&(typeof evidence.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(evidence.record_hash))?!1:evidence.record===void 0||isRetainedHistoryRecordShape(evidence.record)}function isHistoryRewriteEvidenceList(evidenceEntries){try{for(const evidence of evidenceEntries){if(!isHistoryReanchorEvidence(evidence))return!1;resolveHistoryHashAlgorithm(evidence.hash_algorithm)}return!0}catch{return!1}}function matchesRetainedHistoryRecord(evidence){const record=evidence.record;return record!==void 0&&record.before_hash===evidence.before_hash&&record.after_hash===evidence.after_hash&&record.item_hash_version===evidence.item_hash_version&&record.hash_algorithm===evidence.hash_algorithm&&record.record_hash_version===evidence.record_hash_version&&record.record_hash===evidence.record_hash&&hashHistoryPatch(record.patch)===evidence.patch_hash}function reconstructPriorHistoryRecord(current,evidence,priorEvidence){if(evidence.patch&&hashHistoryPatch(evidence.patch)!==evidence.patch_hash)return{kind:"patch_hash_mismatch"};if(evidence.record)return matchesRetainedHistoryRecord(evidence)?{kind:"record",entry:evidence.record}:{kind:"record_hash_mismatch"};const priorPatch=evidence.patch??current.patch;if(hashHistoryPatch(priorPatch)!==evidence.patch_hash)return{kind:"digest_only"};const priorRecord={...current,before_hash:evidence.before_hash,after_hash:evidence.after_hash,patch:priorPatch,hash_algorithm:evidence.hash_algorithm,...evidence.item_hash_version===void 0?{}:{item_hash_version:evidence.item_hash_version},...evidence.record_hash_version===void 0?{}:{record_hash_version:evidence.record_hash_version},...evidence.record_hash===void 0?{}:{record_hash:evidence.record_hash},...priorEvidence.length===0?{}:{reanchor_evidence:priorEvidence}};return evidence.hash_algorithm===void 0&&delete priorRecord.hash_algorithm,priorEvidence.length===0&&delete priorRecord.reanchor_evidence,evidence.item_hash_version===void 0&&delete priorRecord.item_hash_version,evidence.record_hash_version===void 0||evidence.record_hash===void 0?{kind:"legacy",entry:priorRecord}:{kind:"record",entry:priorRecord}}function verifyHistoryRewriteEvidence(entry){const evidenceEntries=entry.reanchor_evidence;if(evidenceEntries===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(evidenceEntries)||!isHistoryRewriteEvidenceList(evidenceEntries))return{ok:!1,error:"rewrite_evidence_invalid"};if(evidenceEntries.length===0)return{ok:!0,coverage:"none"};let reconstructed=entry;for(let index=evidenceEntries.length-1;index>=0;index-=1){const evidence=evidenceEntries[index],prior=reconstructPriorHistoryRecord(reconstructed,evidence,evidenceEntries.slice(0,index));if(prior.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(prior.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(prior.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(prior.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!verifyHistoryRecordHash(prior.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};reconstructed=prior.entry}return{ok:!0,coverage:"complete"}}function compareOptionalStrings(left,right){return(left??"").localeCompare(right??"")}function compareOptionalNumbers(left,right){return(left??0)-(right??0)}function compareJsonValues(left,right,fallback){return JSON.stringify(left??fallback).localeCompare(JSON.stringify(right??fallback))}function compareLegacyLinkedTests(left,right){return[left.scope.localeCompare(right.scope),compareOptionalStrings(left.path,right.path),compareOptionalStrings(left.command,right.command),compareOptionalNumbers(left.timeout_seconds,right.timeout_seconds),compareOptionalStrings(left.pm_context_mode,right.pm_context_mode),+!!left.shared_host_safe-+!!right.shared_host_safe,compareJsonValues(left.env_clear,right.env_clear,[]),compareJsonValues(left.env_set,right.env_set,{}),compareJsonValues(left.assert_stdout_contains,right.assert_stdout_contains,[]),compareJsonValues(left.assert_stdout_regex,right.assert_stdout_regex,[]),compareJsonValues(left.assert_stderr_contains,right.assert_stderr_contains,[]),compareJsonValues(left.assert_stderr_regex,right.assert_stderr_regex,[]),compareOptionalNumbers(left.assert_stdout_min_lines,right.assert_stdout_min_lines),compareJsonValues(left.assert_json_field_equals,right.assert_json_field_equals,{}),compareJsonValues(left.assert_json_field_gte,right.assert_json_field_gte,{}),compareOptionalStrings(left.note,right.note)].find(comparison=>comparison!==0)??0}function decodeJsonPointer(path2){return!path2||path2==="/"?[]:path2.startsWith("/")?path2.slice(1).split("/").map(segment=>segment.replaceAll("~1","/").replaceAll("~0","~")):[]}function isDefinedPointerPath(document,path2){const segments=decodeJsonPointer(path2);if(segments.length===0)return!0;let cursor=document;for(const segment of segments){const arrayIndex=/^(0|[1-9]\d*)$/.test(segment)?Number(segment):-1,next=Array.isArray(cursor)?arrayIndex>=0&&arrayIndex<cursor.length?cursor[arrayIndex]:void 0:isRecord(cursor)&&Object.prototype.hasOwnProperty.call(cursor,segment)?cursor[segment]:void 0;if(next===void 0)return!1;cursor=next}return!0}function normalizeHistoryPatchOps(beforeDocument,patch){const normalized=[];let replayCursor=structuredClone(beforeDocument);for(const operation of patch){const normalizedOperation=operation.op==="replace"&&!isDefinedPointerPath(replayCursor,operation.path)?{...operation,op:"add"}:operation;normalized.push(normalizedOperation),replayCursor=jsonPatch.applyPatch(replayCursor,[normalizedOperation],!0,!0).newDocument}return normalized}function canonicalHashDocument(document,version,legacyV2Fields=!1){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{front_matter:{},body:document.body??""};const canonical=canonicalDocument(document),epochMetadata=version===1||version===2&&legacyV2Fields?{...canonical.metadata,...canonical.metadata.dependencies===void 0?{}:{dependencies:canonical.metadata.dependencies.map(dependency=>({...dependency,id:dependency.id.toLowerCase()}))},...canonical.metadata.tests===void 0?{}:{tests:canonical.metadata.tests.map(({workspace_context_mode:_workspaceContextMode,provenance:_provenance,provenance_invalid:_provenanceInvalid,...test})=>test)},...canonical.metadata.test_runs===void 0?{}:{test_runs:canonical.metadata.test_runs.map(({executions:_executions,...testRun})=>testRun)}}:canonical.metadata,metadata=version===1&&epochMetadata.tests?{...epochMetadata,tests:[...epochMetadata.tests].sort(compareLegacyLinkedTests)}:epochMetadata;return{front_matter:orderObject(toItemRecord(metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function canonicalPatchDocument(document){if(!(document.metadata&&Object.keys(document.metadata).length>0))return{metadata:{},body:document.body??""};const canonical=canonicalDocument(document);return{metadata:orderObject(toItemRecord(canonical.metadata),ITEM_METADATA_KEY_ORDER),body:canonical.body}}function hashDocument(document){return hashDocumentForVersion(document,CURRENT_HISTORY_ITEM_HASH_VERSION)}function hashDocumentForVersion(document,version,algorithm){if(!SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(supportedVersion=>supportedVersion===version))throw new TypeError(`unsupported_item_hash_version:${String(version)}`);return historyDigest(stableStringify(canonicalHashDocument(document,version)),algorithm)}function hashDocumentVerificationCandidates(document,version,algorithm){const canonicalHash=hashDocumentForVersion(document,version,algorithm);return version===2?[canonicalHash,historyDigest(stableStringify(canonicalHashDocument(document,version,!0)),algorithm)]:[canonicalHash]}function hashEmptyDocument(){return sha256Hex(stableStringify(EMPTY_LEGACY_HASH_DOCUMENT))}function createHistoryEntry(params){const operation=normalizeHistoryOperationForWrite(params.op),beforeHashCanonical=canonicalHashDocument(params.before,CURRENT_HISTORY_ITEM_HASH_VERSION),afterHashCanonical=canonicalHashDocument(params.after,CURRENT_HISTORY_ITEM_HASH_VERSION),beforePatchCanonical=canonicalPatchDocument(params.before),afterPatchCanonical=canonicalPatchDocument(params.after),rawPatch=jsonPatch.compare(beforePatchCanonical,afterPatchCanonical),patch=normalizeHistoryPatchOps(beforePatchCanonical,rawPatch),agentIdentity=resolveHistoryAgentIdentity(params.author),provenanceOutcomes=agentIdentity.harness?Object.fromEntries(Object.entries(diagnoseAgentIdentity().provenance_outcomes).filter(([dimension,outcome])=>outcome.resolver!==void 0&&(outcome.status!=="resolved"||agentIdentity.provenance?.[dimension]?.source==="probe"))):void 0,context=provenanceOutcomes===void 0||Object.keys(provenanceOutcomes).length===0?params.context:{...params.context,agent_provenance_outcomes:provenanceOutcomes},algorithm=params.hashAlgorithm??CURRENT_HISTORY_HASH_ALGORITHM,entry={hash_algorithm:algorithm,ts:params.nowIso,author:params.author,author_source:params.authorSource??resolveHistoryAuthorSource(params.author),...agentIdentity.harness?{agent_harness:agentIdentity.harness}:{},...agentIdentity.model?{agent_model:agentIdentity.model}:{},...agentIdentity.model_source?{agent_model_source:agentIdentity.model_source}:{},...agentIdentity.instance?{agent_instance:agentIdentity.instance}:{},...agentIdentity.provenance?{agent_provenance:agentIdentity.provenance}:{},...agentIdentity.episode?{agent_episode:agentIdentity.episode}:{},op:operation,patch,before_hash:historyDigest(stableStringify(beforeHashCanonical),algorithm),after_hash:historyDigest(stableStringify(afterHashCanonical),algorithm),item_hash_version:CURRENT_HISTORY_ITEM_HASH_VERSION,message:params.message===void 0?void 0:params.message,...context===void 0?{}:{context}};return sealHistoryRecord({...entry,event_class:classifyHistoryEvent(entry)})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function invalidHistoryTimestamp(message){return new PmCliError(message,EXIT_CODE.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function fallbackHistoryTimestamp(entry){const ts=entry.ts.trim();if(ts.length===0)return nowIso();if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(ts!==entry.ts)throw invalidHistoryTimestamp("History timestamp must not contain surrounding whitespace");return entry.ts}function withHistoryTimestamp(value,fallbackTs){const ts=value.ts;if(typeof ts=="string"&&ts.trim().length>0){if(!isMillisecondPrecisionRfc3339DateTime(ts))throw invalidHistoryTimestamp("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return value}return{...value,ts:fallbackTs}}function serializeHistoryLine(value,fallbackEntry){const fallbackTs=fallbackHistoryTimestamp(fallbackEntry);if(typeof value=="string"){let parsed;try{parsed=JSON.parse(value)}catch{return value}return isRecord(parsed)?JSON.stringify(withHistoryTimestamp(parsed,fallbackTs)):value}return isRecord(value)?JSON.stringify(withHistoryTimestamp(value,fallbackTs)):JSON.stringify(value)}async function applyHistoryAppendOverride(historyPath,entry,result){if(result===!1)return!0;if(typeof result=="string"){const line2=serializeHistoryLine(result,entry);return await appendHistoryLineWithIdentityReservation(historyPath,line2),await invalidateHistoryDriftCacheForPath(historyPath),await removeHistoryEventIndexForHistoryPath(historyPath),!0}if(typeof result!="object"||result===null)return!1;const record=result;if(record.skip===!0)return!0;const nextHistoryPath=typeof record.history_path=="string"?record.history_path:historyPath,line=serializeHistoryLine(typeof record.line=="string"?record.line:record.entry??entry,entry);return await appendHistoryLineWithIdentityReservation(nextHistoryPath,line),await invalidateHistoryDriftCacheForPath(nextHistoryPath),await removeHistoryEventIndexForHistoryPath(nextHistoryPath),!0}async function appendHistoryLineWithIdentityReservation(historyPath,line){let record;try{record=JSON.parse(line)}catch{record=null}if(!isRecord(record)||record.op!=="create"){await appendLineAtomic(historyPath,line);return}await fs.mkdir(path.dirname(historyPath),{recursive:!0});try{await fs.writeFile(historyPath,`${line}
2
+ `,{encoding:"utf8",flag:"wx"})}catch(error){throw error.code!=="EEXIST"?error:new PmCliError("This item identity is reserved by an existing history stream.",EXIT_CODE.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function appendHistoryEntry(historyPath,entry){const override=await runActiveServiceOverride("history_append",{history_path:historyPath,entry});if(override.handled&&await applyHistoryAppendOverride(historyPath,entry,override.result))return;const timestampedEntry=entry.ts.trim().length>0?entry:{...entry,ts:fallbackHistoryTimestamp(entry)},normalizedEntry=sealHistoryRecord({...timestampedEntry,hash_algorithm:resolveHistoryHashAlgorithm(timestampedEntry.hash_algorithm),event_class:classifyHistoryEvent(timestampedEntry)});await appendHistoryEntryWithEventIndex(historyPath,normalizedEntry,async()=>{await appendHistoryLineWithIdentityReservation(historyPath,serializeHistoryLine(normalizedEntry,normalizedEntry))}),await invalidateHistoryDriftCacheForPath(historyPath)}const _testOnly={decodeJsonPointer,isDefinedPointerPath};export{CURRENT_HISTORY_ITEM_HASH_VERSION,CURRENT_HISTORY_RECORD_HASH_VERSION,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,SUPPORTED_HISTORY_RECORD_HASH_VERSIONS,_testOnly,appendHistoryEntry,createHistoryEntry,hasNewerRecordSealFormat,hashDocument,hashDocumentForVersion,hashDocumentVerificationCandidates,hashEmptyDocument,hashHistoryPatch,hashHistoryRecord,hashHistoryStream,isCompleteHistoryRecord,resealHistoryRewrite,sealHistoryRecord,verifyHistoryRecordHash,verifyHistoryRewriteEvidence};
3
3
  //# sourceMappingURL=history.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="02424d1c-c29f-5a13-b711-d50267170b9f")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok)throw new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="cd7d3a47-d37a-55f4-aa60-4fc3ea08d528")}catch{}})();import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";import{historyVersionOffset}from"./version-address.js";import{EMPTY_REPLAY_DOCUMENT,verifyHistoryChain,verifyHistoryChainWithVersion,tryApplyReplayPatch}from"./replay.js";function findHistoryIndexAtTimestamp(history,parsedTarget){let historyIndex=-1;return history.forEach((entry,index)=>{const entryTimestamp=Date.parse(entry.ts);if(!Number.isFinite(entryTimestamp))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);entryTimestamp<=parsedTarget&&(historyIndex=index)}),historyIndex}function buildHistoryTargetGuidance(history,offset){const firstTimestamp=history[0]?.ts??null,lastTimestamp=history.at(-1)?.ts??null,guidance={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:firstTimestamp,last_timestamp:lastTimestamp}};return lastTimestamp!==null&&(guidance.examples=[lastTimestamp],offset!==null&&(guidance.examples.unshift(String(offset+1),String(offset+history.length)),guidance.valid_range.first_version=offset+1,guidance.valid_range.last_version=offset+history.length)),{guidance,lastTimestamp}}function extractPatchFailureContext(patch,error){const failure={};if(error instanceof Error&&error.message.trim().length>0&&(failure.reason=error.message.trim()),typeof error!="object"||error===null)return failure;const candidate=error;if(typeof candidate.index=="number"&&Number.isInteger(candidate.index)&&candidate.index>=0&&(failure.patchIndex=candidate.index),typeof candidate.operation=="object"&&candidate.operation!==null){const operation=candidate.operation;Object.assign(failure,Object.fromEntries(["op","path","from"].flatMap(field=>{const value=operation[field];return typeof value=="string"?[[field,value]]:[]})))}if(failure.patchIndex!==void 0){const fallback=patch[failure.patchIndex];fallback&&(failure.op??=fallback.op,failure.path??=fallback.path,failure.from??=fallback.from)}return failure}function resolveHistoryTarget(target,history,options={}){const trimmed=target.trim(),errorSubject=options.errorSubject??"history",errorSubjectTitle=errorSubject==="restore"?"Restore":"History",{guidance,lastTimestamp}=buildHistoryTargetGuidance(history,historyVersionOffset(history,!0));if(!trimmed)throw new PmCliError(`Missing ${errorSubject} target. Use a timestamp or version number.`,EXIT_CODE.USAGE,guidance);if(/^\d+$/.test(trimmed)){const offset=historyVersionOffset(history),version=Number(trimmed);if(version>=1&&version<=offset)throw new PmCliError(`History version ${version} was pruned by compaction.`,EXIT_CODE.USAGE,{...guidance,code:"history_version_pruned"});if(!Number.isSafeInteger(version)||version<1||version>offset+history.length)throw new PmCliError(`${errorSubjectTitle} version must be between ${offset+1} and ${offset+history.length} for this item.`,EXIT_CODE.USAGE,guidance);return{kind:"version",raw:trimmed,historyIndex:version-offset-1}}const parsedTarget=Date.parse(trimmed);if(!Number.isFinite(parsedTarget))throw new PmCliError(`Invalid ${errorSubject} target "${target}". Use a positive version number or ISO timestamp.`,EXIT_CODE.USAGE,guidance);const historyIndex=findHistoryIndexAtTimestamp(history,parsedTarget);if(historyIndex<0||options.allowFutureTimestamp!==!0&&parsedTarget>Date.parse(lastTimestamp))throw new PmCliError(errorSubject==="restore"?`No history entries exist at or before timestamp ${trimmed}.`:`No history entry exists at timestamp ${trimmed}.`,EXIT_CODE.USAGE,guidance);return{kind:"timestamp",raw:trimmed,historyIndex}}function applyHistoryPatch(current,patch,entryNumber,entryOp){const applied=tryApplyReplayPatch(current,patch);if(applied.ok)return applied.document;const failure=extractPatchFailureContext(patch,applied.error),tokens=[`history_op=${entryOp}`,failure.patchIndex===void 0?null:`patch_index=${failure.patchIndex}`,failure.op?`op=${failure.op}`:null,failure.path?`path=${failure.path}`:null,failure.from?`from=${failure.from}`:null].filter(token=>token!==null);throw new PmCliError(`Failed to apply history patch at entry ${entryNumber} (${tokens.join(", ")}). ${failure.reason??String(applied.error)}`,EXIT_CODE.GENERIC_FAILURE)}function unreconstructableHistoryVersion(targetIndex,liveBridge){return new PmCliError(`History entry ${targetIndex+1} lies between an unrecorded change and the record that repaired it, so its historical state cannot be reconstructed.`,EXIT_CODE.USAGE,{code:"history_version_unreconstructable",required:liveBridge?"Choose a version before the bridged break or from its bridge onward.":"Choose a version whose record is not marked replay_inexact.",nextSteps:[liveBridge?"Run pm history <id> --full to find the bridge record and the versions around it.":"Run pm history <id> --full and pick a version whose record has no replay_inexact marker."]})}function replayHistoryToTarget(history,targetIndex){const first=history[0];if(first&&first.op!=="create"&&first.op!=="history_compact_baseline"){const baseline=tryApplyReplayPatch(EMPTY_REPLAY_DOCUMENT,first.patch);if(!baseline.ok||typeof baseline.document.metadata.id!="string")throw new PmCliError("History starts without a reconstructable item baseline.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}if(history[targetIndex]?.replay_inexact===!0)throw unreconstructableHistoryVersion(targetIndex,!1);const selected=history.slice(0,targetIndex+1),verification=verifyHistoryChain([...selected]);let document=structuredClone(EMPTY_REPLAY_DOCUMENT);for(let index=0;index<=targetIndex;index+=1){const entry=history[index];if(!entry)throw new PmCliError(`History target entry ${index+1} does not exist.`,EXIT_CODE.USAGE);document=applyHistoryPatch(document,entry.patch,index+1,entry.op)}if(!verification.ok){const bridged=verifyHistoryChainWithVersion([...history]);throw bridged.ok&&bridged.bridged_segments?.some(segment=>segment.start<=targetIndex&&targetIndex<segment.end)?unreconstructableHistoryVersion(targetIndex,!0):new PmCliError(`History cannot be replayed: ${verification.errors.join(", ")}.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:verification.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]})}return document}function ensureMaterializedHistoryTarget(replayDocument,target){if(Object.keys(replayDocument.metadata).length>0){if(typeof replayDocument.metadata.id!="string"||!Array.isArray(replayDocument.metadata.tags))throw new PmCliError("History has no complete item baseline for this target.",EXIT_CODE.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return replayDocument}throw new PmCliError(`History target ${target.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,EXIT_CODE.USAGE)}export{applyHistoryPatch,ensureMaterializedHistoryTarget,extractPatchFailureContext,replayHistoryToTarget,resolveHistoryTarget};
2
2
  //# sourceMappingURL=projection.js.map
@@ -19,5 +19,14 @@ source:BigIntStats|null;}
19
19
  * that supplied the bytes, whatever happens to the path meanwhile.
20
20
  */
21
21
  export declare function readIdentifiedHistorySnapshot(historyPath:string,itemId:string):Promise<IdentifiedHistoryStreamSnapshot>;
22
+ /**
23
+ * Describe why one decoded JSONL value cannot be a history record, or return
24
+ * null for an object. Readers dereference every line as an object, so a JSON
25
+ * null, boolean, number, string or array refuses here with a typed error
26
+ * instead of crashing a reader; objects keep each reader's legacy tolerance.
27
+ */
28
+ export declare function describeHistoryRecordDefect(value:unknown):string|null;
29
+ /** Whether one decoded JSON value is a scalar that cannot encode or hide a record. */
30
+ export declare function isNonRecordScalar(value:unknown):boolean;
22
31
  /** Read and validate one item's JSONL history stream without mutating it. */
23
32
  export declare function readHistoryEntries(historyPath:string,itemId:string):Promise<HistoryEntry[]>;
@@ -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]="72d9ef42-50f7-5a57-8210-f4e514197598")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error});return decodeHistorySnapshot(historyPath,itemId,rawBytes)}async function readIdentifiedHistorySnapshot(historyPath,itemId){const handle=await fs.open(historyPath,"r").catch(error=>{if(isFileAbsentError(error))return null;throw error});if(handle===null)return{...await decodeHistorySnapshot(historyPath,itemId,null),source:null};try{const source=await handle.stat({bigint:!0}),rawBytes=await handle.readFile();return{...await decodeHistorySnapshot(historyPath,itemId,rawBytes),source}}finally{await handle.close()}}async function decodeHistorySnapshot(historyPath,itemId,rawBytes){const raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(line)try{entries.push(JSON.parse(line))}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw,raw_bytes:rawBytes,entries}}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{readHistoryEntries,readHistorySnapshot,readIdentifiedHistorySnapshot};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2560e353-1428-540b-bf0b-3c157bdb3b3b")}catch{}})();import fs from"node:fs/promises";import{isFileAbsentError}from"../fs/fs-utils.js";import{runActiveOnReadHooks}from"../extensions/index.js";import{EXIT_CODE}from"../shared/constants.js";import{findFirstMergeConflictMarker}from"../shared/conflict-markers.js";import{PmCliError}from"../shared/errors.js";async function readHistorySnapshot(historyPath,itemId){const rawBytes=await fs.readFile(historyPath).catch(error=>{if(isFileAbsentError(error))return null;throw error});return decodeHistorySnapshot(historyPath,itemId,rawBytes)}async function readIdentifiedHistorySnapshot(historyPath,itemId){const handle=await fs.open(historyPath,"r").catch(error=>{if(isFileAbsentError(error))return null;throw error});if(handle===null)return{...await decodeHistorySnapshot(historyPath,itemId,null),source:null};try{const source=await handle.stat({bigint:!0}),rawBytes=await handle.readFile();return{...await decodeHistorySnapshot(historyPath,itemId,rawBytes),source}}finally{await handle.close()}}async function decodeHistorySnapshot(historyPath,itemId,rawBytes){const raw=rawBytes?.toString("utf8")??null;if(raw===null)return{raw,raw_bytes:rawBytes,entries:[]};if(await runActiveOnReadHooks({path:historyPath,scope:"project"}),raw.trim()==="")return{raw,raw_bytes:rawBytes,entries:[]};const conflictMarker=findFirstMergeConflictMarker(raw);if(conflictMarker)throw new PmCliError(`History for ${itemId} contains merge conflict markers at line ${conflictMarker.line} (${conflictMarker.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${itemId}`,`pm restore ${itemId} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});const entries=[];for(const[index,rawLine]of raw.split(/\r?\n/).entries()){const line=rawLine.trim();if(!line)continue;let parsed;try{parsed=JSON.parse(line)}catch{throw new PmCliError(`History for ${itemId} contains invalid JSON at line ${index+1}. Repair or restore the history stream and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}const defect=describeHistoryRecordDefect(parsed);if(defect!==null)throw new PmCliError(`History for ${itemId} holds ${defect} at line ${index+1}, which is not a history record. Remove or restore the line and retry.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_record_invalid",item_id:itemId,reason:defect,details:{line:index+1},required:"Every history line must be one JSON object record.",nextSteps:[`Run pm history-repair ${itemId} --salvage-tail --dry-run: it removes a line that cannot hold a record (a JSON null, boolean or number) and keeps every record.`,"Otherwise recover the line from version control or a backup."]});entries.push(parsed)}return{raw,raw_bytes:rawBytes,entries}}function describeHistoryRecordDefect(value){return value===null?"a JSON null":Array.isArray(value)?"a JSON array":typeof value=="object"?null:`a JSON ${typeof value}`}function isNonRecordScalar(value){return value===null||typeof value=="boolean"||typeof value=="number"}async function readHistoryEntries(historyPath,itemId){return(await readHistorySnapshot(historyPath,itemId)).entries}export{describeHistoryRecordDefect,isNonRecordScalar,readHistoryEntries,readHistorySnapshot,readIdentifiedHistorySnapshot};
2
2
  //# sourceMappingURL=read.js.map