@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
@@ -0,0 +1,6 @@
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0c0c89bc-0ba8-5679-b3e0-e972c2922104")}catch{}})();import{isUtf8}from"node:buffer";import{constants}from"node:fs";import{lstat,open,readFile,stat}from"node:fs/promises";import{AtomicLinkUnsupportedError,createFileAtomic}from"../../core/fs/atomic-create.js";import{invalidateHistoryDriftCacheForPath}from"../../core/history/drift-cache.js";import{isFileAbsentError}from"../../core/fs/fs-utils.js";import jsonPatch from"fast-json-patch";import{describeHistoryBreak,digestBridgedSegment}from"../../core/history/bridge.js";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{classifyHistoryEvent}from"../../core/history/event-classification.js";import{SUPPORTED_HISTORY_ITEM_HASH_VERSIONS,sealHistoryRecord}from"../../core/history/history.js";import{cloneEmptyReplayDocument,replayHashVerificationCandidates,toReplayDocument,tryApplyReplayPatch,verifyHistoryChainWithVersion}from"../../core/history/replay.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{nowIso}from"../../core/shared/time.js";const BEFORE_HASH_MISMATCH=/^verify_failed:before_hash_mismatch:entry_(\d+)$/u,PATCH_APPLY_FAILED=/^verify_failed:patch_apply_failed:entry_(\d+)$/u;function refuseAppendOnly(id,reason,message,verificationErrors=[]){throw new PmCliError(message,EXIT_CODE.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:id,reason,...verificationErrors.length>0?{verification_errors:verificationErrors}:{},required:"An append-only repair can only bridge chain breaks whose recorded links and patches still replay.",nextSteps:[`Run pm history-repair ${id} --dry-run to preview the rewriting repair, which re-anchors the recorded entries instead.`]})}function locateFirstBreak(id,verification){if(verification.ok)return null;const only=verification.errors.length===1?verification.errors[0]:"",unreplayable=PATCH_APPLY_FAILED.exec(only);unreplayable!==null&&refuseAppendOnly(id,"patch_does_not_replay",`History entry ${unreplayable[1]} of ${id} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`,verification.errors);const match=BEFORE_HASH_MISMATCH.exec(only),index=match===null?0:Number(match[1])-1;return index<1&&refuseAppendOnly(id,"chain_failure_not_a_break",`History for ${id} fails verification for a reason an append-only bridge cannot name (${verification.errors.join(", ")}).`,verification.errors),index}function replayStrictly(id,entries){let replay=cloneEmptyReplayDocument();for(const[index,entry]of entries.entries()){const applied=tryApplyReplayPatch(replay,entry.patch);applied.ok||refuseAppendOnly(id,"patch_does_not_replay",`History entry ${index+1} of ${id} does not apply without the unrecorded change, so only a rewriting repair can keep its effect.`),replay=applied.document}return replay}function resolveAppendedRecordSurface(id,entries,firstBreak,finalReplay,itemReplay){let algorithm;try{algorithm=resolveHistoryHashAlgorithm(entries.at(-1).hash_algorithm)}catch{refuseAppendOnly(id,"chain_failure_not_a_break",`History for ${id} ends with record ${entries.length}, whose digest algorithm this build cannot anchor on.`)}const declared=[...entries].reverse().find(entry=>SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version))?.item_hash_version;if(declared!==void 0)return{itemHashVersion:declared,explicitVersion:!0,algorithm};const verified=firstBreak===null?entries:entries.slice(0,firstBreak),prefixVersion=verifyHistoryChainWithVersion(verified).item_hash_version,tail=entries.at(-1).after_hash,proven=SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.filter(version=>[finalReplay,itemReplay].some(document=>document!==null&&replayHashVerificationCandidates(document,version,algorithm).includes(tail)));let itemHashVersion=prefixVersion;return proven.includes(prefixVersion)||(proven.length===0&&refuseAppendOnly(id,"hash_surface_ambiguous",`History for ${id} declares no hash epoch, and neither replay nor the on-disk item proves its last record's epoch.`),itemHashVersion=proven.at(-1)),{itemHashVersion,explicitVersion:itemHashVersion!==1,algorithm}}function resolveTailVariant(id,surface,previousAfterHash,finalReplay,itemReplay){const candidates=document=>replayHashVerificationCandidates(document,surface.itemHashVersion,surface.algorithm),itemCandidates=candidates(itemReplay);if(new Set(itemCandidates).size===1)return 0;const proven=[candidates(finalReplay),itemCandidates].map(hashes=>hashes.indexOf(previousAfterHash)).find(index=>index>=0);return proven===void 0&&refuseAppendOnly(id,"hash_surface_ambiguous",`History for ${id} records an epoch-2 hash variant that neither replay nor the on-disk item proves, so an appended record cannot anchor on it.`),proven}function buildAppendedRepairRecord(params){const{entries,surface,finalReplay,itemReplay}=params,previousAfterHash=entries.at(-1).after_hash,variant=resolveTailVariant(params.id,surface,previousAfterHash,finalReplay,itemReplay),record={hash_algorithm:surface.algorithm,ts:nowIso(),author:params.author,op:"history_repair",patch:jsonPatch.compare(finalReplay,itemReplay),before_hash:previousAfterHash,after_hash:replayHashVerificationCandidates(itemReplay,surface.itemHashVersion,surface.algorithm)[variant],message:params.message,...surface.explicitVersion?{item_hash_version:surface.itemHashVersion}:{},...params.breaks.length===0?{}:{bridge:{version:1,breaks:params.breaks,segment_digest:digestBridgedSegment(entries.slice(params.segmentStart),{hash_algorithm:surface.algorithm})}}};return sealHistoryRecord({...record,event_class:classifyHistoryEvent(record)})}function describeAppendOnlyRepair(message,breaks,reconciled){return message!==void 0?message:`${[...breaks>0?[`history-repair bridged ${breaks} chain break${breaks===1?"":"s"} without rewriting recorded entries`]:[],...reconciled?["reconciled replay with the on-disk item"]:[]].join("; ")}.`}function collectBreaks(entries,firstBreak){if(firstBreak===null)return[];const breaks=[describeHistoryBreak(entries[firstBreak-1],entries[firstBreak])];for(let index=firstBreak+1;index<entries.length;index+=1)entries[index].before_hash!==entries[index-1].after_hash&&breaks.push(describeHistoryBreak(entries[index-1],entries[index]));return breaks}async function assertSameStream(id,handle,historyPath,statPath){const[written,current]=[await handle.stat(),await statPath(historyPath).catch(()=>null)];(current===null||current.ino!==written.ino||current.dev!==written.dev)&&refuseAppendOnly(id,"stream_changed",`History for ${id} was replaced while the repair appended; the bridge was not recorded, retry.`)}async function readStreamPrefix(handle,limit){const buffer=Buffer.alloc(limit);let filled=0;for(;filled<limit;){const{bytesRead}=await handle.read({buffer,offset:filled,length:limit-filled,position:filled});if(bytesRead===0)break;filled+=bytesRead}return buffer.subarray(0,filled)}async function appendRepairRecord(id,historyPath,verifiedRaw,record,statPath=stat){const handle=await open(historyPath,constants.O_RDWR|constants.O_APPEND|constants.O_NOFOLLOW).catch(error=>{throw isFileAbsentError(error)&&refuseAppendOnly(id,"stream_changed",`History for ${id} was removed after the repair verified it; retry.`),error.code==="ELOOP"&&refuseLinkedStream(id),error});try{const bytes=await handle.readFile();isUtf8(bytes)||refuseAppendOnly(id,"stream_not_utf8",`History for ${id} is not valid UTF-8, so its bytes cannot be kept exactly.`);const raw=bytes.toString("utf8");raw!==verifiedRaw&&refuseAppendOnly(id,"stream_changed",`History for ${id} changed after the repair verified it; retry.`);const appended=`${raw===""||raw.endsWith(`
2
+ `)?"":`
3
+ `}${JSON.stringify(record)}
4
+ `;await handle.appendFile(appended),await handle.sync(),await assertSameStream(id,handle,historyPath,statPath);const expected=Buffer.concat([bytes,Buffer.from(appended)]);(await readStreamPrefix(handle,expected.length+1)).equals(expected)||refuseAppendOnly(id,"stream_changed",`History for ${id} received another write while the repair appended; run pm health to re-verify the stream.`),await assertSameStream(id,handle,historyPath,statPath)}finally{await handle.close()}}async function createStreamExclusively(id,historyPath,record){let published;try{published=await createFileAtomic(historyPath,`${JSON.stringify(record)}
5
+ `,{sync:!0})}catch(error){throw error instanceof AtomicLinkUnsupportedError?new PmCliError(`History for ${id} cannot be rebuilt here: the tracker's filesystem cannot publish a new stream atomically (${error.code}).`,EXIT_CODE.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:id,reason:"stream_publish_unsupported",required:"Rebuilding an absent stream needs a filesystem with hard links; no stream was published.",nextSteps:[`Restore ${id}'s history stream from version control or a backup, or run the repair from a clone on a filesystem with hard links.`]}):error}published||refuseAppendOnly(id,"stream_changed",`History for ${id} was created after the repair verified it; retry.`)}async function appendRecordToVerifiedStream(id,historyPath,verifiedRaw,record){await(verifiedRaw===null?createStreamExclusively(id,historyPath,record):appendRepairRecord(id,historyPath,verifiedRaw,record)),await invalidateHistoryDriftCacheForPath(historyPath)}function refuseLinkedStream(id){throw new PmCliError(`History for ${id} is a symbolic link, so an appended record could land in another stream.`,EXIT_CODE.CONFLICT,{code:"history_append_only_repair_unavailable",item_id:id,reason:"stream_not_regular_file",required:"A history stream must be a regular file at its own path; no bytes were changed.",nextSteps:[`Restore ${id}'s own history stream as a regular file from version control or a backup. When none exists and the item is live, move the link aside and preview the rebuild with pm history-repair ${id} --dry-run.`]})}async function assertRegularStreamEntry(id,historyPath){(await lstat(historyPath).catch(()=>null))?.isSymbolicLink()===!0&&refuseLinkedStream(id)}async function assertAppendOnlyStreamEncoding(id,historyPath){await assertRegularStreamEntry(id,historyPath);const bytes=await readFile(historyPath).catch(()=>null);bytes!==null&&!isUtf8(bytes)&&refuseAppendOnly(id,"stream_not_utf8",`History for ${id} is not valid UTF-8, so its bytes cannot be kept exactly.`)}function buildAppendOnlyRepairPlan(subject,options,snapshot,helpers){const{entries}=snapshot,id=subject.id,before=verifyHistoryChainWithVersion(entries),firstBreak=locateFirstBreak(id,before),breaks=collectBreaks(entries,firstBreak);breaks.length>0&&snapshot.loadedItem===null&&refuseAppendOnly(id,"item_missing",`History for ${id} has a chain break, but no on-disk item exists to anchor an append-only bridge.`);const finalReplay=replayStrictly(id,entries),itemReplay=snapshot.loadedItem===null?null:toReplayDocument(snapshot.loadedItem.document),reconciliation=itemReplay===null?void 0:helpers.analyzeDiscard(entries,finalReplay,itemReplay),reconcile=reconciliation!==void 0,changed=breaks.length>0||reconcile,surface=resolveAppendedRecordSurface(id,entries,firstBreak,finalReplay,itemReplay),appended=changed?buildAppendedRepairRecord({id,entries,surface,finalReplay,itemReplay,author:snapshot.author,message:describeAppendOnlyRepair(options.message,breaks.length,reconcile),breaks,segmentStart:firstBreak??entries.length}):null,rewrittenEntries=appended===null?entries:[...entries,appended],after=verifyHistoryChainWithVersion(rewrittenEntries);after.ok||refuseAppendOnly(id,"bridge_does_not_verify",`An append-only bridge for ${id} would not verify (${after.errors.join(", ")}).`,after.errors);const receipt=appended?.bridge===void 0?void 0:{...appended.bridge,first_break_entry:firstBreak+1},planWarnings=helpers.collectWarnings(changed,0,reconciliation);return{changed,rewrittenEntries,applyRewrite:async verified=>appendRepairRecord(id,subject.historyPath,verified.historyRawUnderLock,appended),report:({verification,warnings})=>reportAppendOnlyRepair({subject,options,entries,before,surface,changed,itemReplay,reconciliation,receipt,verification,warnings:[...planWarnings,...warnings]})}}function reportAppendOnlyRepair(params){const{subject,entries,surface,itemReplay}=params;return{id:subject.id,dry_run:params.options.dryRun===!0,changed:params.changed,history:{path:subject.historyPath,entries_scanned:entries.length,chain_drift_before:!params.before.ok,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:params.reconciliation!==void 0,audit_entry_added:params.changed&&params.options.dryRun!==!0,verify_ok:params.verification.ok,verify_errors:params.verification.errors,item_hash_version_before:params.before.item_hash_version??null,item_hash_version_after:surface.itemHashVersion,version_disposition:"preserved"},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:itemReplay===null?null:replayHashVerificationCandidates(itemReplay,surface.itemHashVersion,surface.algorithm).includes(entries.at(-1).after_hash)},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...params.receipt===void 0?{}:{bridge:params.receipt},...params.reconciliation===void 0?{}:{reconciliation:params.reconciliation},warnings:[...new Set(params.warnings)].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()}}const _testOnly={appendRepairRecord};export{_testOnly,appendRecordToVerifiedStream,assertAppendOnlyStreamEncoding,assertRegularStreamEntry,buildAppendOnlyRepairPlan};
6
+ //# sourceMappingURL=append-only-repair.js.map
@@ -11,7 +11,7 @@ author?:string;
11
11
  force?:boolean;}
12
12
  /** Inputs captured before a transform, bound to the later under-lock drift checks. */
13
13
  export interface HistoryMaintenanceSnapshot{
14
- /** Original bytes used to decode `entries`, never a second independent read. */
14
+ /** Original bytes used to decode `entries`, never a second independent read; empty for a reseed of an absent stream. */
15
15
  raw:string;
16
16
  /** Original stream, including historical anchors and immutable record evidence. */
17
17
  entries:HistoryEntry[];
@@ -56,6 +56,12 @@ operation:HistoryMaintenanceOperation;
56
56
  /** Preview and ownership controls. */
57
57
  options:HistoryMaintenanceOptions;
58
58
  /** Pure planning or evidence reads; persistence belongs in the returned transaction callbacks. */
59
- transform:(snapshot:HistoryMaintenanceSnapshot)=> HistoryMaintenancePlan<Result>|Promise<HistoryMaintenancePlan<Result>>;}
59
+ transform:(snapshot:HistoryMaintenanceSnapshot)=> HistoryMaintenancePlan<Result>|Promise<HistoryMaintenancePlan<Result>>;
60
+ /**
61
+ * Plan for a live item whose stream is absent or holds no record, receiving
62
+ * an empty `raw` and `entries`. Without it such a stream refuses, because
63
+ * the transform has no record to work on (pm-3os5p6).
64
+ */
65
+ reseed?:(snapshot:HistoryMaintenanceSnapshot,stream:{absent:boolean;})=> HistoryMaintenancePlan<Result>|Promise<HistoryMaintenancePlan<Result>>;}
60
66
  /** Verify every transform before writing and reject concurrent item or stream changes under the lock. */
61
67
  export declare function runHistoryMaintenance<Result>(params:HistoryMaintenanceParams<Result>):Promise<Result>;
