Retain acknowledged structural prefixes during conflict recovery

This commit is contained in:
2026-11-08 03:04:39 +08:00
parent f741a4830f
commit 78194e9f95
5 changed files with 137 additions and 20 deletions
+22
View File
@@ -0,0 +1,22 @@
import type { Change, Document, ElementRecord, Id, Registry } from './types.ts';
import { applyChanges, validateDocument } from './document.ts';
import { freeze } from './values.ts';
/** Pure history execution, also used to validate recovery proposals before publication. */
export function planHistoryChanges(initial:Document,planned:readonly Change[],registry:Registry){
const generations=new Map<Id,Map<number,number>>();
const incarnation=(id:Id,value:number)=>{const mapping=generations.get(id);while(mapping?.has(value))value=mapping.get(value)!;return value;};
const remap=(change:Change):Change=>{
if(change.kind==='field'){const next=incarnation(change.target.id,change.target.incarnation);return next===change.target.incarnation?change:freeze({...change,target:{...change.target,incarnation:next}});}
if(change.kind==='element'){const record=(value:ElementRecord|null)=>value?{...value,incarnation:incarnation(value.id,value.incarnation)}:null;return freeze({...change,before:record(change.before),after:record(change.after)});}
return change;
};
let document=initial;const changes:Change[]=[];
for(const original of planned){
let change=remap(original);
if(change.kind==='element'&&!change.before&&change.after){const dead=document.tombstones.get(change.id);if(dead!==undefined&&change.after.incarnation<=dead){const mapping=generations.get(change.id)??new Map<number,number>();mapping.set(change.after.incarnation,dead+1);generations.set(change.id,mapping);change=remap(change);}}
document=applyChanges(document,[change]);changes.push(change);
}
validateDocument(document,registry);
return{document,changes:freeze(changes),remap,restored:generations.size>0};
}