import { prepareLargeRecord, validateAttachment, attachmentRecord, writeBudgetBytes, MAX_XRPC_REQUEST_BYTES } from './large-record.mjs'; const encoder = new TextEncoder(); const tidAlphabet = '234567abcdefghijklmnopqrstuvwxyz'; const allowedCollections = new Set(['org.tangled.track.ticket', 'org.tangled.feed.comment', 'org.tangled.label.definition']); const retryStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); export function canonical(value) { if (Array.isArray(value)) return value.map(canonical); if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])); return value; } export async function digest(value) { const bytes = await crypto.subtle.digest('SHA-256', encoder.encode(JSON.stringify(canonical(value)))); return [...new Uint8Array(bytes)].map(byte => byte.toString(16).padStart(2, '0')).join(''); } export class MigrationFailure extends Error { constructor(code, phase, operationId, retryable = false) { super(`${phase} failed for ${operationId}: ${code}`); this.name = 'MigrationFailure'; Object.assign(this, { code, phase, operationId, retryable }); } } // Only structured status/code data crosses the adapter boundary. Raw provider // errors can contain request bodies, OAuth details, or reflected credentials. export function safeFailure(error, phase, operationId) { if (error instanceof MigrationFailure) return error; const status = Number.isInteger(error?.status) && error.status >= 100 && error.status <= 599 ? error.status : undefined; const providerCode = typeof error?.code === 'string' && /^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/.test(error.code) ? error.code : undefined; const failure = new MigrationFailure(providerCode ?? (status ? `HTTP_${status}` : 'NETWORK_OR_ADAPTER_ERROR'), phase, operationId, !status || retryStatuses.has(status)); if (status) failure.status = status; return failure; } function recordURI(plan, op) { return `at://${plan.repoDid}/${op.collection}/${op.rkey}`; } function withoutEditorFields(record) { if (!record || typeof record !== 'object' || Array.isArray(record)) return record; return Object.fromEntries(Object.entries(record).filter(([key]) => !['x-tngl-editor', 'x-tngl-change'].includes(key))); } function ensureReceipt(receipt, expectedURI) { if (receipt?.uri !== expectedURI || typeof receipt.cid !== 'string' || !receipt.cid) throw new Error('Invalid record receipt'); return { uri: receipt.uri, cid: receipt.cid, ...(receipt['x-tngl-change'] ? { change: receipt['x-tngl-change'] } : {}) }; } function attestationKey(startedAt, index) { let n = (BigInt(Date.parse(startedAt)) * 1000n + BigInt(index)) << 10n; if (n < 0n || n > 0xffffffffffffffffn) throw new Error('Invalid migration timestamp'); let result = ''; for (let i = 0; i < 13; i++) { result = tidAlphabet[Number(n & 31n)] + result; n >>= 5n; } return result; } export function operationAttestationKey(plan, checkpoint, operationId, final = false) { const index = plan.operations.findIndex(op => op.id === operationId); const generation = checkpoint.retryGenerations?.[operationId] ?? 0; if (index < 0 || !Number.isInteger(generation) || generation < 0 || generation > 1000) throw new Error('Invalid retry generation'); return attestationKey(checkpoint.startedAt, index + generation * 2 * plan.operations.length + (final ? plan.operations.length : 0)); } export function attachmentAttestationKey(plan, checkpoint, operationId) { const index = plan.operations.findIndex(op => op.id === operationId); if (index < 0) throw new Error('Unknown attachment operation'); return attestationKey(checkpoint.startedAt, plan.operations.length * 2002 + index); } export function newCheckpoint(plan, startedAt = new Date().toISOString()) { if (!Number.isFinite(Date.parse(startedAt))) throw new Error('Invalid migration timestamp'); return { version: 1, repoDid: plan.repoDid, planHash: plan.planHash, startedAt, entries: {}, inFlight: {}, retryGenerations: {} }; } export async function validateRuntimeCheckpoint(plan, checkpoint) { if (!plan || plan.version !== 1 || !/^did:[a-z]+:[^\s/?#]+$/.test(plan.repoDid ?? '') || !Array.isArray(plan.operations)) throw new Error('Invalid migration plan'); const ids = new Set(), recordKeys = new Set(); for (const op of plan.operations) { const key = `${op.collection}/${op.rkey}`; if (typeof op.id !== 'string' || ids.has(op.id) || !allowedCollections.has(op.collection) || op.record?.$type !== op.collection || !/^[A-Za-z0-9._~:-]{1,512}$/.test(op.rkey ?? '') || ['.', '..'].includes(op.rkey) || recordKeys.has(key) || !Array.isArray(op.dependencies)) throw new Error('Invalid migration operation'); if (op.requiresLatestSubject && (op.collection !== 'org.tangled.feed.comment' || !op.subjectUri?.startsWith(`at://${plan.repoDid}/org.tangled.track.ticket/`))) throw new Error('Invalid comment subject'); ids.add(op.id); recordKeys.add(key); } for (const op of plan.operations) if (op.dependencies.some(id => !ids.has(id))) throw new Error('Unknown migration dependency'); const { planHash, ...content } = plan; if (await digest(content) !== planHash) throw new Error('Plan hash mismatch'); if (checkpoint.version !== 1 || checkpoint.repoDid !== plan.repoDid || (checkpoint.planHash && checkpoint.planHash !== planHash)) throw new Error('Checkpoint destination or plan differs'); if (!checkpoint.entries || typeof checkpoint.entries !== 'object' || Array.isArray(checkpoint.entries) || !checkpoint.inFlight || typeof checkpoint.inFlight !== 'object' || Array.isArray(checkpoint.inFlight)) throw new Error('Invalid checkpoint'); if (!Number.isFinite(Date.parse(checkpoint.startedAt))) throw new Error('Invalid checkpoint timestamp'); const operations = new Map(plan.operations.map((op, index) => [op.id, { op, index }])); if (checkpoint.retryGenerations !== undefined && (!checkpoint.retryGenerations || typeof checkpoint.retryGenerations !== 'object' || Array.isArray(checkpoint.retryGenerations))) throw new Error('Invalid retry generations'); for (const [id, generation] of Object.entries(checkpoint.retryGenerations ?? {})) { if (!operations.has(id) || !Number.isInteger(generation) || generation < 0 || generation > 1000) throw new Error('Invalid retry generation'); } if (checkpoint.attachments !== undefined && (!checkpoint.attachments || typeof checkpoint.attachments !== 'object' || Array.isArray(checkpoint.attachments))) throw new Error('Invalid attachments'); for (const [id, proof] of Object.entries(checkpoint.attachments ?? {})) { const op = operations.get(id)?.op; if (!op || !mintedCollection(op.collection)) throw new Error('Unknown attachment operation'); await validateAttachment(plan, checkpoint, op, proof, attachmentAttestationKey(plan, checkpoint, id), digest); } const validateAttestation = (value, index) => { if (value.attestationRkey !== operationAttestationKey(plan, checkpoint, plan.operations[index].id) || value.attestationCreatedAt !== checkpoint.startedAt) throw new Error('Checkpoint attestation metadata differs'); }; for (const [id, entry] of Object.entries(checkpoint.entries)) { const found = operations.get(id), op = found?.op; if (!op || entry.recordHash !== op.recordHash || entry.sourceHash !== op.sourceHash || !['written', 'attested', 'attested-open', 'state-written'].includes(entry.stage)) throw new Error('Checkpoint source differs'); validateAttestation(entry, found.index); if (entry.protocol === 'server-minted') { if (!mintedCollection(op.collection)) throw new Error('Invalid minted collection'); actualReceipt(entry, plan, op); const needsFinal = op.collection === 'org.tangled.track.ticket' && op.record.state !== 'open'; if (['attested-open', 'state-written'].includes(entry.stage) && !needsFinal) throw new Error('Invalid state update stage'); if (needsFinal && (entry.finalAttestationRkey !== operationAttestationKey(plan, checkpoint, op.id, true) || entry.finalAttestationCreatedAt !== checkpoint.startedAt || !entry.initialCid)) throw new Error('Invalid final attribution metadata'); const proof = checkpoint.attachments?.[op.id]; if (proof && proof.stage !== 'ArtifactAttested') throw new Error('Attachment is not attested'); const expected = proof ? attachmentRecord(structuredClone(op.record), proof) : structuredClone(op.record); if (op.requiresLatestSubject) expected.subject = { $type: 'com.atproto.repo.strongRef', uri: subjectURI(plan, checkpoint, op), cid: entry.subjectCid }; if (await digest(expected) !== await digest(entry.desiredRecord)) throw new Error('Checkpoint desired payload differs'); if (!entry.actualRecord || (await digest(semantic(entry.actualRecord)) !== await digest(semantic(expected)) && await digest(semantic(entry.actualRecord)) !== await digest(semantic({ ...expected, state: 'open' })))) throw new Error('Checkpoint actual payload differs'); if (['attested', 'state-written'].includes(entry.stage) && await digest(semantic(entry.actualRecord)) !== await digest(semantic(expected))) throw new Error('Final record state differs'); continue; } ensureReceipt(entry, recordURI(plan, op)); const written = op.requiresLatestSubject ? { ...op.record, subject: { $type: 'com.atproto.repo.strongRef', uri: op.subjectUri, cid: entry.subjectCid } } : op.record; if ((op.requiresLatestSubject && !entry.subjectCid) || await digest(written) !== entry.writtenRecordHash) throw new Error('Checkpoint written payload differs'); } for (const [id, marker] of Object.entries(checkpoint.inFlight)) { const found = operations.get(id), op = found?.op; if (!op || checkpoint.entries[id] || marker.sourceHash !== op.sourceHash || marker.recordHash !== op.recordHash || await digest(marker.record) !== marker.writtenRecordHash) throw new Error('In-flight checkpoint differs'); validateAttestation(marker, found.index); let wanted = op.requiresLatestSubject ? { ...op.record, subject: { $type: 'com.atproto.repo.strongRef', uri: marker.protocol === 'server-minted' ? subjectURI(plan, checkpoint, op) : op.subjectUri, cid: marker.subjectCid } } : op.record; if (checkpoint.attachments?.[op.id] && (marker.createAttempted || await digest(wanted) !== marker.writtenRecordHash)) { if (checkpoint.attachments[op.id].stage !== 'ArtifactAttested') throw new Error('Attachment is not attested'); wanted = attachmentRecord(wanted, checkpoint.attachments[op.id]); } if ((op.requiresLatestSubject && !marker.subjectCid) || await digest(wanted) !== marker.writtenRecordHash) throw new Error('In-flight subject differs'); } return checkpoint; } async function read(adapter, uri, operationId, options) { const attempts = options.readAttempts ?? 3; if (!Number.isInteger(attempts) || attempts < 1 || attempts > 5) throw new Error('Read attempts must be between one and five'); for (let i = 0; i < attempts; i++) { try { return await adapter.readRecord(uri, { signal: options.signal }); } catch (error) { const failure = safeFailure(error, 'Read Record', operationId); if (!failure.retryable || i + 1 === attempts || options.signal?.aborted) throw failure; await (options.sleep ?? (ms => new Promise(resolve => setTimeout(resolve, ms))))(Math.min(250 * 2 ** i, 2000)); } } } /** Execute at most one operation. Durable persistence must precede every mutation. */ export async function executeNext({ plan, checkpoint, adapter, persist, signal, ...options }) { await validateRuntimeCheckpoint(plan, checkpoint); if (typeof persist !== 'function') throw new Error('Durable checkpoint persistence is required'); if (signal?.aborted) return { status: 'paused', checkpoint }; const op = plan.operations.find(item => checkpoint.entries[item.id]?.stage !== 'attested'); if (!op) return { status: 'complete', checkpoint }; if (!op.dependencies.every(id => checkpoint.entries[id]?.stage === 'attested')) throw new MigrationFailure('DEPENDENCY_NOT_ATTESTED', 'Plan', op.id); if (await digest(op.record) !== op.recordHash || await digest(op.sourceMetadata) !== op.sourceHash) throw new MigrationFailure('SOURCE_HASH_MISMATCH', 'Plan', op.id); if (adapter.serverAssignedKeys && mintedCollection(op.collection)) return executeMinted({ plan, checkpoint, adapter, persist, signal, ...options }, op); const next = structuredClone(checkpoint); let entry = next.entries[op.id]; try { if (!entry) { let marker = next.inFlight[op.id]; if (!marker) { let record = structuredClone(op.record), subjectCid; if (op.requiresLatestSubject) { const subject = await read(adapter, op.subjectUri, op.id, { ...options, signal }); if (subject?.uri !== op.subjectUri || !subject.cid) throw new MigrationFailure('SUBJECT_NOT_FOUND', 'Resolve Comment Subject', op.id); subjectCid = subject.cid; record.subject = { $type: 'com.atproto.repo.strongRef', uri: subject.uri, cid: subject.cid }; } const index = plan.operations.findIndex(item => item.id === op.id); marker = { record, recordHash: op.recordHash, sourceHash: op.sourceHash, writtenRecordHash: await digest(record), ...(subjectCid ? { subjectCid } : {}), attestationRkey: operationAttestationKey(plan, next, op.id), attestationCreatedAt: next.startedAt }; next.inFlight[op.id] = marker; await persist(structuredClone(next)); } // Reconcile every deterministic key, including after a lost create response. // The knot's create operation must be insert-only; it must not use putRecord. let saved = await read(adapter, recordURI(plan, op), op.id, { ...options, signal }); if (saved) { ensureReceipt(saved, recordURI(plan, op)); const existing = withoutEditorFields(saved.value); // A prior valid comment pins the ticket version that existed when it // was written. A later parent edit does not make that comment a duplicate. if (op.requiresLatestSubject && existing?.subject?.uri === op.subjectUri && existing.subject.cid) { const comparable = { ...marker.record, subject: { ...marker.record.subject, cid: existing.subject.cid } }; if (await digest(existing) !== await digest(comparable)) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Reconcile Record', op.id); marker.record = comparable; marker.subjectCid = existing.subject.cid; marker.writtenRecordHash = await digest(comparable); } else if (op.collection === 'org.tangled.label.definition' ? await digest(labelSemantic(existing)) !== await digest(labelSemantic(marker.record)) : await digest(existing) !== marker.writtenRecordHash) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Reconcile Record', op.id); } else { if (signal?.aborted) return { status: 'paused', checkpoint: next }; if (op.requiresLatestSubject) { const subject = await read(adapter, op.subjectUri, op.id, { ...options, signal }); if (subject?.uri !== op.subjectUri || !subject.cid) throw new MigrationFailure('SUBJECT_NOT_FOUND', 'Resolve Comment Subject', op.id); if (subject.cid !== marker.subjectCid) { marker.subjectCid = subject.cid; marker.record = { ...marker.record, subject: { $type: 'com.atproto.repo.strongRef', uri: subject.uri, cid: subject.cid } }; marker.writtenRecordHash = await digest(marker.record); await persist(structuredClone(next)); } } // Finish credentials, write, hydration and durable receipt before honoring Pause. try { saved = await adapter.createRecord({ collection: op.collection, rkey: op.rkey, record: marker.record }, {}); } catch (error) { throw safeFailure(error, 'Create Record', op.id); } } const receipt = ensureReceipt(saved, recordURI(plan, op)); entry = { ...receipt, recordHash: op.recordHash, sourceHash: op.sourceHash, writtenRecordHash: marker.writtenRecordHash, ...(marker.subjectCid ? { subjectCid: marker.subjectCid } : {}), attestationRkey: marker.attestationRkey, attestationCreatedAt: marker.attestationCreatedAt, stage: 'written' }; next.entries[op.id] = entry; delete next.inFlight[op.id]; await persist(structuredClone(next)); } if (signal?.aborted) return { status: 'paused', checkpoint: next }; try { await adapter.attest({ subject: { uri: entry.uri, cid: entry.cid }, rkey: entry.attestationRkey, createdAt: entry.attestationCreatedAt, ...(entry.change ? { change: entry.change } : {}) }, {}); } catch (error) { throw safeFailure(error, 'Attest Record', op.id); } entry.stage = 'attested'; await persist(structuredClone(next)); return { status: signal?.aborted ? 'paused' : 'progress', checkpoint: next, operationId: op.id }; } catch (error) { const failure = safeFailure(error, 'Migration', op.id); failure.checkpoint = next; throw failure; } } export async function migrate({ onProgress = result => {}, ...options }) { let checkpoint = options.checkpoint; while (true) { const result = await executeNext({ ...options, checkpoint }); checkpoint = result.checkpoint; await onProgress(result); if (result.status !== 'progress') return result; } } const mintedCollection = collection => ['org.tangled.track.ticket', 'org.tangled.feed.comment'].includes(collection); export function recordSemantic(record) { const value = Object.fromEntries(Object.entries(record).filter(([key]) => !['createdAt', 'repo', 'x-tngl-editor', 'x-tngl-change'].includes(key))); // Deployed knots may omit the optional union tag on label references. // Keep unknown tags intact so an unexpected type remains a conflict. if (Array.isArray(value.tangledLabels)) value.tangledLabels = value.tangledLabels.map(token => { if (token?.$type !== 'org.tangled.label.defs#labelToken') return token; const { $type, ...fields } = token; return fields; }); for (const key of ['subject', 'replyTo']) { if (value[key]?.$type === 'com.atproto.repo.strongRef') { const { $type, ...fields } = value[key]; value[key] = fields; } } return value; } const semantic = recordSemantic; function actualReceipt(receipt, plan, op) { const prefix = `at://${plan.repoDid}/${op.collection}/`; if (!receipt?.uri?.startsWith(prefix) || !/^[A-Za-z0-9._~:-]+$/.test(receipt.uri.slice(prefix.length))) throw new Error('Invalid minted record receipt'); return ensureReceipt(receipt, receipt.uri); } function subjectURI(plan, checkpoint, op) { const parent = plan.operations.find(candidate => recordURI(plan, candidate) === op.subjectUri); const uri = parent && checkpoint.entries[parent.id]?.uri; if (!uri) throw new MigrationFailure('SUBJECT_NOT_FOUND', 'Resolve Comment Subject', op.id); return uri; } async function executeMinted({ plan, checkpoint, adapter, persist, signal, ...options }, op) { const next = structuredClone(checkpoint), index = plan.operations.indexOf(op); let entry = next.entries[op.id]; const save = () => persist(structuredClone(next)); const same = async (a, b) => await digest(semantic(a)) === await digest(semantic(b)); const attest = async (value, final = false) => adapter.attest({ subject: { uri: value.uri, cid: value.cid }, rkey: operationAttestationKey(plan, next, op.id, final), createdAt: next.startedAt, ...(value.change ? { change: value.change } : {}) }, {}); try { if (!entry) { let marker = next.inFlight[op.id]; if (!marker) { let record = structuredClone(op.record), subjectCid; if (op.requiresLatestSubject) { const uri = subjectURI(plan, next, op), subject = await read(adapter, uri, op.id, { ...options, signal }); if (subject?.uri !== uri || !subject.cid) throw new MigrationFailure('SUBJECT_NOT_FOUND', 'Resolve Comment Subject', op.id); subjectCid = subject.cid; record.subject = { $type: 'com.atproto.repo.strongRef', uri, cid: subjectCid }; } const prepared = await prepareLargeRecord({ plan, checkpoint: next, op, record, adapter, persist, key: attachmentAttestationKey(plan, next, op.id), digest, signal }); if (prepared.paused) return { status: 'paused', checkpoint: next }; record = prepared.record; marker = { protocol: 'server-minted', record, recordHash: op.recordHash, sourceHash: op.sourceHash, writtenRecordHash: await digest(record), ...(subjectCid ? { subjectCid } : {}), attestationRkey: operationAttestationKey(plan, next, op.id), attestationCreatedAt: next.startedAt }; next.inFlight[op.id] = marker; await save(); } // An old intent was persisted before the rejected caller-key request. // Upgrade it only after lookup; the logical plan and label receipts stay intact. if (writeBudgetBytes(plan, op, marker.record) > MAX_XRPC_REQUEST_BYTES) { if (marker.createAttempted) throw new MigrationFailure('AMBIGUOUS_CREATE_OUTCOME', 'Reconcile Record', op.id); const prepared = await prepareLargeRecord({ plan, checkpoint: next, op, record: marker.record, adapter, persist, key: attachmentAttestationKey(plan, next, op.id), digest, signal }); if (prepared.paused) return { status: 'paused', checkpoint: next }; marker.record = prepared.record; marker.writtenRecordHash = await digest(marker.record); await save(); } const desired = structuredClone(marker.record); if (op.requiresLatestSubject) { const uri = subjectURI(plan, next, op); desired.subject.uri = uri; } const opening = op.collection === 'org.tangled.track.ticket' ? { ...desired, state: 'open' } : desired; const candidates = await adapter.findRecords({ collection: op.collection, record: desired, operationId: op.id }, { signal }); if (!Array.isArray(candidates)) throw new Error('Invalid reconciliation result'); if (candidates.length > 1) throw new MigrationFailure('MULTIPLE_SOURCE_MATCHES', 'Reconcile Record', op.id); let saved = candidates[0]; if (saved) { actualReceipt(saved, plan, op); if (op.requiresLatestSubject && saved.value?.subject?.uri === desired.subject.uri) { desired.subject.cid = saved.value.subject.cid; opening.subject.cid = saved.value.subject.cid; } if (!await same(saved.value, opening) && !await same(saved.value, desired)) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Reconcile Record', op.id); } else { if (marker.createAttempted) throw new MigrationFailure('AMBIGUOUS_CREATE_OUTCOME', 'Reconcile Record', op.id); if (signal?.aborted) return { status: 'paused', checkpoint: next }; if (op.requiresLatestSubject) { const subject = await read(adapter, desired.subject.uri, op.id, { ...options, signal }); if (!subject?.cid) throw new MigrationFailure('SUBJECT_NOT_FOUND', 'Resolve Comment Subject', op.id); desired.subject.cid = subject.cid; opening.subject.cid = subject.cid; } Object.assign(marker, { record: desired, subjectCid: desired.subject?.cid, writtenRecordHash: await digest(desired), createAttempted: true, protocol: 'server-minted' }); await save(); // Finish credentials, write, hydration and durable receipt before honoring Pause. try { saved = await adapter.createRecord({ collection: op.collection, record: opening }, {}); } catch (error) { throw safeFailure(error, 'Create Record', op.id); } if (!saved?.value) throw new MigrationFailure('MISSING_AUTHORITATIVE_RECORD', 'Reconcile Record', op.id); } if (!saved?.value || (!await same(saved.value, opening) && !await same(saved.value, desired))) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Reconcile Record', op.id); entry = { ...actualReceipt(saved, plan, op), initialCid: saved.cid, ...(saved['x-tngl-change'] ? { initialChange: saved['x-tngl-change'] } : {}), ...(op.collection === 'org.tangled.track.ticket' && op.record.state !== 'open' ? { finalAttestationRkey: operationAttestationKey(plan, next, op.id, true), finalAttestationCreatedAt: next.startedAt } : {}), protocol: 'server-minted', recordHash: op.recordHash, sourceHash: op.sourceHash, writtenRecordHash: marker.writtenRecordHash, ...(desired.subject ? { subjectCid: desired.subject.cid } : {}), attestationRkey: marker.attestationRkey, attestationCreatedAt: marker.attestationCreatedAt, stage: 'written', desiredRecord: desired, actualRecord: saved.value }; next.entries[op.id] = entry; delete next.inFlight[op.id]; await save(); } if (signal?.aborted) return { status: 'paused', checkpoint: next }; if (entry.stage === 'written') { try { await attest(entry); } catch (error) { throw safeFailure(error, 'Attest Record', op.id); } entry.stage = op.collection === 'org.tangled.track.ticket' && op.record.state !== 'open' ? 'attested-open' : 'attested'; await save(); } if (entry.stage === 'attested-open') { const current = await read(adapter, entry.uri, op.id, { ...options, signal }); if (!current) throw new MigrationFailure('RECORD_NOT_FOUND', 'Finalize State', op.id); const desired = { ...withoutEditorFields(current.value), state: op.record.state }; let receipt, actual; if (await same(current.value, entry.desiredRecord)) { receipt = actualReceipt(current, plan, op); actual = current.value; } else { if (current.cid !== entry.cid || !await same(current.value, entry.actualRecord)) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Finalize State', op.id); if (signal?.aborted) return { status: 'paused', checkpoint: next }; await save(); try { const saved = await adapter.putRecord({ uri: entry.uri, record: desired, swapRecord: current.cid }, {}); receipt = actualReceipt(saved, plan, op); actual = saved.value; if (!actual || !await same(actual, entry.desiredRecord)) throw new MigrationFailure('EXISTING_RECORD_CONFLICT', 'Finalize State', op.id); } catch (error) { throw safeFailure(error, 'Finalize State', op.id); } } Object.assign(entry, receipt, { actualRecord: actual, stage: 'state-written' }); await save(); } if (signal?.aborted) return { status: 'paused', checkpoint: next }; if (entry.stage === 'state-written') { try { await attest(entry, true); } catch (error) { throw safeFailure(error, 'Attest Final State', op.id); } entry.stage = 'attested'; await save(); } return { status: signal?.aborted ? 'paused' : 'progress', checkpoint: next, operationId: op.id }; } catch (error) { const failure = safeFailure(error, 'Migration', op.id); failure.checkpoint = next; throw failure; } } export function labelSemantic(record) { const result = withoutEditorFields(record); const { createdAt, ...fields } = result; if (typeof fields.color === 'string') fields.color = fields.color.toUpperCase(); return fields; }