@runeditrun/rer 0.2.99 → 0.2.100

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 (72) hide show
  1. package/cli/README.md +88 -2
  2. package/cli/business/bounded-waves.d.mts +23 -0
  3. package/cli/business/bounded-waves.mjs +57 -0
  4. package/cli/business/catchup-task.mjs +9 -2
  5. package/cli/business/command.mjs +8 -3
  6. package/cli/business/export-inputs.mjs +12 -2
  7. package/cli/business/export-task.mjs +9 -2
  8. package/cli/business/legacy-package.mjs +117 -0
  9. package/cli/business/local-commands.mjs +10 -1
  10. package/cli/business/package-transfer.mjs +127 -0
  11. package/cli/business/state.mjs +3 -3
  12. package/cli/business/vendor-door.mjs +83 -11
  13. package/cli/business/vendors/README.md +41 -2
  14. package/cli/business/vendors/common.mjs +81 -0
  15. package/cli/business/vendors/index.mjs +12 -2
  16. package/cli/business/vendors/zendesk-attachments.mjs +57 -0
  17. package/cli/business/vendors/zendesk-encode.mjs +133 -0
  18. package/cli/business/vendors/zendesk-guide.mjs +34 -0
  19. package/cli/business/vendors/zendesk-package.mjs +28 -0
  20. package/cli/business/vendors/zendesk-pages.mjs +61 -0
  21. package/cli/business/vendors/zendesk-people.mjs +7 -0
  22. package/cli/business/vendors/zendesk-store.mjs +154 -0
  23. package/cli/business/vendors/zendesk-tickets.mjs +21 -0
  24. package/cli/business/vendors/zendesk-token.mjs +31 -0
  25. package/cli/business/vendors/zendesk-transport.mjs +48 -0
  26. package/cli/business/vendors/zendesk.mjs +61 -0
  27. package/cli/deploy-command.mjs +5 -4
  28. package/cli/deploy-inputs.mjs +1 -1
  29. package/cli/deploy.mjs +6 -4
  30. package/cli/production-auth.mjs +16 -3
  31. package/cli/production-mail.mjs +18 -1
  32. package/cli/site.mjs +1 -1
  33. package/global/CHANGELOG.md +21 -0
  34. package/modules/deploy-kit/README.md +10 -0
  35. package/modules/deploy-kit/provider.mjs +18 -2
  36. package/modules/import-kit/src/d1/jobs.ts +3 -1
  37. package/modules/import-kit/src/d1/retirement-scope.ts +2 -2
  38. package/modules/import-kit/src/d1/retirement-tally.ts +1 -0
  39. package/modules/import-kit/src/d1/retirement.ts +15 -5
  40. package/modules/import-kit/src/d1/types.ts +3 -0
  41. package/modules/import-kit/src/d1/wave-boundary.ts +33 -0
  42. package/modules/import-kit/src/d1/wave-retirement.ts +47 -0
  43. package/modules/import-kit/src/door/ADOPTING.md +37 -0
  44. package/modules/import-kit/src/door/README.md +66 -0
  45. package/modules/import-kit/src/door/admission.ts +13 -3
  46. package/modules/import-kit/src/door/authority.ts +1 -0
  47. package/modules/import-kit/src/door/failures.ts +1 -1
  48. package/modules/import-kit/src/door/grants.ts +19 -5
  49. package/modules/import-kit/src/door/handler.ts +12 -1
  50. package/modules/import-kit/src/door/index.ts +6 -0
  51. package/modules/import-kit/src/door/package.ts +121 -0
  52. package/modules/import-kit/src/door/planning.ts +44 -19
  53. package/modules/import-kit/src/door/protocol.ts +4 -2
  54. package/modules/import-kit/src/door/schema.ts +2 -0
  55. package/modules/import-kit/src/door/store.ts +2 -2
  56. package/modules/import-kit/src/door/types.ts +24 -1
  57. package/modules/import-kit/src/door/waves/README.md +158 -0
  58. package/modules/import-kit/src/door/waves/digests.ts +38 -0
  59. package/modules/import-kit/src/door/waves/inventory.ts +84 -0
  60. package/modules/import-kit/src/door/waves/journal.ts +19 -0
  61. package/modules/import-kit/src/door/waves/lifecycle.ts +242 -0
  62. package/modules/import-kit/src/door/waves/preparation.ts +190 -0
  63. package/modules/import-kit/src/door/waves/schema.ts +73 -0
  64. package/modules/import-kit/src/door/waves/store.ts +112 -0
  65. package/modules/import-kit/src/door/waves/types.ts +76 -0
  66. package/onboarding/adapter.mjs +7 -1
  67. package/onboarding/operator-installer.mjs +3 -1
  68. package/package.json +1 -1
  69. package/scripts/publish-check/README.md +20 -0
  70. package/scripts/publish-check/diagnostics.mjs +73 -0
  71. package/scripts/publish-check/slots.py +37 -7
  72. package/scripts/publish-check.mjs +64 -37
