app

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

private-storage.spec.ts (30611B)


      1 import { expect, test, type Page } from '@playwright/test';
      2 import { build } from 'vite';
      3 import { fileURLToPath } from 'node:url';
      4 import { createHash } from 'node:crypto';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 import type * as Storage from './harness/private-storage.ts';
      7 declare global {
      8   interface Window {
      9     hcp080: typeof Storage;
     10     hcp080Fixture: Awaited<ReturnType<typeof Storage.makeFixture>>;
     11   }
     12 }
     13 let server: Awaited<ReturnType<typeof createStaticHarness>>, bundle: string;
     14 test.beforeAll(async () => {
     15   server = await createStaticHarness();
     16   const result = await build({
     17     configFile: false,
     18     logLevel: 'silent',
     19     build: {
     20       write: false,
     21       minify: false,
     22       lib: {
     23         entry: fileURLToPath(
     24           new URL('./harness/private-storage.ts', import.meta.url)
     25         ),
     26         name: 'hcp080',
     27         formats: ['iife']
     28       }
     29     }
     30   });
     31   const output = Array.isArray(result) ? result[0] : result;
     32   if (!('output' in output)) throw Error('missing bundle');
     33   const chunks = output.output.filter((item) => item.type === 'chunk');
     34   expect(chunks).toHaveLength(1);
     35   bundle = chunks[0].code;
     36   console.log(
     37     JSON.stringify({
     38       fixture: 'HCP080_REAL_IDB_CIPHERTEXT_SCHEMA_QUOTAS',
     39       bundleSha256: createHash('sha256').update(bundle).digest('hex'),
     40       moduleIds: Object.keys(chunks[0].modules),
     41       qualification:
     42         'Controlled source-only IDB/structural signed ciphertext; no nested admission or actual operator Q'
     43     })
     44   );
     45 });
     46 test.afterAll(async () => server.close());
     47 async function load(page: Page) {
     48   await page.goto(server.url + '/search');
     49   await page.addScriptTag({ content: bundle });
     50   await page.evaluate(async () => {
     51     window.hcp080Fixture = await window.hcp080.makeFixture();
     52   });
     53 }
     54 test('durable rows contain only ciphertext/minimal metadata and preserve original reservation retry', async ({
     55   page
     56 }) => {
     57   await load(page);
     58   const result = await page.evaluate(async () => {
     59     const f = window.hcp080Fixture,
     60       s = window.hcp080;
     61     await f.reserve(0);
     62     const base = f.handle(f.reservation(0)),
     63       next = f.handle(f.operation(0));
     64     const commit = await s.commitPrivateRecord(f.repository, next, base),
     65       retry = await f.reserve(0);
     66     const receive = f.received(0),
     67       received = await s.commitPrivateRecord(
     68         f.repository,
     69         f.handle(receive),
     70         null
     71       );
     72     const sends = await f.rows('private_sends'),
     73       inbox = await f.rows('received_envelopes');
     74     return {
     75       commit,
     76       retry: retry.ok && retry.state,
     77       received: received.ok,
     78       stored: JSON.stringify([...sends, ...inbox]),
     79       publicCount: (await f.rows('public_drafts')).length
     80     };
     81   });
     82   expect(result.commit.ok).toBe(true);
     83   expect(result.retry).toBe('existing');
     84   expect(result.received).toBe(true);
     85   expect(result.publicCount).toBe(0);
     86   for (const value of [
     87     'HCP080 private plaintext sentinel',
     88     '"body"',
     89     '"subject"',
     90     '"contact"',
     91     '"product"'
     92   ])
     93     expect(result.stored).not.toContain(value);
     94 });
     95 test('duplicate signed outer fields grant no handle and preserve existing local evidence', async ({
     96   page
     97 }) => {
     98   await load(page);
     99   const result = await page.evaluate(async () => {
    100     const f = window.hcp080Fixture,
    101       s = window.hcp080;
    102     await f.reserve(0);
    103     const before = JSON.stringify(await f.rows('private_sends')),
    104       operation = f.operation(0),
    105       received = f.received(0);
    106     const poison = (wire: string) =>
    107       '{"\\u0063ontent":"PRIVATE_DUPLICATE_SENTINEL",' + wire.slice(1);
    108     const values = [
    109       s.decodePrivateRecord(
    110         JSON.stringify({
    111           ...operation,
    112           self: { ...operation.self, wire: poison(operation.self.wire) }
    113         }),
    114         s.owner,
    115         operation.id
    116       ),
    117       s.decodePrivateRecord(
    118         JSON.stringify({ ...received, outer: poison(received.outer) }),
    119         s.owner,
    120         received.id
    121       )
    122     ];
    123     return {
    124       accepted: values.filter((v) => v.ok).length,
    125       unchanged: before === JSON.stringify(await f.rows('private_sends')),
    126       received: (await f.rows('received_envelopes')).length
    127     };
    128   });
    129   expect(result).toEqual({ accepted: 0, unchanged: true, received: 0 });
    130 });
    131 test('conflicting ciphertext CAS preserves the original artifact and exact retries reconcile', async ({
    132   page
    133 }) => {
    134   await load(page);
    135   const result = await page.evaluate(async () => {
    136     const f = window.hcp080Fixture,
    137       s = window.hcp080;
    138     await f.reserve(0);
    139     const base = f.handle(f.reservation(0)),
    140       a = f.handle(f.operation(0)),
    141       b = f.handle(f.operation(0));
    142     const [first, second] = await Promise.all([
    143       s.commitPrivateRecord(f.repository, a, base),
    144       s.commitPrivateRecord(f.repository, b, base)
    145     ]);
    146     const winner = first.ok ? a : b,
    147       before = JSON.stringify(await f.rows('private_sends'));
    148     const retry = await s.commitPrivateRecord(f.repository, winner, base);
    149     return {
    150       accepted: [first, second].filter((r) => r.ok).length,
    151       refused: [first, second].filter((r) => !r.ok && r.reason === 'conflict')
    152         .length,
    153       retry: retry.ok && retry.value.state,
    154       unchanged: before === JSON.stringify(await f.rows('private_sends')),
    155       count: (await f.rows('private_sends')).length
    156     };
    157   });
    158   expect(result).toEqual({
    159     accepted: 1,
    160     refused: 1,
    161     retry: 'existing',
    162     unchanged: true,
    163     count: 1
    164   });
    165 });
    166 test('owner-bound handles and loads reject cross-owner or reflected capabilities', async ({
    167   page
    168 }) => {
    169   await load(page);
    170   const result = await page.evaluate(async () => {
    171     const f = window.hcp080Fixture,
    172       s = window.hcp080,
    173       record = f.received(0);
    174     await s.commitPrivateRecord(f.repository, f.handle(record), null);
    175     const foreign = { ...f.reservation(1), owner: s.peer, peer: s.owner },
    176       decoded = s.decodePrivateRecord(
    177         JSON.stringify(foreign),
    178         s.peer,
    179         foreign.id
    180       );
    181     const cross = decoded.ok
    182       ? await s.commitPrivateRecord(f.repository, decoded.value, null)
    183       : undefined;
    184     const reflected = await s.commitPrivateRecord(
    185       {} as typeof f.repository,
    186       f.handle(record),
    187       null
    188     );
    189     const wrong = await s.loadPrivateRecord(
    190       f.repository,
    191       'received_envelopes',
    192       'a'.repeat(64)
    193     );
    194     return {
    195       cross,
    196       reflected,
    197       wrong,
    198       count: (await f.rows('received_envelopes')).length
    199     };
    200   });
    201   expect(result.cross?.ok).toBe(false);
    202   expect(result.reflected.ok).toBe(false);
    203   expect(result.wrong.ok).toBe(false);
    204   expect(result.count).toBe(1);
    205 });
    206 test('unknown schema or corrupt owner records remain unchanged, never reset to an empty inbox', async ({
    207   page
    208 }) => {
    209   await load(page);
    210   const result = await page.evaluate(async () => {
    211     const f = window.hcp080Fixture,
    212       s = window.hcp080,
    213       good = f.received(0),
    214       bad = f.received(1);
    215     await s.commitPrivateRecord(f.repository, f.handle(good), null);
    216     await f.inject('received_envelopes', [
    217       {
    218         owner: s.owner,
    219         id: bad.id,
    220         wire: JSON.stringify({ ...bad, schema: 999 })
    221       }
    222     ]);
    223     const before = JSON.stringify(await f.rows('received_envelopes')),
    224       next = f.received(2),
    225       result = await s.commitPrivateRecord(f.repository, f.handle(next), null);
    226     return {
    227       result,
    228       unchanged: before === JSON.stringify(await f.rows('received_envelopes'))
    229     };
    230   });
    231   expect(result.result).toEqual({ ok: false, reason: 'corrupt_record' });
    232   expect(result.unchanged).toBe(true);
    233 });
    234 test('two actual connections race for the last send slot without evicting existing evidence', async ({
    235   page,
    236   context
    237 }) => {
    238   await load(page);
    239   await page.evaluate(async () => {
    240     const f = window.hcp080Fixture;
    241     for (let i = 0; i < 99; i++) {
    242       const r = await f.reserve(i);
    243       if (!r.ok) throw Error('seed failure');
    244     }
    245   });
    246   const second = await context.newPage();
    247   await load(second);
    248   const [a, b] = await Promise.all([
    249     page.evaluate(() => window.hcp080Fixture.reserve(100)),
    250     second.evaluate(() => window.hcp080Fixture.reserve(101))
    251   ]);
    252   expect([a, b].filter((value) => value.ok)).toHaveLength(1);
    253   expect(
    254     [a, b].filter((value) => !value.ok && value.reason === 'capacity')
    255   ).toHaveLength(1);
    256   expect(
    257     await page.evaluate(
    258       async () => (await window.hcp080Fixture.rows('private_sends')).length
    259     )
    260   ).toBe(100);
    261 });
    262 test('private-send stored UTF8 bytes refuse oversized updates and preserve their exact base', async ({
    263   page
    264 }) => {
    265   test.setTimeout(86_400_000);
    266   await load(page);
    267   const result = await page.evaluate(async () => {
    268     const f = window.hcp080Fixture,
    269       s = window.hcp080;
    270     let stopped = false,
    271       count = 0;
    272     for (let i = 0; i < 100; i++) {
    273       const reservation = await f.reserve(i);
    274       if (!reservation.ok) throw Error('reservation seed failed');
    275       const before = JSON.stringify(await f.rows('private_sends'));
    276       const update = await s.commitPrivateRecord(
    277         f.repository,
    278         f.handle(f.operation(i, true)),
    279         f.handle(f.reservation(i))
    280       );
    281       if (!update.ok) {
    282         if (update.reason !== 'capacity') throw Error('wrong byte refusal');
    283         stopped = before === JSON.stringify(await f.rows('private_sends'));
    284         count = i;
    285         break;
    286       }
    287     }
    288     return {
    289       stopped,
    290       count,
    291       received: (await f.rows('received_envelopes')).length
    292     };
    293   });
    294   expect(result.stopped).toBe(true);
    295   expect(result.count).toBeGreaterThan(0);
    296   expect(result.count).toBeLessThan(100);
    297   expect(result.received).toBe(0);
    298 });
    299 test('received count cap remains separate from a full unresolved outbox and refuses without eviction', async ({
    300   page
    301 }) => {
    302   test.setTimeout(86_400_000);
    303   await load(page);
    304   const result = await page.evaluate(async () => {
    305     const f = window.hcp080Fixture,
    306       s = window.hcp080;
    307     for (let i = 0; i < 100; i++) {
    308       const r = await f.reserve(i);
    309       if (!r.ok) throw Error('send seed failure');
    310     }
    311     const rows = [];
    312     for (let i = 0; i < 2000; i++) {
    313       const r = f.received(i);
    314       rows.push({
    315         owner: s.owner,
    316         id: r.id,
    317         wire: s.privateRecordWire(f.handle(r), s.owner, r.id)
    318       });
    319     }
    320     await f.inject('received_envelopes', rows);
    321     const candidate = f.received(2001);
    322     const before = JSON.stringify(await f.rows('received_envelopes')),
    323       result = await s.commitPrivateRecord(
    324         f.repository,
    325         f.handle(candidate),
    326         null
    327       );
    328     return {
    329       result,
    330       unchanged: before === JSON.stringify(await f.rows('received_envelopes')),
    331       sends: (await f.rows('private_sends')).length,
    332       count: (await f.rows('received_envelopes')).length
    333     };
    334   });
    335   expect(result.result).toEqual({ ok: false, reason: 'capacity' });
    336   expect(result.unchanged).toBe(true);
    337   expect(result.sends).toBe(100);
    338   expect(result.count).toBe(2000);
    339 });
    340 test('received 48MiB byte cap refuses below count cap and preserves both independent namespaces', async ({
    341   page
    342 }) => {
    343   test.setTimeout(86_400_000);
    344   await load(page);
    345   const result = await page.evaluate(async () => {
    346     const f = window.hcp080Fixture,
    347       s = window.hcp080,
    348       rows = [];
    349     let bytes = 0;
    350     let candidate = f.received(0, true);
    351     while (true) {
    352       const wire = s.privateRecordWire(
    353         f.handle(candidate),
    354         s.owner,
    355         candidate.id
    356       )!;
    357       const row = { owner: s.owner, id: candidate.id, wire },
    358         size = new TextEncoder().encode(JSON.stringify(row)).length;
    359       if (bytes + size > 50331648) break;
    360       rows.push(row);
    361       bytes += size;
    362       candidate = f.received(rows.length, true);
    363     }
    364     await f.inject('received_envelopes', rows);
    365     await f.reserve(0);
    366     const before = JSON.stringify(await f.rows('received_envelopes')),
    367       result = await s.commitPrivateRecord(
    368         f.repository,
    369         f.handle(candidate),
    370         null
    371       );
    372     return {
    373       result,
    374       unchanged: before === JSON.stringify(await f.rows('received_envelopes')),
    375       count: rows.length,
    376       bytes,
    377       sends: (await f.rows('private_sends')).length
    378     };
    379   });
    380   expect(result.result).toEqual({ ok: false, reason: 'capacity' });
    381   expect(result.unchanged).toBe(true);
    382   expect(result.count).toBeLessThan(2000);
    383   expect(result.bytes).toBeLessThanOrEqual(50331648);
    384   expect(result.sends).toBe(1);
    385 });
    386 test('real transaction abort never acknowledges or retains a new ciphertext row', async ({
    387   page
    388 }) => {
    389   await load(page);
    390   const result = await page.evaluate(async () => {
    391     const f = window.hcp080Fixture,
    392       s = window.hcp080,
    393       r = f.received(0),
    394       original = Reflect.get<IDBObjectStore, 'put'>(
    395         IDBObjectStore.prototype,
    396         'put'
    397       );
    398     IDBObjectStore.prototype.put = function (...args) {
    399       const request = original.apply(this, args);
    400       request.addEventListener('success', () => this.transaction.abort(), {
    401         once: true
    402       });
    403       return request;
    404     };
    405     let result;
    406     try {
    407       result = await s.commitPrivateRecord(f.repository, f.handle(r), null);
    408     } finally {
    409       IDBObjectStore.prototype.put = original;
    410     }
    411     return { result, count: (await f.rows('received_envelopes')).length };
    412   });
    413   expect(result.result.ok).toBe(false);
    414   expect(result.count).toBe(0);
    415 });
    416 
    417 test('CR008 probe CAS retains exact immutable ciphertext/bindings and native completion', async ({
    418   page
    419 }) => {
    420   await load(page);
    421   const result = await page.evaluate(async () => {
    422     const f = window.hcp080Fixture,
    423       s = window.hcp080,
    424       reservation = f.probe(0),
    425       prepared = { ...reservation, revision: 1, self: f.probe(0, true).self },
    426       base = f.handle(reservation),
    427       next = f.handle(prepared);
    428     const create = await s.commitPrivateRecord(f.repository, base, null),
    429       commit = await s.commitPrivateRecord(f.repository, next, base),
    430       loaded = await s.loadPrivateRecord(
    431         f.repository,
    432         'private_sends',
    433         reservation.id
    434       ),
    435       retry = await s.commitPrivateRecord(f.repository, next, base);
    436     const before = JSON.stringify(await f.rows('private_sends'));
    437     const changes = [
    438       { rumorHash: 'e'.repeat(64) },
    439       { createdAt: prepared.createdAt + 1 },
    440       { self: f.probe(1, true).self },
    441       { binding: { ...prepared.binding, preferenceId: 'e'.repeat(64) } }
    442     ];
    443     const refused = [];
    444     for (const patch of changes) {
    445       const decoded = s.decodePrivateRecord(
    446         JSON.stringify({ ...prepared, revision: 2, ...patch }),
    447         s.owner,
    448         reservation.id
    449       );
    450       refused.push(
    451         !decoded.ok ||
    452           !(await s.commitPrivateRecord(f.repository, decoded.value, next)).ok
    453       );
    454     }
    455     const ordinary = { ...f.operation(0), revision: 2, self: prepared.self },
    456       decodedOrdinary = s.decodePrivateRecord(
    457         JSON.stringify(ordinary),
    458         s.owner,
    459         reservation.id
    460       );
    461     if (!decodedOrdinary.ok)
    462       throw Error('valid ordinary family transition control missing');
    463     refused.push(
    464       !(await s.commitPrivateRecord(f.repository, decodedOrdinary.value, next))
    465         .ok
    466     );
    467     return {
    468       create: create.ok,
    469       commit: commit.ok,
    470       retry: retry.ok && retry.value.state,
    471       original:
    472         loaded.ok &&
    473         s.privateRecordWire(loaded.value, s.owner, reservation.id) ===
    474           s.privateRecordWire(next, s.owner, reservation.id),
    475       refused,
    476       unchanged: before === JSON.stringify(await f.rows('private_sends')),
    477       count: (await f.rows('private_sends')).length
    478     };
    479   });
    480   expect(result).toEqual({
    481     create: true,
    482     commit: true,
    483     retry: 'existing',
    484     original: true,
    485     refused: [true, true, true, true, true],
    486     unchanged: true,
    487     count: 1
    488   });
    489 });
    490 
    491 test('CR008 append-only probe receipts use whole-wire CAS under actual concurrent writers', async ({
    492   page
    493 }) => {
    494   await load(page);
    495   const result = await page.evaluate(async () => {
    496     const f = window.hcp080Fixture,
    497       s = window.hcp080,
    498       reservation = f.probe(0),
    499       prepared = { ...reservation, revision: 1, self: f.probe(0, true).self! },
    500       base = f.handle(reservation),
    501       next = f.handle(prepared);
    502     await s.commitPrivateRecord(f.repository, base, null);
    503     await s.commitPrivateRecord(f.repository, next, base);
    504     const fact = {
    505         actionId: s.id(1),
    506         origin: prepared.binding.archiveTargets[0],
    507         role: 'access_archive',
    508         attempt: 1,
    509         eventId: prepared.self.eventId,
    510         status: 'unknown',
    511         observedAtMilliseconds: 1,
    512         readbackWire: null
    513       },
    514       a = { ...prepared, revision: 2, receipts: [fact] },
    515       b = {
    516         ...prepared,
    517         revision: 2,
    518         receipts: [{ ...fact, actionId: s.id(2) }]
    519       };
    520     const races = await Promise.all(
    521       [a, b].map((row) =>
    522         s.commitPrivateRecord(f.repository, f.handle(row), next)
    523       )
    524     );
    525     const loaded = await s.loadPrivateRecord(
    526       f.repository,
    527       'private_sends',
    528       prepared.id
    529     );
    530     if (!loaded.ok) throw Error('probe disappeared');
    531     const row = JSON.parse(
    532       s.privateRecordWire(loaded.value, s.owner, prepared.id)!
    533     ) as typeof a;
    534     const deleted = await s.commitPrivateRecord(
    535         f.repository,
    536         f.handle({ ...row, revision: 3, receipts: [] }),
    537         loaded.value
    538       ),
    539       relabelled = await s.commitPrivateRecord(
    540         f.repository,
    541         f.handle({
    542           ...row,
    543           revision: 3,
    544           receipts: [{ ...row.receipts[0], status: 'accepted' }]
    545         }),
    546         loaded.value
    547       ),
    548       append = await s.commitPrivateRecord(
    549         f.repository,
    550         f.handle({
    551           ...row,
    552           revision: 3,
    553           receipts: [...row.receipts, { ...fact, status: 'accepted' }]
    554         }),
    555         loaded.value
    556       );
    557     return {
    558       races: races.map((r) => (r.ok ? 'committed' : r.reason)).sort(),
    559       deleted: deleted.ok,
    560       relabelled: relabelled.ok,
    561       append: append.ok,
    562       count: (await f.rows('private_sends')).length
    563     };
    564   });
    565   expect(result).toEqual({
    566     races: ['committed', 'conflict'],
    567     deleted: false,
    568     relabelled: false,
    569     append: true,
    570     count: 1
    571   });
    572 });
    573 
    574 test('CR008 probes and ordinary sends share exactly 100 retained rows in both admission directions', async ({
    575   page
    576 }) => {
    577   await load(page);
    578   const result = await page.evaluate(async () => {
    579     const f = window.hcp080Fixture,
    580       s = window.hcp080;
    581     const originals = Array.from({ length: 99 }, (_, n) =>
    582       n < 50 ? f.probe(n) : f.reservation(n)
    583     );
    584     await f.inject(
    585       'private_sends',
    586       originals.map((row) => ({
    587         owner: s.owner,
    588         id: row.id,
    589         wire: s.privateRecordWire(f.handle(row), s.owner, row.id)
    590       }))
    591     );
    592     const ordinary = await f.reserve(100),
    593       before = JSON.stringify(await f.rows('private_sends')),
    594       probe = await s.commitPrivateRecord(
    595         f.repository,
    596         f.handle(f.probe(101)),
    597         null
    598       ),
    599       full = await f.reserve(102),
    600       collision = await f.reserve(0);
    601     return {
    602       ordinary: ordinary.ok,
    603       probe: probe.ok ? 'unexpected' : probe.reason,
    604       full: full.ok ? 'unexpected' : full.reason,
    605       collision: collision.ok ? 'unexpected' : collision.reason,
    606       unchanged: before === JSON.stringify(await f.rows('private_sends')),
    607       count: (await f.rows('private_sends')).length
    608     };
    609   });
    610   expect(result).toEqual({
    611     ordinary: true,
    612     probe: 'capacity',
    613     full: 'capacity',
    614     collision: 'conflict',
    615     unchanged: true,
    616     count: 100
    617   });
    618 });
    619 
    620 test('CR008 outbox bytes include complete probe artifact/readback metadata below the row ceiling', async ({
    621   page
    622 }) => {
    623   await load(page);
    624   const result = await page.evaluate(async () => {
    625     const f = window.hcp080Fixture,
    626       s = window.hcp080;
    627     const rows = [];
    628     let total = 0;
    629     for (let index = 0; index < 100; index++) {
    630       const probe = f.probe(index, true, true),
    631         self = probe.self!,
    632         record = {
    633           ...probe,
    634           revision: 2,
    635           receipts: [
    636             {
    637               actionId: s.id(500),
    638               origin: probe.binding.readTargets[0],
    639               role: 'access_readback',
    640               attempt: 1,
    641               eventId: self.eventId,
    642               status: 'readback',
    643               observedAtMilliseconds: 1,
    644               readbackWire: self.wire
    645             }
    646           ]
    647         },
    648         row = {
    649           owner: s.owner,
    650           id: record.id,
    651           wire: s.privateRecordWire(f.handle(record), s.owner, record.id)
    652         },
    653         bytes = new TextEncoder().encode(JSON.stringify(row)).length;
    654       if (total + bytes > 8 * 1024 * 1024) break;
    655       total += bytes;
    656       rows.push(row);
    657     }
    658     if (!rows.length || rows.length >= 100)
    659       throw Error('byte boundary not exercised');
    660     await f.inject('private_sends', rows);
    661     const original = JSON.parse(rows[rows.length - 1].wire!) as {
    662         owner: string;
    663         id: string;
    664         revision: number;
    665         receipts: {
    666           actionId: string;
    667           origin: string;
    668           role: string;
    669           attempt: number;
    670           eventId: string;
    671           status: string;
    672           observedAtMilliseconds: number;
    673           readbackWire: string;
    674         }[];
    675       },
    676       next = {
    677         ...original,
    678         revision: original.revision + 1,
    679         receipts: [...original.receipts]
    680       },
    681       oldBytes = new TextEncoder().encode(
    682         JSON.stringify(rows[rows.length - 1])
    683       ).length;
    684     let growth = 0;
    685     for (
    686       let index = 0;
    687       index < 10 && total + growth <= 8 * 1024 * 1024;
    688       index++
    689     ) {
    690       next.receipts.push({
    691         ...original.receipts[0],
    692         actionId: s.id(600 + index)
    693       });
    694       const row = {
    695         owner: next.owner,
    696         id: next.id,
    697         wire: s.privateRecordWire(f.handle(next), next.owner, next.id)
    698       };
    699       growth = new TextEncoder().encode(JSON.stringify(row)).length - oldBytes;
    700     }
    701     if (total + growth <= 8 * 1024 * 1024)
    702       throw Error('bounded update did not cross byte cap');
    703     const before = JSON.stringify(await f.rows('private_sends')),
    704       refused = await s.commitPrivateRecord(
    705         f.repository,
    706         f.handle(next),
    707         f.handle(original)
    708       ),
    709       inventory = await s.inspectPrivateStorage(f.repository, 'private_sends'),
    710       physicalBytes = (await f.rows('private_sends')).reduce<number>(
    711         (sum, row) =>
    712           sum + new TextEncoder().encode(JSON.stringify(row)).length,
    713         0
    714       );
    715     return {
    716       refused: refused.ok ? 'unexpected' : refused.reason,
    717       actualBytes: physicalBytes === total,
    718       meteredBytes: inventory.ok && inventory.value.bytes === total,
    719       belowCountCap: rows.length < 100,
    720       unchanged: before === JSON.stringify(await f.rows('private_sends'))
    721     };
    722   });
    723   expect(result).toEqual({
    724     refused: 'capacity',
    725     actualBytes: true,
    726     meteredBytes: true,
    727     belowCountCap: true,
    728     unchanged: true
    729   });
    730 });
    731 
    732 test('CR008 a probe can take the mixed last slot while the next ordinary reservation is refused', async ({
    733   page
    734 }) => {
    735   await load(page);
    736   const result = await page.evaluate(async () => {
    737     const f = window.hcp080Fixture,
    738       s = window.hcp080;
    739     const records = Array.from({ length: 99 }, (_, n) =>
    740       n < 50 ? f.reservation(n) : f.probe(n)
    741     );
    742     await f.inject(
    743       'private_sends',
    744       records.map((row) => ({
    745         owner: row.owner,
    746         id: row.id,
    747         wire: s.privateRecordWire(f.handle(row), row.owner, row.id)
    748       }))
    749     );
    750     const probe = await s.commitPrivateRecord(
    751         f.repository,
    752         f.handle(f.probe(100)),
    753         null
    754       ),
    755       before = JSON.stringify(await f.rows('private_sends')),
    756       ordinary = await f.reserve(101);
    757     return {
    758       probe: probe.ok,
    759       ordinary: ordinary.ok ? 'unexpected' : ordinary.reason,
    760       unchanged: before === JSON.stringify(await f.rows('private_sends')),
    761       count: (await f.rows('private_sends')).length
    762     };
    763   });
    764   expect(result).toEqual({
    765     probe: true,
    766     ordinary: 'capacity',
    767     unchanged: true,
    768     count: 100
    769   });
    770 });
    771 
    772 test('CR008 actual probe growth leaves insufficient physical bytes for an ordinary reservation', async ({
    773   page
    774 }) => {
    775   await load(page);
    776   const result = await page.evaluate(async () => {
    777     const f = window.hcp080Fixture,
    778       s = window.hcp080,
    779       cap = 8 * 1024 * 1024;
    780     const makeRecord = (index: number) => {
    781       const probe = f.probe(index, true, true),
    782         self = probe.self!;
    783       return {
    784         ...probe,
    785         self,
    786         revision: 2,
    787         receipts: [
    788           {
    789             actionId: s.id(500),
    790             origin: probe.binding.readTargets[0],
    791             role: 'access_readback',
    792             attempt: 1,
    793             eventId: self.eventId,
    794             status: 'readback',
    795             observedAtMilliseconds: 1,
    796             readbackWire: self.wire
    797           }
    798         ]
    799       };
    800     };
    801     type Record = ReturnType<typeof makeRecord>;
    802     const stored = (record: { owner: string; id: string }) => ({
    803       owner: record.owner,
    804       id: record.id,
    805       wire: s.privateRecordWire(f.handle(record), record.owner, record.id)
    806     });
    807     const bytes = (record: { owner: string; id: string }) =>
    808       new TextEncoder().encode(JSON.stringify(stored(record))).length;
    809     // Signed-wire whitespace varies structural fixture charging, not inner
    810     // nonce/source proof. Every readback retains the same exact outer wire.
    811     const withWire = (record: Record, wire: string): Record => ({
    812       ...record,
    813       self: { ...record.self, wire },
    814       receipts: record.receipts.map((fact) => ({ ...fact, readbackWire: wire }))
    815     });
    816     const records: Record[] = [];
    817     let total = 0;
    818     for (let index = 0; index < 100; index++) {
    819       const record = makeRecord(index),
    820         size = bytes(record);
    821       if (total + size > cap) break;
    822       total += size;
    823       records.push(record);
    824     }
    825     if (!records.length || records.length >= 100)
    826       throw Error('byte-only fixture missing');
    827     const original = records[records.length - 1],
    828       originalBytes = bytes(original),
    829       next = { ...original, revision: 3, receipts: [...original.receipts] };
    830     for (
    831       let index = 0;
    832       index < 10 && total - originalBytes + bytes(next) <= cap;
    833       index++
    834     )
    835       next.receipts.push({
    836         ...original.receipts[0],
    837         actionId: s.id(600 + index)
    838       });
    839     const ordinaryBytes = bytes(f.reservation(999)),
    840       overflow = total - originalBytes + bytes(next) - cap,
    841       perCharacter =
    842         bytes(next) - bytes(withWire(next, original.self.wire.slice(0, -1))),
    843       trim = Math.ceil(
    844         (overflow + Math.floor(ordinaryBytes / 2)) / perCharacter
    845       );
    846     if (
    847       overflow <= 0 ||
    848       perCharacter <= 0 ||
    849       trim <= 0 ||
    850       !original.self.wire.endsWith('\n'.repeat(trim))
    851     )
    852       throw Error('invalid byte boundary adjustment');
    853     const wire = original.self.wire.slice(0, -trim),
    854       baseline = withWire(original, wire),
    855       candidate = withWire(next, wire);
    856     records[records.length - 1] = baseline;
    857     const baselineBytes = total - originalBytes + bytes(baseline),
    858       expected = baselineBytes - bytes(baseline) + bytes(candidate);
    859     if (expected > cap || cap - expected >= ordinaryBytes)
    860       throw Error('ordinary denial boundary not reached');
    861     await f.inject('private_sends', records.map(stored));
    862     const growth = await s.commitPrivateRecord(
    863         f.repository,
    864         f.handle(candidate),
    865         f.handle(baseline)
    866       ),
    867       before = JSON.stringify(await f.rows('private_sends')),
    868       ordinary = await f.reserve(999),
    869       inventory = await s.inspectPrivateStorage(f.repository, 'private_sends'),
    870       actual = (await f.rows('private_sends')).reduce<number>(
    871         (sum, row) =>
    872           sum + new TextEncoder().encode(JSON.stringify(row)).length,
    873         0
    874       );
    875     return {
    876       growth: growth.ok,
    877       ordinary: ordinary.ok ? 'unexpected' : ordinary.reason,
    878       bytesExact:
    879         actual === expected &&
    880         inventory.ok &&
    881         inventory.value.bytes === expected,
    882       belowCountCap: records.length < 100,
    883       unchanged: before === JSON.stringify(await f.rows('private_sends'))
    884     };
    885   });
    886   expect(result).toEqual({
    887     growth: true,
    888     ordinary: 'capacity',
    889     bytesExact: true,
    890     belowCountCap: true,
    891     unchanged: true
    892   });
    893 });
    894 
    895 test('CR008 ordinary reservation rejects a corrupt probe tail without skipping owner rows', async ({
    896   page
    897 }) => {
    898   await load(page);
    899   const result = await page.evaluate(async () => {
    900     const f = window.hcp080Fixture,
    901       s = window.hcp080,
    902       good = f.probe(0),
    903       corrupt = f.probe(99);
    904     await f.inject('private_sends', [
    905       {
    906         owner: s.owner,
    907         id: good.id,
    908         wire: s.privateRecordWire(f.handle(good), s.owner, good.id)
    909       },
    910       {
    911         owner: s.owner,
    912         id: corrupt.id,
    913         wire: JSON.stringify({
    914           ...corrupt,
    915           nonce: 'PRIVATE_CORRUPTION_SENTINEL'
    916         })
    917       }
    918     ]);
    919     const before = JSON.stringify(await f.rows('private_sends')),
    920       result = await f.reserve(100);
    921     return {
    922       refused: result.ok ? 'unexpected' : result.reason,
    923       unchanged: before === JSON.stringify(await f.rows('private_sends'))
    924     };
    925   });
    926   expect(result).toEqual({ refused: 'corrupt_record', unchanged: true });
    927 });
    928 
    929 test('CR008 native abort cannot acknowledge or retain a new probe reservation', async ({
    930   page
    931 }) => {
    932   await load(page);
    933   const result = await page.evaluate(async () => {
    934     const f = window.hcp080Fixture,
    935       s = window.hcp080,
    936       row = f.probe(0),
    937       original = Reflect.get<IDBObjectStore, 'put'>(
    938         IDBObjectStore.prototype,
    939         'put'
    940       );
    941     IDBObjectStore.prototype.put = function (...args) {
    942       const request = original.apply(this, args);
    943       request.addEventListener('success', () => this.transaction.abort(), {
    944         once: true
    945       });
    946       return request;
    947     };
    948     let committed;
    949     try {
    950       committed = await s.commitPrivateRecord(
    951         f.repository,
    952         f.handle(row),
    953         null
    954       );
    955     } finally {
    956       IDBObjectStore.prototype.put = original;
    957     }
    958     return {
    959       acknowledged: committed.ok,
    960       count: (await f.rows('private_sends')).length
    961     };
    962   });
    963   expect(result).toEqual({ acknowledged: false, count: 0 });
    964 });