Reconcile AI output ownership without duplicating or rewinding elements

This commit is contained in:
2026-11-08 01:26:33 +08:00
parent 77fddb9f1a
commit 0c7fae6e32
5 changed files with 107 additions and 41 deletions
+6 -3
View File
@@ -209,15 +209,18 @@ export async function openProjectEngine(options: EngineOptions) {
const conflicts=new Map(previous.conflicts);
try {
for(const event of page.events) {
if(event.seq<=current.cursor || event.type!=='step.applied')continue;
if(event.seq<=current.cursor || event.type!=='step.applied'&&!(event.type==='step.output'&&event.model&&typeof event.model==='object'&&!Array.isArray(event.model)&&event.model.complete===true))continue;
const canvas=event.board_id as Id,version=event.canvas_version as number;
if(!Number.isSafeInteger(version)||version<1)throw fault('invalid_run_response');
// A later document receipt already includes this event; never rewind its participant.
if(version<=(versions.get(canvas)??0))continue;
if([...previous.ledger.requests.values()].some(request=>request.phase!=='resolved'&&request.canvasIds.includes(canvas)))throw fault('run_waiting_for_receipts');
const model=event.model as {[key:string]:Json}|undefined,context=model?.complete===true,participants=context?Object.keys(model.versions as {[key:string]:Json}):[canvas];
if([...previous.ledger.requests.values()].some(request=>request.phase!=='resolved'&&request.canvasIds.some(id=>participants.includes(id))))throw fault('run_waiting_for_receipts');
if(!options.runs)throw fault('run_interpreter_unavailable');
const snapshot={...root,runtime:{...previous,acknowledged,versions}};
const proposal=options.runs.canonical(event,snapshot);acknowledged=proposal.document;versions=proposal.versions;
const proposal=options.runs.canonical(event,snapshot);
for(const record of previous.ledger.operations.values())if(record.phase!=='resolved')for(const change of record.intent.changes)if(change.kind==='field'&&(change.field==='geometry'||change.field==='path')){const before=acknowledged.elements.get(change.target.id),after=proposal.document.elements.get(change.target.id);if(before&&after&&before.ownerCanvasId!==after.ownerCanvasId)throw fault('ownership_conflict',[change.target.id]);}
acknowledged=proposal.document;versions=proposal.versions;
}
const document=replayPending(acknowledged,previous.ledger,options.registry),runs=new Map(previous.runs);
const appliedOutputIds=[...new Set([...(current.appliedOutputIds??[]),...page.events.filter(event=>event.type==='step.applied'&&typeof event.output_id==='string').map(event=>event.output_id as Id)])];
+21
View File
@@ -150,3 +150,24 @@ export function mergeFoundryModel(value: unknown, participants: readonly Id[], s
const document = createDocument(previous.projectId, [...canvases.values()], [...elements.values()], tombstones); validateDocument(document, registry);
return Object.freeze({ document, versions: readMap(serverVersions) });
}
/** A relocated result carries a complete ownership context. Retain later ACKs
* per canvas; validate the combined tree before publishing any ownership change. */
export function mergeFoundryRunContext(value: unknown, snapshot: EngineSnapshot, registry: Registry, rootId: Id) {
const chunk=modelChunk(value);
if(!chunk.complete||chunk.projectId!==rootId)throw fault('invalid_run_context');
const previous=snapshot.runtime.acknowledged,canvases=new Map(previous.canvases),elements=new Map(previous.elements),tombstones=new Map(previous.tombstones),serverVersions=new Map(snapshot.runtime.versions),replace=new Set<Id>();
for(const [id,version] of chunk.versions)if(version>=(snapshot.runtime.versions.get(id)??0)){
if(version===snapshot.runtime.versions.get(id)){
const incoming=chunk.elements.filter(element=>element.ownerCanvasId===id).sort((a,b)=>a.id.localeCompare(b.id)),known=[...previous.elements.values()].filter(element=>element.ownerCanvasId===id).sort((a,b)=>a.id.localeCompare(b.id));
if(!equal(chunk.canvases.find(canvas=>canvas.id===id),previous.canvases.get(id))||!equal(incoming,known))throw fault('same_version_context_conflict',[id]);
}
replace.add(id);serverVersions.set(id,version);canvases.delete(id);
}
for(const canvas of chunk.canvases)if(replace.has(canvas.id))canvases.set(canvas.id,canvas);
for(const [id,element] of elements)if(replace.has(element.ownerCanvasId))elements.delete(id);
for(const element of chunk.elements)if(replace.has(element.ownerCanvasId)){if(elements.has(element.id))throw fault('canonical_scope_mismatch',[element.id]);elements.set(element.id,element);}
for(const [id,generation] of chunk.tombstones)tombstones.set(id,Math.max(tombstones.get(id)??0,generation));
const document=createDocument(rootId,[...canvases.values()],[...elements.values()],tombstones);validateDocument(document,registry);
return Object.freeze({document,versions:readMap(serverVersions)});
}
+11 -5
View File
@@ -4,7 +4,7 @@ import { validateRunInput } from '../canvas-runtime/runs.ts';
import type { RunEvent, RunPage, RunPort, RunRecord, RunStatus, RunModel } from '../canvas-runtime/runs.ts';
import type { FrozenRequest } from '../canvas-runtime/ledger.ts';
import type { OperationStatus } from '../canvas-runtime/scheduler.ts';
import { mergeFoundryModel, type ServiceTransport } from './foundry.ts';
import { mergeFoundryModel, mergeFoundryRunContext, type ServiceTransport } from './foundry.ts';
const uuid = /^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i;
const statuses = new Set(['queued','running','succeeded','failed','conflict','cancelled','partially_succeeded']);
@@ -101,7 +101,9 @@ export function createFoundryRuns(options: {workspaceId: Id; rootId: Id; registr
return{runId:request.runId,runStatus:body.run_status as RunStatus};
}
if(request.kind!=='run.apply'||body.node_id!==raw.node_id||body.output_id!==raw.output_id||body.board_id!==raw.target_canvas_id||body.target_incarnation!==raw.target_incarnation||body.document_format_version!==1)throw fault('run_identity_mismatch');
const proposal=mergeFoundryModel(body.model,[raw.target_canvas_id as Id],snapshot,options.registry,options.rootId),target=proposal.document.elements.get(raw.node_id as Id),version=integer(body.canvas_version,1);
const model=object(body.model),board=raw.target_canvas_id as Id;
const scoped=model.complete===true?{...model,complete:false,canvases:array(model.canvases).filter(value=>object(value).id===board),elements:array(model.elements).filter(value=>object(value).ownerCanvasId===board),versions:{[board]:object(model.versions)[board]},tombstones:{},removedCanvasIds:[]}:model;
const proposal=mergeFoundryModel(scoped,[board],snapshot,options.registry,options.rootId),target=proposal.document.elements.get(raw.node_id as Id),version=integer(body.canvas_version,1);
if(proposal.versions.get(raw.target_canvas_id as Id)!==version||version!==request.expectedVersions[raw.target_canvas_id as Id]+1||target?.incarnation!==raw.target_incarnation||target?.ownerCanvasId!==raw.target_canvas_id)throw fault('run_identity_mismatch');
return{runId:request.runId,outputId:raw.output_id as Id,proposal};
},
@@ -114,7 +116,10 @@ export function createFoundryRuns(options: {workspaceId: Id; rootId: Id; registr
if(event.run_id!==run.id||integer(event.seq,1)!==cursor+1||typeof event.type!=='string')throw fault('invalid_run_response');cursor++;
if(event.type==='step.applied'||event.type==='step.output'){
const step=steps.find(step=>step.step_id===event.step_id);
if(!step||step.board_id!==event.board_id||step.node_id!==event.node_id||event.type==='step.applied'&&(step.target_incarnation!==event.target_incarnation||event.document_format_version!==1))throw fault('run_identity_mismatch');
if(!step||step.node_id!==event.node_id)throw fault('run_identity_mismatch');
const relocated=step.board_id!==event.board_id;
if(relocated&&(!uuid.test(string(event.board_id))||event.origin_board_id!==step.board_id||event.canonical_root!==options.rootId||event.target_incarnation!==step.target_incarnation))throw fault('run_identity_mismatch');
if(event.type==='step.applied'&&(step.target_incarnation!==event.target_incarnation||event.document_format_version!==1||relocated&&object(event.model).complete!==true))throw fault('run_identity_mismatch');
}
}
if(integer(body.next_seq)!==cursor||events.length>100||body.has_more&&events.length===0)throw fault('invalid_run_response');
@@ -122,8 +127,9 @@ export function createFoundryRuns(options: {workspaceId: Id; rootId: Id; registr
},
canonical(event,snapshot){
const board=string(event.board_id),version=integer(event.canvas_version,1),current=snapshot.runtime.acknowledged.elements.get(string(event.node_id));
if(event.type!=='step.applied'||!current||current.ownerCanvasId!==board||current.incarnation!==event.target_incarnation)throw fault('run_identity_mismatch');
const proposal=mergeFoundryModel(event.model,[board],snapshot,options.registry,options.rootId),target=proposal.document.elements.get(string(event.node_id));
const context=object(event.model).complete===true;
if(!['step.applied','step.output'].includes(event.type)||!current||current.incarnation!==event.target_incarnation||!context&&current.ownerCanvasId!==board||context&&event.canonical_root!==options.rootId)throw fault('run_identity_mismatch');
const proposal=context?mergeFoundryRunContext(event.model,snapshot,options.registry,options.rootId):mergeFoundryModel(event.model,[board],snapshot,options.registry,options.rootId),target=proposal.document.elements.get(string(event.node_id));
if(proposal.versions.get(board)!==version||!target||target.ownerCanvasId!==board||target.incarnation!==event.target_incarnation)throw fault('run_identity_mismatch');
return proposal;
},