@@ -0,0 +1,84 @@
1
+ import type { DoorRecord, DoorRequest, DoorSnapshot } from '../types.ts';
2
+ import type { D1Sql } from '../../d1/types.ts';
3
+ import { canonicalJson, attachmentHash, sha256 } from '../../provenance/identity.ts';
4
+ import { importedTargets, recordKey } from '../inventory.ts';
5
+ import { DoorError } from '../protocol.ts';
6
+ import { authorized, sql } from '../store.ts';
7
+ import { childSnapshot, children, hash } from './store.ts';
8
+ import type { WaveRoot } from './types.ts';
9
+
10
+ /** Snapshot pages are read independently. Request budgets are never waived for
11
+ * a large inventory or a native adapter lacking compact exact predicates. */
12
+ export async function records(request: DoorRequest, id: string | null, retained = true): Promise<DoorRecord[]> {
13
+ if (!id) return [];
14
+ const root = await request.options.database.prepare('SELECT * FROM ik_door_wave_roots WHERE id=? AND installation_id=? AND namespace=? AND destination=? AND state=\'completed\'')
15
+ .bind(id,request.access.installationId,request.access.namespace,request.options.destination).first<WaveRoot>();
16
+ if (!root) throw new DoorError('complete_parent_baseline_required',409);
17
+ const result: DoorRecord[] = [];
18
+ for (const child of await children(request,root)) result.push(...(await childSnapshot(request,child)).records);
19
+ // Retained-gone ownership is cumulative, but never counted as delivered source.
20
+ const seen = new Set(result.map(recordKey));
21
+ for (const old of retained ? await records(request,root.previous_id) : []) if (!seen.has(recordKey(old))) result.push(old);
22
+ return result;
23
+ }
24
+ export async function prior(request: DoorRequest, root: WaveRoot) {
25
+ return new Map((await records(request,root.previous_id)).map(record=>[recordKey(record),record]));
26
+ }
27
+ /** Re-read exact journal ownership and byte-bearing native values. The kit's
28
+ * read fences the complete native set, rather than accepting a client receipt. */
29
+ export async function ownedFence(request: DoorRequest, rows: DoorRecord[]): Promise<D1Sql[]> {
30
+ const targets = rows.flatMap(row=>row.targets);
31
+ const found = await importedTargets(request,targets).catch(async error=>{
32
+ if (error instanceof Error && error.message==='IMPORT_ATOMIC_GUARD') {await authorized(request);throw new DoorError('native_edit_conflict',409);}
33
+ throw error;
34
+ });
35
+ if (found.some(row=>!row.matches)) throw new DoorError('native_edit_conflict',409);
36
+ const predicates: D1Sql[] = [];
37
+ for (let i=0;i<targets.length;i++) {
38
+ const t = targets[i], p = found[i].provenance;
39
+ const current = await request.options.targets.read(request.options.database,request.options.destination,t.kind,t.id);
40
+ if (!current || current.revision !== p.appliedRevision || sha256(canonicalJson(current.value)) !== p.valueHash
41
+ || attachmentHash(current.attachment) !== p.attachmentHash) throw new DoorError('native_edit_conflict',409);
42
+ predicates.push(request.options.targets.matches(current,request.options.destination,t.kind,t.id),
43
+ sql(`EXISTS(SELECT 1 FROM ik_provenance WHERE id=? AND job_id=? AND reversed=0 AND json_extract(record_json,'$.appliedRevision')=? AND json_extract(record_json,'$.valueHash')=? AND json_extract(record_json,'$.attachmentHash') IS ?)`,p.id,p.jobId,p.appliedRevision,p.valueHash,p.attachmentHash));
44
+ }
45
+ return predicates;
46
+ }
47
+ export function conjunction(predicates: D1Sql[]): D1Sql {
48
+ return predicates.length ? sql(predicates.map(p=>`(${p.sql})`).join(' AND '),...predicates.flatMap(p=>p.params ?? [])) : sql('1');
49
+ }
50
+ /** Before every child batch, future baselines and earlier siblings are checked
51
+ * together. A sibling's actual journal replaces only its reviewed baselines. */
52
+ export async function executionFence(request: DoorRequest, root: WaveRoot, executingOrdinal = -1) {
53
+ const predicates: D1Sql[] = [], completed: DoorRecord[] = [], replacing = new Set<string>();
54
+ for (const child of await children(request,root)) {
55
+ const snapshot = await childSnapshot(request,child);
56
+ for (const record of snapshot.records) replacing.add(recordKey(record));
57
+ const job = child.job_id ? await request.options.database.prepare('SELECT state,checkpoint FROM ik_jobs WHERE id=?').bind(child.job_id).first<any>() : null;
58
+ if (job?.state === 'completed') { if (child.ordinal!==executingOrdinal) completed.push(...snapshot.records); continue; }
59
+ for (const baseline of snapshot.wave.descriptor.baseline) {
60
+ // A partially committed child's own completed targets are fenced by its
61
+ // actual journal below; its uncommitted targets keep the prepared baseline.
62
+ const provenance = child.job_id ? await request.options.database.prepare("SELECT json_extract(record_json,'$.appliedRevision') AS applied_revision,json_extract(record_json,'$.valueHash') AS value_hash,json_extract(record_json,'$.attachmentHash') AS attachment_hash FROM ik_provenance WHERE job_id=? AND target_kind=? AND target_id=? AND reversed=0").bind(child.job_id,baseline.kind,baseline.id).first<any>() : null;
63
+ const current = await request.options.targets.read(request.options.database,root.destination,baseline.kind,baseline.id);
64
+ if (provenance) {
65
+ if (!current || current.revision !== provenance.applied_revision || hash(current.value) !== provenance.value_hash || attachmentHash(current.attachment) !== provenance.attachment_hash) throw new DoorError('native_edit_conflict',409);
66
+ if (child.ordinal!==executingOrdinal) predicates.push(request.options.targets.matches(current,root.destination,baseline.kind,baseline.id));
67
+ } else {
68
+ if (canonicalJson(current ?? null) !== canonicalJson(baseline.row)) throw new DoorError('native_edit_conflict',409);
69
+ if (child.ordinal!==executingOrdinal) predicates.push(request.options.targets.matches(baseline.row,root.destination,baseline.kind,baseline.id));
70
+ }
71
+ }
72
+ }
73
+ const retained = [...(await prior(request,root)).values()].filter(record=>!replacing.has(recordKey(record)));
74
+ predicates.push(...await ownedFence(request,[...completed,...retained]));
75
+ return conjunction(predicates);
76
+ }
77
+ export function snapshotRecords(snapshot: DoorSnapshot, old: Map<string,DoorRecord>, relationshipHash: string): DoorRecord[] {
78
+ return snapshot.plan.entries.map(entry=>{
79
+ const previous = old.get(recordKey(entry.source));
80
+ return {kind:entry.source.kind,sourceId:entry.source.sourceId,sourceHash:entry.rejection && previous ? previous.sourceHash : hash([entry.source.payloadHash,relationshipHash,snapshot.plan.mappingVersion]),
81
+ targets:entry.effects.length ? entry.effects.map(effect=>({kind:effect.targetKind,id:effect.targetId,ownerPlanId:snapshot.id,sourceIdentity:entry.identity})) : previous?.targets ?? [],
82
+ ...(entry.rejection || entry.unmapped.length ? {explanation:entry.rejection ?? entry.unmapped.map(u=>u.reason).join('; ')} : {})};
83
+ });
84
+ }
@@ -0,0 +1,19 @@
1
+ import type { ImportPlan } from '../../types.ts';
2
+ import { jsonChunks } from '../../d1/sets.ts';
3
+ import { sql } from '../store.ts';
4
+ import { hash } from './store.ts';
5
+
6
+ /** A completed flag alone is not reconciliation. Every primary disposition,
7
+ * including an archive/rejection with no native effect, needs its exact durable
8
+ * decision and source claim. These predicates are rechecked at final commit. */
9
+ export function childJournalGuards(jobId: string, plan: ImportPlan) {
10
+ const expected=plan.entries.map((entry,ordinal)=>[ordinal,entry.identity,entry.source.payloadHash,hash(entry.effects)]);
11
+ return [
12
+ sql('(SELECT count(*) FROM ik_d1_entries WHERE job_id=?)=?',jobId,expected.length),
13
+ ...jsonChunks(expected).map(body=>sql(`NOT EXISTS(SELECT 1 FROM json_each(?) x WHERE NOT EXISTS(
14
+ SELECT 1 FROM ik_d1_entries e JOIN ik_sources s ON s.identity=e.source_identity
15
+ WHERE e.job_id=? AND e.ordinal=json_extract(x.value,'$[0]') AND e.source_identity=json_extract(x.value,'$[1]')
16
+ AND e.effects_hash=json_extract(x.value,'$[3]') AND e.owner_job_id=? AND s.job_id=e.owner_job_id
17
+ AND s.source_hash=json_extract(x.value,'$[2]') AND s.effects_hash=e.effects_hash AND s.mapping_version=?))`,body,jobId,jobId,plan.mappingVersion)),
18
+ ];
19
+ }
@@ -0,0 +1,242 @@
1
+ import {childJournalGuards} from './journal.ts';
2
+ import {storedInventoryHash} from './digests.ts';
3
+ import { Buffer } from 'node:buffer';
4
+ import type { DoorRequest } from '../types.ts';
5
+ import type { D1ImportContext } from '../../d1/types.ts';
6
+ import { createD1ImportJob, readD1ImportJob } from '../../d1/jobs.ts';
7
+ import { applyD1ImportBatches } from '../../d1/apply.ts';
8
+ import { rollbackD1Import, undoD1Import } from '../../d1/reverse.ts';
9
+ import { readD1ImportOriginals } from '../../d1/originals.ts';
10
+ import { assertion, authorized, sql, transact } from '../store.ts';
11
+ import { DoorError } from '../protocol.ts';
12
+ import { recordKey } from '../inventory.ts';
13
+ import { failedPlan, reasonCode, requireNewPlan } from '../failures.ts';
14
+ import { sizeLimitError } from '../limits.ts';
15
+ import { sha256 } from '../../provenance/identity.ts';
16
+ import { bindWaveContext } from '../../d1/wave-boundary.ts';
17
+ import { BOUNDED_WAVES, totalKeys, zeroTotals, type WaveCensus, type WaveChild, type WaveRoot } from './types.ts';
18
+ import { activeParent, approve, assertPredicate, authority, childSnapshot, children, hash, parentFingerprint, rootFence, rootRow } from './store.ts';
19
+ import { conjunction, executionFence, ownedFence, prior, records } from './inventory.ts';
20
+
21
+ async function transition(request: DoorRequest, root: WaveRoot, state: string, extra = sql('1')) {
22
+ await transact(request.options.database,authority(request,extra),[
23
+ assertion(rootFence(root)),sql('UPDATE ik_door_wave_roots SET state=? WHERE id=?',state,root.id),
24
+ ]);
25
+ root.state=state;
26
+ }
27
+ export async function seal(request: DoorRequest, input: Record<string,unknown>) {
28
+ const root=await rootRow(request,input), expected=JSON.parse(root.census_json) as WaveCensus;
29
+ if (root.state!=='preparing') return parentView(request,root);
30
+ if (root.pages!==expected.children) throw new DoorError('complete_census_required',409);
31
+ const upload = await request.options.database.prepare('SELECT total_bytes FROM ik_door_uploads WHERE id=?').bind(root.upload_id).first<any>();
32
+ if (!upload) throw new DoorError('parent_custody_missing',410);
33
+ const totals=zeroTotals(), byKind:Record<string,number>=Object.create(null), nativeByTable:Record<string,number>=Object.create(null);
34
+ const relationships:string[]=[];
35
+ const seen=new Set<string>(), changes={additions:0,replacements:0,unchanged:0,rejected:0,unmapped:0};
36
+ for (const child of await children(request,root)) {
37
+ for (const key of totalKeys) totals[key]+=child[key];
38
+ const snapshot=await childSnapshot(request,child), d=snapshot.wave.descriptor;
39
+ for (const [kind,n] of Object.entries(snapshot.plan.counts.byKind)) byKind[kind]=(byKind[kind] ?? 0)+n;
40
+ for (const [table,n] of Object.entries(d.nativeByTable)) nativeByTable[table]=(nativeByTable[table] ?? 0)+n;
41
+ relationships.push(d.relationshipsHash);
42
+ for (const record of snapshot.records) seen.add(hash([record.kind,record.sourceId]));
43
+ changes.additions+=snapshot.differences.additions.length;changes.replacements+=snapshot.differences.replacements.length;changes.unchanged+=snapshot.differences.unchanged.length;
44
+ changes.rejected+=snapshot.plan.counts.rejected;
45
+ // Unchanged sources retain their earlier disposition, including an empty
46
+ // target set. New or changed targetless sources still require a proposal.
47
+ const unchanged=new Set(snapshot.differences.unchanged);
48
+ changes.unmapped+=snapshot.records.filter(r=>!r.targets.length && !unchanged.has(recordKey(r))).length;
49
+ }
50
+ if (totalKeys.some(k=>totals[k]!==expected[k]) || hash(byKind)!==hash(expected.byKind) || hash(nativeByTable)!==hash(expected.nativeByTable)) throw new DoorError('aggregate_census_mismatch',422);
51
+ // Every verified indexed file, including context and objects, has one custody
52
+ // owner. Transport bytes remain distinct from logical original/native bytes.
53
+ const {packageUpload}=await import('../package.ts'), {uploadRow}=await import('../uploads.ts');
54
+ const pkg=await packageUpload(request,await uploadRow(request,root.upload_id));
55
+ const member=await request.options.database.prepare("SELECT count(*) n FROM ik_door_wave_members WHERE parent_id=? AND type='file'").bind(root.id).first<any>();
56
+ if (member?.n!==pkg.files.length || totals.storedBytes!==pkg.files.reduce((n,f)=>n+f.bytes,0)) throw new DoorError('complete_file_coverage_required',422);
57
+ const inventoryHash=await storedInventoryHash(request.options.database,root.id);
58
+ const previousRoot=root.previous_id ? await request.options.database.prepare('SELECT fingerprint FROM ik_door_wave_roots WHERE id=?').bind(root.previous_id).first<any>() : null;
59
+ if (inventoryHash!==expected.inventoryHash || hash(relationships)!==expected.relationshipsHash || (previousRoot?.fingerprint ?? hash([]))!==expected.baselineHash) throw new DoorError('complete_inventory_hash_mismatch',422);
60
+ if (root.catchup===1) {
61
+ const previous=await request.options.database.prepare('SELECT census_json FROM ik_door_wave_roots WHERE id=? AND state=\'completed\'').bind(root.previous_id).first<any>();
62
+ const baseline=previous && JSON.parse(previous.census_json).source;
63
+ const gone=(await records(request,root.previous_id,false)).filter(r=>!seen.has(hash([r.kind,r.sourceId]))).length;
64
+ const reason=!baseline?'empty_baseline':gone?'source_records_gone':changes.rejected || changes.unmapped?'rejected_or_unmapped_records':(changes.additions+changes.replacements)*100>=baseline*5?'change_must_be_under_five_percent':null;
65
+ if (reason) throw new DoorError('catchup_requires_proposal:'+reason,409);
66
+ }
67
+ const fingerprint=parentFingerprint(root);
68
+ await transact(request.options.database,authority(request),[
69
+ assertion(rootFence(root)),sql("UPDATE ik_door_wave_roots SET fingerprint=?,state='sealed' WHERE id=?",fingerprint,root.id),
70
+ ]);
71
+ return parentView(request,{...root,fingerprint,state:'sealed'});
72
+ }
73
+ export async function reviewParent(request: DoorRequest, input: Record<string,unknown>) {
74
+ const root=await rootRow(request,input);
75
+ if (!['sealed','approved','applying','completed'].includes(root.state) || !root.fingerprint) throw new DoorError('sealed_parent_required',409);
76
+ if (await storedInventoryHash(request.options.database,root.id)!==JSON.parse(root.census_json).inventoryHash) throw new DoorError('aggregate_census_mismatch',409);
77
+ await approve(request,root,-1,root.fingerprint);
78
+ if (root.state==='sealed') await transition(request,root,'approved');
79
+ return parentView(request,root);
80
+ }
81
+ function approvalFence(request: DoorRequest, root: WaveRoot, child: WaveChild) {
82
+ return conjunction([activeParent(request,root),sql(`EXISTS(SELECT 1 FROM ik_door_wave_approvals WHERE parent_id=? AND ordinal=? AND revoked=0 AND fingerprint=? AND approval_id=? AND approved_at=? AND owner=?)`,root.id,child.ordinal,child.fingerprint,request.access.approvalRecordId,request.access.approvedAt,request.access.email)]);
83
+ }
84
+ async function context(request: DoorRequest, root: WaveRoot, child: WaveChild, mode: 'apply'|'reverse'|'read'): Promise<D1ImportContext> {
85
+ const snapshot=await childSnapshot(request,child);
86
+ if (hash(request.options.bounded!.native(snapshot.plan))!==hash(snapshot.wave.descriptor.projections)) throw new DoorError('native_accounting_changed',409);
87
+ const fence=mode==='read'?sql('1'):await executionFence(request,root,child.ordinal);
88
+ const approved=mode==='apply'?approvalFence(request,root,child):activeParent(request,root);
89
+ const externalChild=request.options.bounded!.authority({...request.access.bounded!,childFingerprint:child.fingerprint},request.access.action);
90
+ const associated=sql("EXISTS(SELECT 1 FROM ik_door_plans p LEFT JOIN ik_jobs j ON j.id=p.job_id WHERE p.id=? AND p.fingerprint=? AND (p.job_id IS NULL OR (j.operation_key=? AND j.fingerprint=p.fingerprint)))",child.plan_id,snapshot.plan.fingerprint,'door:'+child.plan_id);
91
+ const active=conjunction([approved,externalChild,associated,rootFence(root),fence,sql('EXISTS(SELECT 1 FROM ik_door_plan_chunks WHERE plan_id=?)',child.plan_id)]);
92
+ const result: D1ImportContext={destination:root.destination,namespace:snapshot.kitNamespace,mappingVersion:root.mapping_version,
93
+ operationKey:'door:'+child.plan_id,reviewedFingerprint:snapshot.plan.fingerprint,
94
+ storage:{database:request.options.database,targets:request.options.targets},batchSize:request.options.bounded!.batchSize ?? 20,maxBatches:1,reversalPolicy:'strict',
95
+ authorization:{principalId:request.options.ownerPrincipalId,predicate(action,destination) {
96
+ if (destination!==root.destination || !['read',...(mode==='apply'?['create','apply']:mode==='reverse'?['undo','rollback']:[])].includes(action)) return sql('0');
97
+ return authority(request,active);
98
+ }}};
99
+ bindWaveContext(result,root.id,mode);
100
+ return result;
101
+ }
102
+ export async function applyChild(request: DoorRequest, input: Record<string,unknown>) {
103
+ const root=await rootRow(request,input);
104
+ if (!['approved','applying','completed'].includes(root.state)) throw new DoorError('approved_parent_required',409);
105
+ if (!Number.isSafeInteger(input.ordinal) || (input.ordinal as number)<0) throw new DoorError('invalid_child_ordinal',400);
106
+ const all=await children(request,root), child=all[input.ordinal as number];
107
+ if (!child || request.access.bounded?.childFingerprint!==child.fingerprint || input.reviewedFingerprint!==child.fingerprint) throw new DoorError('child_fingerprint_mismatch');
108
+ const failure=await failedPlan(request,child.plan_id);if (failure) requireNewPlan(child.plan_id,failure);
109
+ if (child.source>Math.min(request.access.maxRecords,request.options.limits?.maxRecords ?? request.access.maxRecords) || child.native>Math.min(request.access.maxRecords,request.options.limits?.maxRecords ?? request.access.maxRecords)) throw new DoorError('child_exceeds_grant_quota',413);
110
+ await assertPredicate(request,activeParent(request,root),'parent_approval_revoked');
111
+ for (const predecessor of all.slice(0,child.ordinal)) {
112
+ const job=predecessor.job_id && await request.options.database.prepare('SELECT state FROM ik_jobs WHERE id=?').bind(predecessor.job_id).first<any>();
113
+ if (!job || job.state!=='completed') throw new DoorError('child_dependency_incomplete',409);
114
+ }
115
+ await approve(request,root,child.ordinal,child.fingerprint);
116
+ if (root.state==='approved') await transition(request,root,'applying',activeParent(request,root));
117
+ const snapshot=await childSnapshot(request,child), ctx=await context(request,root,child,'apply');
118
+ const job=await createD1ImportJob(snapshot.plan,ctx);
119
+ await transact(request.options.database,authority(request,approvalFence(request,root,child)),[
120
+ sql('INSERT OR IGNORE INTO ik_door_wave_origins(job_id,parent_id,ordinal,plan_id,fingerprint) VALUES(?,?,?,?,?)',job.id,root.id,child.ordinal,child.plan_id,snapshot.plan.fingerprint),
121
+ assertion(sql('EXISTS(SELECT 1 FROM ik_door_wave_origins WHERE job_id=? AND parent_id=? AND ordinal=? AND plan_id=? AND fingerprint=?)',job.id,root.id,child.ordinal,child.plan_id,snapshot.plan.fingerprint)),
122
+ sql('UPDATE ik_door_plans SET job_id=? WHERE id=? AND (job_id IS NULL OR job_id=?)',job.id,child.plan_id,job.id),
123
+ assertion(sql('EXISTS(SELECT 1 FROM ik_door_plans WHERE id=? AND job_id=?)',child.plan_id,job.id)),
124
+ ]);
125
+ const result=await applyD1ImportBatches(job.id,ctx).catch(async error=>{
126
+ if (sizeLimitError(error)) throw error;
127
+ const code=reasonCode(error);
128
+ // Durable failure bookkeeping grants no native authority. A concurrent
129
+ // successful batch or erasure prevents this exact pre-batch transition.
130
+ await transact(request.options.database,sql('1'),[
131
+ assertion(sql('(SELECT count(*) FROM ik_d1_erasure_journal WHERE destination=?)=?',root.destination,root.epoch)),
132
+ assertion(sql('EXISTS(SELECT 1 FROM ik_door_plan_chunks WHERE plan_id=?)',child.plan_id)),
133
+ assertion(sql("EXISTS(SELECT 1 FROM ik_door_grants WHERE installation_id=? AND jti=? AND action='apply-child' AND namespace=?)",root.installation_id,request.nonce!.jti,root.namespace)),
134
+ assertion(sql("EXISTS(SELECT 1 FROM ik_jobs WHERE id=? AND fingerprint=? AND fence=? AND checkpoint=? AND state IN ('queued','applying'))",job.id,job.fingerprint,job.fence,job.checkpoint)),
135
+ sql('INSERT INTO ik_door_apply_failures(plan_id,reason_code) VALUES(?,?)',child.plan_id,code),
136
+ sql("UPDATE ik_jobs SET state='failed',error=?,fence=fence+1 WHERE id=?",code,job.id),
137
+ ]);
138
+ throw new DoorError(code,code==='import_door_apply_transient'?503:409,{parentId:root.id,ordinal:child.ordinal,requiresNewParent:true,requiresNewApproval:true});
139
+ });
140
+ return {protocol:BOUNDED_WAVES,parentId:root.id,ordinal:child.ordinal,fingerprint:child.fingerprint,job:result,
141
+ childSuccess:result.state==='completed',aggregateSuccess:false};
142
+ }
143
+ export async function finalize(request: DoorRequest, input: Record<string,unknown>) {
144
+ const root=await rootRow(request,input);
145
+ if (!['applying','completed'].includes(root.state)) throw new DoorError('parent_not_applied',409);
146
+ const parent=activeParent(request,root);
147
+ await assertPredicate(request,parent,'parent_approval_revoked');
148
+ const all=await children(request,root), expected=JSON.parse(root.census_json) as WaveCensus;
149
+ if (await storedInventoryHash(request.options.database,root.id)!==expected.inventoryHash) throw new DoorError('aggregate_census_mismatch',409);
150
+ if (all.length!==expected.children) throw new DoorError('aggregate_children_missing',409);
151
+ const totals=zeroTotals(), guards=[parent,rootFence(root)];
152
+ const dispositions={mapped:0,rejected:0,explained:0,reused:0};
153
+ let protocolBytes=0;
154
+ const delivered=[], old=await prior(request,root);
155
+ for (const child of all) {
156
+ if (!child.job_id) throw new DoorError('aggregate_children_missing',409);
157
+ const revision=await request.options.database.prepare('SELECT revision FROM ik_d1_custody_states WHERE job_id=?').bind(child.job_id).first<{revision:number}>();
158
+ if (!revision) throw new DoorError('aggregate_child_journal_mismatch',409);
159
+ guards.push(sql('EXISTS(SELECT 1 FROM ik_d1_custody_states WHERE job_id=? AND revision=?)',child.job_id,revision.revision),
160
+ sql('EXISTS(SELECT 1 FROM ik_door_wave_origins WHERE job_id=? AND parent_id=? AND ordinal=? AND plan_id=?)',child.job_id,root.id,child.ordinal,child.plan_id));
161
+ const ctx=await context(request,root,child,'read'), job=await readD1ImportJob(child.job_id,ctx);
162
+ if (job.state!=='completed' || job.checkpoint!==job.total) throw new DoorError('aggregate_children_incomplete',409);
163
+ const snapshot=await childSnapshot(request,child);
164
+ if (job.total!==snapshot.sourceCount) throw new DoorError('aggregate_child_journal_mismatch',409);
165
+ const journal=childJournalGuards(job.id,snapshot.plan);
166
+ for (const guard of journal) await assertPredicate(request,guard,'aggregate_child_journal_mismatch');
167
+ guards.push(...journal);
168
+ for (const original of await readD1ImportOriginals(child.job_id,ctx)) {
169
+ if (original.original.status!=='retained') throw new DoorError('aggregate_bytes_unreadable',410);
170
+ const bytes=Buffer.from(original.original.base64,'base64');
171
+ if (bytes.length!==original.size || sha256(bytes)!==original.sha256) throw new DoorError('aggregate_bytes_unreadable',410);
172
+ }
173
+ guards.push(request.options.bounded!.authority({...request.access.bounded!,childFingerprint:child.fingerprint},'finalize-parent'),sql(`EXISTS(SELECT 1 FROM ik_jobs WHERE id=? AND state='completed' AND fingerprint=? AND fence=? AND checkpoint=?)`,job.id,job.fingerprint,job.fence,job.checkpoint),
174
+ sql('EXISTS(SELECT 1 FROM ik_door_wave_approvals WHERE parent_id=? AND ordinal=? AND revoked=0 AND fingerprint=?)',root.id,child.ordinal,child.fingerprint));
175
+ dispositions.mapped+=snapshot.plan.counts.mapped;dispositions.rejected+=snapshot.plan.counts.rejected;dispositions.explained+=snapshot.records.filter(r=>!r.targets.length && !snapshot.plan.entries.find(e=>e.source.kind===r.kind && e.source.sourceId===r.sourceId)?.rejection).length;dispositions.reused+=snapshot.differences.unchanged.length;
176
+ protocolBytes+=snapshot.plan.source.artifacts.filter(a=>a.name==='rer-package.json').reduce((n,a)=>n+a.size,0);
177
+ delivered.push(...snapshot.records);
178
+ for (const key of totalKeys) totals[key]+=child[key];
179
+ }
180
+ if (totalKeys.some(k=>totals[k]!==expected[k])) throw new DoorError('aggregate_census_mismatch',409);
181
+ const seen=new Set(delivered.map(r=>hash([r.kind,r.sourceId]))), gone=[...old.values()].filter(r=>!seen.has(hash([r.kind,r.sourceId])));
182
+ guards.push(...await ownedFence(request,[...delivered,...gone]));
183
+ const lineage=sql('EXISTS(SELECT 1 FROM ik_door_namespaces WHERE installation_id=? AND namespace=? AND ((pending_id=? AND head_id IS ?) OR (pending_id IS NULL AND head_id=?)))',root.installation_id,root.namespace,root.id,root.previous_id,root.id);
184
+ await transact(request.options.database,authority(request,conjunction([...guards.slice(0,1),lineage])),[
185
+ ...guards.slice(1).map(assertion),
186
+ sql("UPDATE ik_door_wave_roots SET state='completed' WHERE id=?",root.id),
187
+ sql('UPDATE ik_door_namespaces SET head_id=?,pending_id=NULL WHERE installation_id=? AND namespace=?',root.id,root.installation_id,root.namespace),
188
+ ],[...guards.filter((_,i)=>i!==1),rootFence({...root,state:'completed'})]);
189
+ return {protocol:BOUNDED_WAVES,parentId:root.id,fingerprint:root.fingerprint,aggregateSuccess:true,completeHead:root.id,
190
+ counts:totals,dispositions,nativeSuccess:dispositions.rejected===0 && dispositions.explained===0,metadata:{manifestCopies:all.length,originalManifestBytes:protocolBytes},retainedNativeTargets:gone.reduce((n,r)=>n+r.targets.length,0),goneButRetained:gone.map(r=>({kind:r.kind,sourceId:r.sourceId})),children:all.length};
191
+ }
192
+ export async function reverseParent(request: DoorRequest, input: Record<string,unknown>) {
193
+ const root=await rootRow(request,input), parent=activeParent(request,root);
194
+ await assertPredicate(request,parent,'parent_approval_revoked');
195
+ // A lost final response must resolve to the same durable reversal even after
196
+ // the complete head has already been restored to the previous snapshot.
197
+ if (root.state==='reversed') return parentView(request,root);
198
+ const line=await request.options.database.prepare('SELECT head_id,pending_id FROM ik_door_namespaces WHERE installation_id=? AND namespace=?').bind(root.installation_id,root.namespace).first<any>();
199
+ if (!line || (line.pending_id!==root.id && line.head_id!==root.id) || line.pending_id && line.pending_id!==root.id) throw new DoorError('parent_superseded',409);
200
+ if (!['approved','applying','completed','reversing'].includes(root.state)) throw new DoorError('parent_reverse_refused',409);
201
+ // Full known-conflict preflight, followed by each ordinary strict transaction.
202
+ // This is resumable partial reversal, never whole-database atomicity.
203
+ await executionFence(request,root);
204
+ if (root.state!=='reversing') {
205
+ // Reserve the same pending-parent slot before reversing a completed head.
206
+ // A catch-up prepared after our read cannot race or be cleared by Undo.
207
+ await transact(request.options.database,authority(request,parent),[
208
+ assertion(rootFence(root)),sql("UPDATE ik_door_wave_roots SET state='reversing' WHERE id=?",root.id),
209
+ sql('UPDATE ik_door_namespaces SET pending_id=? WHERE installation_id=? AND namespace=?',root.id,root.installation_id,root.namespace),
210
+ ],[rootFence({...root,state:'reversing'})]);
211
+ root.state='reversing';
212
+ }
213
+ const all=await children(request,root);
214
+ for (const child of all.toReversed()) {
215
+ if (!child.job_id) continue;
216
+ const ctx=await context(request,root,child,'reverse'), job=await readD1ImportJob(child.job_id,ctx);
217
+ if (['undone','rolled_back'].includes(job.state)) continue;
218
+ const result=await (['completed','undoing'].includes(job.state)?undoD1Import:rollbackD1Import)(job.id,ctx);
219
+ return {protocol:BOUNDED_WAVES,parentId:root.id,state:'reversing',ordinal:child.ordinal,job:result,aggregateSuccess:false};
220
+ }
221
+ await transact(request.options.database,authority(request,parent),[
222
+ assertion(rootFence(root)),
223
+ sql("UPDATE ik_door_wave_roots SET state='reversed' WHERE id=?",root.id),
224
+ sql('UPDATE ik_door_namespaces SET head_id=CASE WHEN head_id=? THEN ? ELSE head_id END,pending_id=NULL WHERE installation_id=? AND namespace=?',root.id,root.previous_id,root.installation_id,root.namespace),
225
+ ],[rootFence({...root,state:'reversed'})]);
226
+ return parentView(request,{...root,state:'reversed'});
227
+ }
228
+ async function parentView(request: DoorRequest, root: WaveRoot) {
229
+ const all=await children(request,root), states=[];
230
+ for (const child of all) {
231
+ const job=child.job_id ? await request.options.database.prepare('SELECT state,checkpoint,total,error FROM ik_jobs WHERE id=?').bind(child.job_id).first<any>() : null;
232
+ states.push({ordinal:child.ordinal,fingerprint:child.fingerprint,source:child.source,native:child.native,job:job ?? null,childSuccess:job?.state==='completed',skipped:!job && root.state==='reversed'});
233
+ }
234
+ const withdrawn=root.state==='withdrawn' || root.epoch!==request.epoch;
235
+ return {protocol:BOUNDED_WAVES,parentId:root.id,fingerprint:root.fingerprint,state:withdrawn?'withdrawn':root.state,
236
+ census:JSON.parse(root.census_json),children:states,progress:{expected:JSON.parse(root.census_json).children,applied:states.filter(c=>c.childSuccess).length,pending:states.filter(c=>!c.skipped && (!c.job || ['queued','applying'].includes(c.job.state))).length,skipped:states.filter(c=>c.skipped).length,failed:states.filter(c=>c.job?.state==='failed').length,reversed:states.filter(c=>['undone','rolled_back'].includes(c.job?.state)).length,withdrawn},aggregateSuccess:false,completionRecorded:!withdrawn && root.state==='completed'};
237
+ }
238
+ export async function waveStatus(request: DoorRequest, input: Record<string,unknown>) {
239
+ const root=await rootRow(request,input,true), result=await parentView(request,root);
240
+ await authorized({...request,authority:authority(request)});
241
+ return result;
242
+ }
@@ -0,0 +1,190 @@
1
+ import {inventoryMember, type WaveInventoryMember} from './digests.ts';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { Buffer } from 'node:buffer';
4
+ import type { DoorRequest, DoorSnapshot } from '../types.ts';
5
+ import type { MappingResult, SourceBundle } from '../../types.ts';
6
+ import { limitsFor, RecordCollector } from '../../readers/records.ts';
7
+ import { planD1Import } from '../../d1/jobs.ts';
8
+ import { packageUpload } from '../package.ts';
9
+ import { bundleBytes, uploadRow, text } from '../uploads.ts';
10
+ import { DoorError } from '../protocol.ts';
11
+ import { sourceRefusal } from '../refusals.ts';
12
+ import { assertion, lineage, sql, transact } from '../store.ts';
13
+ import { forget, refuseErased } from '../planning.ts';
14
+ import { recordKey, importedTargets } from '../inventory.ts';
15
+ import { BOUNDED_WAVES, totalKeys, zeroTotals, type WaveCensus, type WaveDescriptor, type WaveMetadata, type WaveRoot } from './types.ts';
16
+ import { authority, children, hash, opaque, revision, rootFence, rootRow, saveChild } from './store.ts';
17
+ import { prior, snapshotRecords } from './inventory.ts';
18
+
19
+ const count = (n: unknown): n is number => Number.isSafeInteger(n) && (n as number)>=0;
20
+ const digest = (s: unknown): s is string => typeof s === 'string' && /^[a-f0-9]{64}$/.test(s);
21
+ const byKind = (v: Record<string,number>) => v && typeof v==='object' && !Array.isArray(v) && Object.entries(v).every(([k,n])=>k.length>0 && count(n));
22
+ function census(value: WaveCensus): WaveCensus {
23
+ if (!value || Object.keys(value).some(k=>![...totalKeys,'children','byKind','nativeByTable','inventoryHash','relationshipsHash','baselineHash','sourceMode','highWater','accountingVersion'].includes(k)) || !totalKeys.every(k=>count(value[k])) || !count(value.children) || !value.children || value.sourceMode !== 'complete'
24
+ || !byKind(value.byKind) || !byKind(value.nativeByTable) || Object.values(value.byKind).reduce((a,b)=>a+b,0)!==value.source
25
+ || Object.values(value.nativeByTable).reduce((a,b)=>a+b,0)!==value.native
26
+ || ![value.inventoryHash,value.relationshipsHash,value.baselineHash].every(digest) || !opaque(value.accountingVersion) || !opaque(value.highWater)) throw new DoorError('invalid_complete_census',422);
27
+ return JSON.parse(JSON.stringify(value));
28
+ }
29
+ export function planningContext(request: DoorRequest, namespace: string) {
30
+ return {destination:request.options.destination,namespace,mappingVersion:request.options.mapping.version,
31
+ storage:{database:request.options.database,targets:request.options.targets},authorization:{principalId:request.options.ownerPrincipalId,predicate:()=>authority(request)}};
32
+ }
33
+ async function begin(request: DoorRequest, input: Record<string,unknown>) {
34
+ const b = revision(request), upload = await uploadRow(request,text(input.uploadId,'upload_id'));
35
+ const pkg = await packageUpload(request,upload), totals = census(await request.options.bounded!.describe(pkg));
36
+ if (pkg.manifest.records.total!==null && (totals.source!==pkg.manifest.records.total || hash(totals.byKind)!==hash(pkg.manifest.records.byKind))) throw new DoorError('package_record_count_mismatch',422);
37
+ const binding = {protocol:BOUNDED_WAVES,migration:b.migration,revision:b.revision,policy:b.policy};
38
+ const priorRoot = await request.options.database.prepare("SELECT * FROM ik_door_wave_roots WHERE installation_id=? AND namespace=? AND json_extract(binding_json,'$.migration')=? AND json_extract(binding_json,'$.revision')=?")
39
+ .bind(request.access.installationId,request.access.namespace,b.migration,b.revision).first<WaveRoot>();
40
+ if (priorRoot) {
41
+ if (priorRoot.bundle_sha256!==upload.bundle_sha256 || priorRoot.binding_json!==JSON.stringify(binding) || priorRoot.state==='cancelled') throw new DoorError('parent_revision_immutable',409);
42
+ return rootRow(request,{parentId:priorRoot.id});
43
+ }
44
+ const current = await lineage(request);
45
+ if (current.pending_id || current.head_id) {
46
+ const held=await request.options.database.prepare('SELECT state,epoch FROM ik_door_wave_roots WHERE id=?').bind(current.pending_id ?? current.head_id).first<any>();
47
+ if (held && (held.state==='withdrawn' || held.epoch!==request.epoch)) throw new DoorError('source_erased',410);
48
+ }
49
+ if (current.pending_id) throw new DoorError('namespace_has_pending_import',409);
50
+ if (!!current.head_id !== (input.catchup === true)) throw new DoorError(current.head_id?'catchup_required':'catchup_requires_baseline',409);
51
+ const root: WaveRoot = {id:randomUUID(),installation_id:request.access.installationId,namespace:request.access.namespace,destination:request.options.destination,
52
+ owner:request.access.email,mapping_version:request.options.mapping.version,bundle_sha256:upload.bundle_sha256,upload_id:upload.id,previous_id:current.head_id,
53
+ epoch:request.epoch,binding_json:JSON.stringify(binding),census_json:JSON.stringify(totals),fingerprint:null,state:'preparing',pages:0,chain:hash([]),catchup:input.catchup===true?(request.access.catchup==='bounded'?1:2):0};
54
+ // No implicit conversion of an ordinary or withdrawn baseline.
55
+ if (root.previous_id) {
56
+ await prior(request,root);
57
+ const previous=await request.options.database.prepare('SELECT binding_json FROM ik_door_wave_roots WHERE id=?').bind(root.previous_id).first<any>();
58
+ if (!previous || JSON.parse(previous.binding_json).migration!==b.migration) throw new DoorError('migration_lineage_changed',409);
59
+ }
60
+ await transact(request.options.database,authority(request),[
61
+ sql('INSERT OR IGNORE INTO ik_door_namespaces(installation_id,namespace) VALUES(?,?)',root.installation_id,root.namespace),
62
+ assertion(sql('EXISTS(SELECT 1 FROM ik_door_namespaces WHERE installation_id=? AND namespace=? AND head_id IS ? AND pending_id IS NULL)',root.installation_id,root.namespace,root.previous_id)),
63
+ assertion(sql("? IS NULL OR EXISTS(SELECT 1 FROM ik_door_wave_roots WHERE id=? AND state='completed' AND fingerprint=? AND epoch=?)",root.previous_id,root.previous_id,totals.baselineHash,root.epoch)),
64
+ sql(`INSERT INTO ik_door_wave_roots(id,installation_id,namespace,destination,owner,mapping_version,bundle_sha256,upload_id,previous_id,epoch,binding_json,census_json,fingerprint,state,pages,chain,catchup) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,...Object.values(root)),
65
+ sql('UPDATE ik_door_namespaces SET pending_id=? WHERE installation_id=? AND namespace=?',root.id,root.installation_id,root.namespace),
66
+ ]);
67
+ return root;
68
+ }
69
+ export async function prepare(request: DoorRequest, input: Record<string,unknown>) {
70
+ if (input.cancel===true) {
71
+ const root=await rootRow(request,input);
72
+ const clear=sql("NOT EXISTS(SELECT 1 FROM ik_door_wave_approvals WHERE parent_id=?) AND NOT EXISTS(SELECT 1 FROM ik_door_wave_children c JOIN ik_jobs j ON j.operation_key='door:'||c.plan_id WHERE c.parent_id=?)",root.id,root.id);
73
+ await transact(request.options.database,authority(request,clear),[
74
+ assertion(rootFence(root)),
75
+ sql('DELETE FROM ik_door_plan_chunks WHERE plan_id IN (SELECT plan_id FROM ik_door_wave_children WHERE parent_id=?)',root.id),
76
+ sql("UPDATE ik_door_wave_roots SET state='cancelled' WHERE id=?",root.id),
77
+ sql('UPDATE ik_door_namespaces SET pending_id=NULL WHERE installation_id=? AND namespace=? AND pending_id=?',root.installation_id,root.namespace,root.id),
78
+ ]);
79
+ return {protocol:BOUNDED_WAVES,parentId:root.id,state:'cancelled',aggregateSuccess:false};
80
+ }
81
+ try { return await preparePage(request,input); }
82
+ catch (caught) {
83
+ const refused=caught instanceof DoorError ? caught : sourceRefusal(caught);
84
+ if (refused && ['source_erased','source_credential','source_invalid_or_credential_source_data'].includes(refused.code)) {
85
+ const row=input.parentId ? await request.options.database.prepare('SELECT upload_id,id FROM ik_door_wave_roots WHERE id=? AND installation_id=? AND namespace=?').bind(input.parentId,request.access.installationId,request.access.namespace).first<any>() : null;
86
+ const upload=await uploadRow(request,text(row?.upload_id ?? input.uploadId,'upload_id'));
87
+ const segments: import('../uploads.ts').UploadRow[]=[];
88
+ try { await packageUpload(request,upload,rows=>segments.push(...rows)); } catch { /* Already missing custody stays missing. */ }
89
+ await forget(request,upload,segments);
90
+ const root=row ?? await request.options.database.prepare('SELECT id FROM ik_door_wave_roots WHERE upload_id=? AND installation_id=? AND namespace=?').bind(upload.id,request.access.installationId,request.access.namespace).first<any>();
91
+ if (root) await transact(request.options.database,authority(request),[
92
+ sql('DELETE FROM ik_door_plan_chunks WHERE plan_id IN (SELECT plan_id FROM ik_door_wave_children WHERE parent_id=?)',root.id),
93
+ sql("UPDATE ik_door_wave_roots SET state='withdrawn' WHERE id=?",root.id),
94
+ ]);
95
+ }
96
+ throw refused ?? caught;
97
+ }
98
+ }
99
+ async function preparePage(request: DoorRequest, input: Record<string,unknown>) {
100
+ if (Object.keys(input).some(k=>!['parentId','uploadId','ordinal','catchup'].includes(k)) || !count(input.ordinal) || input.catchup!==undefined && typeof input.catchup!=='boolean') throw new DoorError('invalid_prepare_input',400);
101
+ const root = input.parentId ? await rootRow(request,input) : await begin(request,input);
102
+ const expected = JSON.parse(root.census_json) as WaveCensus;
103
+ if (input.ordinal < root.pages) {
104
+ const child = (await children(request,root))[input.ordinal];
105
+ return {protocol:BOUNDED_WAVES,parentId:root.id,state:root.state,next:root.pages,child:{ordinal:child.ordinal,fingerprint:child.fingerprint}};
106
+ }
107
+ if (root.state !== 'preparing' || input.ordinal !== root.pages || root.pages >= expected.children) throw new DoorError('preparation_cursor_mismatch',409);
108
+ const upload = await uploadRow(request,root.upload_id), segments: any[]=[];
109
+ const pkg = await packageUpload(request,upload,rows=>segments.push(...rows));
110
+ if (hash(census(await request.options.bounded!.describe(pkg))) !== hash(expected)) throw new DoorError('preparation_census_changed',409);
111
+ const limits = limitsFor({...request.options.limits,maxRecords:Math.min(request.access.maxRecords,request.options.limits?.maxRecords ?? request.access.maxRecords)});
112
+ const unit = await request.options.bounded!.page(pkg,root.pages,Object.freeze({...limits}));
113
+ if (!unit || Object.keys(unit).some(k=>!['id','dependsOn','records','files','aliases','relationshipsHash'].includes(k)) || !opaque(unit.id) || !Array.isArray(unit.dependsOn) || unit.dependsOn.some(d=>!opaque(d)) || new Set(unit.dependsOn).size!==unit.dependsOn.length
114
+ || !Array.isArray(unit.aliases) || unit.aliases.some(a=>!a || Object.keys(a).some(k=>!['kind','sourceId','role','files'].includes(k)) || typeof a.kind!=='string' || !a.kind || typeof a.sourceId!=='string' || !a.sourceId || !['context','archive','rejected','metadata'].includes(a.role) || !Array.isArray(a.files) || a.files.some(path=>typeof path!=='string' || !pkg.files.some(f=>f.path===path)))
115
+ || !Array.isArray(unit.records) || !unit.records.length || unit.records.some(r=>!r || Object.keys(r).some(k=>!['kind','sourceId','payload','pointer'].includes(k))) || !Array.isArray(unit.files) || unit.files.some(f=>!f || Object.keys(f).some(k=>!['path','role','logicalBytes'].includes(k))) || !digest(unit.relationshipsHash)) throw new DoorError('invalid_native_work_unit',422);
116
+ if (unit.records.length>limits.maxRecords) throw new DoorError('child_exceeds_source_quota',413,{source:unit.records.length,limit:limits.maxRecords});
117
+ const metadata={id:unit.id,dependsOn:[...unit.dependsOn],relationshipsHash:unit.relationshipsHash,files:unit.files.map(f=>({...f})),aliases:unit.aliases.map(a=>({...a,files:[...a.files]}))},sourceCount=unit.records.length;
118
+ const previousChildren = await children(request,root), dependsOn = metadata.dependsOn.map(hash);
119
+ if (dependsOn.some(dep=>!previousChildren.some(child=>child.unit_hash===dep))) throw new DoorError('child_dependency_unprepared',409);
120
+ const namespace = 'door-wave:' + hash([root.installation_id,root.namespace,root.destination,JSON.parse(root.binding_json).migration,JSON.parse(root.binding_json).revision]);
121
+ const collector = new RecordCollector(namespace,limits);
122
+ collector.add(unit.records,{artifact:'rer-package.json'},root.bundle_sha256);
123
+ const totals = zeroTotals(), members: WaveInventoryMember[] = [];
124
+ const source: SourceBundle = collector.bundle;
125
+ source.artifacts.push({name:'rer-package.json',sha256:root.bundle_sha256,size:upload.total_bytes,original:{status:'available' as const,base64:Buffer.from(await bundleBytes(request,upload)).toString('base64')}});
126
+ const fileRoles = new Set<string>();
127
+ for (const file of metadata.files) {
128
+ const declared = pkg.files.find(f=>f.path===file.path);
129
+ if (!declared || fileRoles.has(file.path) || !['source','object','context'].includes(file.role) || !count(file.logicalBytes)) throw new DoorError('invalid_work_unit_file',422);
130
+ fileRoles.add(file.path);
131
+ const bytes = await pkg.read(file.path);
132
+ source.artifacts.push({name:file.path,sha256:declared.sha256,size:bytes.length,original:{status:'available',base64:Buffer.from(bytes).toString('base64')}});
133
+ members.push(inventoryMember('file',file.path,[declared.sha256,declared.bytes,file.role,file.logicalBytes]));
134
+ totals.storedBytes+=bytes.length; totals.logicalBytes+=file.logicalBytes;
135
+ if (file.role==='object') totals.objects++;
136
+ if (file.role==='context') totals.contextBytes+=bytes.length;
137
+ }
138
+ const old = await prior(request,root), id = randomUUID();
139
+ const differences: DoorSnapshot['differences'] = {additions:[],replacements:[],unchanged:[],gone:[],conflicts:[]};
140
+ const mapper = {version:root.mapping_version,map(record: SourceBundle['records'][number]): MappingResult {
141
+ const key=recordKey(record), before=old.get(key);
142
+ if (before && before.sourceHash===hash([record.payloadHash,metadata.relationshipsHash,root.mapping_version])) {
143
+ differences.unchanged.push(key); return {effects:[],unmapped:[{reason:'Unchanged source; exact earlier journal retained.'}]};
144
+ }
145
+ const mapped=request.options.mapping.map(record);
146
+ if (before?.targets.length && !mapped.rejection) {
147
+ const keys=mapped.effects.map(e=>hash([e.targetKind,e.targetId])).sort(), previous=before.targets.map(t=>hash([t.kind,t.id])).sort();
148
+ if (hash(keys)!==hash(previous)) throw new DoorError('changed_target_set_requires_proposal',409);
149
+ }
150
+ if (mapped.rejection) differences.conflicts.push(key);
151
+ else if (mapped.effects.length) (before?.targets.length?differences.replacements:differences.additions).push(key);
152
+ return mapped;
153
+ }};
154
+ // Establish earlier ownership before deriving replacement revisions.
155
+ const oldTargets=[...old.values()].flatMap(r=>r.targets), found=await importedTargets(request,oldTargets);
156
+ if (found.some(row=>!row.matches)) throw new DoorError('native_edit_conflict',409);
157
+ const revisions=new Map(oldTargets.map((t,i)=>[hash([t.kind,t.id]),found[i].provenance.appliedRevision]));
158
+ const mapping={...mapper,map(record:typeof source.records[number]) {const mapped=mapper.map(record);return {...mapped,effects:mapped.effects.map(e=>revisions.has(hash([e.targetKind,e.targetId]))?{...e,expectedRevision:revisions.get(hash([e.targetKind,e.targetId]))}:e)};}};
159
+ const plan = await planD1Import(source,mapping,planningContext(request,namespace));
160
+ if (plan.counts.duplicates || plan.entries.length!==sourceCount) throw new DoorError('duplicate_source_membership',422);
161
+ await refuseErased(request,upload,plan,segments);
162
+ const suppliedNative = request.options.bounded!.native(plan);
163
+ const native = Array.isArray(suppliedNative) ? suppliedNative.map(row=>({...row})) : suppliedNative;
164
+ if (!Array.isArray(native) || native.some(n=>!n || Object.keys(n).some(k=>!['table','key','valueHash','storedBytes','blobBytes'].includes(k)) || typeof n.table!=='string' || !n.table || typeof n.key!=='string' || !n.key || !digest(n.valueHash) || !count(n.storedBytes) || !count(n.blobBytes))
165
+ || native.length<plan.counts.effects) throw new DoorError('invalid_native_accounting',422);
166
+ totals.source=plan.counts.unique; totals.native=native.length;
167
+ const nativeByTable:Record<string,number>=Object.create(null);
168
+ for (const row of native) { nativeByTable[row.table]=(nativeByTable[row.table] ?? 0)+1; totals.blobBytes+=row.blobBytes;totals.nativeBytes+=row.storedBytes; members.push(inventoryMember('native',[row.table,row.key],row)); }
169
+ totals.aliases=metadata.aliases.length;
170
+ for (const alias of metadata.aliases) members.push(inventoryMember('alias',[alias.kind,alias.sourceId],alias));
171
+ const stable=[...plan.entries.map(entry=>hash([entry.source.kind,entry.source.sourceId])),...metadata.aliases.map(a=>hash([a.kind,a.sourceId]))];
172
+ const withdrawn=await request.options.database.prepare("SELECT 1 FROM ik_door_wave_members m JOIN ik_door_wave_roots r ON r.id=m.parent_id WHERE r.installation_id=? AND r.namespace=? AND r.destination=? AND r.state='withdrawn' AND r.epoch<? AND m.type IN ('source','alias') AND m.identity IN (SELECT value FROM json_each(?)) LIMIT 1").bind(root.installation_id,root.namespace,root.destination,root.epoch,JSON.stringify(stable)).first();
173
+ const erasedAlias=await request.options.database.prepare('SELECT 1 FROM ik_door_wave_erased_aliases WHERE installation_id=? AND namespace=? AND destination=? AND identity IN (SELECT value FROM json_each(?)) LIMIT 1').bind(root.installation_id,root.namespace,root.destination,JSON.stringify(stable)).first();
174
+ if (withdrawn || erasedAlias) throw new DoorError('source_erased',410);
175
+ for (const entry of plan.entries) members.push(inventoryMember('source',[entry.source.kind,entry.source.sourceId],entry.source.payloadHash));
176
+ if (totals.native>limits.maxRecords) throw new DoorError('child_exceeds_native_quota',413,{native:totals.native,limit:limits.maxRecords});
177
+ for (const effect of plan.entries.flatMap(e=>e.effects)) if (effect.attachment && !source.artifacts.some(a=>a.sha256===effect.attachment!.sha256)) throw new DoorError('attachment_original_not_accounted',422);
178
+ const baseline=[];
179
+ for (const effect of plan.entries.flatMap(e=>e.effects)) baseline.push({kind:effect.targetKind,id:effect.targetId,row:await request.options.targets.read(request.options.database,root.destination,effect.targetKind,effect.targetId) ?? null});
180
+ if (totalKeys.some(k=>!count(totals[k]))) throw new DoorError('native_accounting_overflow',413);
181
+ const descriptor: WaveDescriptor = {...totals,ordinal:root.pages,unitHash:hash(metadata.id),dependsOn,membershipHash:hash(members),planFingerprint:plan.fingerprint,
182
+ relationshipsHash:metadata.relationshipsHash,nativeByTable,baseline,projections:native,fingerprint:''};
183
+ const {fingerprint:_fingerprint,...reviewed}=descriptor;
184
+ descriptor.fingerprint=hash(reviewed);
185
+ const snapshot: DoorSnapshot & {wave:WaveMetadata} = {id,namespace:root.namespace,bundleSha256:root.bundle_sha256,kitNamespace:namespace,
186
+ previous:root.previous_id,records:[],sourceCount:totals.source,plan,differences,standingApproval:null,wave:{unit:metadata,descriptor}};
187
+ snapshot.records=snapshotRecords(snapshot,old,metadata.relationshipsHash);
188
+ await saveChild(request,root,snapshot,members,hash([root.chain,descriptor.fingerprint]));
189
+ return {protocol:BOUNDED_WAVES,parentId:root.id,state:'preparing',next:root.pages+1,child:{ordinal:root.pages,fingerprint:descriptor.fingerprint,totals}};
190
+ }