/** * 混合原生编辑、已确认操作、undo/redo 和异步尺寸修正的历史恢复规划器。 * 先由已保存 transition 反推出私有起点,再按事件顺序应用用户审阅选择,生成新 history 与 replay 证据。 * 所有游标/栈/entry 变化都留在本次规划对象内;外层 coordinator 成功后才统一发布 Root,不能直接修改现有 history。 */ import type { Change, Document, FieldChange, HistoryEntry, HistoryState, Id, OperationIntent, Registry } from '../canvas-core/types.ts'; import { applyHistoryTransition, describeHistoryTransition } from '../canvas-core/history-transition.ts'; import { invert } from '../canvas-core/document.ts'; import { planHistoryChanges } from '../canvas-core/history.ts'; import { equal, fault, freeze, readMap } from '../canvas-core/values.ts'; import { rebaseIntent, type IntentContext } from './change-rebase.ts'; import { sameHistory, type HistoryReplay, type HistoryReplayEvent } from './history-replay.ts'; import { historyEventSource } from './history-event-source.ts'; import type { EngineSnapshot } from './contracts.ts'; import { planCreationSize, validateCreationSizeEffect } from '../canvas-core/creation-size-plan.ts'; /** Native history events are reconstructed from evidence; all cursors remain private until the recovery root is accepted. */ /** 一次同步恢复规划会话:从已验证 snapshot/pending 取事件,逆向条件回放历史元数据得到 baseline。 * 不逆向执行文档 changes 或访问服务;document 的 fresh 重规划由 project/rebaseIntent 处理。 * 调用方按事件顺序为每项 project→分配替代操作→accept,最后 finish→evidence,并同一个恢复 Root 采纳。 * snapshot/registry 沿用不可变输入;方法会改变私有游标/history,失败不自动回滚或封闭会话,应丢弃本次规划对象。 * limit 约束重建 user 贡献时的 undo 容量,不代表所有外部事件证据都可截断;无异步预算/网络/持久化。 */ export function createHistoryJournalRecovery(snapshot:EngineSnapshot,pending:readonly OperationIntent[],registry:Registry,limit:number){ if(!Number.isSafeInteger(limit)||limit<1)throw fault('invalid_history_limit'); // historyEventSource 可能提供 adoption 虚拟事件;给每项补私有 before/after 以便核对后续取舍。 const pendingIds=new Set(pending.map(intent=>intent.id)),source=historyEventSource(snapshot,pending); const events=source.events.map(event=>({...event,before:undefined as HistoryState|undefined,after:undefined as HistoryState|undefined})); let history=snapshot.history,adopted:HistoryState|undefined; try{ // 逆序条件回放元数据,确定原区间起点;adoption 还要确认其 anchor 与整体 transition 一致。 for(let index=events.length-1;index>=0;index--){const event=events[index];if(source.adoption&&index===source.adoption.count-1)adopted=history;event.after=history;history=applyHistoryTransition(history,event.transition,'reverse');event.before=history;} if(source.adoption){if(!adopted)throw fault('recovery_history_transition_conflict');const before=applyHistoryTransition(adopted,source.adoption.transition,'reverse'),expected=applyHistoryTransition(before,source.adoption.replay.anchor,'forward');if(!sameHistory(history,expected))throw fault('recovery_history_transition_conflict');} }catch{throw fault('recovery_history_transition_conflict');} // 新证据的所有 transition 都绑定即将发布的同一个 Root revision,不冒充多次服务提交。 const baseline=history,replayEvents:HistoryReplayEvent[]=[],adoptionRevision=snapshot.rootRevision+1; /** 记录私有 history 的一次真实变化;关联操作即使 no-op 也留证据,调整事件不造 operation。 */ function recordStep(before:HistoryState,entryId:Id|undefined,operationId?:Id){const transition=describeHistoryTransition(before,history,adoptionRevision,entryId,!!operationId);if(transition)replayEvents.push(operationId?freeze({kind:'operation' as const,operationId,transition}):freeze({kind:'adjustment' as const,transition}));} // events 保存证据中的原始 before/after,history 是随取舍变化的新候选,不能混成同一份状态。 // next 指下个事件;touched 标本轮审阅项,retired 解释清 redo/容量淘汰/无效果删除;remap/sizeHistory 仅服务当前 project→accept。 let next=0;const touched=new Set(),retired=new Set();let remap:((change:Change)=>Change)|undefined; let sizeHistory: HistoryState | undefined; /** 捕获双栈数组和 entry 表成员为新只读 history,不暴露私有可变容器。 */ const state=(undo:readonly Id[],redo:readonly Id[],entries:ReadonlyMap)=>Object.freeze({undo:freeze([...undo]),redo:freeze([...redo]),entries:readMap(entries)}); /** 只按下个 record 的 intent.id 检查位置,不逐字段比对外来 intent;协调器须传同快照中受信意图。 * 不能按网络返回顺序跳过/交换,adjustment 和已结算事件由 advance 先消费。 */ const eventFor=(intent:OperationIntent)=>{const event=events[next];if(!event||event.record?.intent.id!==intent.id)throw fault('recovery_history_event_order',[intent.id]);return event;}; /** 审阅已有分组项:纯字段按 target ID/代次/field 的最后 after 判断 fresh 是否还保留该贡献。 * 最终值/存在性匹配才保留该字段的原整条链,不将每条都压成一次最后值;不匹配就移除此字段贡献。 * geometry/path 的 owner 还须与原 ACK 一致;含 owner/端点或整记录的前缀必须可完整逆向规划。 * 只返回 changes,不移动文档;不在这里恢复被远端覆盖的旧字段值。 */ function reviewPrefix(entry:HistoryEntry,document:Document):readonly Change[]{ const prefix=entry.changes; if(prefix.every(change=>change.kind==='field'&&!['ownerCanvasId','source','target'].includes(change.field))){ // 同目标/代次/字段以最后 after 判断是否仍有效,再保留该字段原有链,不能抹掉组内其它手动修改。 const fields=prefix as readonly FieldChange[],last=new Map();const key=(change:FieldChange)=>JSON.stringify([change.target.id,change.target.incarnation,change.field]);for(const change of fields)last.set(key(change),change); for(const change of fields)if(['geometry','path'].includes(change.field)&&document.elements.get(change.target.id)?.ownerCanvasId!==snapshot.runtime.acknowledged.elements.get(change.target.id)?.ownerCanvasId)throw fault('recovery_history_prefix_conflict',[entry.id]); const keep=new Set([...last].filter(([,change])=>{const target=document.elements.get(change.target.id);if(target?.incarnation!==change.target.incarnation)return false;const field=change.field.startsWith('data.')?change.field.slice(5):undefined,value=field===undefined?(target as unknown as Record)[change.field]:target.data[field]??null;return equal(value,change.after)&&(field===undefined||Object.hasOwn(target.data,field)===(change.afterPresent??true));}).map(([key])=>key));return fields.filter(change=>keep.has(key(change))); } try{planHistoryChanges(document,invert(prefix),registry);}catch{throw fault('recovery_history_prefix_conflict',[entry.id]);}return prefix; } /** 无 replacement 的 user 贡献不追加新 changes;首次触及且还在 undo 的旧项才审阅原前缀。 * 空前缀退休并从两栈移除,非空则保留;无 entryId(history=false)、已 touched 或不在 undo 时不重复处理。 */ function skipUser(intent:OperationIntent,document:Document){ const event=eventFor(intent),id=event.transition.entryId;if(!id)return;const entry=history.entries.get(id); if(!entry){retired.add(id);return;} if(touched.has(id)||!history.undo.includes(id))return; const changes=reviewPrefix(entry,document),entries=new Map(history.entries);if(changes.length)entries.set(id,freeze({...entry,changes}));else{entries.delete(id);retired.add(id);}history=state(history.undo.filter(key=>entries.has(key)),history.redo.filter(key=>entries.has(key)),entries); } /** 以原事件 after 的 label/group 等元数据加入贡献,append 必须与原有分组/栈顶关系相容。 * 先清 redo 并标 retired;pending 首次触及旧项才审阅 fresh 前缀,随后追加本轮 changes/operationId。 * 新项压 undo,超过 limit 从栈底淘汰;已退休原组可按证据重新建立,不借旧 ID 静默改写任意已有项。 */ function addUser(intent:OperationIntent,changes:readonly Change[],operationId:Id,pending:boolean,document?:Document){ const event=eventFor(intent),id=event.transition.entryId;if(!id)return; const original=event.after!.entries.get(id);if(!original)throw fault('recovery_history_transition_conflict',[id]); const entries=new Map(history.entries),undo=[...history.undo];for(const removed of history.redo){entries.delete(removed);retired.add(removed);} const prior=entries.get(id),originalAppend=event.before!.entries.has(id),appending=!!prior; if(originalAppend&&(!prior&&!retired.has(id)||prior&&undo.at(-1)!==id)||!originalAppend&&prior)throw fault('recovery_history_traversal_order',[id]); // 第一次触及已有分组项时按 fresh document 审阅前缀,之后只追加本轮已经规划的变化。 const prefix=pending&&prior&&!touched.has(id)&&document?reviewPrefix(prior,document):prior?.changes??[]; const {changes:_changes,operationIds:_operations,...metadata}=original; entries.set(id,freeze({...metadata,changes:[...prefix,...changes],operationIds:[...(prior?.operationIds??[]),operationId]}));if(!appending)undo.push(id);while(undo.length>limit){const removed=undo.shift()!;entries.delete(removed);retired.add(removed);}history=state(undo,[],entries);retired.delete(id);if(pending)touched.add(id); } /** 重放无服务操作的历史调整,只支持有明确证据的项修正/删除;不允许无根据重新排列双栈。 */ function applyAdjustment(event:typeof events[number]){ const before=event.before!,after=event.after!,removed=new Set([...before.entries.keys()].filter(id=>!after.entries.has(id))); if(!equal(after.undo,before.undo.filter(id=>!removed.has(id)))||!equal(after.redo,before.redo.filter(id=>!removed.has(id))))throw fault('recovery_history_adjustment_conflict'); const entries=new Map(history.entries); for(const patch of event.transition.entries){const current=entries.get(patch.id),original=before.entries.get(patch.id),desired=after.entries.get(patch.id);if(equal(current,desired))continue;if(!original||!equal(current,original))throw fault('recovery_history_adjustment_conflict',[patch.id]);if(desired)entries.set(patch.id,desired);else{entries.delete(patch.id);retired.add(patch.id);}} history=state(history.undo.filter(id=>entries.has(id)),history.redo.filter(id=>entries.has(id)),entries); } /** 消费目标 pending 之前(或 finish 时剩余)的 adjustment 与已有结果事件,逐个 recordStep/推进 next。 * 带 record 者不得是另一个 pending,resolution 只接受 applied/elided;不在此独立校验 phase/服务回执真实性。 * 默认尺寸、user、undo/redo 分别走专用逻辑,其它 origin 明确拒绝;不会重发这些已结算操作。 */ function advance(intent?:OperationIntent){ while(next>(); /** 仅同 ID 且代次确实改变时登记,不能把两个不同元素意外映为同一生命周期。 */ const pair=(a:{id:Id;incarnation:number}|null,b:{id:Id;incarnation:number}|null)=>{if(a&&b&&a.id===b.id&&a.incarnation!==b.incarnation){const values=maps.get(a.id)??new Map();values.set(a.incarnation,b.incarnation);maps.set(a.id,values);}}; before.changes.forEach((a,index)=>{const b=after.changes[index];if(a.kind==='field'&&b?.kind==='field')pair(a.target,b.target);else if(a.kind==='element'&&b?.kind==='element'){pair(a.before,b.before);pair(a.after,b.after);}}); /** 仅重写 field target 与整元素 before/after 代次,不修改 canvas 记录或冻结服务请求。 */ return(change:Change):Change=>{const record=(value:T|null)=>value?{...value,incarnation:maps.get(value.id)?.get(value.incarnation)??value.incarnation}:null;if(change.kind==='field')return freeze({...change,target:record(change.target)!});if(change.kind==='element')return freeze({...change,before:record(change.before),after:record(change.after)});return change;}; } /** 已有 applied/elided 结果的遍历必须命中当前栈顶,且原事件前后变化与审阅后的正向效果精确对应。 * 只重建历史移动/关联并为其它项重映代次,不执行已结算文档变化,也不改旧 operation/request。 */ function addConfirmedTraversal(intent:OperationIntent){ const event=eventFor(intent),id=event.transition.entryId,undo=[...history.undo],redo=[...history.redo],source=intent.origin==='undo'?undo:redo,destination=intent.origin==='undo'?redo:undo; if(!id||source.at(-1)!==id)throw fault('recovery_history_traversal_order',id?[id]:[]); const entry=history.entries.get(id)!,before=event.before!.entries.get(id),after=event.after!.entries.get(id),changes=intent.origin==='undo'?invert(intent.changes):intent.changes; // An applied action is a fact. Its history may move only if the reviewed prefix still denotes that exact forward effect. if(!before||!after||!equal(entry.changes,before.changes)||!equal(changes,after.changes))throw fault('recovery_history_confirmed_traversal_conflict',[id]); // restore 映射只推进其它可遍历历史;原操作/请求的历史身份和字节保持原样。 const entries=new Map(history.entries),map=incarnationRemap(before,after);for(const[otherId,other]of entries)if(otherId!==id)entries.set(otherId,freeze({...other,changes:other.changes.map(map)})); entries.set(id,freeze({...entry,changes,operationIds:[...entry.operationIds,intent.id]}));source.pop();destination.push(id);history=state(undo,redo,entries); } /** 已结算默认尺寸使用原 transition 的 entry changes 修正,要求该事件两栈不动、当前 changes/label/group 仍匹配。 * 不再次运行尺寸文档命令;只给所属创建项追加逻辑操作关联,其它被修正项保留各自关联。 */ function addConfirmedSize(intent: OperationIntent) { validateCreationSizeEffect(intent.historyEffect); const event = eventFor(intent), entries = new Map(history.entries); if (event.transition.entryId !== intent.historyEffect.entryId || !equal(event.before!.undo, event.after!.undo) || !equal(event.before!.redo, event.after!.redo)) throw fault('recovery_history_size_conflict'); for (const patch of event.transition.entries) { const current = entries.get(patch.id), before = event.before!.entries.get(patch.id), after = event.after!.entries.get(patch.id); if (!current || !before || !after || !equal(current.changes, before.changes) || current.label !== before.label || current.groupId !== before.groupId) throw fault('recovery_history_size_conflict', [patch.id]); entries.set(patch.id, freeze({ ...current, changes: after.changes, operationIds: patch.id === intent.historyEffect.entryId ? [...current.operationIds, intent.id] : current.operationIds })); } history = state(history.undo, history.redo, entries); } return{ /** 先 advance 结算前置事件,再为当前 pending 返回 fresh 文档候选;自身对应的历史贡献等 accept。 * 尺寸专用 planner 暂存 sizeHistory;touched 遍历按审阅后的 entry 重新规划,其它 keep 意图走 rebaseIntent。 * 丢弃返回零文档变化但仍可能校验原遍历可行性;空 changes 直接返回,不消费事件游标。 * 此调用可能已经改变前置私有 history,不能当无状态 query,也不能并发交错不同项的 project/accept。 */ project(document:Document,intent:OperationIntent,context:IntentContext,keep:boolean){ if(!intent.changes.length)return{document,changes:[] as readonly Change[]};advance(intent);const event=eventFor(intent),id=event.transition.entryId;remap=undefined;sizeHistory=undefined; // 尺寸效果通过专用 planner 重算 history;keep=false 不发布旧自动尺寸。 if (intent.historyEffect) { validateCreationSizeEffect(intent.historyEffect); if (!keep) return { document, changes: [] as readonly Change[] }; const effect = intent.historyEffect, plan = planCreationSize(document, history, registry, effect.entryId, effect.target, effect.size); sizeHistory = plan.history; return { document: plan.document, changes: plan.changes }; } // 遍历项必须核对新栈顶;被审阅改过的 entry 使用新变化计划,不能套用旧 inverse 覆盖 fresh 内容。 if(['undo','redo'].includes(intent.origin)){ if(!id)throw fault('recovery_history_traversal_order');const entry=history.entries.get(id); if(!keep){ if(!entry){if(!retired.has(id))throw fault('recovery_history_traversal_order',[id]);return{document,changes:[] as readonly Change[]};} const direction=history.undo.at(-1)===id?'undo':history.redo.at(-1)===id?'redo':undefined; if(direction)try{planHistoryChanges(document,direction==='undo'?invert(entry.changes):entry.changes,registry);}catch{throw fault('recovery_history_traversal_conflict',[id]);} return{document,changes:[] as readonly Change[]}; } if(!entry||history[intent.origin==='undo'?'undo':'redo'].at(-1)!==id)throw fault('recovery_history_traversal_order',[id]); if(touched.has(id)){try{const planned=planHistoryChanges(document,intent.origin==='undo'?invert(entry.changes):entry.changes,registry);remap=planned.remap;return planned;}catch{throw fault('recovery_history_traversal_conflict',[id]);}} remap=incarnationRemap(event.before!.entries.get(id)!,event.after!.entries.get(id)!); } // 普通保留意图经显式审阅后重新规划;丢弃返回零文档变化,不自行伪造成功回执。 return keep?rebaseIntent(document,intent,context,registry):{document,changes:[] as readonly Change[]}; }, /** 在协调器确定 replacement 后,按当前 project 结果更新私有历史、记 replay 并将 next 加一。 * replacement/keep/before/after 须与此前 project 配对;接口不独立比对该语义或自动生成新 ID/账本记录。 * user 按贡献维护组,尺寸采用暂存计划,keep 遍历有剩余效果才移到另一栈,否则退休该项。 * 不发布 Root、不持久化审计;调用失败后不要继续使用可能已部分推进的同一规划会话。 */ accept(intent:OperationIntent,replacement:OperationIntent|undefined,keep:boolean,before:Document,after:Document){ if(!intent.changes.length)return;const previous=history,event=eventFor(intent),id=event.transition.entryId; if (intent.historyEffect) { if (keep) { if (!sizeHistory) throw fault('recovery_history_size_conflict'); // 自动尺寸沿用原创建历史,只有确实产生 replacement 才追加新逻辑操作关联。 const entries = new Map(sizeHistory.entries), owner = entries.get(intent.historyEffect.entryId); if (!owner) throw fault('recovery_history_size_conflict'); if (replacement) entries.set(owner.id, freeze({ ...owner, operationIds: [...owner.operationIds, replacement.id] })); for (const [entryId, entry] of entries) if (!equal(entry, history.entries.get(entryId))) touched.add(entryId); history = state(sizeHistory.undo, sizeHistory.redo, entries); } } // 普通编辑按贡献维护分组;没有 replacement 时仍保留可证明的旧前缀。 else if(intent.origin==='user'){if(replacement)addUser(intent,replacement.changes,replacement.id,true,before);else skipUser(intent,before);} // 新遍历还要能从 after 反向回放;无剩余效果则退休而非制造虚假 redo。 else if(['undo','redo'].includes(intent.origin)&&id&&keep){ const entries=new Map(history.entries),undo=[...history.undo],redo=[...history.redo],source=intent.origin==='undo'?undo:redo,destination=intent.origin==='undo'?redo:undo,entry=entries.get(id)!;source.pop(); if(replacement){const changes=intent.origin==='undo'?invert(replacement.changes):replacement.changes;try{planHistoryChanges(after,intent.origin==='undo'?changes:invert(changes),registry);}catch{throw fault('recovery_history_traversal_conflict',[id]);}if(remap)for(const[otherId,other]of entries)if(otherId!==id)entries.set(otherId,freeze({...other,changes:other.changes.map(remap)}));entries.set(id,freeze({...entry,changes,operationIds:[...entry.operationIds,replacement.id]}));destination.push(id);}else{entries.delete(id);retired.add(id);} history=state(undo,redo,entries);touched.add(id); } recordStep(previous,id,replacement?.id);next++; }, /** 消费剩余已结算/调整事件并返回候选 history;未处理 pending 会拒绝,不静默跳过。 * 不设置 finished 锁或自动保存,协调器仍需整体校验并原子采纳文档/历史/账本。 */ finish(){advance();return history;}, /** 完成 finish 后作为最后步骤输出证据:原 history→baseline 的 anchor,加本次有序元数据增量。 * 所有 transition 绑定 snapshot.rootRevision+1,不表示多次服务写入或已持久化成功。 * freeze 直接包含 replayEvents 数组,会冻结该会话的事件缓冲;提前调用后不能再向它追加规划事件。 */ evidence():HistoryReplay{return freeze({version:1 as const,anchor:describeHistoryTransition(snapshot.history,baseline,adoptionRevision,undefined,true)!,events:replayEvents});}, }; }