@@ -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]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();import{runActiveOnWriteHooks}from"../../core/extensions/index.js";import{readHistorySnapshot}from"../../core/history/read.js";import{executeHistoryRewrite,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{historyEntriesToRaw,verifyHistoryChain}from"../../core/history/replay.js";import{resolveAuthor}from"../../core/shared/author.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{readLocatedItem}from"../../core/store/item-store.js";async function runHistoryMaintenance(params){const{subject,settings,operation,options}=params,snapshot=await readHistorySnapshot(subject.historyPath,subject.id);if(snapshot.raw===null)throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND);if(snapshot.entries.length===0)throw new PmCliError(`No history entries exist for ${subject.id}; nothing to ${operation.slice(8)}.`,EXIT_CODE.USAGE);const loadedItem=subject.located?await readLocatedItem(subject.located,{schema:settings.schema}):null,author=resolveAuthor(options.author,settings.author_default),plan=await params.transform({raw:snapshot.raw,entries:snapshot.entries,verification:verifyHistoryChain(snapshot.entries),loadedItem,author}),verification=verifyHistoryChain(plan.rewrittenEntries);if(!verification.ok)throw new PmCliError(`${operation} produced an invalid rewritten chain (${verification.errors.join(", ")}).`,EXIT_CODE.GENERIC_FAILURE);const warnings=plan.changed&&!options.dryRun?await executeHistoryRewrite({pmRoot:params.pmRoot,subject,settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:snapshot.raw,currentItemRawBeforeLock:loadedItem?.raw??null,operation,author,force:options.force,itemDocument:loadedItem?.document??null,applyRewrite:async verified=>{await plan.beforeWrite?.(),plan.applyRewrite?await plan.applyRewrite(verified):await writeHistoryRawWithRollback({historyPath:subject.historyPath,nextHistoryRaw:historyEntriesToRaw(plan.rewrittenEntries),historyRawUnderLock:verified.historyRawUnderLock})},applyPostRewrite:plan.afterWrite??(async()=>runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:`${operation.replace("-","_")}:history`}))}):[];return plan.report({verification,warnings})}export{runHistoryMaintenance};
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]="0676366f-63e6-502f-8505-b58bdb20377a")}catch{}})();import{runActiveOnWriteHooks}from"../../core/extensions/index.js";import{readHistorySnapshot}from"../../core/history/read.js";import{executeHistoryRewrite,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{historyEntriesToRaw,verifyHistoryChain}from"../../core/history/replay.js";import{resolveAuthor}from"../../core/shared/author.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{readLocatedItem}from"../../core/store/item-store.js";function assertTransformableStream(id,operation,snapshot){if(snapshot.raw===null)throw new PmCliError(`No history stream exists for ${id}.`,EXIT_CODE.NOT_FOUND);if(snapshot.entries.length===0)throw new PmCliError(`No history entries exist for ${id}; nothing to ${operation.slice(8)}.`,EXIT_CODE.USAGE)}async function runHistoryMaintenance(params){const{subject,settings,operation,options}=params,snapshot=await readHistorySnapshot(subject.historyPath,subject.id),reseed=snapshot.entries.length===0&&subject.located!==null?params.reseed:void 0;reseed===void 0&&assertTransformableStream(subject.id,operation,snapshot);const loadedItem=subject.located?await readLocatedItem(subject.located,{schema:settings.schema}):null,author=resolveAuthor(options.author,settings.author_default),planSnapshot={raw:snapshot.raw??"",entries:snapshot.entries,verification:verifyHistoryChain(snapshot.entries),loadedItem,author},plan=await(reseed===void 0?params.transform(planSnapshot):reseed(planSnapshot,{absent:snapshot.raw===null})),verification=verifyHistoryChain(plan.rewrittenEntries);if(!verification.ok)throw new PmCliError(`${operation} produced an invalid rewritten chain (${verification.errors.join(", ")}).`,EXIT_CODE.GENERIC_FAILURE);const warnings=plan.changed&&!options.dryRun?await executeHistoryRewrite({pmRoot:params.pmRoot,subject,settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:snapshot.raw,currentItemRawBeforeLock:loadedItem?.raw??null,operation,author,force:options.force,itemDocument:loadedItem?.document??null,applyRewrite:async verified=>{await plan.beforeWrite?.(),plan.applyRewrite?await plan.applyRewrite(verified):await writeHistoryRawWithRollback({historyPath:subject.historyPath,nextHistoryRaw:historyEntriesToRaw(plan.rewrittenEntries),historyRawUnderLock:verified.historyRawUnderLock})},applyPostRewrite:plan.afterWrite??(async()=>runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:`${operation.replace("-","_")}:history`}))}):[];return plan.report({verification,warnings})}export{runHistoryMaintenance};
2
2
  //# sourceMappingURL=maintenance.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]="2bf264bf-c03f-5b5d-a9ea-000dac514705")}catch{}})();import{hasNewerRecordSealFormat}from"../../core/history/history.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";const RECORD_INTEGRITY_FAILURE=/^(incomplete_record_hash_envelope|record_hash_mismatch|unsupported_record_hash_version|rewrite_evidence_[a-z_]+):entry_(\d+)$/u;function recordVersionRefusal(id,entry){return new PmCliError(`History entry ${entry} of ${id} is sealed in a record format this pm version cannot read, so it cannot repair the stream.`,EXIT_CODE.CONFLICT,{code:"history_record_version_unsupported",item_id:id,reason:"unsupported_record_hash_version",details:{entry:Number(entry),reason:"unsupported_record_hash_version"},required:"Upgrade pm to a version that reads the stream's record format; no bytes were changed.",nextSteps:["Run npm install -g @unbrained/pm-cli@latest, then run pm health again."]})}function reanchorOrRefuse(id,entries,reanchor){try{return reanchor()}catch(error){const failure=error instanceof TypeError?RECORD_INTEGRITY_FAILURE.exec(error.message):null;if(failure===null)throw error;const record=entries[Number(failure[2])-1];throw record!==void 0&&hasNewerRecordSealFormat(record)?recordVersionRefusal(id,failure[2]):new PmCliError(`History entry ${failure[2]} of ${id} no longer matches its seal (${failure[1]}), so a repair cannot tell which part of the record to keep.`,EXIT_CODE.CONFLICT,{code:"history_record_integrity_invalid",item_id:id,reason:failure[1],details:{entry:Number(failure[2]),reason:failure[1]},required:"Restore the item's history stream from version control or a backup; no bytes were changed.",nextSteps:[`Run pm history ${id} --verify --full to locate the record, restore the stream, then run pm history ${id} --verify --strict-exit.`]})}}export{reanchorOrRefuse};
2
+ //# sourceMappingURL=reanchor-refusal.js.map
@@ -0,0 +1,15 @@
1
+ import type{HistorySubject}from "./subject.js";import type{HistoryMaintenancePlan,HistoryMaintenanceSnapshot}from "./maintenance.js";import type{HistoryRepairCommandOptions,HistoryRepairResult}from "../history-repair.js";
2
+ /** Receipt for a stream that history-repair rebuilt from the on-disk item. */
3
+ export interface HistoryRepairReseedReceipt{
4
+ /** `missing_stream` when the stream file was absent, `empty_stream` when it held no record. */
5
+ reason:"missing_stream"|"empty_stream";
6
+ /** Earlier versions were never recorded or were lost; version 1 is the item as of the repair. */
7
+ prior_versions:"unrecorded";}
8
+ /**
9
+ * Plan the baseline record for a live item's absent or record-less stream.
10
+ * Both repair modes use it: the stream holds no recorded line to rewrite, so
11
+ * the baseline is appended through O_APPEND after any whitespace the stream
12
+ * held (or the stream is created exclusively), and bytes another writer
13
+ * added are never replaced.
14
+ */
15
+ export declare function buildHistoryReseedPlan(subject:HistorySubject,options:HistoryRepairCommandOptions,snapshot:HistoryMaintenanceSnapshot,stream:{absent:boolean;}):HistoryMaintenancePlan<HistoryRepairResult>;
@@ -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]="c389c6ea-195d-54ff-b3ff-215212036271")}catch{}})();import{createHistoryEntry,CURRENT_HISTORY_ITEM_HASH_VERSION}from"../../core/history/history.js";import{appendRecordToVerifiedStream}from"./append-only-repair.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{nowIso}from"../../core/shared/time.js";function buildHistoryReseedPlan(subject,options,snapshot,stream){const reseed={reason:stream.absent?"missing_stream":"empty_stream",prior_versions:"unrecorded"},item=snapshot.loadedItem,itemPath=subject.located.itemPath,record=createHistoryEntry({nowIso:nowIso(),author:snapshot.author,op:"history_repair",before:EMPTY_CANONICAL_DOCUMENT,after:item.document,message:options.message??`history-repair rebuilt ${stream.absent?"the missing":"the empty"} history stream from the on-disk item; earlier versions are not recorded.`,context:{history_reseed:{contract_version:1,...reseed}}}),dryRun=options.dryRun===!0;return{changed:!0,rewrittenEntries:[record],applyRewrite:async verified=>appendRecordToVerifiedStream(subject.id,subject.historyPath,verified.historyRawUnderLock,record),report:({verification,warnings})=>({id:subject.id,dry_run:dryRun,changed:!0,history:{path:subject.historyPath,entries_scanned:0,chain_drift_before:!0,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!0,audit_entry_added:!dryRun,verify_ok:verification.ok,verify_errors:verification.errors,item_hash_version_before:null,item_hash_version_after:CURRENT_HISTORY_ITEM_HASH_VERSION,version_disposition:"preserved"},item:{exists:!0,path:itemPath,matched_chain_before:!1},provenance_normalization:{requested:options.normalizeProvenance===!0,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},reseed,warnings:[...new Set(warnings)],generated_at:nowIso()})}}export{buildHistoryReseedPlan};
2
+ //# sourceMappingURL=reseed.js.map
@@ -1,18 +1,29 @@
1
1
  import{type HistoryItemHashVersion}from "../../core/history/history.js";import type{ItemTypeRegistry}from "../../core/item/type-registry.js";import type{HistoryEntry,PmSettings}from "../../types/index.js";import type{HistorySubject}from "../history-redact.js";import type{HistoryRepairCommandOptions,HistoryRepairResult}from "../history-repair.js";
2
- /** Evidence describing only the discarded suffix, without retaining its contents. */
2
+ /** Evidence describing only the discarded bytes, without retaining their contents. */
3
3
  export interface HistorySalvageReceipt{
4
- /** One-based physical line where invalid trailing bytes begin. */
4
+ /** One-based physical line of the first discarded line: a non-record line or the start of the invalid suffix. */
5
5
  first_invalid_line:number;
6
- /** UTF-8 bytes removed from the suffix. */
6
+ /** UTF-8 bytes removed, counting non-record lines and the invalid suffix. */
7
7
  discarded_bytes:number;
8
- /** SHA-256 of the removed bytes for local backup comparison. */
8
+ /** SHA-256 of the removed bytes, concatenated in file order, for local backup comparison. */
9
9
  discarded_sha256:string;
10
10
  /** Number of complete verified records retained. */
11
- retained_entries:number;}
11
+ retained_entries:number;
12
+ /** Lines removed before the invalid suffix because their JSON value (null, a boolean or a number) cannot hold a record; absent when none. */
13
+ non_record_lines?:number;}
12
14
  /**
13
- * Select a hash-verified prefix. Any parseable JSON after the first invalid
14
- * line makes the corruption interior and therefore unsalvageable by truncation.
15
+ * Select the records to keep. Discarding an invalid suffix requires a
16
+ * hash-verified prefix, because truncation must not cut a chain whose damage
17
+ * it cannot see. Removing only lines that cannot hold a record conceals
18
+ * nothing, so it keeps a chain that does not verify and reports the verdict:
19
+ * the chain fault is left to history-repair (pm-rpucvb). Any parseable JSON
20
+ * after the first invalid line makes the corruption interior and therefore
21
+ * unsalvageable by truncation.
15
22
  */
16
- export declare function inspectHistoryTail(raw:string):{entries:HistoryEntry[];prefix:string;receipt:HistorySalvageReceipt|null;itemHashVersion:HistoryItemHashVersion;};
23
+ export declare function inspectHistoryTail(raw:string):{entries:HistoryEntry[];prefix:string;receipt:HistorySalvageReceipt|null;
24
+ /** Epoch for the audit record; undefined keeps an implicit stream implicit. */
25
+ itemHashVersion:HistoryItemHashVersion|undefined;
26
+ /** Chain verdict for the retained records. */
27
+ verification:{ok:boolean;errors:string[];};};
17
28
  /** Salvage one explicitly selected stream under its normal ownership and lock policy. */
18
29
  export declare function salvageHistoryTail(params:{pmRoot:string;subject:HistorySubject;settings:PmSettings;typeRegistry:ItemTypeRegistry;options:HistoryRepairCommandOptions;author:string;}):Promise<HistoryRepairResult>;
