app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

local-inventory.spec.ts (27740B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { createHash } from 'node:crypto';
      4 import { fileURLToPath } from 'node:url';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Database from '../../src/lib/persistence/database.ts';
      7 import type * as Records from '../../src/lib/persistence/records.ts';
      8 import type * as Quota from '../../src/lib/persistence/quota.ts';
      9 import type {
     10   PublicOperationRecord,
     11   PreferenceOperationRecord
     12 } from '../../src/lib/contracts/local-records.ts';
     13 import { getEventHash, finalizeEvent } from 'applesauce-core/helpers';
     14 import { randomUUID } from 'node:crypto';
     15 import type * as Drafts from '../../src/lib/persistence/drafts.ts';
     16 declare global {
     17   interface Window {
     18     hcp049: typeof Database & typeof Drafts & typeof Quota & typeof Records;
     19     hcp049Database: Database.BrowserDatabase;
     20     hcp049Repository: Drafts.PublicDraftRepository;
     21     hcp049Quota: Quota.PublicQuotaRepository;
     22   }
     23 }
     24 const owner =
     25   '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798';
     26 const form = {
     27   title: '',
     28   description: 'unfinished',
     29   location: '',
     30   amount: '.',
     31   currency: '',
     32   unit: '',
     33   quantity: '',
     34   contactType: '' as const,
     35   contactValue: ''
     36 };
     37 test('explicit cleanup cancellation before admission acquires no transaction and retains the original draft', async ({
     38   page
     39 }) => {
     40   await load(page);
     41   const result = await page.evaluate(async (form) => {
     42     const api = window.hcp049;
     43     const draft = await api.createPublicDraft(window.hcp049Repository, form);
     44     if (!draft.ok) throw Error('original draft absent');
     45     const scan = await api.inspectPublicStorage(window.hcp049Quota);
     46     if (!scan.ok) throw Error('original inventory absent');
     47     const cleanup = api.reviewPublicCleanup(window.hcp049Quota, scan.value, [
     48       'public_draft:' + draft.value.id
     49     ]);
     50     if (!cleanup.ok) throw Error('original cleanup absent');
     51     const cancellation = new AbortController();
     52     cancellation.abort();
     53     const descriptor = Object.getOwnPropertyDescriptor(
     54       IDBDatabase.prototype,
     55       'transaction'
     56     );
     57     if (!descriptor) throw Error('native transaction method absent');
     58     const native = descriptor.value as IDBDatabase['transaction'];
     59     let acquisitions = 0;
     60     IDBDatabase.prototype.transaction = function (...args) {
     61       acquisitions++;
     62       return native.apply(this, args);
     63     };
     64     let committed: Awaited<ReturnType<typeof api.commitPublicCleanup>>;
     65     try {
     66       committed = await api.commitPublicCleanup(
     67         window.hcp049Quota,
     68         cleanup.value,
     69         cancellation.signal
     70       );
     71     } finally {
     72       Object.defineProperty(IDBDatabase.prototype, 'transaction', descriptor);
     73     }
     74     const retained = await api.readPublicDraft(
     75       window.hcp049Repository,
     76       draft.value.id
     77     );
     78     return { committed, acquisitions, retained, original: draft };
     79   }, form);
     80   expect(result.committed).toEqual({ ok: false, reason: 'aborted' });
     81   expect(result.acquisitions).toBe(0);
     82   expect(result.retained).toEqual(result.original);
     83 });
     84 let server: Awaited<ReturnType<typeof createStaticHarness>>;
     85 let bundle: string;
     86 test.beforeAll(async () => {
     87   server = await createStaticHarness();
     88   const source = (name: string) =>
     89     fileURLToPath(
     90       new URL('../../src/lib/persistence/' + name, import.meta.url)
     91     );
     92   // Compile the exact current production modules together so both use the same
     93   // genuine WeakMap database ownership. This virtual entry is test-only.
     94   const result = await build({
     95     configFile: false,
     96     logLevel: 'silent',
     97     plugins: [
     98       {
     99         name: 'hcp049-test-entry',
    100         resolveId(id) {
    101           if (id === 'virtual:hcp049') return '\0hcp049';
    102         },
    103         load(id) {
    104           if (id === '\0hcp049')
    105             return `export * from ${JSON.stringify(source('database.ts'))};export * from ${JSON.stringify(source('drafts.ts'))};export * from ${JSON.stringify(source('quota.ts'))};export * from ${JSON.stringify(source('records.ts'))};`;
    106         }
    107       }
    108     ],
    109     build: {
    110       write: false,
    111       minify: false,
    112       rolldownOptions: { input: 'virtual:hcp049' },
    113       lib: { entry: 'virtual:hcp049', name: 'hcp049', formats: ['iife'] }
    114     }
    115   });
    116   const output = Array.isArray(result) ? result[0] : result;
    117   if (!('output' in output)) throw new Error('missing test bundle');
    118   const chunks = output.output.filter((item) => item.type === 'chunk');
    119   expect(chunks).toHaveLength(1);
    120   bundle = chunks[0].code;
    121   console.log(
    122     JSON.stringify({
    123       fixture: 'HCP049_ACTUAL_MODULES_REAL_IDB',
    124       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
    125       exposure: 'test-only virtual entry, no production route or dependency'
    126     })
    127   );
    128 });
    129 test.afterAll(async () => server.close());
    130 async function load(page: Page, selectedOwner = owner) {
    131   await page.goto(server.url + '/search');
    132   await page.addScriptTag({ content: bundle });
    133   await page.evaluate(async (expectedOwner) => {
    134     const api = window.hcp049;
    135     const opened = await api.openBrowserDatabase();
    136     if (opened.state !== 'ready') throw new Error(opened.reason);
    137     const repository = api.createPublicDraftRepository(
    138       opened.owner,
    139       expectedOwner
    140     );
    141     if (!repository) throw new Error('missing repository');
    142     window.hcp049Database = opened.owner;
    143     window.hcp049Repository = repository;
    144     const quota = api.createPublicQuotaRepository(opened.owner, expectedOwner);
    145     if (!quota) throw new Error('missing quota repository');
    146     window.hcp049Quota = quota;
    147   }, selectedOwner);
    148 }
    149 function operation(content = 'public quota fixture'): PublicOperationRecord {
    150   const id = randomUUID();
    151   const template = {
    152     pubkey: owner,
    153     kind: 30402,
    154     created_at: 100,
    155     tags: [
    156       ['d', 'quota'],
    157       ['published_at', '100']
    158     ],
    159     content
    160   };
    161   return {
    162     schema: 1,
    163     family: 'public_operation',
    164     owner,
    165     id,
    166     revision: 0,
    167     source: { type: 'draft', id, revision: 0 },
    168     capture: {
    169       kind: 30402,
    170       wire: JSON.stringify(template),
    171       hash: getEventHash(template),
    172       targets: ['wss://one.example.org'],
    173       policyFingerprint: 'a'.repeat(64)
    174     },
    175     artifact: null,
    176     receipts: []
    177   };
    178 }
    179 async function admit(
    180   page: Page,
    181   row: PublicOperationRecord | PreferenceOperationRecord
    182 ) {
    183   return page.evaluate(async (row) => {
    184     const api = window.hcp049;
    185     const decoded = api.decodePublicRecord(
    186       JSON.stringify(row),
    187       row.owner,
    188       row.id
    189     );
    190     if (!decoded.ok) throw new Error(decoded.reason);
    191     return api.admitPublicOperation(window.hcp049Quota, row.id, decoded.value);
    192   }, row);
    193 }
    194 async function seed(
    195   page: Page,
    196   rows: readonly (PublicOperationRecord | PreferenceOperationRecord)[]
    197 ) {
    198   await page.evaluate(async (rows) => {
    199     const api = window.hcp049;
    200     for (const row of rows) {
    201       const decoded = api.decodePublicRecord(
    202         JSON.stringify(row),
    203         row.owner,
    204         row.id
    205       );
    206       if (!decoded.ok) throw new Error(decoded.reason);
    207     }
    208     const transaction = api.browserDatabaseTransaction(
    209       window.hcp049Database,
    210       ['public_operations', 'preference_operations'],
    211       'readwrite'
    212     );
    213     for (const row of rows)
    214       transaction
    215         .objectStore(
    216           row.family === 'public_operation'
    217             ? 'public_operations'
    218             : 'preference_operations'
    219         )
    220         .put({ owner: row.owner, id: row.id, wire: JSON.stringify(row) });
    221     await new Promise<void>((resolve, reject) => {
    222       transaction.addEventListener('complete', () => resolve());
    223       transaction.addEventListener('abort', () =>
    224         reject(new Error('fixture seed aborted'))
    225       );
    226     });
    227   }, rows);
    228 }
    229 test('two genuine tabs race the final operation slot; refusal preserves all original records', async ({
    230   page,
    231   context
    232 }) => {
    233   await load(page);
    234   const initial = Array.from({ length: 99 }, () => operation());
    235   await seed(page, initial);
    236   const second = await context.newPage();
    237   await load(second);
    238   const candidates = [operation(), operation()];
    239   const results = await Promise.all([
    240     admit(page, candidates[0]),
    241     admit(second, candidates[1])
    242   ]);
    243   expect(results.filter((row) => row.ok)).toHaveLength(1);
    244   expect(results.filter((row) => !row.ok)).toEqual([
    245     { ok: false, reason: 'capacity' }
    246   ]);
    247   const snapshot = await page.evaluate(async () => {
    248     const result = await window.hcp049.inspectPublicStorage(window.hcp049Quota);
    249     if (!result.ok) throw new Error(result.reason);
    250     return window.hcp049.publicInventorySnapshot(
    251       window.hcp049Quota,
    252       result.value
    253     );
    254   });
    255   expect(snapshot?.rows).toHaveLength(100);
    256   for (const row of initial)
    257     expect(snapshot?.rows.some((stored) => stored.id === row.id)).toBe(true);
    258   await second.close();
    259 });
    260 test('aggregate 8MiB logical wire admission rejects before count100 and keeps the existing bytes', async ({
    261   page
    262 }) => {
    263   await load(page);
    264   const sample = operation('p'.repeat(220000));
    265   const size = Buffer.byteLength(JSON.stringify(sample));
    266   const count = Math.floor(8388608 / size);
    267   expect(count).toBeLessThan(100);
    268   const rows = Array.from({ length: count }, () => ({
    269     ...sample,
    270     id: randomUUID()
    271   }));
    272   await seed(page, rows);
    273   expect(await admit(page, { ...sample, id: randomUUID() })).toEqual({
    274     ok: false,
    275     reason: 'capacity'
    276   });
    277   const result = await page.evaluate(async () => {
    278     const api = window.hcp049,
    279       inv = await api.inspectPublicStorage(window.hcp049Quota);
    280     if (!inv.ok) throw new Error(inv.reason);
    281     return api.publicInventorySnapshot(window.hcp049Quota, inv.value);
    282   });
    283   expect(result?.rows).toHaveLength(count);
    284   expect(result?.rows.reduce((sum, row) => sum + row.logicalBytes, 0)).toBe(
    285     count * size
    286   );
    287 });
    288 test('reviewed draft cleanup reports local-loss consequences and atomically deletes only the selected record', async ({
    289   page
    290 }) => {
    291   await load(page);
    292   const result = await page.evaluate(async (form) => {
    293     const api = window.hcp049;
    294     const first = await api.createPublicDraft(window.hcp049Repository, form);
    295     const second = await api.createPublicDraft(window.hcp049Repository, {
    296       ...form,
    297       title: 'keep'
    298     });
    299     if (!first.ok || !second.ok) throw new Error('missing drafts');
    300     const inv = await api.inspectPublicStorage(window.hcp049Quota);
    301     if (!inv.ok) throw new Error(inv.reason);
    302     const key = 'public_draft:' + first.value.id;
    303     const reviewed = api.reviewPublicCleanup(window.hcp049Quota, inv.value, [
    304       key
    305     ]);
    306     if (!reviewed.ok) throw new Error(reviewed.reason);
    307     const impact = api.publicCleanupSnapshot(
    308       window.hcp049Quota,
    309       reviewed.value
    310     );
    311     const committed = await api.commitPublicCleanup(
    312       window.hcp049Quota,
    313       reviewed.value
    314     );
    315     const rows = await api.listPublicDrafts(window.hcp049Repository);
    316     return { impact, committed, rows, second: second.value, key };
    317   }, form);
    318   expect(result.impact?.selected).toHaveLength(1);
    319   expect(result.impact?.consequences).toContain(
    320     'does not delete remote copies'
    321   );
    322   expect(result.committed).toEqual({ ok: true, value: [result.key] });
    323   expect(result.rows).toEqual({ ok: true, value: [result.second] });
    324 });
    325 test('pending capture is protected and changed inventory conflicts without partial deletion', async ({
    326   page
    327 }) => {
    328   await load(page);
    329   const row = operation();
    330   expect((await admit(page, row)).ok).toBe(true);
    331   const result = await page.evaluate(
    332     async ({ form, row }) => {
    333       const api = window.hcp049;
    334       const draft = await api.createPublicDraft(window.hcp049Repository, form);
    335       if (!draft.ok) throw new Error(draft.reason);
    336       const inv = await api.inspectPublicStorage(window.hcp049Quota);
    337       if (!inv.ok) throw new Error(inv.reason);
    338       const protectedResult = api.reviewPublicCleanup(
    339         window.hcp049Quota,
    340         inv.value,
    341         ['public_operation:' + row.id]
    342       );
    343       const reviewed = api.reviewPublicCleanup(window.hcp049Quota, inv.value, [
    344         'public_draft:' + draft.value.id
    345       ]);
    346       if (!reviewed.ok) throw new Error(reviewed.reason);
    347       const updated = await api.savePublicDraft(
    348         window.hcp049Repository,
    349         draft.value.id,
    350         0,
    351         { ...form, title: 'new revision' }
    352       );
    353       const committed = await api.commitPublicCleanup(
    354         window.hcp049Quota,
    355         reviewed.value
    356       );
    357       const retained = await api.readPublicDraft(
    358         window.hcp049Repository,
    359         draft.value.id
    360       );
    361       return { protectedResult, updated, committed, retained };
    362     },
    363     { form, row }
    364   );
    365   expect(result.protectedResult).toEqual({ ok: false, reason: 'protected' });
    366   expect(result.committed).toEqual({ ok: false, reason: 'conflict' });
    367   expect(result.retained).toEqual(result.updated);
    368 });
    369 test('an unknown record added after review aborts cleanup; fixed public stores never enumerate private metadata', async ({
    370   page
    371 }) => {
    372   await load(page);
    373   const result = await page.evaluate(async (form) => {
    374     const api = window.hcp049;
    375     const draft = await api.createPublicDraft(window.hcp049Repository, form);
    376     if (!draft.ok) throw new Error(draft.reason);
    377     const inv = await api.inspectPublicStorage(window.hcp049Quota);
    378     if (!inv.ok) throw new Error(inv.reason);
    379     const reviewed = api.reviewPublicCleanup(window.hcp049Quota, inv.value, [
    380       'public_draft:' + draft.value.id
    381     ]);
    382     if (!reviewed.ok) throw new Error(reviewed.reason);
    383     const transaction = api.browserDatabaseTransaction(
    384       window.hcp049Database,
    385       ['public_operations', 'private_sends'],
    386       'readwrite'
    387     );
    388     transaction.objectStore('public_operations').put({
    389       owner: draft.value.owner,
    390       id: '3d030bf5-901d-45e1-8251-41cbdf805e96',
    391       wire: '{"schema":99}'
    392     });
    393     transaction.objectStore('private_sends').put({
    394       owner: draft.value.owner,
    395       id: 'b1d6d23d-79f3-4779-9b03-e289712cc73f',
    396       wire: 'private metadata sentinel'
    397     });
    398     await new Promise<void>((resolve, reject) => {
    399       transaction.addEventListener('complete', () => resolve());
    400       transaction.addEventListener('abort', () =>
    401         reject(new Error('fixture abort'))
    402       );
    403     });
    404     const acquired: string[][] = [];
    405     const descriptor = Object.getOwnPropertyDescriptor(
    406       IDBDatabase.prototype,
    407       'transaction'
    408     );
    409     if (!descriptor) throw new Error('missing transaction descriptor');
    410     const original = descriptor.value as IDBDatabase['transaction'];
    411     IDBDatabase.prototype.transaction = function (storeNames, mode, options) {
    412       acquired.push(
    413         typeof storeNames === 'string' ? [storeNames] : Array.from(storeNames)
    414       );
    415       return original.call(this, storeNames, mode, options);
    416     };
    417     try {
    418       const committed = await api.commitPublicCleanup(
    419         window.hcp049Quota,
    420         reviewed.value
    421       );
    422       const retained = await api.readPublicDraft(
    423         window.hcp049Repository,
    424         draft.value.id
    425       );
    426       return { committed, retained, acquired };
    427     } finally {
    428       IDBDatabase.prototype.transaction = original;
    429     }
    430   }, form);
    431   expect(result.committed).toEqual({ ok: false, reason: 'corrupt_record' });
    432   expect(result.retained.ok).toBe(true);
    433   expect(
    434     result.acquired
    435       .flat()
    436       .every((store) =>
    437         [
    438           'public_drafts',
    439           'public_operations',
    440           'preference_operations'
    441         ].includes(store)
    442       )
    443   ).toBe(true);
    444 });
    445 
    446 test('cleanup selection reads the reviewed indexed array rather than a replaced iterator', async ({
    447   page
    448 }) => {
    449   await load(page);
    450   const result = await page.evaluate(async (form) => {
    451     const api = window.hcp049;
    452     const first = await api.createPublicDraft(window.hcp049Repository, form);
    453     const second = await api.createPublicDraft(window.hcp049Repository, form);
    454     if (!first.ok || !second.ok) throw new Error('missing drafts');
    455     const inventory = await api.inspectPublicStorage(window.hcp049Quota);
    456     if (!inventory.ok) throw new Error(inventory.reason);
    457     const firstKey = 'public_draft:' + first.value.id;
    458     const secondKey = 'public_draft:' + second.value.id;
    459     const selection = [firstKey];
    460     let iteratorReads = 0;
    461     selection[Symbol.iterator] = () => {
    462       iteratorReads++;
    463       return [secondKey].values();
    464     };
    465     const reviewed = api.reviewPublicCleanup(
    466       window.hcp049Quota,
    467       inventory.value,
    468       selection
    469     );
    470     if (!reviewed.ok) throw new Error(reviewed.reason);
    471     return {
    472       impact: api.publicCleanupSnapshot(window.hcp049Quota, reviewed.value),
    473       firstKey,
    474       iteratorReads
    475     };
    476   }, form);
    477   expect(result.iteratorReads).toBe(0);
    478   expect(result.impact?.selected.map((row) => row.key)).toEqual([
    479     result.firstKey
    480   ]);
    481 });
    482 
    483 function preference(
    484   content = 'public inbox preference fixture'
    485 ): PreferenceOperationRecord {
    486   const id = randomUUID();
    487   const template = {
    488     pubkey: owner,
    489     kind: 10050,
    490     created_at: 100,
    491     tags: [],
    492     content
    493   };
    494   return {
    495     schema: 1,
    496     family: 'preference_operation',
    497     owner,
    498     id,
    499     revision: 0,
    500     consent: 'explicit_review',
    501     source: { type: 'inbox_head', wire: null },
    502     capture: {
    503       kind: 10050,
    504       wire: JSON.stringify(template),
    505       hash: getEventHash(template),
    506       targets: ['wss://one.example.org'],
    507       policyFingerprint: 'a'.repeat(64)
    508     },
    509     artifact: null,
    510     receipts: []
    511   };
    512 }
    513 test('public and preference journals share the count ceiling and exact-wire idempotent replay', async ({
    514   page
    515 }) => {
    516   await load(page);
    517   const first = operation();
    518   expect((await admit(page, first)).ok).toBe(true);
    519   expect(await admit(page, first)).toEqual({
    520     ok: true,
    521     value: { id: first.id, revision: 0 }
    522   });
    523   await seed(
    524     page,
    525     Array.from({ length: 98 }, (_, index) =>
    526       index % 2 ? operation() : preference()
    527     )
    528   );
    529   const last = preference();
    530   expect((await admit(page, last)).ok).toBe(true);
    531   expect(await admit(page, operation())).toEqual({
    532     ok: false,
    533     reason: 'capacity'
    534   });
    535   const snapshot = await page.evaluate(async () => {
    536     const api = window.hcp049,
    537       inv = await api.inspectPublicStorage(window.hcp049Quota);
    538     if (!inv.ok) throw new Error(inv.reason);
    539     return api.publicInventorySnapshot(window.hcp049Quota, inv.value);
    540   });
    541   expect(snapshot?.rows).toHaveLength(100);
    542   expect(
    543     snapshot?.rows.filter((row) => row.family === 'preference_operation')
    544   ).toHaveLength(50);
    545 });
    546 test('mixed preference/public exact stored wires share the 8MiB aggregate ceiling', async ({
    547   page
    548 }) => {
    549   await load(page);
    550   const publicSample = operation('p'.repeat(220000)),
    551     preferenceSample = preference('q'.repeat(220000));
    552   let bytes = 0;
    553   const rows: (PublicOperationRecord | PreferenceOperationRecord)[] = [];
    554   for (let index = 0; index < 100; index++) {
    555     const row = {
    556       ...(index % 2 ? preferenceSample : publicSample),
    557       id: randomUUID()
    558     };
    559     const size = Buffer.byteLength(JSON.stringify(row));
    560     if (bytes + size > 8388608) break;
    561     rows.push(row);
    562     bytes += size;
    563   }
    564   await seed(page, rows);
    565   expect(await admit(page, { ...preferenceSample, id: randomUUID() })).toEqual({
    566     ok: false,
    567     reason: 'capacity'
    568   });
    569   const snapshot = await page.evaluate(async () => {
    570     const api = window.hcp049,
    571       inv = await api.inspectPublicStorage(window.hcp049Quota);
    572     if (!inv.ok) throw new Error(inv.reason);
    573     return api.publicInventorySnapshot(window.hcp049Quota, inv.value);
    574   });
    575   expect(snapshot?.rows.reduce((sum, row) => sum + row.logicalBytes, 0)).toBe(
    576     bytes
    577   );
    578   expect(
    579     snapshot?.rows.some((row) => row.family === 'preference_operation')
    580   ).toBe(true);
    581 });
    582 function signedSettledOperation(): PublicOperationRecord {
    583   const key = crypto.getRandomValues(new Uint8Array(32));
    584   try {
    585     const base = finalizeEvent(
    586       {
    587         kind: 30402,
    588         created_at: 100,
    589         tags: [['d', 'quota']],
    590         content: 'public signature fixture'
    591       },
    592       key
    593     );
    594     const template = {
    595       pubkey: base.pubkey,
    596       kind: 30402,
    597       created_at: 101,
    598       tags: [['d', 'quota']],
    599       content: 'public settled artifact fixture'
    600     };
    601     const hash = getEventHash(template);
    602     const wire = JSON.stringify(template);
    603     const artifact = finalizeEvent(
    604       { ...template, tags: template.tags.map((tag) => [...tag]) },
    605       key
    606     );
    607     const id = randomUUID();
    608     return {
    609       schema: 1,
    610       family: 'public_operation',
    611       owner: base.pubkey,
    612       id,
    613       revision: 0,
    614       source: { type: 'draft', id, revision: 0 },
    615       capture: {
    616         kind: 30402,
    617         wire,
    618         hash,
    619         targets: ['wss://one.example.org'],
    620         policyFingerprint: 'a'.repeat(64)
    621       },
    622       artifact: { eventId: artifact.id, wire: JSON.stringify(artifact) },
    623       receipts: [
    624         {
    625           actionId: randomUUID(),
    626           origin: 'wss://one.example.org',
    627           role: 'publication',
    628           attempt: 1,
    629           eventId: artifact.id,
    630           status: 'accepted',
    631           observedAtMilliseconds: 1000,
    632           readbackWire: null
    633         }
    634       ]
    635     };
    636   } finally {
    637     key.fill(0);
    638   }
    639 }
    640 test('actual verified signed settled operation permits reviewed local cleanup; unresolved history remains protected', async ({
    641   page
    642 }) => {
    643   const settled = signedSettledOperation();
    644   await load(page, settled.owner);
    645   const uncertain: PublicOperationRecord = {
    646     ...settled,
    647     id: randomUUID(),
    648     receipts: [
    649       ...settled.receipts,
    650       {
    651         ...settled.receipts[0],
    652         status: 'unknown',
    653         observedAtMilliseconds: 1001
    654       }
    655     ]
    656   };
    657   expect((await admit(page, settled)).ok).toBe(true);
    658   expect((await admit(page, uncertain)).ok).toBe(true);
    659   const result = await page.evaluate(
    660     async ({ settled, uncertain }) => {
    661       const api = window.hcp049,
    662         inv = await api.inspectPublicStorage(window.hcp049Quota);
    663       if (!inv.ok) throw new Error(inv.reason);
    664       const denied = api.reviewPublicCleanup(window.hcp049Quota, inv.value, [
    665         'public_operation:' + uncertain.id
    666       ]);
    667       const reviewed = api.reviewPublicCleanup(window.hcp049Quota, inv.value, [
    668         'public_operation:' + settled.id
    669       ]);
    670       if (!reviewed.ok) throw new Error(reviewed.reason);
    671       const removed = await api.commitPublicCleanup(
    672         window.hcp049Quota,
    673         reviewed.value
    674       );
    675       const next = await api.inspectPublicStorage(window.hcp049Quota);
    676       if (!next.ok) throw new Error(next.reason);
    677       return {
    678         denied,
    679         removed,
    680         remaining: api.publicInventorySnapshot(window.hcp049Quota, next.value)
    681       };
    682     },
    683     { settled, uncertain }
    684   );
    685   expect(result.denied).toEqual({ ok: false, reason: 'protected' });
    686   expect(result.removed).toEqual({
    687     ok: true,
    688     value: ['public_operation:' + settled.id]
    689   });
    690   expect(result.remaining?.rows.map((row) => row.id)).toEqual([uncertain.id]);
    691 });
    692 test('successful native put and delete requests followed by transaction abort never acknowledge or lose records', async ({
    693   page
    694 }) => {
    695   await load(page);
    696   const row = operation();
    697   const result = await page.evaluate(
    698     async ({ row, form }) => {
    699       const api = window.hcp049;
    700       const decoded = api.decodePublicRecord(
    701         JSON.stringify(row),
    702         row.owner,
    703         row.id
    704       );
    705       if (!decoded.ok) throw new Error(decoded.reason);
    706       const putDescriptor = Object.getOwnPropertyDescriptor(
    707         IDBObjectStore.prototype,
    708         'put'
    709       );
    710       const deleteDescriptor = Object.getOwnPropertyDescriptor(
    711         IDBObjectStore.prototype,
    712         'delete'
    713       );
    714       if (!putDescriptor || !deleteDescriptor)
    715         throw new Error('missing native methods');
    716       const nativePut = putDescriptor.value as IDBObjectStore['put'];
    717       const nativeDelete = deleteDescriptor.value as IDBObjectStore['delete'];
    718       let putSuccesses = 0,
    719         deleteSuccesses = 0;
    720       IDBObjectStore.prototype.put = function (...args) {
    721         const request = nativePut.apply(this, args);
    722         request.addEventListener('success', () => {
    723           putSuccesses++;
    724           this.transaction.abort();
    725         });
    726         return request;
    727       };
    728       let inserted: Quota.PublicQuotaResult<
    729         Readonly<{ id: string; revision: number }>
    730       >;
    731       try {
    732         inserted = await api.admitPublicOperation(
    733           window.hcp049Quota,
    734           row.id,
    735           decoded.value
    736         );
    737       } finally {
    738         Object.defineProperty(IDBObjectStore.prototype, 'put', putDescriptor);
    739       }
    740       const draft = await api.createPublicDraft(window.hcp049Repository, form);
    741       if (!draft.ok) throw new Error(draft.reason);
    742       const inventory = await api.inspectPublicStorage(window.hcp049Quota);
    743       if (!inventory.ok) throw new Error(inventory.reason);
    744       const reviewed = api.reviewPublicCleanup(
    745         window.hcp049Quota,
    746         inventory.value,
    747         ['public_draft:' + draft.value.id]
    748       );
    749       if (!reviewed.ok) throw new Error(reviewed.reason);
    750       IDBObjectStore.prototype.delete = function (...args) {
    751         const request = nativeDelete.apply(this, args);
    752         request.addEventListener('success', () => {
    753           deleteSuccesses++;
    754           this.transaction.abort();
    755         });
    756         return request;
    757       };
    758       let deleted: Quota.PublicQuotaResult<readonly string[]>;
    759       try {
    760         deleted = await api.commitPublicCleanup(
    761           window.hcp049Quota,
    762           reviewed.value
    763         );
    764       } finally {
    765         Object.defineProperty(
    766           IDBObjectStore.prototype,
    767           'delete',
    768           deleteDescriptor
    769         );
    770       }
    771       const retained = await api.readPublicDraft(
    772         window.hcp049Repository,
    773         draft.value.id
    774       );
    775       const next = await api.inspectPublicStorage(window.hcp049Quota);
    776       if (!next.ok) throw new Error(next.reason);
    777       return {
    778         inserted,
    779         deleted,
    780         putSuccesses,
    781         deleteSuccesses,
    782         retained,
    783         inventory: api.publicInventorySnapshot(window.hcp049Quota, next.value)
    784       };
    785     },
    786     { row, form }
    787   );
    788   expect(result.putSuccesses).toBe(1);
    789   expect(result.deleteSuccesses).toBe(1);
    790   expect(result.inserted).toEqual({ ok: false, reason: 'aborted' });
    791   expect(result.deleted).toEqual({ ok: false, reason: 'aborted' });
    792   expect(result.retained.ok).toBe(true);
    793   expect(result.inventory?.rows).toHaveLength(1);
    794   expect(result.inventory?.rows[0].family).toBe('public_draft');
    795 });
    796 
    797 test('negative proxy-array length cannot mint an empty cleanup authorization', async ({
    798   page
    799 }) => {
    800   await load(page);
    801   const result = await page.evaluate(async (form) => {
    802     const api = window.hcp049;
    803     const draft = await api.createPublicDraft(window.hcp049Repository, form);
    804     if (!draft.ok) throw new Error(draft.reason);
    805     const inventory = await api.inspectPublicStorage(window.hcp049Quota);
    806     if (!inventory.ok) throw new Error(inventory.reason);
    807     let indexedReads = 0;
    808     const selection = new Proxy(['public_draft:' + draft.value.id], {
    809       get(target, key, receiver) {
    810         if (key === 'length') return -1;
    811         if (key === '0') indexedReads++;
    812         return Reflect.get(target, key, receiver) as unknown;
    813       }
    814     });
    815     const reviewed = api.reviewPublicCleanup(
    816       window.hcp049Quota,
    817       inventory.value,
    818       selection
    819     );
    820     return { reviewed, indexedReads };
    821   }, form);
    822   expect(result.reviewed).toEqual({ ok: false, reason: 'invalid_selection' });
    823   expect(result.indexedReads).toBe(0);
    824 });