@@ -1,4 +1,6 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6fc9a054-8905-522e-a166-049730d0e1ae")}catch{}})();import{isUtf8}from"node:buffer";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{readFile}from"node:fs/promises";import{isFileMissingError,readFileIfExists}from"../../core/fs/fs-utils.js";import{acquireLock}from"../../core/lock/lock.js";import{createHistoryEntry,sealHistoryRecord}from"../../core/history/history.js";import{checkHistoryRewriteOwnership,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{replayHistoryToTarget}from"../../core/history/projection.js";import{replayToItemDocument,verifyHistoryChainWithVersion}from"../../core/history/replay.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../../core/shared/constants.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../../core/extensions/index.js";import{locateItem,readLocatedItemSnapshot}from"../../core/store/item-store.js";function decodeSalvageLine(line){let parsed;try{parsed=JSON.parse(line)}catch{if(line.trimStart().startsWith("{")&&line.includes("}"))throw new PmCliError("History salvage cannot discard a potentially complete record with trailing corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return null}if(typeof parsed!="object"||parsed===null||Array.isArray(parsed))throw new PmCliError("History salvage would conceal interior corruption or a malformed record.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});const entry=parsed;if(!Array.isArray(entry.patch)||![entry.ts,entry.author,entry.op,entry.before_hash,entry.after_hash].every(field=>typeof field=="string"))throw new PmCliError("History salvage requires complete history records before the invalid tail.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return entry}function inspectHistoryTail(raw){if(findFirstMergeConflictMarker(raw))throw new PmCliError("Resolve history merge conflicts before salvage.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});const entries=[];let offset=0,invalidOffset,invalidLine=0;for(const[index,line]of raw.split(`
2
- `).entries()){if(!line.trim()){offset+=line.length+1;continue}const parsed=decodeSalvageLine(line);if(parsed===null){invalidOffset===void 0&&(invalidOffset=offset,invalidLine=index+1),offset+=line.length+1;continue}if(invalidOffset!==void 0)throw new PmCliError("History salvage would discard a record or conceal interior corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});entries.push(parsed),offset+=line.length+1}const verification=verifyHistoryChainWithVersion(entries);if(!verification.ok||verification.item_hash_version===void 0)throw new PmCliError("History salvage requires a nonempty verified prefix.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",verification_errors:verification.errors,required:"Recover an intact history prefix from version control or a backup."});return{entries,itemHashVersion:verification.item_hash_version,prefix:invalidOffset===void 0?raw:raw.slice(0,invalidOffset),receipt:invalidOffset===void 0?null:{first_invalid_line:invalidLine,discarded_bytes:Buffer.byteLength(raw.slice(invalidOffset)),discarded_sha256:sha256Hex(raw.slice(invalidOffset)),retained_entries:entries.length}}}async function readSalvageOwnership(located,settings,fallback){if(!located)return{itemRaw:null,document:fallback,live:null};const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return{itemRaw:snapshot.raw,document:snapshot.document??fallback,live:snapshot.document}}function assertSalvageRevision(pmRoot,id,ownership){ownership.itemRaw!==null&&ownership.live===null&&assertItemRevisionExpectationsOnUnreadable(pmRoot,id,ownership.itemRaw);const live=ownership.live??EMPTY_CANONICAL_DOCUMENT;return assertItemMutationPreconditions(pmRoot,live,id),live}async function readSalvageStream(historyPath){let bytes;try{bytes=await readFile(historyPath)}catch(error){if(isFileMissingError(error))return null;throw error}if(!isUtf8(bytes))throw new PmCliError("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return bytes.toString("utf8")}async function salvageHistoryTail(params){const{subject,settings,options,author}=params;if([options.normalizeProvenance,options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById].some(Boolean))throw new PmCliError("Tail salvage cannot be combined with other repair modes.",EXIT_CODE.USAGE);const raw=await readSalvageStream(subject.historyPath);if(raw===null)throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND);await runActiveOnReadHooks({path:subject.historyPath,scope:"project"});const selected=inspectHistoryTail(raw),replay=replayHistoryToTarget(selected.entries,selected.entries.length-1),document=replayToItemDocument(replay);if(typeof replay.metadata.id=="string"&&replay.metadata.id!==subject.id)throw new PmCliError("History belongs to another item; salvage refused.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});const ownership=await readSalvageOwnership(subject.located,settings,document),warnings=checkHistoryRewriteOwnership({itemDocument:ownership.document,subjectId:subject.id,author,force:options.force,settings}),version=selected.itemHashVersion,dryRun=options.dryRun===!0,changed=selected.receipt!==null;if(changed&&!dryRun){const release=await acquireLock(params.pmRoot,subject.id,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const currentRaw=await readSalvageStream(subject.historyPath),located=await locateItem(params.pmRoot,subject.id,settings.id_prefix,settings.item_format,params.typeRegistry.type_to_folder),currentItem=located?await readFileIfExists(located.itemPath):null;if(currentRaw!==raw||currentItem!==ownership.itemRaw)throw assertSalvageRevision(params.pmRoot,subject.id,await readSalvageOwnership(located,settings,document)),new PmCliError("History or item changed while waiting for salvage lock; retry.",EXIT_CODE.CONFLICT);const live=assertSalvageRevision(params.pmRoot,subject.id,ownership),audit=sealHistoryRecord({...createHistoryEntry({hashAlgorithm:resolveHistoryHashAlgorithm(selected.entries.at(-1).hash_algorithm),nowIso:nowIso(),author,op:"history_salvage",before:document,after:document,message:options.message,context:{history_salvage:selected.receipt}}),before_hash:selected.entries.at(-1).after_hash,after_hash:selected.entries.at(-1).after_hash,item_hash_version:version});await writeHistoryRawWithRollback({historyPath:subject.historyPath,historyRawUnderLock:raw,nextHistoryRaw:`${selected.prefix}${JSON.stringify(audit)}
3
- `}),advanceItemMutationPreconditions(params.pmRoot,live,subject.id),warnings.push(...await runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await release()}}return{id:subject.id,dry_run:dryRun,changed,history:{path:subject.historyPath,entries_scanned:selected.entries.length,chain_drift_before:!1,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:changed&&!dryRun,verify_ok:!0,verify_errors:[],item_hash_version_before:version,item_hash_version_after:version,version_disposition:"preserved"},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...selected.receipt?{salvage:selected.receipt}:{},warnings,generated_at:nowIso()}}export{inspectHistoryTail,salvageHistoryTail};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="28c1b131-2a07-5308-96de-40bac827a210")}catch{}})();import{isUtf8}from"node:buffer";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{readFile}from"node:fs/promises";import{isFileMissingError,readFileIfExists}from"../../core/fs/fs-utils.js";import{acquireLock}from"../../core/lock/lock.js";import{createHistoryEntry,sealHistoryRecord}from"../../core/history/history.js";import{checkHistoryRewriteOwnership,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{replayHistoryToTarget}from"../../core/history/projection.js";import{cloneEmptyReplayDocument,lenientApplyReplayPatch,replayToItemDocument,tryApplyReplayPatch,verifyHistoryChainWithVersion}from"../../core/history/replay.js";import{SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../../core/history/history.js";import{findFirstMergeConflictMarker}from"../../core/shared/conflict-markers.js";import{describeHistoryRecordDefect,isNonRecordScalar}from"../../core/history/read.js";import{EMPTY_CANONICAL_DOCUMENT,EXIT_CODE}from"../../core/shared/constants.js";import{advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable}from"../../core/store/item-mutation-precondition.js";import{PmCliError}from"../../core/shared/errors.js";import{sha256Hex}from"../../core/shared/serialization.js";import{nowIso}from"../../core/shared/time.js";import{runActiveOnReadHooks,runActiveOnWriteHooks}from"../../core/extensions/index.js";import{locateItem,readLocatedItemSnapshot}from"../../core/store/item-store.js";function decodeSalvageLine(line){const text=line.trim();let parsed;try{parsed=JSON.parse(text)}catch{if(text.startsWith("{")&&text.includes("}"))throw new PmCliError("History salvage cannot discard a potentially complete record with trailing corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return{kind:"invalid"}}if(isNonRecordScalar(parsed))return{kind:"non_record"};if(describeHistoryRecordDefect(parsed)!==null)throw new PmCliError("History salvage would conceal interior corruption or a malformed record.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});const entry=parsed;if(!Array.isArray(entry.patch)||![entry.ts,entry.author,entry.op,entry.before_hash,entry.after_hash].every(field=>typeof field=="string"))throw new PmCliError("History salvage requires complete history records before the invalid tail.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return{kind:"record",entry}}function newestDeclaredEpoch(entries){return[...entries].reverse().find(entry=>SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.includes(entry.item_hash_version))?.item_hash_version}function inspectHistoryTail(raw){if(findFirstMergeConflictMarker(raw))throw new PmCliError("Resolve history merge conflicts before salvage.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});const scan=scanSalvageLines(raw),judged=judgeRetainedChain(scan);return{entries:scan.entries,...judged,...selectSalvagedBytes(raw,scan.nonRecord,scan.invalidOffset,scan.invalidLine,scan.entries.length)}}function scanSalvageLines(raw){const scan={entries:[],nonRecord:[],invalidOffset:void 0,invalidLine:0};let offset=0;for(const[index,line]of raw.split(`
2
+ `).entries()){const start=offset;if(offset+=line.length+1,!line.trim())continue;const decoded=decodeSalvageLine(line);if(decoded.kind==="record"){if(scan.invalidOffset!==void 0)throw new PmCliError("History salvage would discard a record or conceal interior corruption.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:"Recover the damaged record from version control or a backup; no bytes were changed."});scan.entries.push(decoded.entry)}else decoded.kind==="non_record"&&scan.invalidOffset===void 0?scan.nonRecord.push({start,end:Math.min(offset,raw.length),line:index+1}):scan.invalidOffset===void 0&&(scan.invalidOffset=start,scan.invalidLine=index+1)}return scan}function judgeRetainedChain(scan){const verification=verifyHistoryChainWithVersion(scan.entries),verified=verification.ok&&verification.item_hash_version!==void 0;if(!(scan.invalidOffset===void 0&&scan.nonRecord.length>0)&&(scan.entries.length===0||!verified)){const nothingToDiscard=scan.entries.length>0&&scan.invalidOffset===void 0;throw new PmCliError("History salvage requires a nonempty verified prefix.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",verification_errors:verification.errors,required:"Recover an intact history prefix from version control or a backup.",...nothingToDiscard?{nextSteps:["Run pm history-repair <id> --append-only --dry-run: salvage has nothing to discard, and the chain needs a repair."]}:{}})}return{itemHashVersion:verified?verification.item_hash_version:newestDeclaredEpoch(scan.entries),verification:{ok:verification.ok,errors:verification.errors}}}function salvageHashAlgorithm(last){try{return resolveHistoryHashAlgorithm(last.hash_algorithm)}catch{const unknownLabel=typeof last.hash_algorithm=="string";throw new PmCliError(unknownLabel?"History salvage cannot anchor its record: the last kept record uses a digest algorithm this pm version cannot compute.":"History salvage cannot anchor its record: the last kept record's digest label is malformed.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused",required:unknownLabel?"Upgrade pm to a version that reads the stream's digest algorithm; no bytes were changed.":"Recover the damaged record from version control or a backup; no bytes were changed.",nextSteps:[unknownLabel?"Run npm install -g @unbrained/pm-cli@latest, then preview the salvage again.":"Run pm history <id> --verify --full to locate the record, then restore the stream from version control or a backup."]})}}function salvagedStream(selected,author,message){const last=selected.entries.at(-1);if(last===void 0)return selected.prefix;const empty=EMPTY_CANONICAL_DOCUMENT,{item_hash_version:_stamped,...entry}=createHistoryEntry({hashAlgorithm:salvageHashAlgorithm(last),nowIso:nowIso(),author,op:"history_salvage",before:empty,after:empty,message,context:{history_salvage:selected.receipt}}),audit=sealHistoryRecord({...entry,before_hash:last.after_hash,after_hash:last.after_hash,...selected.itemHashVersion===void 0?{}:{item_hash_version:selected.itemHashVersion}});return`${selected.prefix}${JSON.stringify(audit)}
3
+ `}function assertSalvageIdentity(id,replay){if(typeof replay.metadata.id=="string"&&replay.metadata.id!==id)throw new PmCliError("History belongs to another item; salvage refused.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"})}function replayRetainedRecords(id,selected){const strict=selected.verification.ok;let replay=cloneEmptyReplayDocument(),lastItem=replay;for(const entry of selected.entries){const applied=strict?tryApplyReplayPatch(replay,entry.patch):void 0;replay=applied?.ok===!0?applied.document:lenientApplyReplayPatch(replay,entry.patch,entry.op).document,assertSalvageIdentity(id,replay),Object.keys(replay.metadata).length>0&&(lastItem=replay)}return strict&&selected.entries.length>0?{final:replayHistoryToTarget(selected.entries,selected.entries.length-1),lastItem}:{final:replay,lastItem}}function selectSalvagedBytes(raw,nonRecord,invalidOffset,invalidLine,retainedEntries){const retainedEnd=invalidOffset??raw.length,discarded=[...nonRecord.map(({start,end})=>raw.slice(start,end)),raw.slice(retainedEnd)].join("");let prefix="",cursor=0;for(const{start,end}of nonRecord)prefix+=raw.slice(cursor,start),cursor=end;return prefix+=raw.slice(cursor,retainedEnd),prefix!==""&&!prefix.endsWith(`
4
+ `)&&(prefix+=`
5
+ `),discarded===""?{prefix,receipt:null}:{prefix,receipt:{first_invalid_line:nonRecord[0]?.line??invalidLine,discarded_bytes:Buffer.byteLength(discarded),discarded_sha256:sha256Hex(discarded),retained_entries:retainedEntries,...nonRecord.length>0?{non_record_lines:nonRecord.length}:{}}}}function assertJudgeableSalvageOwner(id,document,force){const assignee=document.metadata?.assignee;if(!(force||assignee===void 0||assignee===null||typeof assignee=="string"))throw new PmCliError(`The recorded owner of ${id} is not a name, so salvage cannot check ownership.`,EXIT_CODE.CONFLICT,{code:"history_salvage_refused",item_id:id,reason:"owner_malformed",details:{reason:"owner_malformed"},required:"Recover the damaged record from version control or a backup, or override ownership deliberately; no bytes were changed.",nextSteps:[`Inspect ${id}'s raw history stream file or restore it from version control or a backup, or rerun the salvage with --force to override ownership.`]})}async function readSalvageOwnership(located,settings,fallback){if(!located)return{itemRaw:null,document:fallback,live:null};const snapshot=await readLocatedItemSnapshot(located,{schema:settings.schema});return{itemRaw:snapshot.raw,document:snapshot.document??fallback,live:snapshot.document}}function assertSalvageRevision(pmRoot,id,ownership){ownership.itemRaw!==null&&ownership.live===null&&assertItemRevisionExpectationsOnUnreadable(pmRoot,id,ownership.itemRaw);const live=ownership.live??EMPTY_CANONICAL_DOCUMENT;return assertItemMutationPreconditions(pmRoot,live,id),live}async function readSalvageStream(historyPath){let bytes;try{bytes=await readFile(historyPath)}catch(error){if(isFileMissingError(error))return null;throw error}if(!isUtf8(bytes))throw new PmCliError("History salvage requires UTF-8 input; recover binary corruption from a byte-preserving backup.",EXIT_CODE.CONFLICT,{code:"history_salvage_refused"});return bytes.toString("utf8")}async function salvageHistoryTail(params){const{subject,settings,options,author}=params;if([options.normalizeProvenance,options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById].some(Boolean))throw new PmCliError("Tail salvage cannot be combined with other repair modes.",EXIT_CODE.USAGE);const raw=await readSalvageStream(subject.historyPath);if(raw===null)throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND);await runActiveOnReadHooks({path:subject.historyPath,scope:"project"});const selected=inspectHistoryTail(raw),replayed=replayRetainedRecords(subject.id,selected),document=replayToItemDocument(replayed.final),nextHistoryRaw=selected.receipt===null?raw:salvagedStream(selected,author,options.message),ownership=await readSalvageOwnership(subject.located,settings,replayToItemDocument(replayed.lastItem));assertJudgeableSalvageOwner(subject.id,ownership.document,options.force===!0);const warnings=checkHistoryRewriteOwnership({itemDocument:ownership.document,subjectId:subject.id,author,force:options.force,settings}),dryRun=options.dryRun===!0,changed=selected.receipt!==null;if(changed&&!dryRun){const release=await acquireLock(params.pmRoot,subject.id,settings.locks.ttl_seconds,author,!!options.force,settings.governance.force_required_for_stale_lock,settings.locks.wait_ms);try{const currentRaw=await readSalvageStream(subject.historyPath),located=await locateItem(params.pmRoot,subject.id,settings.id_prefix,settings.item_format,params.typeRegistry.type_to_folder),currentItem=located?await readFileIfExists(located.itemPath):null;if(currentRaw!==raw||currentItem!==ownership.itemRaw)throw assertSalvageRevision(params.pmRoot,subject.id,await readSalvageOwnership(located,settings,document)),new PmCliError("History or item changed while waiting for salvage lock; retry.",EXIT_CODE.CONFLICT);const live=assertSalvageRevision(params.pmRoot,subject.id,ownership);await writeHistoryRawWithRollback({historyPath:subject.historyPath,historyRawUnderLock:raw,nextHistoryRaw}),advanceItemMutationPreconditions(params.pmRoot,live,subject.id),warnings.push(...await runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:"history_salvage:history"}))}finally{await release()}}return reportSalvage(subject,selected,{changed,dryRun,warnings})}function salvageFollowUp(subject,selected){return selected.entries.length===0?subject.located===null?[]:[`history_stream_empty:${subject.id}:run pm history-repair ${subject.id}`]:selected.verification.ok?[]:[`history_chain_unverified:${subject.id}:run pm history-repair ${subject.id} --append-only --dry-run, or pm history-repair ${subject.id} --dry-run when a bridge refuses`]}function reportSalvage(subject,selected,outcome){const version=selected.itemHashVersion,{ok,errors}=selected.verification;return{id:subject.id,dry_run:outcome.dryRun,changed:outcome.changed,history:{path:subject.historyPath,entries_scanned:selected.entries.length,chain_drift_before:!ok,entries_rehashed:0,entries_patch_repaired:0,converted_replace_to_add:0,skipped_ops:0,reconciled_with_item:!1,audit_entry_added:outcome.changed&&!outcome.dryRun&&selected.entries.length>0,verify_ok:ok,verify_errors:errors,item_hash_version_before:version??null,item_hash_version_after:version??1,version_disposition:"preserved"},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:null},provenance_normalization:{requested:!1,changed:!1,events_changed:0,observations_removed:0,invalid_values:[]},...selected.receipt?{salvage:selected.receipt}:{},warnings:[...outcome.warnings,...salvageFollowUp(subject,selected)],generated_at:nowIso()}}export{inspectHistoryTail,salvageHistoryTail};
4
6
  //# sourceMappingURL=salvage.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="be76e0e9-a03e-528f-8386-28c620f78976")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import path from"node:path";import{createHistoryEntry,hashHistoryStream,sealHistoryRecord,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../core/history/history.js";import{selectHistoryCompactBulkTargets}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument,replayHashVerificationCandidates,replayToItemDocument,toReplayDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{historyVersionOffset}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{pathExists}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue,parseBulkIdsText}from"../core/io/bulk-ids-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnReadHooks}from"../core/extensions/index.js";import{isJudgeableHistoryRecord,recordedPrefixActivity}from"./governance/stale-work.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";function parseBeforeBoundary(before,entries){if(before===void 0)return{kind:"default",raw:null,compactCount:entries.length,retainedCount:0};const raw=before.trim();if(raw.length===0)throw new PmCliError("history-compact --before requires a non-empty value.",EXIT_CODE.USAGE);if(/^\d+$/.test(raw)){const version=Number.parseInt(raw,10),offset=historyVersionOffset(entries);if(!Number.isSafeInteger(version)||version<offset+1||version>offset+entries.length+1)throw new PmCliError(`history-compact --before version must be between ${offset+1} and ${offset+entries.length+1}.`,EXIT_CODE.USAGE);const compactCount2=version-offset-1;return{kind:"version",raw,compactCount:compactCount2,retainedCount:entries.length-compactCount2}}const beforeTs=Date.parse(raw);if(!Number.isFinite(beforeTs))throw new PmCliError(`Invalid history-compact --before value "${before}". Use a version number or ISO timestamp.`,EXIT_CODE.USAGE);let compactCount=0;for(const[index,entry]of entries.entries()){const entryTs=Date.parse(entry.ts);if(!Number.isFinite(entryTs))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);if(entryTs>=beforeTs)break;compactCount+=1}return{kind:"timestamp",raw,compactCount,retainedCount:entries.length-compactCount}}function replayHistoryAndResolveCheckpoint(entries,compactCount){let replay=cloneEmptyReplayDocument(),checkpoint=cloneEmptyReplayDocument();for(let index=0;index<entries.length;index+=1){const entry=entries[index];replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),index+1===compactCount&&(checkpoint=structuredClone(replay))}return{checkpoint,finalReplay:replay}}function describeHistoryCompactCurrentItem(loadedItem,historyEntries){if(!loadedItem)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const lastEntry=historyEntries[historyEntries.length-1];return{loadedItem,currentItemRawBeforeLock:loadedItem.raw,matchedChainBefore:SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(version=>(lastEntry.item_hash_version===void 0||lastEntry.item_hash_version===version)&&replayHashVerificationCandidates(toReplayDocument(loadedItem.document),version,resolveHistoryHashAlgorithm(lastEntry.hash_algorithm)).includes(lastEntry.after_hash))}}function buildHistoryCompactMessage(options,boundary){return typeof options.message=="string"&&options.message.trim().length>0?options.message:boundary.raw===null?`history-compact compacted full stream (${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}).`:`history-compact compacted ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"} before ${boundary.raw}.`}function buildHistoryCompactBaselineMessage(boundary){return boundary.raw===null?`history-compact baseline snapshot after compacting ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${boundary.raw}.`}function assertPrunedRecordsJudgeable(entries,compactCount){const index=entries.slice(0,compactCount).findIndex(entry=>!isJudgeableHistoryRecord(entry));if(index===-1)return;const damage=Number.isFinite(Date.parse(entries[index].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new PmCliError(`History for this item contains ${damage} at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}function buildHistoryCompactEntries(params){if(!params.changed)return{rewrittenEntries:params.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};const{checkpoint,finalReplay}=replayHistoryAndResolveCheckpoint(params.historyEntries,params.boundary.compactCount),retained=params.historyEntries.slice(params.boundary.compactCount),offset=historyVersionOffset(params.historyEntries,!0),checkpointEntry=params.historyEntries[params.boundary.compactCount-1],baselineEntry=createHistoryEntry({hashAlgorithm:resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm),nowIso:params.historyEntries[params.boundary.compactCount-1].ts,author:params.author,op:"history_compact_baseline",before:replayToItemDocument(cloneEmptyReplayDocument()),after:replayToItemDocument(checkpoint),message:buildHistoryCompactBaselineMessage(params.boundary),context:{history_compaction:{contract_version:1,version_offset:offset===null?null:offset+params.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:recordedPrefixActivity(params.historyEntries.slice(0,params.boundary.compactCount)),pruned_entry_count:params.boundary.compactCount,pruned_stream_digest:hashHistoryStream(params.historyEntries.slice(0,params.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),rewrittenEntries=[sealHistoryRecord({...baselineEntry,before_hash:replayHashVerificationCandidates(cloneEmptyReplayDocument(),checkpointEntry.item_hash_version??1,resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm))[0],after_hash:checkpointEntry.after_hash,item_hash_version:checkpointEntry.item_hash_version}),...retained];return params.dryRun||rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_compact",before:replayToItemDocument(finalReplay),after:replayToItemDocument(finalReplay),message:buildHistoryCompactMessage(params.options,params.boundary)})),{rewrittenEntries,baselineEntryAdded:!0,auditEntryAdded:!params.dryRun}}async function runHistoryCompact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-compact",options,transform:snapshot=>buildHistoryCompactPlan(subject,options,snapshot)})}function buildHistoryCompactPlan(subject,options,snapshot){const historyPath=subject.historyPath,historyEntries=snapshot.entries,chainVerification=snapshot.verification;if(!chainVerification.ok)throw new PmCliError(`history-compact requires a valid history chain (${chainVerification.errors.join(", ")}). Run pm history-repair ${subject.id} first.`,EXIT_CODE.CONFLICT);const boundary=parseBeforeBoundary(options.before,historyEntries);assertPrunedRecordsJudgeable(historyEntries,boundary.compactCount);const changed=boundary.compactCount>0,dryRun=!!options.dryRun,author=snapshot.author,warnings=[];changed||warnings.push("history_compact_noop_before_boundary");const currentItem=describeHistoryCompactCurrentItem(snapshot.loadedItem,historyEntries);currentItem.matchedChainBefore===!1&&warnings.push("history_compact_item_chain_mismatch");const{rewrittenEntries,baselineEntryAdded,auditEntryAdded}=buildHistoryCompactEntries({historyEntries,boundary,changed,dryRun,author,options}),offset=historyVersionOffset(historyEntries,!0),firstRetainedEntry=boundary.retainedCount>0&&offset!==null?offset+boundary.compactCount+1:null;return{changed,rewrittenEntries,report:({verification:rewrittenVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,compact_boundary:{kind:boundary.kind,before:boundary.raw,entries_compacted:boundary.compactCount,entries_retained:boundary.retainedCount,first_retained_entry:firstRetainedEntry},history:{path:historyPath,entries_scanned:historyEntries.length,entries_after:rewrittenEntries.length,baseline_entry_added:baselineEntryAdded,audit_entry_added:auditEntryAdded,verify_ok:rewrittenVerify.ok,verify_errors:rewrittenVerify.errors},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:currentItem.matchedChainBefore},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES=3;function normalizeHistoryCompactBulkOptions(options){for(const key of["allOver","minEntries"]){const value=options[key];if(value!==void 0&&(!Number.isSafeInteger(value)||value<0))throw new PmCliError(`history-compact ${key} must be a non-negative safe integer.`,EXIT_CODE.USAGE)}const normalizedIdsText=normalizeBulkIdsValue(options.ids);if(options.ids!==void 0&&normalizedIdsText==="")throw new PmCliError("history-compact ids requires at least one valid item ID.",EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...options,ids:normalizedIdsText===void 0?void 0:parseBulkIdsText(normalizedIdsText)}}function assertHistoryCompactTarget(id,bulk){const hasIds=bulk.ids!==void 0&&bulk.ids.length>0,hasScan=bulk.allOver!==void 0||bulk.scope!==void 0;if((id!==void 0?1:0)+(hasIds?1:0)+(hasScan?1:0)==0)throw new PmCliError("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",EXIT_CODE.USAGE);if(id!==void 0&&(hasIds||hasScan))throw new PmCliError("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",EXIT_CODE.USAGE);if(hasIds&&hasScan)throw new PmCliError("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",EXIT_CODE.USAGE)}function countHistoryStreamEntries(raw){let count=0;for(const line of raw.split(/\r?\n/))line.trim().length>0&&(count+=1);return count}async function collectHistoryCompactBulkCandidates(params){const statusRegistry=resolveRuntimeStatusRegistry(params.settings.schema),classifier=lifecycleClassifierFromStatusRegistry(statusRegistry),items=await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema),bucketById=new Map(items.map(item=>[item.id,classifier.classify(item.status)])),historyDir=path.join(params.pmRoot,"history"),candidates=[],preselectionErrors=[];if(!await pathExists(historyDir))return{candidates,preselectionErrors};const historyFiles=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right));for(const fileName of historyFiles){const historyPath=path.join(historyDir,fileName),id=fileName.slice(0,-6);try{const raw=await fs.readFile(historyPath,"utf8");await runActiveOnReadHooks({path:historyPath,scope:"project"}),candidates.push({id,entries:countHistoryStreamEntries(raw),bucket:bucketById.get(id)??null})}catch(error){preselectionErrors.push({id,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error)})}}return{candidates,preselectionErrors}}async function runHistoryCompactBulkRow(params){if(!params.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:params.row.id,outcome:"skipped",entries_before:params.row.entries,entries_after:null,skip_reason:params.row.skip_reason,changed:!1,error:null}};try{const result=await runHistoryCompact(params.row.id,{dryRun:params.dryRun,author:params.options.author,message:params.options.message,force:params.options.force},params.global);return{selected:!0,compacted:!0,errored:!1,result:{id:params.row.id,outcome:"compacted",entries_before:params.row.entries,entries_after:result.history.entries_after,skip_reason:null,changed:result.changed,error:null}}}catch(error){return{selected:!0,compacted:!1,errored:!0,result:{id:params.row.id,outcome:"errored",entries_before:params.row.entries,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,params.pmRoot)}}}}async function runHistoryCompactBulk(options,global2){const normalizedOptions=normalizeHistoryCompactBulkOptions(options),{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),{candidates,preselectionErrors}=await collectHistoryCompactBulkCandidates({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder}),mode=normalizedOptions.ids!==void 0&&normalizedOptions.ids.length>0?"ids":"scan",minEntries=options.minEntries??HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,policy=settings.history.compact_policy,policyThresholdApplied=mode==="scan"&&options.allOver===void 0&&policy.enabled,allOver=options.allOver??(policyThresholdApplied?policy.max_entries:void 0),selection=selectHistoryCompactBulkTargets(candidates,{ids:normalizedOptions.ids,scope:options.scope,minEntries,allOver}),dryRun=!!options.dryRun,results=[...preselectionErrors],totals={streams_considered:candidates.length+preselectionErrors.length,selected:0,items_compacted:0,items_skipped:0,items_errored:preselectionErrors.length};for(const row of selection){const outcome=await runHistoryCompactBulkRow({pmRoot,row,options:normalizedOptions,dryRun,global:global2});if(results.push(outcome.result),!outcome.selected){totals.items_skipped+=1;continue}totals.selected+=1,outcome.compacted&&(totals.items_compacted+=1),outcome.errored&&(totals.items_errored+=1)}return{bulk:!0,dry_run:dryRun,mode,scope:options.scope??null,criteria:{min_entries:minEntries,all_over:allOver??null,policy_threshold_applied:policyThresholdApplied},totals,results,generated_at:nowIso()}}export{HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="822ae2f6-91d4-51db-96c9-bb5c5db5c337")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import path from"node:path";import{createHistoryEntry,hashHistoryStream,sealHistoryRecord,SUPPORTED_HISTORY_ITEM_HASH_VERSIONS}from"../core/history/history.js";import{selectHistoryCompactBulkTargets}from"../core/history/history-compact-bulk.js";import{cloneEmptyReplayDocument,replayHashVerificationCandidates,replayToItemDocument,toReplayDocument,verifyHistoryChainWithVersion}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{historyVersionOffset}from"../core/history/version-address.js";import{lifecycleClassifierFromStatusRegistry}from"../core/governance/metadata-coverage.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{listAllItemMetadataLight}from"../core/store/item-store.js";import{pathExists}from"../core/fs/fs-utils.js";import{normalizeBulkIdsValue,parseBulkIdsText}from"../core/io/bulk-ids-input.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnReadHooks}from"../core/extensions/index.js";import{isJudgeableHistoryRecord,recordedPrefixActivity}from"./governance/stale-work.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";function parseBeforeBoundary(before,entries){if(before===void 0)return{kind:"default",raw:null,compactCount:entries.length,retainedCount:0};const raw=before.trim();if(raw.length===0)throw new PmCliError("history-compact --before requires a non-empty value.",EXIT_CODE.USAGE);if(/^\d+$/.test(raw)){const version=Number.parseInt(raw,10),offset=historyVersionOffset(entries);if(!Number.isSafeInteger(version)||version<offset+1||version>offset+entries.length+1)throw new PmCliError(`history-compact --before version must be between ${offset+1} and ${offset+entries.length+1}.`,EXIT_CODE.USAGE);const compactCount2=version-offset-1;return{kind:"version",raw,compactCount:compactCount2,retainedCount:entries.length-compactCount2}}const beforeTs=Date.parse(raw);if(!Number.isFinite(beforeTs))throw new PmCliError(`Invalid history-compact --before value "${before}". Use a version number or ISO timestamp.`,EXIT_CODE.USAGE);let compactCount=0;for(const[index,entry]of entries.entries()){const entryTs=Date.parse(entry.ts);if(!Number.isFinite(entryTs))throw new PmCliError(`History for this item contains invalid timestamp at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE);if(entryTs>=beforeTs)break;compactCount+=1}return{kind:"timestamp",raw,compactCount,retainedCount:entries.length-compactCount}}function replayHistoryAndResolveCheckpoint(entries,compactCount){let replay=cloneEmptyReplayDocument(),checkpoint=cloneEmptyReplayDocument();for(let index=0;index<entries.length;index+=1){const entry=entries[index];replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),index+1===compactCount&&(checkpoint=structuredClone(replay))}return{checkpoint,finalReplay:replay}}function describeHistoryCompactCurrentItem(loadedItem,historyEntries){if(!loadedItem)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};const lastEntry=historyEntries[historyEntries.length-1];return{loadedItem,currentItemRawBeforeLock:loadedItem.raw,matchedChainBefore:SUPPORTED_HISTORY_ITEM_HASH_VERSIONS.some(version=>(lastEntry.item_hash_version===void 0||lastEntry.item_hash_version===version)&&replayHashVerificationCandidates(toReplayDocument(loadedItem.document),version,resolveHistoryHashAlgorithm(lastEntry.hash_algorithm)).includes(lastEntry.after_hash))}}function buildHistoryCompactMessage(options,boundary){return typeof options.message=="string"&&options.message.trim().length>0?options.message:boundary.raw===null?`history-compact compacted full stream (${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}).`:`history-compact compacted ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"} before ${boundary.raw}.`}function buildHistoryCompactBaselineMessage(boundary){return boundary.raw===null?`history-compact baseline snapshot after compacting ${boundary.compactCount} entr${boundary.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${boundary.raw}.`}function assertPrunedRecordsJudgeable(entries,compactCount){const index=entries.slice(0,compactCount).findIndex(entry=>!isJudgeableHistoryRecord(entry));if(index===-1)return;const damage=Number.isFinite(Date.parse(entries[index].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new PmCliError(`History for this item contains ${damage} at entry ${index+1}.`,EXIT_CODE.GENERIC_FAILURE)}function timestampBoundaryGuidance(entries,segment){const earliest=entries[segment.start].ts,times=entries.slice(0,segment.end+1).map(entry=>Date.parse(entry.ts));if(!times.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${earliest}".`,`Run pm history-compact <id> --before "${earliest}".`];const latest=new Date(times.reduce((max,time)=>Math.max(max,time),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${earliest}", or after "${latest}".`,`Run pm history-compact <id> --before "${earliest}", or with a timestamp after "${latest}".`]}function assertReconstructableCompactBoundary(entries,compactCount){const checkpoint=compactCount-1,segment=(verifyHistoryChainWithVersion(entries).bridged_segments??[]).find(({start,end})=>start<=checkpoint&&checkpoint<end);if(segment===void 0)return;const offset=historyVersionOffset(entries,!0),[checkpointName,required,nextStep]=offset===null?timestampBoundaryGuidance(entries,segment):[`version ${offset+compactCount}`,`Choose --before ${offset+segment.start+1} or lower, or --before ${offset+segment.end+2} or higher.`,`Run pm history-compact <id> --before ${offset+segment.start+1} or --before ${offset+segment.end+2}.`];throw new PmCliError(`history-compact cannot checkpoint ${checkpointName}: it lies inside a bridged segment whose states cannot be reconstructed.`,EXIT_CODE.USAGE,{code:"history_compact_boundary_bridged",required,nextSteps:[nextStep]})}function buildHistoryCompactEntries(params){if(!params.changed)return{rewrittenEntries:params.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};assertReconstructableCompactBoundary(params.historyEntries,params.boundary.compactCount);const{checkpoint,finalReplay}=replayHistoryAndResolveCheckpoint(params.historyEntries,params.boundary.compactCount),retained=params.historyEntries.slice(params.boundary.compactCount),offset=historyVersionOffset(params.historyEntries,!0),checkpointEntry=params.historyEntries[params.boundary.compactCount-1],baselineEntry=createHistoryEntry({hashAlgorithm:resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm),nowIso:params.historyEntries[params.boundary.compactCount-1].ts,author:params.author,op:"history_compact_baseline",before:replayToItemDocument(cloneEmptyReplayDocument()),after:replayToItemDocument(checkpoint),message:buildHistoryCompactBaselineMessage(params.boundary),context:{history_compaction:{contract_version:1,version_offset:offset===null?null:offset+params.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:recordedPrefixActivity(params.historyEntries.slice(0,params.boundary.compactCount)),pruned_entry_count:params.boundary.compactCount,pruned_stream_digest:hashHistoryStream(params.historyEntries.slice(0,params.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),rewrittenEntries=[sealHistoryRecord({...baselineEntry,before_hash:replayHashVerificationCandidates(cloneEmptyReplayDocument(),checkpointEntry.item_hash_version??1,resolveHistoryHashAlgorithm(checkpointEntry.hash_algorithm))[0],after_hash:checkpointEntry.after_hash,item_hash_version:checkpointEntry.item_hash_version,...checkpointEntry.replay_inexact===!0?{replay_inexact:!0}:{}}),...retained];return params.dryRun||rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_compact",before:replayToItemDocument(finalReplay),after:replayToItemDocument(finalReplay),message:buildHistoryCompactMessage(params.options,params.boundary)})),{rewrittenEntries,baselineEntryAdded:!0,auditEntryAdded:!params.dryRun}}async function runHistoryCompact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-compact",options,transform:snapshot=>buildHistoryCompactPlan(subject,options,snapshot)})}function buildHistoryCompactPlan(subject,options,snapshot){const historyPath=subject.historyPath,historyEntries=snapshot.entries,chainVerification=snapshot.verification;if(!chainVerification.ok)throw new PmCliError(`history-compact requires a valid history chain (${chainVerification.errors.join(", ")}). Run pm history-repair ${subject.id} first.`,EXIT_CODE.CONFLICT);const boundary=parseBeforeBoundary(options.before,historyEntries);assertPrunedRecordsJudgeable(historyEntries,boundary.compactCount);const changed=boundary.compactCount>0,dryRun=!!options.dryRun,author=snapshot.author,warnings=[];changed||warnings.push("history_compact_noop_before_boundary");const currentItem=describeHistoryCompactCurrentItem(snapshot.loadedItem,historyEntries);currentItem.matchedChainBefore===!1&&warnings.push("history_compact_item_chain_mismatch");const{rewrittenEntries,baselineEntryAdded,auditEntryAdded}=buildHistoryCompactEntries({historyEntries,boundary,changed,dryRun,author,options}),offset=historyVersionOffset(historyEntries,!0),firstRetainedEntry=boundary.retainedCount>0&&offset!==null?offset+boundary.compactCount+1:null;return{changed,rewrittenEntries,report:({verification:rewrittenVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,compact_boundary:{kind:boundary.kind,before:boundary.raw,entries_compacted:boundary.compactCount,entries_retained:boundary.retainedCount,first_retained_entry:firstRetainedEntry},history:{path:historyPath,entries_scanned:historyEntries.length,entries_after:rewrittenEntries.length,baseline_entry_added:baselineEntryAdded,audit_entry_added:auditEntryAdded,verify_ok:rewrittenVerify.ok,verify_errors:rewrittenVerify.errors},item:{exists:subject.located!==null,path:subject.located?.itemPath??null,matched_chain_before:currentItem.matchedChainBefore},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES=3;function normalizeHistoryCompactBulkOptions(options){for(const key of["allOver","minEntries"]){const value=options[key];if(value!==void 0&&(!Number.isSafeInteger(value)||value<0))throw new PmCliError(`history-compact ${key} must be a non-negative safe integer.`,EXIT_CODE.USAGE)}const normalizedIdsText=normalizeBulkIdsValue(options.ids);if(options.ids!==void 0&&normalizedIdsText==="")throw new PmCliError("history-compact ids requires at least one valid item ID.",EXIT_CODE.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...options,ids:normalizedIdsText===void 0?void 0:parseBulkIdsText(normalizedIdsText)}}function assertHistoryCompactTarget(id,bulk){const hasIds=bulk.ids!==void 0&&bulk.ids.length>0,hasScan=bulk.allOver!==void 0||bulk.scope!==void 0;if((id!==void 0?1:0)+(hasIds?1:0)+(hasScan?1:0)==0)throw new PmCliError("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",EXIT_CODE.USAGE);if(id!==void 0&&(hasIds||hasScan))throw new PmCliError("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",EXIT_CODE.USAGE);if(hasIds&&hasScan)throw new PmCliError("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",EXIT_CODE.USAGE)}function countHistoryStreamEntries(raw){let count=0;for(const line of raw.split(/\r?\n/))line.trim().length>0&&(count+=1);return count}async function collectHistoryCompactBulkCandidates(params){const statusRegistry=resolveRuntimeStatusRegistry(params.settings.schema),classifier=lifecycleClassifierFromStatusRegistry(statusRegistry),items=await listAllItemMetadataLight(params.pmRoot,params.settings.item_format,params.typeToFolder,void 0,params.settings.schema),bucketById=new Map(items.map(item=>[item.id,classifier.classify(item.status)])),historyDir=path.join(params.pmRoot,"history"),candidates=[],preselectionErrors=[];if(!await pathExists(historyDir))return{candidates,preselectionErrors};const historyFiles=(await fs.readdir(historyDir)).filter(entry=>entry.endsWith(".jsonl")).sort((left,right)=>left.localeCompare(right));for(const fileName of historyFiles){const historyPath=path.join(historyDir,fileName),id=fileName.slice(0,-6);try{const raw=await fs.readFile(historyPath,"utf8");await runActiveOnReadHooks({path:historyPath,scope:"project"}),candidates.push({id,entries:countHistoryStreamEntries(raw),bucket:bucketById.get(id)??null})}catch(error){preselectionErrors.push({id,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error)})}}return{candidates,preselectionErrors}}async function runHistoryCompactBulkRow(params){if(!params.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:params.row.id,outcome:"skipped",entries_before:params.row.entries,entries_after:null,skip_reason:params.row.skip_reason,changed:!1,error:null}};try{const result=await runHistoryCompact(params.row.id,{dryRun:params.dryRun,author:params.options.author,message:params.options.message,force:params.options.force},params.global);return{selected:!0,compacted:!0,errored:!1,result:{id:params.row.id,outcome:"compacted",entries_before:params.row.entries,entries_after:result.history.entries_after,skip_reason:null,changed:result.changed,error:null}}}catch(error){return{selected:!0,compacted:!1,errored:!0,result:{id:params.row.id,outcome:"errored",entries_before:params.row.entries,entries_after:null,skip_reason:null,changed:!1,error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,params.pmRoot)}}}}async function runHistoryCompactBulk(options,global2){const normalizedOptions=normalizeHistoryCompactBulkOptions(options),{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),{candidates,preselectionErrors}=await collectHistoryCompactBulkCandidates({pmRoot,settings,typeToFolder:typeRegistry.type_to_folder}),mode=normalizedOptions.ids!==void 0&&normalizedOptions.ids.length>0?"ids":"scan",minEntries=options.minEntries??HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,policy=settings.history.compact_policy,policyThresholdApplied=mode==="scan"&&options.allOver===void 0&&policy.enabled,allOver=options.allOver??(policyThresholdApplied?policy.max_entries:void 0),selection=selectHistoryCompactBulkTargets(candidates,{ids:normalizedOptions.ids,scope:options.scope,minEntries,allOver}),dryRun=!!options.dryRun,results=[...preselectionErrors],totals={streams_considered:candidates.length+preselectionErrors.length,selected:0,items_compacted:0,items_skipped:0,items_errored:preselectionErrors.length};for(const row of selection){const outcome=await runHistoryCompactBulkRow({pmRoot,row,options:normalizedOptions,dryRun,global:global2});if(results.push(outcome.result),!outcome.selected){totals.items_skipped+=1;continue}totals.selected+=1,outcome.compacted&&(totals.items_compacted+=1),outcome.errored&&(totals.items_errored+=1)}return{bulk:!0,dry_run:dryRun,mode,scope:options.scope??null,criteria:{min_entries:minEntries,all_over:allOver??null,policy_threshold_applied:policyThresholdApplied},totals,results,generated_at:nowIso()}}export{HISTORY_COMPACT_BULK_DEFAULT_MIN_ENTRIES,assertHistoryCompactTarget,runHistoryCompact,runHistoryCompactBulk};
2
2
  //# sourceMappingURL=history-compact.js.map
@@ -1,2 +1,2 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="99336062-727a-5797-8586-117c3c106dcc")}catch{}})();import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{resolveHistorySubject as resolveHistorySubject2}from"./history/subject.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{writeFileAtomic}from"../core/fs/fs-utils.js";import{createHistoryEntry,resealHistoryRewrite,verifyHistoryRecordHash}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath}from"../core/history/drift-cache.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT,historyEntriesToRaw,replayHash,replayToItemDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{canonicalDocument,serializeItemDocument}from"../core/item/item-format.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../core/store/item-metadata-cache.js";import{getItemPath}from"../core/store/paths.js";function normalizeStringArrayInput(value){return Array.isArray(value)?value:typeof value=="string"?[value]:[]}function normalizeRegexFlags(flags){const unique=[];for(const token of flags)unique.includes(token)||unique.push(token);return unique.includes("g")||unique.push("g"),unique.join("")}function invalidRegexRule(index,reason){return new PmCliError(`Invalid --regex value at --regex #${index}: ${reason}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${index}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function parseRegexRule(spec,index=1){const trimmed=spec.trim();if(trimmed.length===0)throw invalidRegexRule(index,"provide a non-empty pattern.");let source=trimmed,flags="g";if(trimmed.startsWith("/")&&trimmed.length>1){const slashIndex=trimmed.lastIndexOf("/");let backslashes=0;for(let index2=slashIndex-1;index2>=0&&trimmed[index2]==="\\";index2--)backslashes++;slashIndex>0&&backslashes%2===0&&/^[dgimsuvy]*$/u.test(trimmed.slice(slashIndex+1))&&(source=trimmed.slice(1,slashIndex),flags=normalizeRegexFlags(trimmed.slice(slashIndex+1)))}if(source.length===0)throw invalidRegexRule(index,"an empty pattern is not allowed.");try{new RegExp(source,flags)}catch{throw invalidRegexRule(index,"provide a valid JavaScript regular expression.")}return{kind:"regex",source,flags}}function buildRedactionRules(literalInput,regexInput){const literalRules=[...new Set(normalizeStringArrayInput(literalInput).map(entry=>entry.trim()))].filter(entry=>entry.length>0).map(entry=>({kind:"literal",value:entry})),seen=new Set,regexRules=normalizeStringArrayInput(regexInput).flatMap((entry,index)=>{const spec=entry.trim();return seen.has(spec)?[]:(seen.add(spec),[parseRegexRule(spec,index+1)])}),rules=[...literalRules,...regexRules];if(rules.length===0)throw new PmCliError("history-redact requires at least one matcher via --literal or --regex.",EXIT_CODE.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return rules}function applyLiteralRule(value,literal,replacement){if(literal.length===0)return{value,replacements:0};let cursor=0,replacements=0;for(;cursor<=value.length;){const index=value.indexOf(literal,cursor);if(index===-1)break;replacements+=1,cursor=index+Math.max(1,literal.length)}return replacements===0?{value,replacements:0}:{value:value.split(literal).join(replacement),replacements}}function applyRegexRule(value,rule,replacement){const regex=new RegExp(rule.source,rule.flags),matches=[...value.matchAll(regex)];return matches.length===0?{value,replacements:0}:{value:value.replace(regex,replacement),replacements:matches.length}}function redactStringValue(value,rules,replacement){let next=value,replacements=0;for(const rule of rules){const result=rule.kind==="literal"?applyLiteralRule(next,rule.value,replacement):applyRegexRule(next,rule,replacement);next=result.value,replacements+=result.replacements}return{value:next,replacements}}function redactUnknownValue(value,rules,replacement){if(typeof value=="string")return redactStringValue(value,rules,replacement);if(Array.isArray(value)){let replacements=0;return{value:value.map(entry=>{const redacted=redactUnknownValue(entry,rules,replacement);return replacements+=redacted.replacements,redacted.value}),replacements}}if(typeof value=="object"&&value!==null){let replacements=0;const nextRecord={};for(const[key,entry]of Object.entries(value)){const redacted=redactUnknownValue(entry,rules,replacement);replacements+=redacted.replacements,nextRecord[key]=redacted.value}return{value:nextRecord,replacements}}return{value,replacements:0}}function redactHistoryPatch(patch,rules,replacement){let replacements=0;return{patch:patch.map(operation=>{if(!Object.prototype.hasOwnProperty.call(operation,"value"))return operation;const redactedValue=redactUnknownValue(operation.value,rules,replacement);return replacements+=redactedValue.replacements,redactedValue.replacements>0?{...operation,value:redactedValue.value}:operation}),replacements}}function inspectHistoryIntegrity(entries){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),hashMismatchesBefore=0,hashMismatchesAfter=0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.before_hash&&(hashMismatchesBefore+=1),replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.after_hash&&(hashMismatchesAfter+=1)}return{hashMismatchesBefore,hashMismatchesAfter,finalDocument:replay}}function redactHistoryEntry(entry,rules,replacement){let replacements=0,changed=!1,reanchorEvidenceRedacted=!1,nextMessage=entry.message;if(typeof entry.message=="string"){const redactedMessage=redactStringValue(entry.message,rules,replacement);nextMessage=redactedMessage.value,replacements+=redactedMessage.replacements,redactedMessage.replacements>0&&(changed=!0)}const redactedPatch=redactHistoryPatch(entry.patch,rules,replacement);replacements+=redactedPatch.replacements,changed||=redactedPatch.replacements>0;const nextReanchorEvidence=entry.reanchor_evidence?.map(evidence=>{const redactedEvidencePatch=evidence.patch?redactHistoryPatch(evidence.patch,rules,replacement):{patch:void 0,replacements:0},redactedEvidenceRecord=evidence.record?redactUnknownValue(evidence.record,rules,replacement):{value:void 0,replacements:0};replacements+=redactedEvidencePatch.replacements,replacements+=redactedEvidenceRecord.replacements;const evidenceChanged=redactedEvidencePatch.replacements>0||redactedEvidenceRecord.replacements>0;if(changed||=evidenceChanged,!evidenceChanged)return evidence;reanchorEvidenceRedacted=!0;const{patch:_sensitivePatch,record:_sensitiveRecord,record_hash:_priorRecordHash,record_hash_version:_priorRecordHashVersion,...digestOnlyEvidence}=evidence;return redactedEvidencePatch.replacements>0?digestOnlyEvidence:{...digestOnlyEvidence,patch:evidence.patch}});return{entry:{...entry,message:nextMessage,patch:redactedPatch.patch,...nextReanchorEvidence?{reanchor_evidence:nextReanchorEvidence}:{}},replacements,changed,reanchorEvidenceRedacted}}function rewriteHistoryEntries(entries,rules,replacement){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),entriesChanged=0,replacements=0;const rewrittenEntries=[];for(let index=0;index<entries.length;index+=1){const original=entries[index],recordVerification=verifyHistoryRecordHash(original);if(!recordVerification.ok)throw new PmCliError(`history-redact refuses invalid immutable record ${index+1} (${recordVerification.error}).`,EXIT_CODE.GENERIC_FAILURE);const redacted=redactHistoryEntry(original,rules,replacement);replacements+=redacted.replacements,redacted.changed&&(entriesChanged+=1);const beforeHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));replay=applyHistoryPatch(replay,redacted.entry.patch,index+1,redacted.entry.op);const afterHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));rewrittenEntries.push(resealHistoryRewrite(original,{...redacted.entry,before_hash:beforeHash,after_hash:afterHash},{retainPriorRecord:redacted.changed,retainPriorRecordHash:!redacted.changed}))}return{entries:rewrittenEntries,finalDocument:replay,entriesChanged,replacements}}function hasItemMetadata(replay){return Object.keys(replay.metadata).length>0}function resolveHistoryRedactNextItem(params){if(!hasItemMetadata(params.finalDocument))return{raw:null,path:null,document:null};const canonical=canonicalDocument(replayToItemDocument(params.finalDocument),{schema:params.settings.schema});if(canonical.metadata.id!==params.subject.id)throw new PmCliError("history-redact would change the item id; narrow your patterns.",EXIT_CODE.USAGE);return{document:canonical,path:getItemPath(params.pmRoot,canonical.metadata.type,params.subject.id,"toon",params.typeToFolder),raw:serializeItemDocument(canonical,{format:"toon",schema:params.settings.schema})}}function buildHistoryRedactMessage(options,rewritten){return typeof options.message=="string"&&options.message.trim().length>0?options.message:`history-redact replaced ${rewritten.replacements} match(es) across ${rewritten.entriesChanged} entr${rewritten.entriesChanged===1?"y":"ies"}.`}function buildHistoryRedactEntries(params){const rewrittenEntries=[...params.rewritten.entries];if(params.dryRun||!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const finalDocument=params.nextItemDocument??replayToItemDocument(params.rewritten.finalDocument);return rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_redact",before:finalDocument,after:finalDocument,message:params.message})),{rewrittenEntries,auditEntryAdded:!0}}function createHistoryRedactTransaction(params){let derivedIndexWarnings=[];return{applyRewrite:async({historyRawUnderLock})=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author),affectedItemPaths=new Set;params.currentItem.path&&affectedItemPaths.add(params.currentItem.path),params.nextItem.path&&affectedItemPaths.add(params.nextItem.path);const itemSnapshots=new Map;params.currentItem.path&&params.currentItem.raw!==null&&itemSnapshots.set(params.currentItem.path,params.currentItem.raw);let rethrowReleaseFailure=()=>{};try{try{params.nextItem.path&&params.nextItem.raw!==null&&params.nextItem.raw!==params.currentItem.raw&&await writeFileAtomic(params.nextItem.path,params.nextItem.raw),params.currentItem.path&&(!params.nextItem.path||params.nextItem.path!==params.currentItem.path)&&await fs.rm(params.currentItem.path,{force:!0}),await writeFileAtomic(params.subject.historyPath,historyEntriesToRaw(params.rewrittenEntries))}catch(error){try{await rollbackHistoryRedactRewrite(params.subject.historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots)}finally{await invalidateHistoryDriftCacheForPath(params.subject.historyPath)}throw error}await invalidateHistoryDriftCacheForPath(params.subject.historyPath);const itemPath=params.nextItem.path??params.currentItem.path;itemPath&&(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:params.typeRegistry.type_to_folder,schema:params.settings.schema,itemPath,...params.currentItem.path?{previousItemPath:params.currentItem.path}:{},document:params.nextItem.document}))}finally{await releaseDerivedIndexLock().catch(error=>{rethrowReleaseFailure=()=>{throw error}})}rethrowReleaseFailure()},afterWrite:async()=>[...derivedIndexWarnings,...await runHistoryRedactWriteHooks(params.subject.historyPath,[params.nextItem.path,params.currentItem.path])]}}async function rollbackHistoryRedactRewrite(historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots){historyRawUnderLock===null?await fs.rm(historyPath,{force:!0}):await writeFileAtomic(historyPath,historyRawUnderLock);for(const itemPath of affectedItemPaths){const snapshot=itemSnapshots.get(itemPath);snapshot===void 0?await fs.rm(itemPath,{force:!0}):await writeFileAtomic(itemPath,snapshot)}}async function runHistoryRedactWriteHooks(historyPath,itemHookPaths){const hookWarnings=[],uniqueItemHookPaths=new Set(itemHookPaths.filter(itemPath=>itemPath!==null));for(const itemHookPath of uniqueItemHookPaths)hookWarnings.push(...await runActiveOnWriteHooks({path:itemHookPath,scope:"project",op:"history_redact"}));return hookWarnings.push(...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"history_redact:history"})),hookWarnings}async function runHistoryRedact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),replacementInput=options.replacement??"",replacementIsDefault=replacementInput.length===0,replacement=replacementIsDefault?"[redacted]":replacementInput,rules=buildRedactionRules(options.literal,options.regex),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-redact",options,transform:snapshot=>buildHistoryRedactPlan({pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault},snapshot)})}function buildHistoryRedactPlan(params,snapshot){const{pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault}=params,historyEntries=snapshot.entries,integritySnapshot=inspectHistoryIntegrity(historyEntries),rewritten=rewriteHistoryEntries(historyEntries,rules,replacement),preexistingHashMismatches=integritySnapshot.hashMismatchesBefore+integritySnapshot.hashMismatchesAfter,dryRun=!!options.dryRun,changed=rewritten.replacements>0,warnings=[];preexistingHashMismatches>0&&warnings.push(`history_redact_preexisting_hash_mismatches:${preexistingHashMismatches}`),changed||warnings.push("history_redact_no_matches");const currentItem={raw:snapshot.loadedItem?.raw??null,path:subject.located?.itemPath??null,document:snapshot.loadedItem?.document??null},nextItem=resolveHistoryRedactNextItem({pmRoot,subject,settings,typeToFolder:typeRegistry.type_to_folder,finalDocument:rewritten.finalDocument}),itemChanged=(currentItem.path??null)!==(nextItem.path??null)||(currentItem.raw??null)!==(nextItem.raw??null),author=snapshot.author,redactionMessage=buildHistoryRedactMessage(options,rewritten),{rewrittenEntries,auditEntryAdded}=buildHistoryRedactEntries({rewritten,dryRun,changed,nextItemDocument:nextItem.document,author,message:redactionMessage});return{changed,rewrittenEntries,...createHistoryRedactTransaction({pmRoot,subject,settings,typeRegistry,currentItem,nextItem,author,rewrittenEntries}),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,patterns:{literal_count:rules.filter(rule=>rule.kind==="literal").length,regex_count:rules.filter(rule=>rule.kind==="regex").length,total_count:rules.length,replacement_is_default:replacementIsDefault},history:{path:subject.historyPath,entries_scanned:historyEntries.length,entries_changed:rewritten.entriesChanged,replacements:rewritten.replacements,hash_mismatches_before:integritySnapshot.hashMismatchesBefore,hash_mismatches_after:integritySnapshot.hashMismatchesAfter,preexisting_hash_mismatches:preexistingHashMismatches,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors},item:{existed_before:currentItem.path!==null,exists_after:nextItem.path!==null,path_before:currentItem.path,path_after:nextItem.path,changed:itemChanged},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const _testOnly={applyLiteralRule,applyRegexRule,buildRedactionRules,hasItemMetadata,normalizeRegexFlags,normalizeStringArrayInput,parseRegexRule,redactStringValue,redactUnknownValue};export{_testOnly,resolveHistorySubject2 as resolveHistorySubject,runHistoryRedact};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="57ff5a29-e0cf-5fb2-9068-b9e2ad45fab6")}catch{}})();import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{resolveHistorySubject as resolveHistorySubject2}from"./history/subject.js";import fs from"node:fs/promises";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{locateBridgedSegments}from"../core/history/bridge.js";import{writeFileAtomic}from"../core/fs/fs-utils.js";import{createHistoryEntry,resealHistoryRewrite,verifyHistoryRecordHash}from"../core/history/history.js";import{invalidateHistoryDriftCacheForPath}from"../core/history/drift-cache.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{EMPTY_REPLAY_DOCUMENT,collectBridgedInteriorIndexes,historyEntriesToRaw,replayHash,replayToItemDocument}from"../core/history/replay.js";import{applyHistoryPatch}from"../core/history/projection.js";import{canonicalDocument,serializeItemDocument}from"../core/item/item-format.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{nowIso}from"../core/shared/time.js";import{runActiveOnWriteHooks}from"../core/extensions/index.js";import{acquireItemMetadataDerivedIndexLock,refreshItemMetadataDerivedIndex}from"../core/store/item-metadata-cache.js";import{getItemPath}from"../core/store/paths.js";function normalizeStringArrayInput(value){return Array.isArray(value)?value:typeof value=="string"?[value]:[]}function normalizeRegexFlags(flags){const unique=[];for(const token of flags)unique.includes(token)||unique.push(token);return unique.includes("g")||unique.push("g"),unique.join("")}function invalidRegexRule(index,reason){return new PmCliError(`Invalid --regex value at --regex #${index}: ${reason}`,EXIT_CODE.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${index}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function parseRegexRule(spec,index=1){const trimmed=spec.trim();if(trimmed.length===0)throw invalidRegexRule(index,"provide a non-empty pattern.");let source=trimmed,flags="g";if(trimmed.startsWith("/")&&trimmed.length>1){const slashIndex=trimmed.lastIndexOf("/");let backslashes=0;for(let index2=slashIndex-1;index2>=0&&trimmed[index2]==="\\";index2--)backslashes++;slashIndex>0&&backslashes%2===0&&/^[dgimsuvy]*$/u.test(trimmed.slice(slashIndex+1))&&(source=trimmed.slice(1,slashIndex),flags=normalizeRegexFlags(trimmed.slice(slashIndex+1)))}if(source.length===0)throw invalidRegexRule(index,"an empty pattern is not allowed.");try{new RegExp(source,flags)}catch{throw invalidRegexRule(index,"provide a valid JavaScript regular expression.")}return{kind:"regex",source,flags}}function buildRedactionRules(literalInput,regexInput){const literalRules=[...new Set(normalizeStringArrayInput(literalInput).map(entry=>entry.trim()))].filter(entry=>entry.length>0).map(entry=>({kind:"literal",value:entry})),seen=new Set,regexRules=normalizeStringArrayInput(regexInput).flatMap((entry,index)=>{const spec=entry.trim();return seen.has(spec)?[]:(seen.add(spec),[parseRegexRule(spec,index+1)])}),rules=[...literalRules,...regexRules];if(rules.length===0)throw new PmCliError("history-redact requires at least one matcher via --literal or --regex.",EXIT_CODE.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return rules}function applyLiteralRule(value,literal,replacement){if(literal.length===0)return{value,replacements:0};let cursor=0,replacements=0;for(;cursor<=value.length;){const index=value.indexOf(literal,cursor);if(index===-1)break;replacements+=1,cursor=index+Math.max(1,literal.length)}return replacements===0?{value,replacements:0}:{value:value.split(literal).join(replacement),replacements}}function applyRegexRule(value,rule,replacement){const regex=new RegExp(rule.source,rule.flags),matches=[...value.matchAll(regex)];return matches.length===0?{value,replacements:0}:{value:value.replace(regex,replacement),replacements:matches.length}}function redactStringValue(value,rules,replacement){let next=value,replacements=0;for(const rule of rules){const result=rule.kind==="literal"?applyLiteralRule(next,rule.value,replacement):applyRegexRule(next,rule,replacement);next=result.value,replacements+=result.replacements}return{value:next,replacements}}function redactUnknownValue(value,rules,replacement){if(typeof value=="string")return redactStringValue(value,rules,replacement);if(Array.isArray(value)){let replacements=0;return{value:value.map(entry=>{const redacted=redactUnknownValue(entry,rules,replacement);return replacements+=redacted.replacements,redacted.value}),replacements}}if(typeof value=="object"&&value!==null){let replacements=0;const nextRecord={};for(const[key,entry]of Object.entries(value)){const redacted=redactUnknownValue(entry,rules,replacement);replacements+=redacted.replacements,nextRecord[key]=redacted.value}return{value:nextRecord,replacements}}return{value,replacements:0}}function redactHistoryPatch(patch,rules,replacement){let replacements=0;return{patch:patch.map(operation=>{if(!Object.prototype.hasOwnProperty.call(operation,"value"))return operation;const redactedValue=redactUnknownValue(operation.value,rules,replacement);return replacements+=redactedValue.replacements,redactedValue.replacements>0?{...operation,value:redactedValue.value}:operation}),replacements}}function inspectHistoryIntegrity(entries){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),hashMismatchesBefore=0,hashMismatchesAfter=0;for(let index=0;index<entries.length;index+=1){const entry=entries[index];replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.before_hash&&(hashMismatchesBefore+=1),replay=applyHistoryPatch(replay,entry.patch,index+1,entry.op),replayHash(replay,void 0,resolveHistoryHashAlgorithm(entry.hash_algorithm))!==entry.after_hash&&(hashMismatchesAfter+=1)}return{hashMismatchesBefore,hashMismatchesAfter,finalDocument:replay}}function redactHistoryEntry(entry,rules,replacement){let replacements=0,changed=!1,reanchorEvidenceRedacted=!1,nextMessage=entry.message;if(typeof entry.message=="string"){const redactedMessage=redactStringValue(entry.message,rules,replacement);nextMessage=redactedMessage.value,replacements+=redactedMessage.replacements,redactedMessage.replacements>0&&(changed=!0)}const redactedPatch=redactHistoryPatch(entry.patch,rules,replacement);replacements+=redactedPatch.replacements,changed||=redactedPatch.replacements>0;const nextReanchorEvidence=entry.reanchor_evidence?.map(evidence=>{const redactedEvidencePatch=evidence.patch?redactHistoryPatch(evidence.patch,rules,replacement):{patch:void 0,replacements:0},redactedEvidenceRecord=evidence.record?redactUnknownValue(evidence.record,rules,replacement):{value:void 0,replacements:0};replacements+=redactedEvidencePatch.replacements,replacements+=redactedEvidenceRecord.replacements;const evidenceChanged=redactedEvidencePatch.replacements>0||redactedEvidenceRecord.replacements>0;if(changed||=evidenceChanged,!evidenceChanged)return evidence;reanchorEvidenceRedacted=!0;const{patch:_sensitivePatch,record:_sensitiveRecord,record_hash:_priorRecordHash,record_hash_version:_priorRecordHashVersion,...digestOnlyEvidence}=evidence;return redactedEvidencePatch.replacements>0?digestOnlyEvidence:{...digestOnlyEvidence,patch:evidence.patch}});return{entry:{...entry,message:nextMessage,patch:redactedPatch.patch,...nextReanchorEvidence?{reanchor_evidence:nextReanchorEvidence}:{}},replacements,changed,reanchorEvidenceRedacted}}function rewriteHistoryEntries(entries,rules,replacement){let replay=structuredClone(EMPTY_REPLAY_DOCUMENT),entriesChanged=0,replacements=0;const rewrittenEntries=[],located=locateBridgedSegments(entries),unproven=[...located.unlocated,...located.undigested];if(unproven.length>0)throw new PmCliError(`history-redact refuses a stream whose bridge at record ${Math.min(...unproven)+1} does not prove its segment; repair the history first.`,EXIT_CODE.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});const inexact=collectBridgedInteriorIndexes(located.segments);for(let index=0;index<entries.length;index+=1){const original=entries[index],recordVerification=verifyHistoryRecordHash(original);if(!recordVerification.ok)throw new PmCliError(`history-redact refuses invalid immutable record ${index+1} (${recordVerification.error}).`,EXIT_CODE.GENERIC_FAILURE);const redacted=redactHistoryEntry(original,rules,replacement);replacements+=redacted.replacements,redacted.changed&&(entriesChanged+=1);const beforeHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm));replay=applyHistoryPatch(replay,redacted.entry.patch,index+1,redacted.entry.op);const afterHash=replayHash(replay,void 0,resolveHistoryHashAlgorithm(original.hash_algorithm)),{bridge:_dissolvedBridge,...unbridged}=redacted.entry;rewrittenEntries.push(resealHistoryRewrite(original,{...unbridged,...inexact.has(index)?{replay_inexact:!0}:{},before_hash:beforeHash,after_hash:afterHash},{retainPriorRecord:redacted.changed||_dissolvedBridge!==void 0,retainPriorRecordHash:!redacted.changed}))}return{entries:rewrittenEntries,finalDocument:replay,entriesChanged,replacements}}function hasItemMetadata(replay){return Object.keys(replay.metadata).length>0}function resolveHistoryRedactNextItem(params){if(!hasItemMetadata(params.finalDocument))return{raw:null,path:null,document:null};const canonical=canonicalDocument(replayToItemDocument(params.finalDocument),{schema:params.settings.schema});if(canonical.metadata.id!==params.subject.id)throw new PmCliError("history-redact would change the item id; narrow your patterns.",EXIT_CODE.USAGE);return{document:canonical,path:getItemPath(params.pmRoot,canonical.metadata.type,params.subject.id,"toon",params.typeToFolder),raw:serializeItemDocument(canonical,{format:"toon",schema:params.settings.schema})}}function buildHistoryRedactMessage(options,rewritten){return typeof options.message=="string"&&options.message.trim().length>0?options.message:`history-redact replaced ${rewritten.replacements} match(es) across ${rewritten.entriesChanged} entr${rewritten.entriesChanged===1?"y":"ies"}.`}function buildHistoryRedactEntries(params){const rewrittenEntries=[...params.rewritten.entries];if(params.dryRun||!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const finalDocument=params.nextItemDocument??replayToItemDocument(params.rewritten.finalDocument);return rewrittenEntries.push(createHistoryEntry({nowIso:nowIso(),author:params.author,op:"history_redact",before:finalDocument,after:finalDocument,message:params.message})),{rewrittenEntries,auditEntryAdded:!0}}function createHistoryRedactTransaction(params){let derivedIndexWarnings=[];return{applyRewrite:async({historyRawUnderLock})=>{const releaseDerivedIndexLock=await acquireItemMetadataDerivedIndexLock(params.pmRoot,params.author),affectedItemPaths=new Set;params.currentItem.path&&affectedItemPaths.add(params.currentItem.path),params.nextItem.path&&affectedItemPaths.add(params.nextItem.path);const itemSnapshots=new Map;params.currentItem.path&&params.currentItem.raw!==null&&itemSnapshots.set(params.currentItem.path,params.currentItem.raw);let rethrowReleaseFailure=()=>{};try{try{params.nextItem.path&&params.nextItem.raw!==null&&params.nextItem.raw!==params.currentItem.raw&&await writeFileAtomic(params.nextItem.path,params.nextItem.raw),params.currentItem.path&&(!params.nextItem.path||params.nextItem.path!==params.currentItem.path)&&await fs.rm(params.currentItem.path,{force:!0}),await writeFileAtomic(params.subject.historyPath,historyEntriesToRaw(params.rewrittenEntries))}catch(error){try{await rollbackHistoryRedactRewrite(params.subject.historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots)}finally{await invalidateHistoryDriftCacheForPath(params.subject.historyPath)}throw error}await invalidateHistoryDriftCacheForPath(params.subject.historyPath);const itemPath=params.nextItem.path??params.currentItem.path;itemPath&&(derivedIndexWarnings=await refreshItemMetadataDerivedIndex({pmRoot:params.pmRoot,preferredFormat:params.settings.item_format,typeToFolder:params.typeRegistry.type_to_folder,schema:params.settings.schema,itemPath,...params.currentItem.path?{previousItemPath:params.currentItem.path}:{},document:params.nextItem.document}))}finally{await releaseDerivedIndexLock().catch(error=>{rethrowReleaseFailure=()=>{throw error}})}rethrowReleaseFailure()},afterWrite:async()=>[...derivedIndexWarnings,...await runHistoryRedactWriteHooks(params.subject.historyPath,[params.nextItem.path,params.currentItem.path])]}}async function rollbackHistoryRedactRewrite(historyPath,historyRawUnderLock,affectedItemPaths,itemSnapshots){historyRawUnderLock===null?await fs.rm(historyPath,{force:!0}):await writeFileAtomic(historyPath,historyRawUnderLock);for(const itemPath of affectedItemPaths){const snapshot=itemSnapshots.get(itemPath);snapshot===void 0?await fs.rm(itemPath,{force:!0}):await writeFileAtomic(itemPath,snapshot)}}async function runHistoryRedactWriteHooks(historyPath,itemHookPaths){const hookWarnings=[],uniqueItemHookPaths=new Set(itemHookPaths.filter(itemPath=>itemPath!==null));for(const itemHookPath of uniqueItemHookPaths)hookWarnings.push(...await runActiveOnWriteHooks({path:itemHookPath,scope:"project",op:"history_redact"}));return hookWarnings.push(...await runActiveOnWriteHooks({path:historyPath,scope:"project",op:"history_redact:history"})),hookWarnings}async function runHistoryRedact(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),replacementInput=options.replacement??"",replacementIsDefault=replacementInput.length===0,replacement=replacementIsDefault?"[redacted]":replacementInput,rules=buildRedactionRules(options.literal,options.regex),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-redact",options,transform:snapshot=>buildHistoryRedactPlan({pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault},snapshot)})}function buildHistoryRedactPlan(params,snapshot){const{pmRoot,subject,settings,typeRegistry,options,rules,replacement,replacementIsDefault}=params,historyEntries=snapshot.entries,integritySnapshot=inspectHistoryIntegrity(historyEntries),rewritten=rewriteHistoryEntries(historyEntries,rules,replacement),preexistingHashMismatches=integritySnapshot.hashMismatchesBefore+integritySnapshot.hashMismatchesAfter,dryRun=!!options.dryRun,changed=rewritten.replacements>0,warnings=[];preexistingHashMismatches>0&&warnings.push(`history_redact_preexisting_hash_mismatches:${preexistingHashMismatches}`),changed||warnings.push("history_redact_no_matches");const currentItem={raw:snapshot.loadedItem?.raw??null,path:subject.located?.itemPath??null,document:snapshot.loadedItem?.document??null},nextItem=resolveHistoryRedactNextItem({pmRoot,subject,settings,typeToFolder:typeRegistry.type_to_folder,finalDocument:rewritten.finalDocument}),itemChanged=(currentItem.path??null)!==(nextItem.path??null)||(currentItem.raw??null)!==(nextItem.raw??null),author=snapshot.author,redactionMessage=buildHistoryRedactMessage(options,rewritten),{rewrittenEntries,auditEntryAdded}=buildHistoryRedactEntries({rewritten,dryRun,changed,nextItemDocument:nextItem.document,author,message:redactionMessage});return{changed,rewrittenEntries,...createHistoryRedactTransaction({pmRoot,subject,settings,typeRegistry,currentItem,nextItem,author,rewrittenEntries}),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,patterns:{literal_count:rules.filter(rule=>rule.kind==="literal").length,regex_count:rules.filter(rule=>rule.kind==="regex").length,total_count:rules.length,replacement_is_default:replacementIsDefault},history:{path:subject.historyPath,entries_scanned:historyEntries.length,entries_changed:rewritten.entriesChanged,replacements:rewritten.replacements,hash_mismatches_before:integritySnapshot.hashMismatchesBefore,hash_mismatches_after:integritySnapshot.hashMismatchesAfter,preexisting_hash_mismatches:preexistingHashMismatches,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors},item:{existed_before:currentItem.path!==null,exists_after:nextItem.path!==null,path_before:currentItem.path,path_after:nextItem.path,changed:itemChanged},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}const _testOnly={applyLiteralRule,applyRegexRule,buildRedactionRules,hasItemMetadata,normalizeRegexFlags,normalizeStringArrayInput,parseRegexRule,redactStringValue,redactUnknownValue};export{_testOnly,resolveHistorySubject2 as resolveHistorySubject,runHistoryRedact};
2
2
  //# sourceMappingURL=history-redact.js.map
@@ -3,11 +3,13 @@
3
3
  *
4
4
  * Implements the pm history repair command surface and its agent-facing runtime behavior.
5
5
  */
6
- import{type ItemRevisionConflictRowFields}from "./lifecycle/item-revision.js";import{type HistorySalvageReceipt}from "./history/salvage.js";import{type ReplayDocument}from "../core/history/replay.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{HistoryEntry}from "../types/index.js";import{type MergeDecisionReceipt}from "./merge/receipts.js";import{type ProvenanceNormalizationReceipt}from "./governance/provenance-health.js";
6
+ import{type ItemRevisionConflictRowFields}from "./lifecycle/item-revision.js";import{type HistorySalvageReceipt}from "./history/salvage.js";import{type HistoryRepairBridgeReceipt}from "./history/append-only-repair.js";import{type HistoryRepairReseedReceipt}from "./history/reseed.js";import{type ReplayDocument}from "../core/history/replay.js";import type{GlobalOptions}from "../core/shared/command-types.js";import type{HistoryEntry}from "../types/index.js";import{type MergeDecisionReceipt}from "./merge/receipts.js";import{type ProvenanceNormalizationReceipt}from "./governance/provenance-health.js";export type{HistoryRepairBridgeReceipt,HistoryRepairReseedReceipt,HistorySalvageReceipt,};
7
7
  /** Documents the history repair command options payload exchanged by command, SDK, and package integrations. */
8
8
  export interface HistoryRepairCommandOptions{
9
- /** Remove only an invalid trailing suffix after a verified prefix; never re-anchor or reconcile. */
9
+ /** Remove lines that cannot hold a record (a JSON null, boolean or number) and an invalid trailing suffix after a verified prefix; never re-anchor or reconcile. */
10
10
  salvageTail?:boolean;
11
+ /** Bridge chain breaks with one appended record instead of re-anchoring recorded entries, so every earlier line stays byte-identical (GH-1715). */
12
+ appendOnly?:boolean;
11
13
  /** Value that configures or reports dry run for this contract. */
12
14
  dryRun?:boolean;
13
15
  /** Value that configures or reports author for this contract. */
@@ -40,6 +42,10 @@ receipt:MergeDecisionReceipt;};}
40
42
  export interface HistoryRepairResult{
41
43
  /** Present when invalid trailing bytes were selected for explicit salvage. */
42
44
  salvage?:HistorySalvageReceipt;
45
+ /** Present when an append-only repair planned or appended a bridge over chain breaks. */
46
+ bridge?:HistoryRepairBridgeReceipt;
47
+ /** Present when the repair rebuilt a live item's absent or record-less stream from the on-disk item (pm-3os5p6). */
48
+ reseed?:HistoryRepairReseedReceipt;
43
49
  /** Stable identifier used to reference this record across commands and storage. */
44
50
  id:string;
45
51
  /** Value that configures or reports dry run for this contract. */
@@ -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]="a5461fc0-40f6-5b8b-a535-494c9d840ed1")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import{salvageHistoryTail}from"./history/salvage.js";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{realpath}from"node:fs/promises";import path from"node:path";import jsonPatch from"fast-json-patch";import{patchPathToChangedField}from"../core/history/history-diff.js";import{normalizeReplayPatchOps,reanchorHistoryEntries,replayHashVerificationCandidates,resolveHistoryRepairItemHashVersion,toReplayDocument,verifyHistoryChainWithVersion}from"../core/history/replay.js";import{sealHistoryRecord}from"../core/history/history.js";import{classifyHistoryEvent}from"../core/history/event-classification.js";import{scanHistoryDrift}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache}from"../core/history/drift-cache.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{sha256Hex,stableStringify}from"../core/shared/serialization.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{listAllItemMetadataWithBody}from"../core/store/item-store.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{isOriginalGitStateRestored}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,summarizeMergeReceipt}from"./merge/receipts.js";import{encodeItemScalarDecisionValue,hashItemScalarDecisionValue}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds,normalizeInvalidHistoryProvenance}from"./governance/provenance-health.js";function replayFieldValue(document,field){return field==="body"?document.body:document.metadata[field]}function isDiagnosticCollectionRow(field,value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const row=value;return field==="comments"?typeof row.created_at=="string"&&typeof row.author=="string"&&typeof row.text=="string":typeof row.path=="string"||field==="tests"&&typeof row.command=="string"}function diagnosticLinkedRecord(value){const result={...value};if(result.source_kind==="merge_union"&&(result.source_kind="local_mutation"),result.provenance!==null&&typeof result.provenance=="object"&&!Array.isArray(result.provenance)){const provenance={...result.provenance};provenance.source_kind==="merge_union"&&(provenance.source_kind="local_mutation"),result.provenance=provenance}return result}function diagnosticCollectionValue(field,value){if(!Array.isArray(value)||!["comments","docs","tests"].includes(field)||!value.every(row=>isDiagnosticCollectionRow(field,row)))return value;const rows=value.map(row=>field==="comments"?row:diagnosticLinkedRecord(row));return[...new Map(rows.map(row=>[stableStringify(row),row])).values()]}function isReplayValuePreserved(replayed,reconciled){if(replayed===void 0||Object.is(replayed,reconciled))return!0;if(Array.isArray(replayed)){if(!Array.isArray(reconciled))return!1;const matched=new Set;return replayed.every(expected=>{const index=reconciled.findIndex((candidate,candidateIndex)=>!matched.has(candidateIndex)&&isReplayValuePreserved(expected,candidate));return index<0?!1:(matched.add(index),!0)})}if(replayed===null||reconciled===null||typeof replayed!="object"||typeof reconciled!="object"||Array.isArray(reconciled))return!1;const reconciledRecord=reconciled;return Object.entries(replayed).every(([key,value])=>Object.hasOwn(reconciledRecord,key)&&isReplayValuePreserved(value,reconciledRecord[key]))}function collectReconciliationEvents(entries,fields){const remaining=new Set(fields),events=[];for(let index=entries.length-1;index>=0&&remaining.size>0;index-=1){const entry=entries[index],entryFields=new Set;for(const op of normalizeReplayPatchOps(entry.patch))entryFields.add(patchPathToChangedField(op.path)),op.from&&entryFields.add(patchPathToChangedField(op.from));const overlap=[...remaining].filter(field=>entryFields.has(field));if(overlap.length!==0){for(const field of overlap)remaining.delete(field);events.push({index:index+1,ts:entry.ts,author:entry.author,op:entry.op,fields:overlap.sort((left,right)=>left.localeCompare(right))})}}return events.reverse()}function analyzeReconciliationDiscard(entries,finalReplay,currentItemReplay){const reconcilePatch=jsonPatch.compare(finalReplay,currentItemReplay);if(reconcilePatch.length===0)return;const reconciledFields=new Set;for(const op of reconcilePatch)reconciledFields.add(patchPathToChangedField(op.path));const preservedFields=new Set([...reconciledFields].filter(field=>isReplayValuePreserved(diagnosticCollectionValue(field,replayFieldValue(finalReplay,field)),diagnosticCollectionValue(field,replayFieldValue(currentItemReplay,field))))),revertedFields=new Set([...reconciledFields].filter(field=>!preservedFields.has(field))),discardedEvents=collectReconciliationEvents(entries,revertedFields),preservedEvents=collectReconciliationEvents(entries,preservedFields),sortedReconciledFields=[...reconciledFields].sort((left,right)=>left.localeCompare(right)),sortedRevertedFields=[...revertedFields].sort((left,right)=>left.localeCompare(right)),sortedPreservedFields=[...preservedFields].sort((left,right)=>left.localeCompare(right)),discardedAuthors=[...new Set(discardedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right)),preservedAuthors=[...new Set(preservedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right));return{reconciled_field_count:reconciledFields.size,reconciled_fields:sortedReconciledFields,reverted_field_count:revertedFields.size,reverted_fields:sortedRevertedFields,discarded_events:discardedEvents,discarded_authors:discardedAuthors,preserved_field_count:preservedFields.size,preserved_fields:sortedPreservedFields,preserved_events:preservedEvents,preserved_authors:preservedAuthors,recovery_hint:discardedEvents.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function canonicalRealPath(value){try{return await realpath(value)}catch{return null}}async function verifyReceiptAgainstSnapshot(params){if(await canonicalRealPath(path.resolve(params.gitWorkspaceRoot,params.receipt.item_path))!==params.currentPath)return null;const declaredFields=[...new Set([...params.receipt.fields_from_theirs,...params.receipt.union_fields,...params.receipt.decisions.map(decision=>decision.field)])].sort(),hashes=params.receipt.merged_field_hashes;if(!hashes||declaredFields.length===0)return null;const hashFields=Object.keys(hashes).sort();if(declaredFields.length!==hashFields.length||declaredFields.some((field,index)=>field!==hashFields[index]))return null;const currentMetadata=params.currentItemReplay.metadata;return declaredFields.every(field=>{const value=field==="body"?params.currentItemReplay.body:currentMetadata[field];return[hashItemScalarDecisionValue(value),sha256Hex(stableStringify(encodeItemScalarDecisionValue(value)))].includes(hashes[field])})?{receipt:params.receipt,declaredFields}:null}async function verifyMergeReceiptProof(params){if(params.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(params.itemPath===null||params.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const itemReceipts=params.proof.receipts.filter(receipt=>receipt.item_id===params.id);if(itemReceipts.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const currentPath=await realpath(params.itemPath),trustedReceipts=[];for(const receipt of itemReceipts){const trusted=await verifyReceiptAgainstSnapshot({receipt,gitWorkspaceRoot:params.proof.gitWorkspaceRoot,currentPath,currentItemReplay:params.currentItemReplay});trusted&&trustedReceipts.push(trusted)}const trustedFields=new Set(trustedReceipts.flatMap(({declaredFields})=>declaredFields)),reconciliationFields=params.reconciliation?.reconciled_fields;return trustedReceipts.length>0&&(reconciliationFields===void 0||reconciliationFields.length>0&&reconciliationFields.every(field=>trustedFields.has(field)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:trustedReceipts.map(({receipt})=>receipt.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function assertHistoryRepairAbandonmentProof(proof,context,chainOk,reanchor){if(proof===void 0)return;const{receipt,gitWorkspaceRoot}=proof,canonicalPath=context.currentItemPath===null?null:path.relative(gitWorkspaceRoot,context.currentItemPath).split(path.sep).join("/");if(!chainOk||reanchor.entriesRehashed!==0||reanchor.entriesPatchRepaired!==0||context.matchedChainBefore!==!0||context.currentItemRawBeforeLock===null||canonicalPath!==receipt.item_path||receipt.operation===void 0||!await isOriginalGitStateRestored(gitWorkspaceRoot,receipt.item_path,receipt.operation,context.currentItemRawBeforeLock))throw new PmCliError("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function resolveHistoryRepairMergeEvidence(params){const requestedReceiptIds=new Set(params.options.mergeReceiptProof?.receipts.filter(receipt=>receipt.item_id===params.subjectId).map(receipt=>receipt.id)??[]),authoritativeReceiptEvidence=params.options.mergeReceiptProof?await inspectMergeReceiptEvidence(params.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:params.pmRoot}):void 0,subjectMergeReceipts=authoritativeReceiptEvidence?.receipts.filter(receipt=>receipt.item_id===params.subjectId&&requestedReceiptIds.has(receipt.id))??[];assertPortableMergeReceiptReferences(requestedReceiptIds,authoritativeReceiptEvidence,params.options.dryRun===!0);const mergeReceiptProof=params.options.mergeReceiptProof?await verifyMergeReceiptProof({proof:{...params.options.mergeReceiptProof,receipts:subjectMergeReceipts},id:params.subjectId,itemPath:params.itemReplayContext.currentItemPath,currentItemReplay:params.itemReplayContext.currentItemReplay,reconciliation:params.reconciliation}):void 0;if(mergeReceiptProof&&!mergeReceiptProof.trusted&&params.options.force!==!0)throw new PmCliError(`Merge receipt evidence for ${params.subjectId} does not prove the exact item snapshot (${mergeReceiptProof.reason}).`,EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const provenMergeReceipts=mergeReceiptProof?.trusted?subjectMergeReceipts.filter(receipt=>mergeReceiptProof.receipt_ids.includes(receipt.id)):[];return{mergeReceiptProof,effectiveAuditContext:provenMergeReceipts.length>0&&params.options.force!==!0?{...params.options.auditContext,merge:{receipts:provenMergeReceipts.map(summarizeMergeReceipt)}}:params.options.auditContext}}function describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion){const currentItemPath=subject.located?.itemPath??null,loadedItem=snapshot.loadedItem,historyEntries=snapshot.entries;if(!loadedItem)return{currentItemReplay:null,currentItemPath,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const currentItemReplay=toReplayDocument(loadedItem.document),lastOriginalAfterHash=historyEntries[historyEntries.length-1].after_hash;return{currentItemReplay,currentItemPath,matchedChainBefore:replayHashVerificationCandidates(currentItemReplay,itemHashVersion,resolveHistoryHashAlgorithm(historyEntries.at(-1)?.hash_algorithm)).includes(lastOriginalAfterHash),currentItemRawBeforeLock:loadedItem.raw,loadedItem}}function buildHistoryRepairMessage(params){return typeof params.message=="string"&&params.message.trim().length>0?params.message:`history-repair re-anchored ${params.entriesRehashed} entr${params.entriesRehashed===1?"y":"ies"}${params.entriesPatchRepaired>0?`, repaired ${params.entriesPatchRepaired} patch(es)`:""}${params.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function buildHistoryRepairEntries(params){const rewrittenEntries=[...params.reanchorEntries];if(!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const afterReplay=params.reconcileNeeded&&params.currentItemReplay?params.currentItemReplay:params.finalReplay,algorithm=resolveHistoryHashAlgorithm(params.reanchorEntries.at(-1)?.hash_algorithm),beforeHashes=replayHashVerificationCandidates(params.finalReplay,params.itemHashVersion,algorithm),previousAfterHash=params.reanchorEntries[params.reanchorEntries.length-1].after_hash,semanticIndex=beforeHashes.indexOf(previousAfterHash),afterHashes=replayHashVerificationCandidates(afterReplay,params.itemHashVersion,algorithm),auditEntry={hash_algorithm:algorithm,ts:nowIso(),author:params.author,op:params.auditOperation,patch:params.reconcileNeeded&&params.currentItemReplay?jsonPatch.compare(params.finalReplay,params.currentItemReplay):[],before_hash:beforeHashes[semanticIndex],after_hash:afterHashes[semanticIndex],message:params.message,...params.explicitItemHashVersion?{item_hash_version:params.itemHashVersion}:{},...params.auditContext===void 0?{}:{context:params.auditContext}};return rewrittenEntries.push(sealHistoryRecord({...auditEntry,event_class:classifyHistoryEvent(auditEntry)})),{rewrittenEntries,auditEntryAdded:!0}}function collectHistoryRepairWarnings(changed,skippedOps,reconciliation){const warnings=[];return changed||warnings.push("history_repair_no_changes"),skippedOps>0&&warnings.push(`history_repair_skipped_unresolvable_ops:${skippedOps}`),reconciliation&&reconciliation.discarded_events.length>0&&warnings.push(`history_repair_reconcile_discards_events:${reconciliation.discarded_events.length}`,`history_repair_discarded_authors:${reconciliation.discarded_authors.join(",")}`),warnings}async function runHistoryRepair(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);return options.salvageTail===!0?salvageHistoryTail({pmRoot,subject,settings,typeRegistry,options,author:resolveAuthor(options.author,settings.author_default)}):runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildHistoryRepairPlan({pmRoot,subject,options},snapshot)})}function shouldAppendForcedHistoryAudit(options,verifiedHistoryEntries,auditContext){const alreadyRecorded=(options.mergeAbandonmentProof!==void 0||options.mergeReceiptProof!==void 0&&options.force!==!0)&&auditContext!==void 0&&verifiedHistoryEntries.some(entry=>entry.record_hash_version!==void 0&&entry.op==="merge_reconcile"&&stableStringify(entry.context)===stableStringify(auditContext));return options.forceAuditEntry===!0&&!alreadyRecorded}async function buildHistoryRepairPlan(params,snapshot){const{pmRoot,subject,options}=params,historyEntries=snapshot.entries,chainBefore=snapshot.verification,chainVersionBefore=verifyHistoryChainWithVersion(historyEntries),provenanceNormalization=options.normalizeProvenance?normalizeInvalidHistoryProvenance(historyEntries):{entries:historyEntries,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},itemHashVersion=resolveHistoryRepairItemHashVersion(provenanceNormalization.entries),explicitVersionsBefore=new Set(provenanceNormalization.entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0)),reanchor=reanchorHistoryEntries(provenanceNormalization.entries,itemHashVersion),itemReplayContext=describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion);await assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor);const finalReplay=reanchor.finalDocument,finalReplayHashes=replayHashVerificationCandidates(finalReplay,itemHashVersion);let reconcileNeeded=!1;if(itemReplayContext.currentItemReplay!==null){const currentItemReplayHashes=replayHashVerificationCandidates(itemReplayContext.currentItemReplay,itemHashVersion);reconcileNeeded=!finalReplayHashes.some((hash,hashIndex)=>hash===currentItemReplayHashes[hashIndex])}const reconciliation=reconcileNeeded&&itemReplayContext.currentItemReplay?analyzeReconciliationDiscard(reanchor.entries,finalReplay,itemReplayContext.currentItemReplay):void 0,{mergeReceiptProof,effectiveAuditContext}=await resolveHistoryRepairMergeEvidence({options,pmRoot,subjectId:subject.id,itemReplayContext,reconciliation}),changed=[reanchor.entriesRehashed>0,reanchor.entriesPatchRepaired>0,reconcileNeeded,shouldAppendForcedHistoryAudit(options,reanchor.entries,effectiveAuditContext),provenanceNormalization.receipt.changed].some(Boolean),author=snapshot.author,dryRun=!!options.dryRun,repairMessage=buildHistoryRepairMessage({message:options.message,entriesRehashed:reanchor.entriesRehashed,entriesPatchRepaired:reanchor.entriesPatchRepaired,reconcileNeeded}),{rewrittenEntries,auditEntryAdded}=buildHistoryRepairEntries({reanchorEntries:reanchor.entries,changed,reconcileNeeded,currentItemReplay:itemReplayContext.currentItemReplay,finalReplay,author,message:repairMessage,auditOperation:options.auditOperation??"history_repair",auditContext:provenanceNormalization.receipt.changed?{...effectiveAuditContext,provenance_normalization:provenanceNormalization.receipt}:effectiveAuditContext,itemHashVersion,explicitItemHashVersion:reanchor.explicitItemHashVersion}),warnings=collectHistoryRepairWarnings(changed,reanchor.skippedOps,reconciliation);return{changed,rewrittenEntries,beforeWrite:async()=>assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,history:{path:subject.historyPath,entries_scanned:historyEntries.length,chain_drift_before:!chainBefore.ok,entries_rehashed:reanchor.entriesRehashed,entries_patch_repaired:reanchor.entriesPatchRepaired,converted_replace_to_add:reanchor.convertedReplaceToAdd,skipped_ops:reanchor.skippedOps,reconciled_with_item:reconcileNeeded,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors,item_hash_version_before:chainVersionBefore.item_hash_version??null,item_hash_version_after:itemHashVersion,version_disposition:explicitVersionsBefore.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:itemReplayContext.currentItemPath!==null,path:itemReplayContext.currentItemPath,matched_chain_before:itemReplayContext.matchedChainBefore},provenance_normalization:{requested:options.normalizeProvenance===!0,...provenanceNormalization.receipt},...reconciliation?{reconciliation}:{},...mergeReceiptProof?{merge_receipt_proof:mergeReceiptProof}:{},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}function assertHistoryRepairTarget(id,all){if(all&&id!==void 0)throw new PmCliError("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",EXIT_CODE.USAGE);if(!all&&id===void 0)throw new PmCliError("history-repair: provide an item <id> or pass --all to repair every drifted stream.",EXIT_CODE.USAGE)}async function runHistoryRepairAll(options,global2){if(options.salvageTail===!0)throw new PmCliError("Tail salvage requires one explicit item ID; --all is not supported.",EXIT_CODE.USAGE);const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),itemReadWarnings=[],items=await listAllItemMetadataWithBody(pmRoot,settings.item_format,typeRegistry.type_to_folder,itemReadWarnings,settings.schema,{forceSourceScan:!0}),drift=await scanHistoryDrift(pmRoot,items),invalidProvenanceIds=options.normalizeProvenance?await listInvalidProvenanceHistoryStreamIds(pmRoot):[],targetedIds=[...new Set([...drift.driftedItems,...invalidProvenanceIds])].sort((left,right)=>left.localeCompare(right)),streams=[],repairWarnings=[],totals={repaired:0,skipped_clean:0,failed:0};for(const driftedId of targetedIds)try{const result=await runHistoryRepair(driftedId,{...options,auditContext:options.auditContextById?.[driftedId],auditContextById:void 0,mergeReceiptProof:options.mergeReceiptProofById?.[driftedId]??options.mergeReceiptProof,mergeReceiptProofById:void 0},global2),outcome=result.changed?"repaired":"skipped_clean";totals[outcome]+=1,repairWarnings.push(...result.warnings.map(warning=>`${driftedId}:${warning}`)),streams.push({id:driftedId,outcome,entries_rehashed:result.history.entries_rehashed,entries_patch_repaired:result.history.entries_patch_repaired,reconciled_with_item:result.history.reconciled_with_item,...result.reconciliation?{reconciliation:result.reconciliation}:{},...result.merge_receipt_proof?{merge_receipt_proof:result.merge_receipt_proof}:{},warnings:result.warnings})}catch(error){totals.failed+=1,streams.push({id:driftedId,outcome:"failed",error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,pmRoot)})}return options.dryRun||await invalidateHistoryDriftCache(pmRoot),{all:!0,dry_run:!!options.dryRun,scanned_streams:items.length,drifted_streams:drift.driftedItems.length,provenance_invalid_streams:invalidProvenanceIds.length,streams,totals,warnings:[...new Set([...itemReadWarnings,...repairWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()}}export{analyzeReconciliationDiscard,assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll};
1
+ (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="59addcc3-b4f7-5d72-9be4-50192a780fb1")}catch{}})();import{itemRevisionConflictRowFields}from"./lifecycle/item-revision.js";import{salvageHistoryTail}from"./history/salvage.js";import{assertAppendOnlyStreamEncoding,assertRegularStreamEntry,buildAppendOnlyRepairPlan}from"./history/append-only-repair.js";import{buildHistoryReseedPlan}from"./history/reseed.js";import{reanchorOrRefuse}from"./history/reanchor-refusal.js";import{resolveHistoryHashAlgorithm}from"../core/history/digest.js";import{realpath}from"node:fs/promises";import path from"node:path";import jsonPatch from"fast-json-patch";import{patchPathToChangedField}from"../core/history/history-diff.js";import{normalizeReplayPatchOps,reanchorHistoryEntries,replayHashVerificationCandidates,resolveHistoryRepairItemHashVersion,toReplayDocument,verifyHistoryChainWithVersion,materializeBridgedSegments}from"../core/history/replay.js";import{sealHistoryRecord}from"../core/history/history.js";import{classifyHistoryEvent}from"../core/history/event-classification.js";import{scanHistoryDrift}from"../core/history/drift-scan.js";import{invalidateHistoryDriftCache}from"../core/history/drift-cache.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{sha256Hex,stableStringify}from"../core/shared/serialization.js";import{resolveAuthor}from"../core/shared/author.js";import{nowIso}from"../core/shared/time.js";import{listAllItemMetadataWithBody}from"../core/store/item-store.js";import{resolveHistoryWorkspace,resolveHistorySubject}from"./history/subject.js";import{runHistoryMaintenance}from"./history/maintenance.js";import{isOriginalGitStateRestored}from"./merge/receipt-operation.js";import{assertPortableMergeReceiptReferences,inspectMergeReceiptEvidence,summarizeMergeReceipt}from"./merge/receipts.js";import{encodeItemScalarDecisionValue,hashItemScalarDecisionValue}from"./merge/three-way.js";import{listInvalidProvenanceHistoryStreamIds,normalizeInvalidHistoryProvenance}from"./governance/provenance-health.js";function replayFieldValue(document,field){return field==="body"?document.body:document.metadata[field]}function isDiagnosticCollectionRow(field,value){if(value===null||typeof value!="object"||Array.isArray(value))return!1;const row=value;return field==="comments"?typeof row.created_at=="string"&&typeof row.author=="string"&&typeof row.text=="string":typeof row.path=="string"||field==="tests"&&typeof row.command=="string"}function diagnosticLinkedRecord(value){const result={...value};if(result.source_kind==="merge_union"&&(result.source_kind="local_mutation"),result.provenance!==null&&typeof result.provenance=="object"&&!Array.isArray(result.provenance)){const provenance={...result.provenance};provenance.source_kind==="merge_union"&&(provenance.source_kind="local_mutation"),result.provenance=provenance}return result}function diagnosticCollectionValue(field,value){if(!Array.isArray(value)||!["comments","docs","tests"].includes(field)||!value.every(row=>isDiagnosticCollectionRow(field,row)))return value;const rows=value.map(row=>field==="comments"?row:diagnosticLinkedRecord(row));return[...new Map(rows.map(row=>[stableStringify(row),row])).values()]}function isReplayValuePreserved(replayed,reconciled){if(replayed===void 0||Object.is(replayed,reconciled))return!0;if(Array.isArray(replayed)){if(!Array.isArray(reconciled))return!1;const matched=new Set;return replayed.every(expected=>{const index=reconciled.findIndex((candidate,candidateIndex)=>!matched.has(candidateIndex)&&isReplayValuePreserved(expected,candidate));return index<0?!1:(matched.add(index),!0)})}if(replayed===null||reconciled===null||typeof replayed!="object"||typeof reconciled!="object"||Array.isArray(reconciled))return!1;const reconciledRecord=reconciled;return Object.entries(replayed).every(([key,value])=>Object.hasOwn(reconciledRecord,key)&&isReplayValuePreserved(value,reconciledRecord[key]))}function collectReconciliationEvents(entries,fields){const remaining=new Set(fields),events=[];for(let index=entries.length-1;index>=0&&remaining.size>0;index-=1){const entry=entries[index],entryFields=new Set;for(const op of normalizeReplayPatchOps(entry.patch))entryFields.add(patchPathToChangedField(op.path)),op.from&&entryFields.add(patchPathToChangedField(op.from));const overlap=[...remaining].filter(field=>entryFields.has(field));if(overlap.length!==0){for(const field of overlap)remaining.delete(field);events.push({index:index+1,ts:entry.ts,author:entry.author,op:entry.op,fields:overlap.sort((left,right)=>left.localeCompare(right))})}}return events.reverse()}function analyzeReconciliationDiscard(entries,finalReplay,currentItemReplay){const reconcilePatch=jsonPatch.compare(finalReplay,currentItemReplay);if(reconcilePatch.length===0)return;const reconciledFields=new Set;for(const op of reconcilePatch)reconciledFields.add(patchPathToChangedField(op.path));const preservedFields=new Set([...reconciledFields].filter(field=>isReplayValuePreserved(diagnosticCollectionValue(field,replayFieldValue(finalReplay,field)),diagnosticCollectionValue(field,replayFieldValue(currentItemReplay,field))))),revertedFields=new Set([...reconciledFields].filter(field=>!preservedFields.has(field))),discardedEvents=collectReconciliationEvents(entries,revertedFields),preservedEvents=collectReconciliationEvents(entries,preservedFields),sortedReconciledFields=[...reconciledFields].sort((left,right)=>left.localeCompare(right)),sortedRevertedFields=[...revertedFields].sort((left,right)=>left.localeCompare(right)),sortedPreservedFields=[...preservedFields].sort((left,right)=>left.localeCompare(right)),discardedAuthors=[...new Set(discardedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right)),preservedAuthors=[...new Set(preservedEvents.map(event=>event.author))].sort((left,right)=>left.localeCompare(right));return{reconciled_field_count:reconciledFields.size,reconciled_fields:sortedReconciledFields,reverted_field_count:revertedFields.size,reverted_fields:sortedRevertedFields,discarded_events:discardedEvents,discarded_authors:discardedAuthors,preserved_field_count:preservedFields.size,preserved_fields:sortedPreservedFields,preserved_events:preservedEvents,preserved_authors:preservedAuthors,recovery_hint:discardedEvents.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function canonicalRealPath(value){try{return await realpath(value)}catch{return null}}async function verifyReceiptAgainstSnapshot(params){if(await canonicalRealPath(path.resolve(params.gitWorkspaceRoot,params.receipt.item_path))!==params.currentPath)return null;const declaredFields=[...new Set([...params.receipt.fields_from_theirs,...params.receipt.union_fields,...params.receipt.decisions.map(decision=>decision.field)])].sort(),hashes=params.receipt.merged_field_hashes;if(!hashes||declaredFields.length===0)return null;const hashFields=Object.keys(hashes).sort();if(declaredFields.length!==hashFields.length||declaredFields.some((field,index)=>field!==hashFields[index]))return null;const currentMetadata=params.currentItemReplay.metadata;return declaredFields.every(field=>{const value=field==="body"?params.currentItemReplay.body:currentMetadata[field];return[hashItemScalarDecisionValue(value),sha256Hex(stableStringify(encodeItemScalarDecisionValue(value)))].includes(hashes[field])})?{receipt:params.receipt,declaredFields}:null}async function verifyMergeReceiptProof(params){if(params.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(params.itemPath===null||params.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};const itemReceipts=params.proof.receipts.filter(receipt=>receipt.item_id===params.id);if(itemReceipts.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};const currentPath=await realpath(params.itemPath),trustedReceipts=[];for(const receipt of itemReceipts){const trusted=await verifyReceiptAgainstSnapshot({receipt,gitWorkspaceRoot:params.proof.gitWorkspaceRoot,currentPath,currentItemReplay:params.currentItemReplay});trusted&&trustedReceipts.push(trusted)}const trustedFields=new Set(trustedReceipts.flatMap(({declaredFields})=>declaredFields)),reconciliationFields=params.reconciliation?.reconciled_fields;return trustedReceipts.length>0&&(reconciliationFields===void 0||reconciliationFields.length>0&&reconciliationFields.every(field=>trustedFields.has(field)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:trustedReceipts.map(({receipt})=>receipt.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function assertHistoryRepairAbandonmentProof(proof,context,chainOk,reanchor){if(proof===void 0)return;const{receipt,gitWorkspaceRoot}=proof,canonicalPath=context.currentItemPath===null?null:path.relative(gitWorkspaceRoot,context.currentItemPath).split(path.sep).join("/");if(!chainOk||reanchor.entriesRehashed!==0||reanchor.entriesPatchRepaired!==0||context.matchedChainBefore!==!0||context.currentItemRawBeforeLock===null||canonicalPath!==receipt.item_path||receipt.operation===void 0||!await isOriginalGitStateRestored(gitWorkspaceRoot,receipt.item_path,receipt.operation,context.currentItemRawBeforeLock))throw new PmCliError("Restored-origin receipt evidence no longer proves the exact clean item snapshot.",EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",recovery:{suggested_retry:"pm merge reconcile --dry-run"}})}async function resolveHistoryRepairMergeEvidence(params){const requestedReceiptIds=new Set(params.options.mergeReceiptProof?.receipts.filter(receipt=>receipt.item_id===params.subjectId).map(receipt=>receipt.id)??[]),authoritativeReceiptEvidence=params.options.mergeReceiptProof?await inspectMergeReceiptEvidence(params.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:params.pmRoot}):void 0,subjectMergeReceipts=authoritativeReceiptEvidence?.receipts.filter(receipt=>receipt.item_id===params.subjectId&&requestedReceiptIds.has(receipt.id))??[];assertPortableMergeReceiptReferences(requestedReceiptIds,authoritativeReceiptEvidence,params.options.dryRun===!0);const mergeReceiptProof=params.options.mergeReceiptProof?await verifyMergeReceiptProof({proof:{...params.options.mergeReceiptProof,receipts:subjectMergeReceipts},id:params.subjectId,itemPath:params.itemReplayContext.currentItemPath,currentItemReplay:params.itemReplayContext.currentItemReplay,reconciliation:params.reconciliation}):void 0;if(mergeReceiptProof&&!mergeReceiptProof.trusted&&params.options.force!==!0)throw new PmCliError(`Merge receipt evidence for ${params.subjectId} does not prove the exact item snapshot (${mergeReceiptProof.reason}).`,EXIT_CODE.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});const provenMergeReceipts=mergeReceiptProof?.trusted?subjectMergeReceipts.filter(receipt=>mergeReceiptProof.receipt_ids.includes(receipt.id)):[];return{mergeReceiptProof,effectiveAuditContext:provenMergeReceipts.length>0&&params.options.force!==!0?{...params.options.auditContext,merge:{receipts:provenMergeReceipts.map(summarizeMergeReceipt)}}:params.options.auditContext}}function describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion){const currentItemPath=subject.located?.itemPath??null,loadedItem=snapshot.loadedItem,historyEntries=snapshot.entries;if(!loadedItem)return{currentItemReplay:null,currentItemPath,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};const currentItemReplay=toReplayDocument(loadedItem.document),lastOriginalAfterHash=historyEntries[historyEntries.length-1].after_hash;return{currentItemReplay,currentItemPath,matchedChainBefore:replayHashVerificationCandidates(currentItemReplay,itemHashVersion,resolveHistoryHashAlgorithm(historyEntries.at(-1)?.hash_algorithm)).includes(lastOriginalAfterHash),currentItemRawBeforeLock:loadedItem.raw,loadedItem}}function buildHistoryRepairMessage(params){return typeof params.message=="string"&&params.message.trim().length>0?params.message:`history-repair re-anchored ${params.entriesRehashed} entr${params.entriesRehashed===1?"y":"ies"}${params.entriesPatchRepaired>0?`, repaired ${params.entriesPatchRepaired} patch(es)`:""}${params.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function buildHistoryRepairEntries(params){const rewrittenEntries=[...params.reanchorEntries];if(!params.changed)return{rewrittenEntries,auditEntryAdded:!1};const afterReplay=params.reconcileNeeded&&params.currentItemReplay?params.currentItemReplay:params.finalReplay,algorithm=resolveHistoryHashAlgorithm(params.reanchorEntries.at(-1)?.hash_algorithm),beforeHashes=replayHashVerificationCandidates(params.finalReplay,params.itemHashVersion,algorithm),previousAfterHash=params.reanchorEntries[params.reanchorEntries.length-1].after_hash,semanticIndex=beforeHashes.indexOf(previousAfterHash),afterHashes=replayHashVerificationCandidates(afterReplay,params.itemHashVersion,algorithm),auditEntry={hash_algorithm:algorithm,ts:nowIso(),author:params.author,op:params.auditOperation,patch:params.reconcileNeeded&&params.currentItemReplay?jsonPatch.compare(params.finalReplay,params.currentItemReplay):[],before_hash:beforeHashes[semanticIndex],after_hash:afterHashes[semanticIndex],message:params.message,...params.explicitItemHashVersion?{item_hash_version:params.itemHashVersion}:{},...params.auditContext===void 0?{}:{context:params.auditContext}};return rewrittenEntries.push(sealHistoryRecord({...auditEntry,event_class:classifyHistoryEvent(auditEntry)})),{rewrittenEntries,auditEntryAdded:!0}}function collectHistoryRepairWarnings(changed,skippedOps,reconciliation){const warnings=[];return changed||warnings.push("history_repair_no_changes"),skippedOps>0&&warnings.push(`history_repair_skipped_unresolvable_ops:${skippedOps}`),reconciliation&&reconciliation.discarded_events.length>0&&warnings.push(`history_repair_reconcile_discards_events:${reconciliation.discarded_events.length}`,`history_repair_discarded_authors:${reconciliation.discarded_authors.join(",")}`),warnings}async function runHistoryRepair(id,options,global2){const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),subject=await resolveHistorySubject(pmRoot,id,settings,typeRegistry.type_to_folder);if(options.salvageTail===!0){if(options.appendOnly===!0)throw new PmCliError("Tail salvage cannot be combined with other repair modes.",EXIT_CODE.USAGE);return salvageHistoryTail({pmRoot,subject,settings,typeRegistry,options,author:resolveAuthor(options.author,settings.author_default)})}if(options.appendOnly===!0)return assertAppendOnlyRepairOptions(options),await assertAppendOnlyStreamEncoding(subject.id,subject.historyPath),runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildAppendOnlyRepairPlan(subject,options,snapshot,{analyzeDiscard:analyzeReconciliationDiscard,collectWarnings:collectHistoryRepairWarnings}),reseed:(snapshot,stream)=>buildHistoryReseedPlan(subject,options,snapshot,stream)});const reseed=isEvidenceBoundRepair(options)?void 0:async(snapshot,stream)=>(await assertRegularStreamEntry(subject.id,subject.historyPath),buildHistoryReseedPlan(subject,options,snapshot,stream));return runHistoryMaintenance({pmRoot,subject,settings,typeRegistry,operation:"history-repair",options,transform:snapshot=>buildHistoryRepairPlan({pmRoot,subject,options},snapshot),reseed})}function isEvidenceBoundRepair(options){return[options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById,options.mergeAbandonmentProof].some(value=>value!==void 0&&value!==!1)}function assertAppendOnlyRepairOptions(options){if([options.normalizeProvenance,options.auditOperation,options.auditContext,options.auditContextById,options.forceAuditEntry,options.mergeReceiptProof,options.mergeReceiptProofById,options.mergeAbandonmentProof].some(value=>value!==void 0&&value!==!1))throw new PmCliError("An append-only repair cannot be combined with other repair modes.",EXIT_CODE.USAGE)}function shouldAppendForcedHistoryAudit(options,verifiedHistoryEntries,auditContext){const alreadyRecorded=(options.mergeAbandonmentProof!==void 0||options.mergeReceiptProof!==void 0&&options.force!==!0)&&auditContext!==void 0&&verifiedHistoryEntries.some(entry=>entry.record_hash_version!==void 0&&entry.op==="merge_reconcile"&&stableStringify(entry.context)===stableStringify(auditContext));return options.forceAuditEntry===!0&&!alreadyRecorded}function normalizeHistoryProvenancePreservingBridges(entries){const probe=normalizeInvalidHistoryProvenance(entries);return probe.receipt.changed?normalizeInvalidHistoryProvenance(materializeBridgedSegments(entries)):probe}async function buildHistoryRepairPlan(params,snapshot){const{pmRoot,subject,options}=params,historyEntries=snapshot.entries,chainBefore=snapshot.verification,chainVersionBefore=verifyHistoryChainWithVersion(historyEntries),provenanceNormalization=options.normalizeProvenance?normalizeHistoryProvenancePreservingBridges(historyEntries):{entries:historyEntries,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},itemHashVersion=resolveHistoryRepairItemHashVersion(provenanceNormalization.entries),explicitVersionsBefore=new Set(provenanceNormalization.entries.map(entry=>entry.item_hash_version).filter(version=>version!==void 0)),reanchor=reanchorOrRefuse(subject.id,provenanceNormalization.entries,()=>reanchorHistoryEntries(provenanceNormalization.entries,itemHashVersion,{callerMarksBridgeCoverage:provenanceNormalization.receipt.changed})),itemReplayContext=describeHistoryRepairItemReplay(subject,snapshot,itemHashVersion);await assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor);const finalReplay=reanchor.finalDocument,finalReplayHashes=replayHashVerificationCandidates(finalReplay,itemHashVersion);let reconcileNeeded=!1;if(itemReplayContext.currentItemReplay!==null){const currentItemReplayHashes=replayHashVerificationCandidates(itemReplayContext.currentItemReplay,itemHashVersion);reconcileNeeded=!finalReplayHashes.some((hash,hashIndex)=>hash===currentItemReplayHashes[hashIndex])}const reconciliation=reconcileNeeded&&itemReplayContext.currentItemReplay?analyzeReconciliationDiscard(reanchor.entries,finalReplay,itemReplayContext.currentItemReplay):void 0,{mergeReceiptProof,effectiveAuditContext}=await resolveHistoryRepairMergeEvidence({options,pmRoot,subjectId:subject.id,itemReplayContext,reconciliation}),changed=[reanchor.entriesRehashed>0,reanchor.entriesPatchRepaired>0,reanchor.entriesResealed>0,reconcileNeeded,shouldAppendForcedHistoryAudit(options,reanchor.entries,effectiveAuditContext),provenanceNormalization.receipt.changed].some(Boolean),author=snapshot.author,dryRun=!!options.dryRun,repairMessage=buildHistoryRepairMessage({message:options.message,entriesRehashed:reanchor.entriesRehashed,entriesPatchRepaired:reanchor.entriesPatchRepaired,reconcileNeeded}),{rewrittenEntries,auditEntryAdded}=buildHistoryRepairEntries({reanchorEntries:reanchor.entries,changed,reconcileNeeded,currentItemReplay:itemReplayContext.currentItemReplay,finalReplay,author,message:repairMessage,auditOperation:options.auditOperation??"history_repair",auditContext:provenanceNormalization.receipt.changed?{...effectiveAuditContext,provenance_normalization:provenanceNormalization.receipt}:effectiveAuditContext,itemHashVersion,explicitItemHashVersion:reanchor.explicitItemHashVersion}),warnings=collectHistoryRepairWarnings(changed,reanchor.skippedOps,reconciliation);return{changed,rewrittenEntries,beforeWrite:async()=>assertHistoryRepairAbandonmentProof(options.mergeAbandonmentProof,itemReplayContext,chainBefore.ok,reanchor),report:({verification:historyVerify,warnings:writeWarnings})=>({id:subject.id,dry_run:dryRun,changed,history:{path:subject.historyPath,entries_scanned:historyEntries.length,chain_drift_before:!chainBefore.ok,entries_rehashed:reanchor.entriesRehashed,entries_patch_repaired:reanchor.entriesPatchRepaired,converted_replace_to_add:reanchor.convertedReplaceToAdd,skipped_ops:reanchor.skippedOps,reconciled_with_item:reconcileNeeded,audit_entry_added:auditEntryAdded,verify_ok:historyVerify.ok,verify_errors:historyVerify.errors,item_hash_version_before:chainVersionBefore.item_hash_version??null,item_hash_version_after:itemHashVersion,version_disposition:explicitVersionsBefore.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:itemReplayContext.currentItemPath!==null,path:itemReplayContext.currentItemPath,matched_chain_before:itemReplayContext.matchedChainBefore},provenance_normalization:{requested:options.normalizeProvenance===!0,...provenanceNormalization.receipt},...reconciliation?{reconciliation}:{},...mergeReceiptProof?{merge_receipt_proof:mergeReceiptProof}:{},warnings:[...new Set([...warnings,...writeWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()})}}function assertHistoryRepairTarget(id,all){if(all&&id!==void 0)throw new PmCliError("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",EXIT_CODE.USAGE);if(!all&&id===void 0)throw new PmCliError("history-repair: provide an item <id> or pass --all to repair every drifted stream.",EXIT_CODE.USAGE)}async function runHistoryRepairAll(options,global2){if(options.salvageTail===!0)throw new PmCliError("Tail salvage requires one explicit item ID; --all is not supported.",EXIT_CODE.USAGE);const{pmRoot,settings,typeRegistry}=await resolveHistoryWorkspace(global2.path),itemReadWarnings=[],items=await listAllItemMetadataWithBody(pmRoot,settings.item_format,typeRegistry.type_to_folder,itemReadWarnings,settings.schema,{forceSourceScan:!0}),drift=await scanHistoryDrift(pmRoot,items),invalidProvenanceIds=options.normalizeProvenance?await listInvalidProvenanceHistoryStreamIds(pmRoot):[],targetedIds=[...new Set([...drift.driftedItems,...invalidProvenanceIds])].sort((left,right)=>left.localeCompare(right)),streams=[],repairWarnings=[],totals={repaired:0,skipped_clean:0,failed:0};for(const driftedId of targetedIds)try{const result=await runHistoryRepair(driftedId,{...options,auditContext:options.auditContextById?.[driftedId],auditContextById:void 0,mergeReceiptProof:options.mergeReceiptProofById?.[driftedId]??options.mergeReceiptProof,mergeReceiptProofById:void 0},global2),outcome=result.changed?"repaired":"skipped_clean";totals[outcome]+=1,repairWarnings.push(...result.warnings.map(warning=>`${driftedId}:${warning}`)),streams.push({id:driftedId,outcome,entries_rehashed:result.history.entries_rehashed,entries_patch_repaired:result.history.entries_patch_repaired,reconciled_with_item:result.history.reconciled_with_item,...result.reconciliation?{reconciliation:result.reconciliation}:{},...result.merge_receipt_proof?{merge_receipt_proof:result.merge_receipt_proof}:{},warnings:result.warnings})}catch(error){totals.failed+=1,streams.push({id:driftedId,outcome:"failed",error:error instanceof Error?error.message:String(error),...await itemRevisionConflictRowFields(error,pmRoot)})}return options.dryRun||await invalidateHistoryDriftCache(pmRoot),{all:!0,dry_run:!!options.dryRun,scanned_streams:items.length,drifted_streams:drift.driftedItems.length,provenance_invalid_streams:invalidProvenanceIds.length,streams,totals,warnings:[...new Set([...itemReadWarnings,...repairWarnings])].sort((left,right)=>left.localeCompare(right)),generated_at:nowIso()}}export{analyzeReconciliationDiscard,assertHistoryRepairTarget,runHistoryRepair,runHistoryRepairAll};
2
2
  //# sourceMappingURL=history-repair.js.map